diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 17648e2d..41e781cd 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -10,7 +10,13 @@ these entries stays in the GitHub releases and the Git history. ## Unreleased +### Breaking +- A custom frontend whose `open()` takes `const ViewLaunch&` declares `static bool providesViewProof()`, `true` when it gives the proof to its view and `false` otherwise, or the developer environment no longer compiles with it: undeclared, its proven view would leave project writes and C++ commands unguarded (#680, ADR-027, `docs/FRONTENDS.md`). +- `cppFunction` (and `Space::cppFunction`) refuses the names starting with `webfront.inspector.`, reserved to the inspectors, with `std::invalid_argument`: rename such a function, and its `webFront.cppFunction(...)` calls in the page, to a name of your own (#680, ADR-027). + ### Added +- Open the inspectors from the WebFront tab's menu of the developer environment: each panel shows in a floating window of the page and can be detached to a native secondary window (WebKitGTK, WKWebView, WebView2) or, with `trustLoopbackClients`, a tab of the system browser; the choice and the place are kept per project (#680, ADR-027, `docs/DEVELOPER_ENVIRONMENT.md`). +- Declare what the inspectors show with `app.watch(name, source)`, whose handle removes the watch when it is destroyed; the Watches panel follows their registrations and removals. Outside the developer environment and in a distribution build, `watch` registers nothing (#680, ADR-027). - Embed a plain interface directory (HTML, JavaScript, CSS, vendored files) from CMake with `webfront_embed_directory(app ui CLASS AppUI)`, without the developer environment: the build regenerates the provider when a file changes, and `fs::DocumentRootFirstFSWith` lets a development root serve in front of it (#675, `docs/EMBEDDED_ASSETS.md`). - Set from the configuration `Referrer-Policy` (`contentPolicy.referrerPolicy`: `"no-referrer"` forbids explicitly that a capability in your URLs leaves in `Referer`), `X-Content-Type-Options: nosniff` (`noSniff`) and the `Cache-Control` of HTML pages (`htmlCacheControl`), on files, route and generated replies unless a reply sets its own (#674, `docs/CONTENT_POLICY.md`). - Keep a capability carried by your URLs out of WebFront's logs with `app.addSecretPrefix("/s/")`: the segment after the prefix is logged as `*` (`/s/*/index.html`) for files, routes, WebSocket upgrades and their failures, whose error messages are not logged (#673, `docs/HTTP_ASSETS.md`). @@ -32,6 +38,9 @@ these entries stays in the GitHub releases and the Git history. - `DeveloperBrowserIntegration-workspace` gives the relaunched bootstrap page the same 60 s to start as the first one, instead of 10 s, which a loaded runner exceeded while the page verified its cached environment (#660). - Applications started from the terminal of a Snap-packaged editor (VSCodium) now run on WebKitGTK without cleaning the environment by hand; `WEBFRONT_KEEP_SNAP_ENVIRONMENT=1` opts out (#662, `docs/WEBKITGTK.md`). +### Security +- Require an admitted client for developer project writes and native terminal commands when the frontend proves its view (ADR-027, #680). + ## [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 diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index b1a263ae..f77fc9bd 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -442,8 +442,34 @@ environment's `mount`, not to the embedded bootstrap page): embedded frontend (WebKitGTK, WKWebView, WebView2, CEF), which proves itself at the handshake, or any loopback page when the application sets `WebFrontConfig::trustLoopbackClients`. With the system browser, which never receives that proof, the entries are therefore unavailable by default, and the menu says to choose an embedded frontend or to set - `trustLoopbackClients`, knowing that any local process can then read the state of the application. The inspector panels - themselves come with the next versions of the environment; until then an admitted page's entries say so. + `trustLoopbackClients`, knowing that any local process can then read the state of the application. + + **The inspector** is one page of the environment, `/webfront/developer/environment/inspector.html?panel=`, that talks + to C++ through the bridge. An entry of the menu opens its panel where the project keeps it: at first, and whenever its + detached container is unavailable, in a **floating window** of the page (moved and resized like the terminal's window, + with the mouse or with the arrow keys on its title bar), whose frame opens no connection of its own and borrows the page's + bridge, since the adapters give the proof of the view to the main frame only. **Detach** moves the panel to a window of its + own, and the next opening of that panel goes there again; **Attach**, in that window, brings it back to the floating + window, where it then opens: + + | Frontend of the page | Detached container | + | --- | --- | + | WebKitGTK, WKWebView, WebView2 | a native secondary window (`webfront.inspector.openWindow`, `openSecondaryWindow`), which carries the proof of the view; opening the panel again brings it to the front, and closing the main window closes it | + | System browser with `trustLoopbackClients` | a tab of the system browser (`window.open`), with its own loopback connection; when the pop-up blocker refuses it, the panel stays in the floating window and a message offers to try again; the tab closes when the page that opened it is gone | + | CEF, or an embedded view without secondary windows | none: Detach is greyed, with the reason in its tooltip (`window.open` there would open a frame without the proof) | + + Attach brings the panel back to the page that detached it only, even when other pages of the application are open on + the same origin. A page keeps its identifier across a reload through Web Locks; in a browser without them, a reloaded + page has a new one, and a tab detached before the reload asks the old page in vain: it says that the main page did not + answer. Close that tab, open the panel from the menu of the reloaded page, then use Attach in the window it opens. The project keeps the detached panels and the floating window's place in + `.webfront/developer/inspector-window.json`. A save that reaches C++ completes or releases its transaction there, + even when its page closes. A page closed before the save reaches C++ may lose its latest choice. + With a frontend that proves its view, developer file writes and starting or cancelling native terminal commands + also require an admitted page. The system browser keeps origin-based access to those operations. + The **Watches** panel lists the application's watches (`app.watch(name, source)`, declared after `bootstrap()`): their + name, the kind of their root and where they were declared. It asks C++ for the revision of their table every 250 ms + (Pause stops it), reads the list again when it changed, and adds or removes the watches that appeared or disappeared. + Their contents, and the other panels, come with the next versions of the environment. The tab is a button (`aria-expanded`, `aria-haspopup="menu"`, 44 px target), its menu a `menu` of `menuitem`s of 44 px, and the window a non-modal dialog. The interface stays in the preview diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 74b4f650..4ceb4392 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -13,7 +13,8 @@ A frontend is a type with: | `static void initialize()` | Called once successfully per frontend type, before the first `BasicWF` listener is created. A thrown exception aborts construction; the next construction retries. | | `static void open(std::string_view port, std::string_view file)` | Called by `show()` / `openAndRun()` on the calling thread, while the HTTP server runs on its own thread. | | `static void open(address, port, page, const ContentPolicy&)` (optional) | Preferred overload receiving the per-application [content policy](CONTENT_POLICY.md). | -| `static void open(address, port, page, const ContentPolicy&, const WindowOptions&, const ViewLaunch&)` (optional) | Richest overload: also receives the [view association](#view-association) proof of this launch. | +| `static void open(address, port, page, const ContentPolicy&, const WindowOptions&, const ViewLaunch&)` (optional) | Richest overload: also receives the [view association](#view-association) proof of this launch. A frontend that offers it declares `static bool providesViewProof()`. | +| `static bool providesViewProof()` (required with the `ViewLaunch` overload) | `true` when the frontend gives the proof to its view, `false` when it does not (the system browser, which receives `ViewLaunch` only for the origin). While it is `true`, the developer environment's project writes and the terminal's C++ commands are refused to a page that is not a local client (ADR-027, section 2). A frontend with the `ViewLaunch` overload that leaves it undeclared fails to compile where WebFront checks it; any other frontend counts as `false`. | | `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. | @@ -55,7 +56,8 @@ on a command line or in a URL. - `NativeOrBrowserFrontend` passes the proof to the native window only. - The association does not protect against a script admitted into the view (ADR-008): it shares the authority of the bridge and could read the property before `WebFront.js`. An adapter that cannot inject a script simply does not implement the overload. -- A custom frontend that wants services restricted to its own view implements the overload and applies +- A custom frontend that wants services restricted to its own view implements the overload, declares + `providesViewProof()` returning `true`, and applies `webfront::detail::viewSecretScript(secret, origin)` (or the engine's equivalent) at the start of the document. The helper returns an empty script, hence no association, unless the secret is lowercase hexadecimal and the origin a plain http origin; give it `webfront::detail::browserOrigin(address, port)` (lowercase, without port 80), which `ViewLaunch::origin` already is. diff --git a/docs/adr/ADR-027-inspecteurs-de-l-etat-de-l-application.md b/docs/adr/ADR-027-inspecteurs-de-l-etat-de-l-application.md index 364a7790..91750435 100644 --- a/docs/adr/ADR-027-inspecteurs-de-l-etat-de-l-application.md +++ b/docs/adr/ADR-027-inspecteurs-de-l-etat-de-l-application.md @@ -4,6 +4,7 @@ | Version | Date | État | Auteur | Évolution | Révision Git | | --- | --- | --- | --- | --- | --- | +| 1.1 | 2026-11-25 | Proposée | Ambroise Leclerc | Hôte détachable (#680) : `webfront.inspector.embedded()` dit à la page hôte si elle peut tourner dans un frontend intégré (vue prouvée, ou frontend actif qui transmet la preuve), ce qui décide de l'onglet du navigateur système ; `webfront.inspector.closeWindow(panneau, hôte)` ferme la fenêtre d'un panneau rattaché ; une fenêtre par panneau et par page hôte, qui seule le rattache ; choix et place conservés dans `inspector-window.json`, lus avec le jeton de leurs octets par `webfront.inspector.readPreferences()`. | À renseigner après intégration. | | 1.0 | 2026-11-25 | Proposée | Ambroise Leclerc | Décision initiale (#678, épique #677) : inspecteurs réservés à l'environnement développeur, accès réservé aux vues prouvées sauf autorisation explicite, nœuds d'arbre sur les types existants du pont, lecture et différences paginées, opérations entières sous le verrou ou sur l'exécuteur de l'application, modification à la demande de l'application, page unique `inspector.html` dans un conteneur choisi sur l'accès effectif. | À renseigner après intégration. | ## État et portée @@ -218,7 +219,8 @@ appels sont : - `webfront.inspector.reset(observateur)` : vide la mémoire de l'observateur pour cette connexion (ci-dessous) ; - `webfront.inspector.limits()` : les bornes de cette section, dont `maxWriteTextBytes`. -Le nombre vaut 200 par défaut et 1 000 au plus. C++ réduit chaque page pour qu'elle tienne dans `responseBudget` et +Le nombre est un argument de chaque appel, puisque le pont n'a pas d'argument facultatif : l'inspecteur demande 200 +par défaut, et C++ le ramène à 1 000 au plus (0 ne demande que la révision, pour `watches`). C++ réduit chaque page pour qu'elle tienne dans `responseBudget` et rend le `suivant` qui reprend là où elle s'arrête : aucun appel ne lève `BufferOverflowException` ni ne dépasse `maxMessageSize`, quel que soit l'état observé. Les seuls échecs d'un appel valide sont les refus typés de cette décision (`webfront.inspector.*`). @@ -652,7 +654,9 @@ booléens, et aucun état de l'application. | `host` | la connexion de la page hôte est admise (section 2) | | `newConnections` | une nouvelle connexion non prouvée serait admise : l'application a choisi `trustLoopbackClients` | -La page se charge dans le premier conteneur qui convient : +Un panneau s'ouvre là où le projet le garde : dans la fenêtre flottante tant qu'il est rattaché, ce qui est son état +initial, et dans son conteneur détaché une fois détaché, tant que ce conteneur reste disponible (sinon la fenêtre +flottante sert de repli). L'ordre qui suit choisit le conteneur d'un panneau **détaché** : 1. **Fenêtre native secondaire** si `secondaryWindow`, donc seulement depuis une page hôte admise (WebKitGTK, WKWebView, WebView2). La fonction réservée `webfront.inspector.openWindow` appelle `openSecondaryWindow`, qui @@ -670,6 +674,43 @@ La page se charge dans le premier conteneur qui convient : 4. **Aucun** sinon (navigateur système sans `trustLoopbackClients`) : les entrées du menu sont désactivées et disent pourquoi (section 2). +La page hôte ne sait pas d'elle-même si elle tourne dans le navigateur système : `containers()` décrit l'accès, pas la +vue. Elle le demande à `webfront.inspector.embedded()`, qui vérifie l'accès comme les autres fonctions et répond vrai +quand l'appelant est une vue prouvée (`UI::isEmbeddedView()`) **ou** quand le frontend actif transmet la preuve à ses +vues. La preuve désigne une vue prouvée, pas l'endroit où tourne une page qui ne l'a pas : sous un tel frontend, une page +admise sans preuve (un cadre d'une vue intégrée, avec `trustLoopbackClients`) peut se trouver dans une vue intégrée, et +on ne lui propose pas d'onglet. Un échec compte aussi comme une vue intégrée, ce qui n'essaie jamais d'onglet. + +Chaque page hôte a un **identifiant** (1 à 64 lettres, chiffres, `-` ou `_`), gardé dans le stockage de session de son +onglet pour qu'un rechargement le garde. Ce stockage étant copié dans une page qu'elle ouvre, l'identifiant n'est repris +que par la page qui en détient le verrou (Web Locks, exclusif pour l'origine, libéré quand la page disparaît) ; sans +Web Locks, chaque chargement en tire un nouveau. Le nom de l'onglet d'un panneau détaché nomme aussi l'hôte, pour qu'une +autre page du même groupe de navigation ne réutilise pas son onglet. Un panneau détaché a sa propre fenêtre, nommée par la page `inspector.html?panel=&host=` : +`openWindow(panneau, hôte, largeur, hauteur)` n'accepte que les panneaux du menu et un identifiant valide, et +`webfront.inspector.closeWindow(panneau, hôte)` ferme celle d'un panneau rattaché de nouveau. Les deux s'exécutent sur +le thread de l'interface, où `openSecondaryWindow` et `requestClose(page)` ne retiennent pas le thread du serveur. Une +fenêtre détachée demande son rattachement par un `BroadcastChannel` de même origine, en nommant son hôte : seule la page +qui l'a détachée le prend, les autres pages de l'application ouvertes sur la même origine l'ignorent. C'est cette page +qui ferme la fenêtre, quand elle le peut : une fenêtre native par `closeWindow` sur sa propre connexion, et un nouveau +détachement n'ouvre la fenêtre qu'une fois cette fermeture terminée ; un onglet qu'elle a ouvert, par sa référence. Une +fermeture demandée par la fenêtre elle-même pourrait sinon refermer celle qu'un détachement fait entre-temps vient de +réutiliser. Un onglet dont elle n'a pas la référence (ouvert avant un rechargement) se ferme lui-même après la réponse, +et le détachement suivant ouvre un onglet sous un autre nom plutôt que de réutiliser celui-ci. + +La liste des observateurs se lit page après page sous la révision de la première ; une page qui répond `changé` fait +recommencer la liste, pour qu'un observateur retiré entre deux pages ne reste pas affiché sous la nouvelle révision. + +Le choix de chaque panneau et la place de la fenêtre flottante sont écrits comme des **changements** du fichier du +projet, relu au moment de l'écriture et validé seulement s'il n'a pas changé depuis (sinon l'écriture recommence) : +plusieurs pages d'un même projet ne défont pas leurs choix. `webfront.inspector.readPreferences()` lit le fichier et +son jeton sous un même verrou du store, le jeton étant calculé sur les octets rendus : un contenu qui change puis revient +entre la lecture et la sauvegarde ne valide pas des choix lus sur un autre contenu. Un fichier absent donne des choix +vides avec le jeton de son absence ; un fichier présent mais illisible fait échouer l'écriture plutôt que de l'écraser. +Un détachement ou un rattachement est écrit aussitôt, la place après une courte pause. Un seul appel admis à +`webfront.inspector.savePreferences` écrit la version conditionnelle, et C++ libère sa transaction en cas d'échec ; un +changement non écrit est repris par l'écriture suivante, après les changements plus récents du même panneau ou de la +place, qui l'emportent. Si la page ferme avant que cet appel arrive, le dernier changement peut être perdu. + La même règle désactive « Détacher » quand aucun conteneur détaché ne donnerait l'accès. Chaque panneau a une action « Détacher / Rattacher », désactivée avec sa raison quand aucun conteneur détaché n'est diff --git a/docs/adr/README.md b/docs/adr/README.md index a0fdc68d..c023b84a 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -69,7 +69,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [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 | -| [ADR-027](ADR-027-inspecteurs-de-l-etat-de-l-application.md) | Application state inspectors in the developer environment only: reserved `webfront.inspector.*` functions refused to unproven views unless the application trusts loopback clients, tree nodes on existing bridge types with paged reads and paged differences, observer operations run whole under the application's lock or on its executor, writes only when the application provides them, one `inspector.html` page in the first container that grants access | Proposed | 2026-11-25 | 1.0 — 2026-11-25 | +| [ADR-027](ADR-027-inspecteurs-de-l-etat-de-l-application.md) | Application state inspectors in the developer environment only: reserved `webfront.inspector.*` functions refused to unproven views unless the application trusts loopback clients, tree nodes on existing bridge types with paged reads and paged differences, observer operations run whole under the application's lock or on its executor, writes only when the application provides them, one `inspector.html` page, shown in a floating window of the page and, for a detached panel only, in the first container that grants access (a native secondary window, else a system-browser tab) | Proposed | 2026-11-25 | 1.1 — 2026-11-25 | Numbering follows the reading topics; milestones and individual file histories provide the chronology, which does not follow the numerical order. diff --git a/include/webfront/Commands.hpp b/include/webfront/Commands.hpp index 20cf04c7..86602192 100644 --- a/include/webfront/Commands.hpp +++ b/include/webfront/Commands.hpp @@ -12,10 +12,13 @@ #pragma once +#include "BridgeError.hpp" +#include "frontend/Frontend.hpp" #include "networking/Tasks.hpp" #include "Task.hpp" #include "UISubscribers.hpp" #include "utils/Json.hpp" +#include "Watches.hpp" #include #include @@ -395,9 +398,11 @@ class Commands { registered(app.template cppFunction( "webfront.commands.start", [owner = registry](UI ui, std::uint32_t id, const std::string& name, const std::string& arguments) { + admitWriter(ui); owner->start(std::move(ui), id, name, arguments); })); registered(app.template cppFunction("webfront.commands.cancel", [owner = registry](UI ui, std::uint32_t id) { + admitWriter(ui); owner->cancel(ui, id); })); registry->keep(app.subscribeUIClosed([weak = std::weak_ptr(registry)](UI ui) { @@ -427,6 +432,13 @@ class Commands { } private: + static void admitWriter(const UI& ui) { + if constexpr (requires { typename App::FrontendProvider; }) { + if (frontend::providesViewProof() && !ui.isLocalClient()) + throw webfront::detail::makeBridgeError(inspect::code::denied, "This command requires an admitted application view"); + } + } + std::shared_ptr> registry; }; diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 373da32d..24b02746 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -14,6 +14,9 @@ #include "system/SafePath.hpp" #include "WebFront.hpp" +#include +#include +#include #include #include @@ -80,6 +83,38 @@ inline constexpr std::tuple inspectorContainers(bool frontendO return {frontendOpensWindows && hostAdmitted, hostAdmitted, trustLoopback}; } +/// The inspector panels a detached window can show (the entries of the tab's menu, js/developer/environment/menu.mjs). +inline constexpr std::array inspectorPanels{"cpp.functions", "cpp.browsers", "cpp.watches", "typescript.packages", "typescript.bridge"}; + +/// The identifier of the page that holds the tab (the inspectors' host): 1 to 64 letters, digits, `-` or `_`. It names the +/// host in the page of a detached panel, so that the panel is attached again to the page that detached it only. +inline bool inspectorHostIdentifier(std::string_view host) noexcept { + return !host.empty() && host.size() <= 64 && std::ranges::all_of(host, [](char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_'; + }); +} + +/// Where the inspectors keep the detached panels and the floating window's place, in the project (inspector-host.mjs). +inline constexpr std::string_view inspectorPreferencesPath = ".webfront/developer/inspector-window.json"; + +/// The page of the environment that shows an inspector panel for a host page, as openSecondaryWindow() names its window: +/// one window per panel and host, so that the same host opening a panel again brings its window to the front. Throws +/// std::invalid_argument for an unknown panel or an invalid host identifier. +inline std::string inspectorPage(std::string_view panel, std::string_view host) { + if (std::ranges::find(inspectorPanels, panel) == inspectorPanels.end()) + throw std::invalid_argument("Unknown inspector panel"); + if (!inspectorHostIdentifier(host)) + throw std::invalid_argument("Invalid inspector host identifier"); + return "webfront/developer/environment/inspector.html?panel=" + std::string(panel) + "&host=" + std::string(host); +} + +/// A window size asked by the page, as a whole number of pixels within what a screen can show. +inline int inspectorWindowExtent(double value, int fallback) { + if (!std::isfinite(value) || value < 320 || value > 8192) + return fallback; + return static_cast(value); +} + /// 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) { @@ -133,21 +168,106 @@ class DeveloperAppWithNetwork : public BasicWF("webfront.developer.entries"); // For the bootstrap shipped with this C++: it republishes the environment only when a published file differs. expose<&Store::digests, Bytes, std::string>("webfront.developer.digests"); - expose<&Store::beginReplacing, std::string, std::string, bool>("webfront.developer.begin"); - expose<&Store::beginNew, std::string, std::string, bool>("webfront.developer.beginNew"); - expose<&Store::write, void, std::string, std::string, std::uint64_t, Bytes>("webfront.developer.write"); - expose<&Store::commit, void, std::string>("webfront.developer.commit"); - expose<&Store::abort, void, std::string>("webfront.developer.abort"); + exposeWrite<&Store::beginReplacing, std::string, std::string, bool>("webfront.developer.begin"); + exposeWrite<&Store::beginNew, std::string, std::string, bool>("webfront.developer.beginNew"); + exposeWrite<&Store::write, void, std::string, std::string, std::uint64_t, Bytes>("webfront.developer.write"); + exposeWrite<&Store::commit, void, std::string>("webfront.developer.commit"); + exposeWrite<&Store::abort, void, std::string>("webfront.developer.abort"); expose<&Store::stateOfLines, std::string, std::string>("webfront.developer.state"); - expose<&Store::commitGroupLines, void, std::string, std::string, std::string>("webfront.developer.commitGroup"); + exposeWrite<&Store::commitGroupLines, void, std::string, std::string, std::string>("webfront.developer.commitGroup"); +#if !(defined(WEBFRONT_DISTRIBUTION) && WEBFRONT_DISTRIBUTION) + registerInspectors(); +#endif + } + #if !(defined(WEBFRONT_DISTRIBUTION) && WEBFRONT_DISTRIBUTION) - // The inspectors exist only in the developer environment and never in a distribution build (ADR-027, section 1). + /// The inspectors exist only in the developer environment and never in a distribution build (ADR-027, section 1). Every + /// function but containers() answers only an admitted page (UI::isLocalClient, section 2). + void registerInspectors() { + using Policy = http::DefaultBuffersPolicy; + static_assert(inspect::responseBudget >= inspect::minPageBytes, + "The buffers policy is too small for the inspectors: an answer must hold a page of one node (ADR-027)"); + using Caller = typename Base::UI; + const auto registry = this->enableInspectors(); // The menu of the environment's tab asks it first: an environment that does not find it says the library is too old. - using Caller = typename Base::UI; - this->template cppFunction, Caller>("webfront.inspector.containers", [trust = this->trustsLoopbackClients()](Caller ui) { - return developer::inspectorContainers(Base::canShowSecondaryWindow(), ui.isLocalClient(), trust); + this->template reservedCppFunction, Caller>( + "webfront.inspector.containers", + [trust = this->trustsLoopbackClients()](Caller ui) { + return developer::inspectorContainers(Base::canShowSecondaryWindow(), ui.isLocalClient(), trust); + }); + // Whether the calling page may run in an embedded frontend: a tab of the system browser is offered only to a page + // that cannot (ADR-027, section 8), since window.open() in an embedded view would open a frame without the proof. + // The proof tells a proven view, not where an unproven page runs: while the active frontend gives its views the + // proof, an admitted page without it (a frame of such a view, under trustLoopbackClients) may be inside one too. + this->template reservedCppFunction("webfront.inspector.embedded", [](Caller ui) { + admit(ui); + return ui.isEmbeddedView() || frontend::providesViewProof(); }); + // The inspectors' choices, read with the token of exactly the bytes returned, then written only if the file still has + // that content: a page applies its changes to what it read, never to a content that changed and came back meanwhile. + this->template reservedCppFunction, std::string>, Caller>( + "webfront.inspector.readPreferences", + [owned = store](Caller ui) { + admit(ui); + return owned->readWithState(std::string{developer::inspectorPreferencesPath}, 64 * 1024); + }); + this->template reservedCppFunction>( + "webfront.inspector.savePreferences", + [owned = store](Caller ui, std::string expected, std::vector bytes) { + admit(ui); + owned->publishFile(std::string{developer::inspectorPreferencesPath}, std::move(bytes), expected); + }); + // The discovery of the watches (section 3): a read of the table, without calling any source. + this->template reservedCppFunction( + "webfront.inspector.watches", + [registry](Caller ui, double revision, double after, double count) { + admit(ui); + return registry->page(revision, after, count, inspect::responseBudget); + }); + // A secondary window of the panel for the host page, with the proof of the view (section 8); opening it again brings it to the front. + // The window is opened on the interface thread, where openSecondaryWindow() does not hold the server's thread. + this->template reservedCppFunction, Caller, std::string, std::string, double, double>( + "webfront.inspector.openWindow", + [this](Caller ui, std::string panel, std::string host, double width, double height) -> ResultTask { + admit(ui); + auto page = developer::inspectorPage(panel, host); + if (!Base::canShowSecondaryWindow()) + throw webfront::detail::makeBridgeError(inspect::code::unavailable, "This frontend cannot open a secondary window"); + WindowOptions options{.title = "WebFront inspector", + .width = developer::inspectorWindowExtent(width, 720), + .height = developer::inspectorWindowExtent(height, 560)}; + // Bound to the interface session that runs when the request is admitted: if that loop ends before the work + // reaches the interface thread, a loop started since is not given a window it was not asked for. + const auto bound = this->currentShowSession(); + // The continuation of then() runs on the interface thread; the task itself resumes on the server's. + co_await networking::ex::then(this->uiExecutor().schedule(), [&] { + if (!this->isCurrentShowSession(bound)) + throw webfront::detail::makeBridgeError(inspect::code::unavailable, "The interface session has ended"); + this->openSecondaryWindow(page, std::move(options)); + }); + }); + // Closes the panel's secondary window of that host, when it is attached again; false when none is open. + this->template reservedCppFunction, Caller, std::string, std::string>( + "webfront.inspector.closeWindow", + [this](Caller ui, std::string panel, std::string host) -> ResultTask { + admit(ui); + auto page = developer::inspectorPage(panel, host); + if (!Base::canShowSecondaryWindow()) + co_return false; + const auto bound = this->currentShowSession(); // as openWindow: never a window of a later session + co_return co_await networking::ex::then(this->uiExecutor().schedule(), [&] { + return this->isCurrentShowSession(bound) && this->requestClose(page); + }); + }); + } + #endif + + /// Refuses a page that is neither the proven view nor, with trustLoopbackClients, a loopback page (ADR-027, section 2). + static void admit(const typename Base::UI& ui) { + if (!ui.isLocalClient()) + throw webfront::detail::makeBridgeError(inspect::code::denied, + "The inspectors answer only a view of the application (or a loopback page with trustLoopbackClients)"); } /// Registers a store operation as a bridge callback; the store stays alive as long as the callback. @@ -158,6 +278,19 @@ class DeveloperAppWithNetwork : public BasicWF + void exposeWrite(std::string name) { + using Caller = typename Base::UI; + this->template cppFunction(std::move(name), [owned = store](Caller ui, Args... arguments) -> Result { + // The inspectors' code (ADR-027, section 2), with a message that names what was refused. + if (frontend::providesViewProof() && !ui.isLocalClient()) + throw webfront::detail::makeBridgeError(inspect::code::denied, + "Project writes require an admitted application view (or a loopback page with trustLoopbackClients)"); + return ((*owned).*Member)(std::move(arguments)...); + }); + } + std::filesystem::path project; std::shared_ptr store; }; diff --git a/include/webfront/Space.hpp b/include/webfront/Space.hpp index 86d44a5b..2f25c3bb 100644 --- a/include/webfront/Space.hpp +++ b/include/webfront/Space.hpp @@ -94,8 +94,12 @@ class BasicSpace { /// As BasicWF::cppFunction, for the pages of this space only; a function of the application of the same name is hidden /// from them. Thread-safe. @return false when the space already has a function of that name, which stays registered + /// @throws std::invalid_argument for a name starting with `webfront.inspector.`: a space can neither hide a function of + /// the inspectors from its pages nor pose as one (ADR-027, section 1) template bool cppFunction(std::string functionName, auto&& function) { + if (inspect::isReservedName(functionName)) + throw std::invalid_argument("webfront::BasicSpace::cppFunction(): names starting with 'webfront.inspector.' are reserved to WebFront"); auto handler = std::make_shared(app.template makeCppHandler(std::forward(function))); std::scoped_lock lock{state->mutex}; return state->functions.try_emplace(std::move(functionName), std::move(handler)).second; diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp new file mode 100644 index 00000000..624d171a --- /dev/null +++ b/include/webfront/Watches.hpp @@ -0,0 +1,486 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-25 +// +// WebFront — core +// Role: The registry of the watches an application declares for the inspectors (ADR-027), and its discovery page. +// Thread: thread-safe | Alloc: unrestricted +// LLM: public API (Watch, Visit) and the bounds of ADR-027 section 3; the registry is read by webfront.inspector.watches + +#pragma once + +#include "http/BuffersPolicy.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::inspect { + +// --- Bounds (ADR-027, section 3) ------------------------------------------------------------------------------- + +/// A watch's name, and the texts of a descriptor (name, location), are at most this many UTF-8 bytes. +inline constexpr std::size_t maxTextBytes = 256; +/// The kind of a node is a word of the closed vocabulary below, at most this many bytes. +inline constexpr std::size_t maxKindBytes = 16; +/// A page holds 200 entries unless the inspector asks for another count, and never more than 1 000. +inline constexpr std::size_t defaultPageCount = 200; +inline constexpr std::size_t maxPageCount = 1000; +/// The bytes of an answer that are not its entries: the message header, the call identifier and the page's own fields. +inline constexpr std::size_t responseHeaderBytes = 64; +/// The smallest answer the inspectors must be able to send: a page of one node, with its header. +inline constexpr std::size_t minPageBytes = 4096; + +/// What an answer may take with the policy: it must fit both the encoding buffer and the message size. +template +inline constexpr std::size_t responseBudget = std::min(Policy::functionCallBufferSize, http::maxMessageSize()); + +/// The error codes of the inspectors (typed codes of ADR-003): the caller is not admitted, or names a watch that is gone. +namespace code { +inline constexpr std::string_view denied = "webfront.inspector.denied"; +inline constexpr std::string_view unknown = "webfront.inspector.unknown"; +inline constexpr std::string_view unavailable = "webfront.inspector.unavailable"; +} // namespace code + +/// The prefix of the names reserved to the inspectors: cppFunction refuses them to the application (ADR-027, section 1). +inline constexpr std::string_view reservedPrefix = "webfront.inspector."; + +[[nodiscard]] inline bool isReservedName(std::string_view name) noexcept { + return name.starts_with(reservedPrefix); +} + +// --- Texts ----------------------------------------------------------------------------------------------------- + +/// The longest prefix of `text` of at most `limit` bytes that does not cut a UTF-8 character. +[[nodiscard]] inline std::string_view utf8Prefix(std::string_view text, std::size_t limit) noexcept { + if (text.size() <= limit) + return text; + std::size_t end = limit; + // Back to the first byte of the character that the limit cuts: continuation bytes are 10xxxxxx. + while (end > 0 && (static_cast(text[end]) & 0xC0u) == 0x80u) + --end; + return text.substr(0, end); +} + +namespace detail { +/// Appends `c` to `visible`, a control character as its visible picture (U+2400 to U+241F, U+2421 for DEL). +inline void appendVisible(std::string& visible, char c) { + const auto byte = static_cast(c); + if (byte < 0x20u || byte == 0x7Fu) { + const unsigned picture = byte == 0x7Fu ? 0x2421u : 0x2400u + byte; // three UTF-8 bytes: E2 90 xx + visible += static_cast(0xE2); + visible += static_cast(0x80u | ((picture >> 6) & 0x3Fu)); + visible += static_cast(0x80u | (picture & 0x3Fu)); + } else + visible += c; +} +inline constexpr std::string_view ellipsis = "\xE2\x80\xA6"; +} // namespace detail + +/// A text of the application made safe to show and bounded: control characters become their visible pictures (U+2400 +/// to U+241F, U+2421 for DEL), then the text is cut to `limit` bytes on a character boundary, ending with "…" when cut. +/// A limit too small for the ellipsis gives the longest prefix that fits, without it. +[[nodiscard]] inline std::string boundedText(std::string_view text, std::size_t limit = maxTextBytes) { + std::string visible; + visible.reserve((std::min)(text.size(), limit)); // parenthesized: Windows headers may define min + for (const char c : text) { + detail::appendVisible(visible, c); + if (visible.size() > limit) + break; // the first byte past the limit is enough to know that it is cut, whatever the limit (npos included) + } + if (visible.size() <= limit) + return visible; + if (limit < detail::ellipsis.size()) + return std::string{utf8Prefix(visible, limit)}; + std::string cut{utf8Prefix(visible, limit - detail::ellipsis.size())}; + cut += detail::ellipsis; + return cut; +} + +/// Where a watch was declared, "file:line", made visible as boundedText() does, then cut from its start when it is too long: +/// the end of the path, the file's name and the line, are what identify it. +[[nodiscard]] inline std::string locationText(std::string_view file, std::uint_least32_t line) { + std::string visible; + for (const char c : std::string(file) + ':' + std::to_string(line)) + detail::appendVisible(visible, c); + if (visible.size() <= maxTextBytes) + return visible; + std::size_t start = visible.size() - (maxTextBytes - detail::ellipsis.size()); + while (start < visible.size() && (static_cast(visible[start]) & 0xC0u) == 0x80u) + ++start; // a character is never cut: its first byte is not a continuation byte + return std::string(detail::ellipsis) + visible.substr(start); +} +[[nodiscard]] inline std::string locationText(const std::source_location& location) { + return locationText(location.file_name(), location.line()); +} + +// --- Kinds (ADR-027, section 4) -------------------------------------------------------------------------------- + +namespace detail { +template +struct is_bitset : std::false_type { }; +template +struct is_bitset> : std::true_type { }; +template +struct is_optional : std::false_type { }; +template +struct is_optional> : std::true_type { }; +template +struct is_variant : std::false_type { }; +template +struct is_variant> : std::true_type { }; +template +struct is_tuple : std::false_type { }; +template +struct is_tuple> : std::true_type { }; +template +struct is_tuple> : std::true_type { }; +template +concept associative = std::ranges::sized_range && requires { + typename T::key_type; + typename T::mapped_type; +}; +} // namespace detail + +/** + * The kind of a node of type T, in the order of ADR-027 section 4: scalars, strings and bitsets, then optional, variant and + * tuples, then sized ranges and associative containers, then a type std::format can write, else `opaque`. Enumerations and + * described types (`enum`, `described`) are recognized once a description is given to the watch. + */ +template +[[nodiscard]] constexpr std::string_view kindOf() noexcept { + using U = std::remove_cvref_t; + if constexpr (std::is_same_v) + return "bool"; + else if constexpr (std::is_integral_v) + return "integer"; + else if constexpr (std::is_floating_point_v) + return "real"; + else if constexpr (std::is_same_v || std::is_same_v) + return "string"; + else if constexpr (detail::is_bitset::value) + return "bitset"; + else if constexpr (detail::is_optional::value) + return "optional"; + else if constexpr (detail::is_variant::value) + return "variant"; + else if constexpr (detail::is_tuple::value) + return "tuple"; + else if constexpr (detail::associative) + return "map"; + else if constexpr (std::ranges::sized_range) + return "sequence"; + else if constexpr (std::formattable) + return "formatted"; + else + return "opaque"; +} + +// --- Sources (ADR-027, section 5) ------------------------------------------------------------------------------ + +/** + * @brief What a watch's visitor source receives: WebFront calls the source with a Visit, and the source calls it once with + * the object, under its own lock, so that the whole operation runs while the object is safe to read. `Visit` + * only reads; `Visit` makes the watch writable. + */ +template +class Visit { +public: + using Object = T; + + explicit Visit(std::function visitor) : run(std::move(visitor)) { } + + void operator()(T& object) const { + run(object); + } + +private: + std::function run; +}; + +namespace detail { +template +struct visit_object { }; +template +struct visit_object> { + using type = T; +}; + +template +struct single_parameter { }; +template +struct single_parameter { + using type = A; +}; +template +struct single_parameter : single_parameter { }; +template +struct single_parameter : single_parameter { }; +template +struct single_parameter : single_parameter { }; +template +struct single_parameter : single_parameter { }; +template +struct single_parameter : single_parameter { }; +// Callable on an lvalue only, as the stored source is invoked. +template +struct single_parameter : single_parameter { }; +template +struct single_parameter : single_parameter { }; +template +struct single_parameter : single_parameter { }; +template +struct single_parameter : single_parameter { }; + +template +struct call_signature { + using type = Source; // a function pointer +}; +template + requires requires { &Source::operator(); } +struct call_signature { + using type = decltype(&Source::operator()); +}; + +/// The object a visitor source visits, when Source is one: a callable whose one parameter is a Visit. +template +concept visitor_source = requires { typename visit_object::type>::type>>::type; }; +} // namespace detail + +/** + * @brief How a watch reaches its object, deduced from its source: a visitor (`[&](Visit visit) { ... visit(object); }`), + * or an accessor that returns a reference or a copy (`[&] -> const T& { return object; }`). Only a visitor of a non-constant + * object is writable: a reference read on the server thread is not, and a copy is not the object (ADR-027, section 6). + */ +template +struct SourceShape; + +template + requires detail::visitor_source +struct SourceShape { + using Object = + typename detail::visit_object::type>::type>>::type; + static constexpr bool visitor = true; + static constexpr bool writable = !std::is_const_v; +}; + +// An accessor gives an object: one that returns nothing (void) gives nothing to show, and is refused. +template + requires(!detail::visitor_source && std::invocable && !std::is_void_v>) +struct SourceShape { + using Object = std::remove_reference_t>; + static constexpr bool visitor = false; + static constexpr bool writable = false; +}; + +template +concept WatchSource = requires { typename SourceShape>::Object; }; + +// --- Registry -------------------------------------------------------------------------------------------------- + +/// A watch as webfront.inspector.watches describes it: (identifier, name, kind of the root, "file:line", writable). +using Descriptor = std::tuple; +/// A page of descriptors: (descriptors, next, revision of the registry, changed). `next` is 0 at the end. +using WatchPage = std::tuple, double, double, bool>; + +/// The largest number a page exchanges exactly with JavaScript (2^53). +inline constexpr double maxExactNumber = 9007199254740992.0; + +/** + * @brief The watches of an application (ADR-027, section 3, "Découverte"). Each registration gets an identifier that is + * never reused while the registry lives, and the registry's revision changes at each registration and each removal. + * Reading it calls no source: it is a read of the table. Thread-safe. + */ +class WatchRegistry { +public: + struct Entry { + std::string name; // as the application gave it: what makes a watch unique + std::string label; // the name as the inspectors show it: control characters visible, bounded (boundedText) + std::string kind; + std::string location; + bool writable = false; + std::shared_ptr source; // what the source captures lives as long as its registration + }; + + /// Registers a watch; throws std::invalid_argument for an empty name, a name longer than maxTextBytes, a kind longer + /// than maxKindBytes, or the name of a watch that is still registered. The location is made visible and bounded as a + /// text of the application is, so that every descriptor fits a page of the smallest budget. + std::uint64_t add(std::string name, std::string_view kind, std::string location, bool writable, std::shared_ptr source) { + checkName(name); + if (kind.empty() || kind.size() > maxKindBytes) + throw std::invalid_argument("A watch's kind is 1 to 16 bytes"); + auto label = boundedText(name); + auto shown = boundedText(location); + auto keeping = source; // declared before the lock: a source released by a failed insertion is destroyed after it + std::scoped_lock lock{mutex}; + for (const auto& [id, entry] : entries) + if (entry.name == name) + throw std::invalid_argument("A watch named '" + name + "' is already registered"); + const auto id = nextId++; + entries.emplace(id, Entry{std::move(name), std::move(label), std::string(kind), std::move(shown), writable, std::move(source)}); + ++currentRevision; + return id; + } + + /// Removes a watch; a removed or unknown identifier is ignored. The source is released outside the registry's lock. + void remove(std::uint64_t id) noexcept { + std::shared_ptr released; + { + std::scoped_lock lock{mutex}; + const auto found = entries.find(id); + if (found == entries.end()) + return; + released = std::move(found->second.source); + entries.erase(found); + ++currentRevision; + } + } + + [[nodiscard]] std::uint64_t revision() const { + std::scoped_lock lock{mutex}; + return currentRevision; + } + + [[nodiscard]] std::size_t size() const { + std::scoped_lock lock{mutex}; + return entries.size(); + } + + [[nodiscard]] bool contains(std::uint64_t id) const { + std::scoped_lock lock{mutex}; + return entries.contains(id); + } + + /** + * The page that webfront.inspector.watches(revision, after, count) answers: the live watches whose identifier is + * greater than `after`, in the order of the identifiers, at most `count` of them (0 asks only for the revision) and as + * many as fit `budget` bytes with the answer's header. `next` is the last identifier served, 0 at the end; `changed` + * tells that `revision` is no longer the registry's. Throws std::invalid_argument for a number that is not a whole + * number from 0 to 2^53, and std::length_error when the first remaining watch does not fit `budget`: an empty page + * ending with 0 would hide the rest (a budget of minPageBytes always holds one). + */ + [[nodiscard]] WatchPage page(double revision, double after, double count, std::size_t budget) const { + const auto known = wholeNumber(revision, "revision"), from = wholeNumber(after, "cursor"); + const auto wanted = std::min(wholeNumber(count, "count"), maxPageCount); + const auto room = budget > responseHeaderBytes ? budget - responseHeaderBytes : 0; + std::scoped_lock lock{mutex}; + std::vector served; + std::size_t used = 0; + std::uint64_t last = 0; + bool more = false; + for (auto entry = entries.upper_bound(from); entry != entries.end(); ++entry) { + const auto bytes = encodedSize(entry->second); + if (served.size() == wanted || used + bytes > room) { + if (served.empty() && wanted != 0) + throw std::length_error("The inspector's page budget cannot hold one watch descriptor"); + more = true; + break; + } + used += bytes; + last = entry->first; + served.emplace_back(static_cast(entry->first), entry->second.label, entry->second.kind, entry->second.location, entry->second.writable); + } + const bool changed = known != currentRevision; + return {std::move(served), more && wanted != 0 ? static_cast(last) : 0.0, static_cast(currentRevision), changed}; + } + + /// The largest number of bytes a descriptor takes encoded: the bound that makes a page of one always fit minPageBytes. + static constexpr std::size_t maxDescriptorBytes = 2 + 9 + (3 + maxTextBytes) + (3 + maxKindBytes) + (3 + maxTextBytes) + 1; + static_assert(maxDescriptorBytes + responseHeaderBytes <= minPageBytes); + + static void checkName(std::string_view name) { + if (name.empty() || name.size() > maxTextBytes) + throw std::invalid_argument("A watch's name is 1 to 256 bytes"); + } + +private: + /// An upper bound of the encoded size of a descriptor: a tuple header, a number, three strings with the longest string + /// header and a boolean. + static std::size_t encodedSize(const Entry& entry) noexcept { + return 2 + 9 + (3 + entry.label.size()) + (3 + entry.kind.size()) + (3 + entry.location.size()) + 1; + } + + static std::uint64_t wholeNumber(double value, std::string_view what) { + if (!std::isfinite(value) || value < 0 || value > maxExactNumber || std::trunc(value) != value) + throw std::invalid_argument("The watches' " + std::string(what) + " must be a whole number from 0 to 2^53"); + return static_cast(value); + } + + mutable std::mutex mutex; + std::map entries; + std::uint64_t nextId = 1; + std::uint64_t currentRevision = 1; // never 0: an inspector that starts with 0 sees a change +}; + +/** + * @brief The handle of a watch, as UISubscription is the handle of a subscription: the watch exists while it lives, and + * the handle stays safe after the application is destroyed. An empty handle registered nothing: outside the developer + * environment, and in a distribution build, `app.watch` returns one (ADR-027, section 1). Move-only. + */ +class Watch { +public: + Watch() = default; + Watch(std::weak_ptr owner, std::uint64_t identifier) : registry(std::move(owner)), watchId(identifier) { } + Watch(const Watch&) = delete; + Watch& operator=(const Watch&) = delete; + Watch(Watch&& other) noexcept : registry(std::move(other.registry)), watchId(std::exchange(other.watchId, 0)) { } + Watch& operator=(Watch&& other) noexcept { + // A handle being destroyed takes no new watch: it could not remove it. The source of the assignment keeps it. + if (this != &other && !destroying) { + // The previous watch is removed once this handle holds the new one: its source, released then, may assign + // this handle again, and that assignment is the one kept. + Watch previous{std::move(*this)}; + registry = std::move(other.registry); + watchId = std::exchange(other.watchId, 0); + } + return *this; + } + ~Watch() { + destroying = true; // a source released by reset() may assign this handle: the assignment is refused + reset(); + } + + /// Removes the watch now; the handle becomes empty. The handle is emptied before the removal and not touched after it: + /// the source, released by the removal, may assign this handle to a new watch, which stays registered. + void reset() noexcept { + const auto id = std::exchange(watchId, 0); + const auto owner = std::exchange(registry, {}).lock(); + if (id != 0 && owner) + owner->remove(id); + } + + /// The identifier the inspectors know the watch by, 0 for an empty handle. + [[nodiscard]] std::uint64_t id() const noexcept { + return watchId; + } + + explicit operator bool() const noexcept { + return watchId != 0; + } + +private: + std::weak_ptr registry; + std::uint64_t watchId = 0; + bool destroying = false; +}; + +} // namespace webfront::inspect diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 2ea0b59b..daa955ce 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -26,6 +26,7 @@ #include "Task.hpp" #include "UISubscribers.hpp" #include "ViewAssociation.hpp" +#include "Watches.hpp" #include "weblink/DomBatch.hpp" #include "weblink/Messages.hpp" #include "weblink/WebLink.hpp" @@ -41,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -1055,6 +1057,17 @@ class BasicWF { friend struct testing::ConnectionIds; // lets a test start the identifiers near their wrap template friend struct testing::LaunchSecret; // lets a test present the secret an embedded view would + template + friend class DeveloperAppWithNetwork; // installs the inspectors' reserved functions (reservedCppFunction) + + /// Registers one of WebFront's own reserved functions (`webfront.inspector.*`), which cppFunction refuses to the + /// application. Only the developer environment calls it, and a name already taken is an error, never ignored: the + /// inspectors' callbacks are WebFront's or none (ADR-027, section 1). + template + void reservedCppFunction(std::string functionName, auto&& function) { + if (!registerCppFunction(functionName, std::forward(function))) + throw std::logic_error("webfront: the reserved function " + functionName + " is already registered"); + } /// Sends `call` to each browser not reported closed whose onUIStarted handlers have returned: at once, on the /// calling thread and outside every lock. For a browser whose handlers are running, `call` is kept, within its @@ -1204,10 +1217,12 @@ class BasicWF { * @param functionName * @param function * @return false when a function of that name was already registered, which stays registered + * @throws std::invalid_argument for a name starting with `webfront.inspector.`, reserved to WebFront (ADR-027) */ template bool cppFunction(std::string functionName, auto&& function) { - return cppFunctions.try_emplace(std::move(functionName), makeCppHandler(std::forward(function))).second; + refuseReservedName(functionName); + return registerCppFunction(std::move(functionName), std::forward(function)); } /** @@ -1222,6 +1237,7 @@ class BasicWF { * @param functionName * @param function * @return false when a function of that name was already registered, which stays registered + * @throws std::invalid_argument for a name starting with `webfront.inspector.`, reserved to WebFront (ADR-027) */ template bool cppFunction(std::string functionName, Function&& function) { @@ -1235,6 +1251,51 @@ class BasicWF { return detail::ApplyArgs::invoke(*this, std::move(functionName), std::forward(function)); } + /** + * @brief Declares a watch: an object or a container of the application that the inspectors of the developer environment + * show (ADR-027, section 5). The watch exists while the returned handle lives. + * + * `source` reaches the object. A visitor, `[&](webfront::inspect::Visit visit) { std::scoped_lock lock{m}; visit(object); }`, + * is called by WebFront and calls the visit once with the object under its own lock: it is the form of an object shared + * between threads, and `Visit` makes the watch writable. An accessor, `[&] -> const T& { return object; }`, returns a + * reference, read on the server thread only (correct only for an object that thread alone touches), or a copy. + * + * Outside the developer environment (`bootstrap("developer")`), and in a distribution build, nothing is registered and + * the handle is empty: declare the watches after bootstrap(). Inside, a watch costs an entry in a table until an + * inspector reads it. Callable from any thread. + * + * @throws std::invalid_argument for an empty name, a name longer than 256 bytes, or the name of a live watch + */ + template + [[nodiscard]] inspect::Watch watch(std::string name, Source&& source, std::source_location location = std::source_location::current()) { + using Stored = std::decay_t; // a function given by name is kept as a pointer + using Shape = inspect::SourceShape; + inspect::WatchRegistry::checkName(name); + const auto registry = inspectorRegistry(); + if (!registry) + return {}; + auto owned = std::make_shared(std::forward(source)); + const auto id = registry->add(std::move(name), + inspect::kindOf(), + inspect::locationText(location), + Shape::writable, + std::static_pointer_cast(std::move(owned))); + return inspect::Watch{registry, id}; + } + +private: + /// The names of the inspectors belong to WebFront: an application can neither hide one nor pose as one (ADR-027, section 1). + static void refuseReservedName(std::string_view functionName) { + if (inspect::isReservedName(functionName)) + throw std::invalid_argument("webfront::BasicWF::cppFunction(): names starting with 'webfront.inspector.' are reserved to WebFront"); + } + + template + bool registerCppFunction(std::string functionName, auto&& function) { + return cppFunctions.try_emplace(std::move(functionName), makeCppHandler(std::forward(function))).second; + } + +public: enum class WindowAction { none, closeWindow }; #ifdef _MSC_VER // A Frontend::open() that unconditionally throws (e.g. CEFFrontend::open() when CEF support @@ -1567,6 +1628,12 @@ class BasicWF { windowOptions.background = "#141821"; } + /// The table of the watches, null until the developer bootstrap enabled it. + [[nodiscard]] std::shared_ptr inspectorRegistry() const { + std::scoped_lock lock{watchRegistryMutex}; + return watchRegistry; + } + /// Whether the application chose WebFrontConfig::trustLoopbackClients: a new connection that is not proven would then /// be a local client when its peer is the loopback (the inspectors' containers, ADR-027 section 8). [[nodiscard]] bool trustsLoopbackClients() const noexcept { @@ -1574,6 +1641,43 @@ class BasicWF { } private: + /// The run of show() that owns the interface: its epoch and the interface loop's session, empty when none runs. Read when a + /// request is admitted (DeveloperAppWithNetwork, a friend), then checked on the interface thread with isCurrentShowSession(): + /// a request admitted for one run never opens or closes a window of the next one. + struct ShowSession { + std::uint64_t epoch{}; + std::optional session; + }; + [[nodiscard]] ShowSession currentShowSession() const { + if constexpr (supportsSecondaryWindow) { + const auto epoch = showEpoch.load(); + if (epoch % 2 == 0) + return {}; + auto session = Frontend::uiExecutor().session(); + if (!session || session->thread != showThread.load() || showEpoch.load() != epoch) + return {}; + return {epoch, std::move(session)}; + } else { + return {}; + } + } + [[nodiscard]] bool isCurrentShowSession(const ShowSession& bound) const { + if (!bound.session) + return false; + const auto now = currentShowSession(); + return now.epoch == bound.epoch && now.session == bound.session; + } + + /// For the developer environment's bootstrap only (DeveloperAppWithNetwork, a friend): from now on, watch() registers in + /// the table that the inspectors read (ADR-027). Returns that table. Private, so that no other subclass gives watch() a + /// table without the bootstrap or in a distribution build, where the handle must stay empty (section 1). + std::shared_ptr enableInspectors() { + std::scoped_lock lock{watchRegistryMutex}; + if (!watchRegistry) + watchRegistry = std::make_shared(); + return watchRegistry; + } + // The constructor has already bound and listened; this thread services the queued I/O. // Launch server only once or restart if previous thread ended void startServerThread() { @@ -1872,24 +1976,26 @@ class BasicWF { } // Before the server: the routes' handlers use it, and the server drains them before it is destroyed. - std::shared_ptr readBinding; - http::Server httpServer; - http::RouteTable::Registration bindRoute; - std::string httpAddress; - std::string httpPort; - std::filesystem::path httpDocRoot; - ContentPolicy contentPolicy; - WindowOptions windowOptions; - const std::string viewSecret = detail::newViewSecret(); // this launch's proof of an embedded view - const bool trustLoopbackClients; - const bool ptyPagesAllowed; - bool developerEnvironment = false; - std::atomic launched{false}; // start() was called - std::atomic showThread{}; // the thread inside this application's Frontend::open(), if any - std::atomic showEpoch{0}; // odd while show() runs its frontend, changes at each entry and exit - std::atomic showRunning{false}; // a show() of this application is in progress - std::atomic shown{false}; // show() was called, whether or not its server still runs - mutable std::mutex linksMutex; // guards webLinks, read from any thread + std::shared_ptr readBinding; + http::Server httpServer; + http::RouteTable::Registration bindRoute; + std::string httpAddress; + std::string httpPort; + std::filesystem::path httpDocRoot; + ContentPolicy contentPolicy; + WindowOptions windowOptions; + const std::string viewSecret = detail::newViewSecret(); // this launch's proof of an embedded view + const bool trustLoopbackClients; + const bool ptyPagesAllowed; + bool developerEnvironment = false; + mutable std::mutex watchRegistryMutex; + std::shared_ptr watchRegistry; // set once by enableInspectors(), read by watch() from any thread + std::atomic launched{false}; // start() was called + std::atomic showThread{}; // the thread inside this application's Frontend::open(), if any + std::atomic showEpoch{0}; // odd while show() runs its frontend, changes at each entry and exit + std::atomic showRunning{false}; // a show() of this application is in progress + std::atomic shown{false}; // show() was called, whether or not its server still runs + mutable std::mutex linksMutex; // guards webLinks, read from any thread struct Connection { std::shared_ptr> link; WebLinkGeneration generation; diff --git a/include/webfront/frontend/EmbeddedFrontend.hpp b/include/webfront/frontend/EmbeddedFrontend.hpp index 52fa4ea3..61119350 100644 --- a/include/webfront/frontend/EmbeddedFrontend.hpp +++ b/include/webfront/frontend/EmbeddedFrontend.hpp @@ -103,6 +103,9 @@ struct ViewOptions { template struct EmbeddedFrontend { static constexpr Action action{Action::closeServerAfterOpen}; + static constexpr bool providesViewProof() noexcept { + return true; + } /// The interface thread while open() runs the toolkit's loop (see UIExecutor.hpp). [[nodiscard]] static UIExecutor uiExecutor() { diff --git a/include/webfront/frontend/Frontend.hpp b/include/webfront/frontend/Frontend.hpp index 4a9053d0..39eeba47 100644 --- a/include/webfront/frontend/Frontend.hpp +++ b/include/webfront/frontend/Frontend.hpp @@ -59,6 +59,7 @@ namespace webfront::frontend { * An optional open(address, port, file, policy, window) overload also receives the application's WindowOptions. * An optional static UIExecutor uiExecutor() publishes the interface thread (UIExecutor.hpp): it is available while * open() runs the frontend's loop, and BasicWF::uiExecutor() forwards it. + * An optional static bool providesViewProof() reports whether the active frontend gives the launch proof to its view. * An optional static bool closeServerAfterOpen() overrides `action` at run time (NativeOrBrowserFrontend). * An optional static void launch(address, port, file) opens the interface and returns without waiting for it: BasicWF::start() * needs it, and a frontend whose window lives in open()'s loop does not offer it. A launch(address, port, file, policy) @@ -84,6 +85,31 @@ concept FrontendType = requires(std::string_view port, std::string_view file) { { Frontend::open(port, file) } -> std::same_as; } && std::same_as, Action>; +namespace detail { +/// A frontend whose open() receives the ViewLaunch proof, which it may give to its view. +template +concept receivesViewLaunch = requires(std::string_view text, const ContentPolicy& policy, const WindowOptions& window, const ViewLaunch& launch) { + Frontend::open(text, text, text, policy, window, launch); +}; +} // namespace detail + +/// Whether the active frontend gives the application window the bridge's launch proof. A frontend whose open() receives +/// ViewLaunch must say it (true when it gives the proof to its view, false when it does not, as the system browser): +/// left undeclared, a view that holds the proof would not be guarded (ADR-027, section 2). Any other is taken as false. +template +[[nodiscard]] bool providesViewProof() { + if constexpr (requires { + { Frontend::providesViewProof() } -> std::same_as; + }) + return Frontend::providesViewProof(); + else { + static_assert(!detail::receivesViewLaunch, + "A frontend whose open() receives ViewLaunch declares static bool providesViewProof(): true when its view " + "gets the proof, false otherwise (ADR-027, section 2; docs/FRONTENDS.md)"); + return false; + } +} + // `action` describes what BasicWF should do after `open()` returns. // Keep the server running when `open()` only launches the UI, and ask BasicWF to // stop it when `open()` returns after the UI session is finished. @@ -91,6 +117,11 @@ struct DefaultBrowserFrontend { static constexpr Action action{Action::keepServerRunning}; static constexpr bool requiresMainThread = false; + /// The system browser never gets the proof (ADR-020), although its open() receives ViewLaunch for the origin. + static constexpr bool providesViewProof() noexcept { + return false; + } + static void initialize() { } /// Opens the page in the system browser and returns at once, without the console wait of open() and without waiting @@ -139,6 +170,10 @@ struct DefaultBrowserFrontend { */ struct BrowserWithUILoopFrontend { static constexpr Action action{Action::keepServerRunning}; + /// The system browser never gets the proof (ADR-020). + static constexpr bool providesViewProof() noexcept { + return false; + } // AppKit's run loop belongs to the main thread; the Windows message pump and the GLib loop run where open() is called. #if defined(__APPLE__) static constexpr bool requiresMainThread = true; @@ -303,6 +338,9 @@ struct NativeOrBrowserFrontendFor { [[nodiscard]] static bool usesNativeWindow() { return state().native.load(); } + [[nodiscard]] static bool providesViewProof() { + return usesNativeWindow() ? frontend::providesViewProof() : frontend::providesViewProof(); + } /// Whether the server stops once open() returns: true for a native window, false for the browser. [[nodiscard]] static bool closeServerAfterOpen() { if constexpr (Native::action == Action::closeServerAfterOpen) diff --git a/include/webfront/system/DeveloperJournal.hpp b/include/webfront/system/DeveloperJournal.hpp index 12218acf..9922ddb7 100644 --- a/include/webfront/system/DeveloperJournal.hpp +++ b/include/webfront/system/DeveloperJournal.hpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -195,6 +196,27 @@ inline std::optional> parseJournal(const std::string& return entries; } +/// The fingerprint() of one file from its content as read: absent (nullopt) or these bytes. A token computed from the bytes a +/// caller got describes exactly them, even if the file changed and came back meanwhile. +inline std::string fingerprintOfContent(const std::optional>& content) { + std::uint64_t hash = 14695981039346656037ULL; + const auto feed = [&hash](const void* data, std::size_t size) { + const auto* bytes = static_cast(data); + for (std::size_t i = 0; i < size; ++i) + hash = (hash ^ bytes[i]) * 1099511628211ULL; + }; + const char present = content ? 1 : 0; + feed(&present, 1); + if (content) { + const auto size = static_cast(content->size()); + feed(&size, sizeof size); + feed(content->data(), content->size()); + } + char text[17]; + std::snprintf(text, sizeof text, "%016llx", static_cast(hash)); + return text; +} + /// Identifies the content of project files: a precondition for publications that were prepared /// from an earlier reading of the project. Not a security measure. inline std::string fingerprint(const std::filesystem::path& root, const std::vector& paths) { diff --git a/include/webfront/system/DeveloperStore.hpp b/include/webfront/system/DeveloperStore.hpp index 88913c9c..199b9341 100644 --- a/include/webfront/system/DeveloperStore.hpp +++ b/include/webfront/system/DeveloperStore.hpp @@ -15,6 +15,7 @@ #include "DeveloperJournal.hpp" #include +#include #include #include #include @@ -32,6 +33,7 @@ #include #include #include +#include #include #include @@ -189,6 +191,33 @@ class Store { return fingerprint(root, paths); } + /// A small project file and the state() of its path, read under one lock: (present, bytes, token). The token is computed + /// from the bytes returned, so that a publication conditioned on it applies only to the content these bytes came from. + /// An absent file gives (false, {}, the token of its absence). Throws when the file exists but cannot be read, or is + /// larger than `limit` bytes. + std::tuple, std::string> readWithState(const std::string& path, std::size_t limit) { + std::scoped_lock lock(mutex); + recover(); + const auto file = projectPath(root, path); + std::error_code error; + if (!std::filesystem::is_regular_file(file, error)) + return {false, {}, fingerprintOfContent(std::nullopt)}; + std::ifstream stream(file, std::ios::binary); + if (!stream) + throw std::runtime_error("Cannot read project file: " + path); + std::vector bytes; + std::array block{}; + while (stream.read(block.data(), static_cast(block.size())) || stream.gcount() > 0) { + bytes.insert(bytes.end(), block.begin(), block.begin() + stream.gcount()); + if (bytes.size() > limit) + throw std::length_error("Project file is too large: " + path); + } + if (stream.bad()) + throw std::runtime_error("Cannot read project file: " + path); + auto token = fingerprintOfContent(std::span(bytes)); + return {true, std::move(bytes), std::move(token)}; + } + /// Why a committed publication could not be completed, if it still cannot. std::optional recoveryFailure() const { std::scoped_lock lock(mutex); @@ -254,6 +283,23 @@ class Store { commitGroup(lines(ids), lines(paths), expected); } + /// A conditional publication of one small file, completed or aborted within one server call. + void publishFile(std::string destination, std::vector bytes, const std::string& expected) { + const auto id = beginReplacing(destination, false); + try { + write(id, "output", 0, std::move(bytes)); + commitGroup({id}, {destination}, expected); + } catch (...) { + std::scoped_lock lock(mutex); + if (const auto found = transactions.find(id); found != transactions.end()) { + std::error_code ignored; + std::filesystem::remove_all(found->second.staging, ignored); + transactions.erase(found); + } + throw; + } + } + void abort(std::string id) { std::scoped_lock lock(mutex); const auto found = transactions.find(id); diff --git a/include/webfront/weblink/Messages.hpp b/include/webfront/weblink/Messages.hpp index 5d47cddb..3ff55a58 100644 --- a/include/webfront/weblink/Messages.hpp +++ b/include/webfront/weblink/Messages.hpp @@ -829,9 +829,9 @@ class FunctionCallBase : public MessageBase { const std::size_t header = type == CodedType::string ? 3 : 5; need(header); if (type == CodedType::string) { - std::uint16_t small; - std::memcpy(&small, data.data() + 1, sizeof(small)); - size = small; + std::uint16_t shortSize; + std::memcpy(&shortSize, data.data() + 1, sizeof(shortSize)); + size = shortSize; } else std::memcpy(&size, data.data() + 1, sizeof(size)); need(header); @@ -841,10 +841,10 @@ class FunctionCallBase : public MessageBase { return header + size; } if (isNumericArrayCode(type)) { - const bool small = type == CodedType::smallArrayU8; - const std::size_t header = small ? 2 : 5; + const bool compact = type == CodedType::smallArrayU8; + const std::size_t header = compact ? 2 : 5; need(header); - if (small) + if (compact) size = static_cast(data[1]); else std::memcpy(&size, data.data() + 1, sizeof(size)); @@ -852,7 +852,7 @@ class FunctionCallBase : public MessageBase { if (data.size() - header < bytes) throw std::runtime_error("Truncated list element"); shape += 'a'; - shape += std::to_string(static_cast(small ? CodedType::arrayU8 : type)); + shape += std::to_string(static_cast(compact ? CodedType::arrayU8 : type)); return header + bytes; } if (type == CodedType::tuple) { diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 5a7329ce..d7588dd6 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -17,13 +17,16 @@ "js/developer/environment/packages.mjs": "37fe2a410e211264cfeaedbff3df50f7e62b02f8088130127d94f92081e2a5ad", "js/developer/environment/starter.mjs": "fd43db1861121577c48a0327436ce39cb9076d7cad0e9e273d40955747cc6a48", "js/developer/environment/paths.mjs": "3b6114df78eb193161c5c84499dda084cb7ff91c56a4496371c30295d00880e3", - "js/developer/environment/runtime.mjs": "7b609a56975809c1f07850f78500d14d447ca12cfa3a6f0ab3718f5cdaef0e1a", + "js/developer/environment/runtime.mjs": "e4b4667149d0afbccd5d9316228939a8f14979c52969cbc8f955b338ad9b88b9", "js/developer/environment/automation.mjs": "79405c89ba7025c1774bc13c9b78d814a07592755dcde018c8659a8015c4b8ed", "js/developer/environment/development.mjs": "1f32f911610c72ad3e935de1c2b138fa275ce9eda04bb63c824d5e09923305a6", "js/developer/environment/testing.mjs": "aeb584505fab5957b9c02e78536e12f7d7f3d12f8adb2e17f1a1a6e395e43f3c", - "js/developer/environment/terminal.mjs": "1d81a28a6e6cfd5bdb1ff8854e17a273b7bcfebf2c97d469b8706db636f3799e", - "js/developer/environment/workspace.mjs": "5af5ea2a9a27c403d60fe54c268ae07741cae8a89da2cc148e4f64114f2b71d7", - "js/developer/environment/menu.mjs": "9399a5d6a4c28cbf775713ae87e59de905a109d67034024abe03b81a5af9eeb4", + "js/developer/environment/terminal.mjs": "e7c3ca8f9833f10e07939277996eb01fb989c986420c96052271ff469fa59062", + "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", + "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", + "js/developer/environment/inspector-host.mjs": "bffcef61b8a5778f53adfea5096c5d5fa277868bbaa39e60142a3493210076fb", + "js/developer/environment/inspector.mjs": "b30d3cf9b0512ba5805a4b873fc11a9399813e88f728c4778116bb5b2ac3475a", + "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", "js/developer/environment/files.mjs": "199336f7f3d23f6370da352993bf4686738b1f394b79aa9883769d19824540e0", @@ -49,8 +52,8 @@ "js/developer/tools/distribution.json": "06c5e81e5fbbe3407488840646fb8dd1b36b540fca43dd85dcd5d7342261a36a", "js/developer/tools/archive.mjs": "da63bb9d796ddfd24ed945b15c53f66a0400eb177886fd4f1c8fd10cafb5a91b", "js/developer/tools/distribution.mjs": "43dfdccc912693db46fd095fd78ae79325abab672d99f89fd569914ef3499cad", - "js/developer/scripts/build.mjs": "a577f4396ab867096bc6fe6876e16e5220121ec8e8dd234fa1e4819d0a1173e1", - "js/developer/webfront.project.json": "0fdbffbec76da90b1e3169debb1e61389986f72141cadfa2420b75be39262e51", + "js/developer/scripts/build.mjs": "a6b64a8a75c9a30118e7f5c843a0feee89ee1372ccd19b7e468c816b23fd1367", + "js/developer/webfront.project.json": "3f4966abb1b3de480ba23f1470835c727f9f2e6507299d5ef522f5c6ba009813", "js/core/bootstrap/bootstrap.bundle.mjs": "18a0567efa928fddbaa3f8d16a4d1e8440f21709ff2e3058d10ba406b2e9b66d", "js/developer/environment/packages.bundle.mjs": "5598a590a9e859a4128075387a6c32963b2246ca120c2d7775851c780ad437f2", "include/webfront/system/DeveloperReleaseData.hpp": "8b3c8800211c13b1984e794de6110d56238e9fb1cfb16afbc2868d57eb91c70e" diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs new file mode 100644 index 00000000..ca8c7ced --- /dev/null +++ b/js/developer/environment/inspector-host.mjs @@ -0,0 +1,566 @@ +// The host of the inspectors (#680, ADR-027 section 8): opens the page inspector.html of the environment in the container that +// gives it access to C++. One page serves every container: a native secondary window (its own proven connection), a tab of +// the system browser (its own connection, admitted only by trustLoopbackClients), or a floating window of this page whose +// frame opens no connection and borrows this page's bridge. Each panel can be detached and attached again; the choice and +// the floating window's place are kept in the project, as the terminal's place is. +import {readProject, call} from './io.mjs'; +import {clampRect, step, minimumSize, windowControls} from './workspace.mjs'; +import {inspectorPanels as panels, panelTitle, inspectorChannel} from './menu.mjs'; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +export {panels, panelTitle}; + +// --- Containers ------------------------------------------------------------------------------------------------ + +/** + * Where a detached panel can go, from what webfront.inspector.containers() allowed (`containers`, null when nothing reaches + * the inspectors) and whether this page is the view of an embedded frontend (`embedded`): a native secondary window when the + * frontend opens one for this admitted page; else a tab of the system browser when new loopback connections are admitted + * and this page is not an embedded view, where window.open() would open a frame without the proof; else null (ADR-027, + * section 8). + */ +export function detachedContainer(containers, {embedded = true} = {}) { + if (!containers?.host) return null; + if (containers.secondaryWindow) return 'window'; + if (containers.newConnections && !embedded) return 'tab'; + return null; +} + +export const hostReasons = { + noDetached: 'No detached window can reach the inspectors from this page: this frontend opens no secondary window, ' + + 'and a tab of the system browser would be refused (it needs the system browser and WebFrontConfig::trustLoopbackClients).', + blocked: 'The browser blocked the inspector\'s tab: allow pop-ups for this page, then try again.', + windowFailed: 'The inspector\'s window could not open', +}; + +/** + * The container a panel opens in: its detached container when the project remembers it detached and one is available, else + * the floating window of this page. Null when nothing reaches the inspectors. + */ +export function containerFor(panel, {containers, embedded, detached}) { + if (!containers?.host) return null; + const away = detachedContainer(containers, {embedded}); + return detached.has(panel) && away ? away : 'floating'; +} + +// --- Remembered choices ---------------------------------------------------------------------------------------- + +/** The panels kept detached and the floating window's place, kept in the project like the terminal's place. */ +export const preferencesPath = '.webfront/developer/inspector-window.json'; + +/** The choices of a file's text: {detached: Set of panel ids, rect or null}; empty ones when it is not one. */ +export function parsePreferences(text) { + const empty = {detached: new Set(), rect: null}; + try { + const {format, detached = [], rect = null} = JSON.parse(text); + if (format !== 1 || !Array.isArray(detached)) return empty; + const valid = rect && ['x', 'y', 'width', 'height'].every(key => Number.isFinite(rect[key]) && Math.abs(rect[key]) < 1e6) + && rect.width > 0 && rect.height > 0; + return {detached: new Set(detached.filter(id => panels.has(id))), + rect: valid ? {x: rect.x, y: rect.y, width: rect.width, height: rect.height} : null}; + } catch { return empty; } +} + +export const formatPreferences = ({detached, rect}) => + JSON.stringify({format: 1, detached: [...detached].sort(), rect: rect ?? null}) + '\n'; + +/** + * Whether a project file is absent, rather than present but unreadable: the directory that holds it, listed, does not name + * it, or is itself absent. A failure to list a directory that exists is thrown. + */ +async function projectFileMissing(bridge, path) { + const slash = path.lastIndexOf('/'); + const directory = slash < 0 ? '' : path.slice(0, slash), name = path.slice(slash + 1); + try { + const names = JSON.parse(decoder.decode(await call(bridge, 'list', directory))); + return !names.includes(name) && !names.includes(`${name}/`); + } catch (error) { + if (directory && await projectFileMissing(bridge, directory)) return true; + throw error; + } +} + +const readPreferencesFunction = 'webfront.inspector.readPreferences'; +const missingFunction = error => error?.code === 'webfront.notFound' || /C\+\+ function '[^']*' was not found/.test(String(error?.message)); + +/** + * The choices the project has, with the token that a save from them is conditioned on: {preferences, token}. Empty choices + * without a file; a file that exists but cannot be read throws. The library reads the file and its token under one lock, the + * token being that of the bytes read: a content that changed and came back meanwhile does not take a save of choices read + * from another one. A library without webfront.inspector.readPreferences gives the token, then the file. + */ +async function readStoredPreferences(bridge) { + try { + const [present, bytes, token] = await bridge.cppFunction(readPreferencesFunction)(); + return {preferences: parsePreferences(present ? decoder.decode(bytes) : ''), token}; + } catch (error) { + if (!missingFunction(error)) throw error; + } + const token = await call(bridge, 'state', preferencesPath); + let bytes; + try { bytes = await readProject(bridge, preferencesPath); } + catch (error) { + if (await projectFileMissing(bridge, preferencesPath).catch(() => false)) return {preferences: parsePreferences(''), token}; + throw error; + } + return {preferences: parsePreferences(decoder.decode(bytes)), token}; +} + +/** The choices to show: empty ones when they cannot be read, which never prevents the inspectors from opening. */ +export async function readPreferences(bridge) { + try { return (await readStoredPreferences(bridge)).preferences; } + catch { return parsePreferences(''); } +} + +/** The choices after `changes` ({panels: Map of panel id to detached, rect: undefined when unchanged}) apply to `current`. */ +export function applyPreferenceChanges(current, {panels, rect}) { + const detached = new Set(current.detached); + for (const [id, away] of panels) if (away) detached.add(id); else detached.delete(id); + return {detached, rect: rect === undefined ? current.rect : rect}; +} + +// Another page writing the choices, or having changed them since they were read: the change is tried again shortly after. +const preferenceConflict = /changed since it was read|already being written/; + +/** + * Applies `changes` to the choices as the project has them now, committed only if the file did not change meanwhile. A file + * that cannot be read fails the write: committing this page's changes alone would erase the choices of the other pages. + */ +async function writePreferenceChanges(bridge, changes) { + for (let attempt = 1; ; ++attempt) { + try { + const {preferences, token} = await readStoredPreferences(bridge); + const text = formatPreferences(applyPreferenceChanges(preferences, changes)); + await bridge.cppFunction('webfront.inspector.savePreferences')(token, encoder.encode(text)); + return; + } catch (error) { + if (attempt === 20 || !preferenceConflict.test(error?.message)) throw error; + await new Promise(resolve => setTimeout(resolve, 10 + Math.random() * 40)); + } + } +} + +/** + * Writes the choices of this page as changes to those of the project, so that the pages of a project do not undo each + * other's: whether a panel is detached is written at once, the window's place shortly after it stops moving. Each write + * reads the file again and applies only what this page changed, and is committed only if the file did not change since + * it was read (else it is tried again). `saved()` writes what is pending and resolves once it is written; a failed write + * keeps the inspector usable, and its changes are written with the next one, after any newer change of the same panel or + * place, which wins. + */ +export function preferencesStore(bridge, delay = 300) { + let timer = null, pending = {panels: new Map(), rect: undefined}, writes = Promise.resolve(); + const flush = () => { + clearTimeout(timer); + timer = null; + if (!pending.panels.size && pending.rect === undefined) return writes; + const changes = pending; + pending = {panels: new Map(), rect: undefined}; + writes = writes.catch(() => {}).then(() => writePreferenceChanges(bridge, changes)).catch(error => { + // Not written: kept for the next write, under the changes made since, which are newer. + for (const [id, away] of changes.panels) if (!pending.panels.has(id)) pending.panels.set(id, away); + if (pending.rect === undefined) pending.rect = changes.rect; + throw error; + }); + return writes; + }; + return { + /** Starts saving the new detached state immediately. */ + detached(id, away) { + pending.panels.set(id, away); + flush().catch(() => {}); + }, + /** Remembers the floating window's place once it stops changing. */ + place(rect) { + pending.rect = rect; + clearTimeout(timer); + timer = setTimeout(() => flush().catch(() => {}), delay); + }, + saved: () => flush(), + }; +} + +/** Where the floating window opens without a remembered place: on the left of the terminal's default place. */ +export function defaultInspectorRect(viewport) { + const width = Math.min(560, viewport.width - 2 * step), height = Math.min(480, viewport.height - 2 * step); + return clampRect({x: step, y: step, width, height}, viewport); +} + +const styles = ` +.webfront-inspector-window{position:fixed;z-index:2147483645;display:flex;flex-direction:column;box-sizing:border-box;background:#141821;border:1px solid #46536a;border-radius:8px;box-shadow:0 8px 32px #000a;resize:both;overflow:hidden;max-width:100vw;max-height:100vh;min-width:min(${minimumSize.width}px,100vw);min-height:min(${minimumSize.height}px,100vh)} +.webfront-inspector-window[hidden]{display:none} +.webfront-inspector-bar{display:flex;flex:none;align-items:center;gap:4px;padding:0 4px 0 12px;background:#202737;color:#e8edf4;font:13px system-ui;cursor:move;user-select:none;touch-action:none} +.webfront-inspector-bar>span{flex:1 1 auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.webfront-inspector-bar:focus-visible,.webfront-inspector-bar button:focus-visible{outline:2px solid #d7fa85;outline-offset:-2px} +.webfront-inspector-bar button{margin:0;min-width:32px;height:32px;padding:0 8px;border:0;border-radius:4px;background:none;color:inherit;font:13px system-ui;cursor:pointer} +.webfront-inspector-bar button:hover:not([aria-disabled=true]){background:#2f3a50} +.webfront-inspector-bar button[aria-disabled=true]{color:#8d97aa;cursor:default} +.webfront-inspector-close{font-size:20px!important;line-height:1} +.webfront-inspector-notice{display:flex;gap:8px;align-items:center;padding:6px 12px;background:#3a2f12;color:#f4e3b5;font:12px system-ui} +.webfront-inspector-notice[hidden]{display:none} +.webfront-inspector-notice button{margin:0 0 0 auto;padding:4px 8px;border:1px solid #f4e3b5;border-radius:4px;background:none;color:inherit;font:inherit;cursor:pointer} +.webfront-inspector-frame{flex:1 1 auto;min-height:0;width:100%;border:0;background:#141821}`; + +/** Where a page keeps its host identifier: the session storage of its tab, so that a reload keeps its detached windows. */ +export const hostKey = 'webfront-inspector-host'; + +const validHost = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value); +const randomHost = view => Array.from(view.crypto.getRandomValues(new Uint8Array(12)), byte => byte.toString(16).padStart(2, '0')).join(''); + +/** Takes the lock `name` for as long as the page lives, when nobody holds it; resolves with whether it did. */ +function holdLock(locks, name) { + return new Promise(resolve => { + locks.request(name, {ifAvailable: true}, lock => { + resolve(Boolean(lock)); + return lock ? new Promise(() => {}) : undefined; // held until the page goes away + }).catch(() => resolve(false)); + }); +} + +/** + * The identifier of this host page (1 to 64 letters, digits, `-` or `_`, which webfront.inspector.openWindow checks), so + * that a detached panel is attached again only to the page that detached it. A reload keeps it: it is kept in the tab's + * session storage. That storage is also copied into a page that this one opens, so the identifier is used only by the page + * that holds its lock (Web Locks, exclusive for the origin, released when the page goes away): a page that finds it held + * takes a new one. Without Web Locks nothing can tell a reload from a copy, and every load takes a new identifier. + */ +export async function claimHostIdentifier(view) { + let stored = null; + try { stored = view.sessionStorage?.getItem(hostKey); } + catch { /* no storage: a new identifier for this load */ } + const locks = view.navigator?.locks; + let claimed = null; + if (locks) { + for (let candidate = validHost(stored) ? stored : randomHost(view), attempt = 0; attempt < 4 && !claimed; ++attempt) { + if (await holdLock(locks, `${hostKey}:${candidate}`)) claimed = candidate; + else candidate = randomHost(view); + } + } + claimed ??= randomHost(view); + try { view.sessionStorage?.setItem(hostKey, claimed); } + catch { /* kept for this load only */ } + return claimed; +} + +/** + * The inspectors' host for the page that holds the tab. `inspectorUrl` is the URL of inspector.html, `access` resolves to what + * the menu read (menu.mjs, inspectorAccess), and `embedded` to whether this page may run in an embedded frontend (by default asked to + * webfront.inspector.embedded(); an error counts as embedded, which never offers a tab). `open(panel)` shows a panel in its + * container, `detach(panel)` and `attach(panel)` move it, and `reason(panel)` says why it cannot be detached ('' when it + * can). `windowOpen` replaces window.open (tests). `hostId` names this page in its detached windows (claimHostIdentifier()). + */ +export async function createInspectorHost({bridge, page, inspectorUrl, access, embedded = null, windowOpen = null, hostId = null}) { + const view = page.defaultView, root = page.documentElement; + const self = hostId ?? await claimHostIdentifier(view); + const viewport = () => ({width: root.clientWidth, height: root.clientHeight}); + const [preferences, containers, isEmbedded] = await Promise.all([ + readPreferences(bridge), + Promise.resolve(access).then(result => result?.containers ?? null), + Promise.resolve(embedded ?? bridge.cppFunction('webfront.inspector.embedded')()).then(Boolean, () => true), + ]); + const store = preferencesStore(bridge); + const openTab = windowOpen ?? ((url, name) => view.open(url, name)); + const urlOf = (panel, extra = {}) => { + const url = new URL(inspectorUrl, view.location.href); + url.searchParams.set('panel', panel); + url.searchParams.set('host', self); + for (const [key, value] of Object.entries(extra)) url.searchParams.set(key, value); + return url.href; + }; + + // The floating window: one per page, showing one panel at a time. + const style = page.createElement('style'); + style.textContent = styles; + page.head.append(style); + const panel = page.createElement('section'); + panel.className = 'webfront-inspector-window'; + panel.hidden = true; + panel.setAttribute('role', 'dialog'); + panel.setAttribute('aria-modal', 'false'); + const bar = page.createElement('div'); + bar.className = 'webfront-inspector-bar'; + bar.tabIndex = 0; + bar.setAttribute('role', 'group'); + bar.setAttribute('aria-label', 'Inspector window: drag it, or use the arrow keys to move it and Shift with the arrow keys to resize it'); + const title = page.createElement('span'); + const detachButton = page.createElement('button'); + detachButton.type = 'button'; + detachButton.className = 'webfront-inspector-detach'; + detachButton.textContent = 'Detach'; + const closeButton = page.createElement('button'); + closeButton.type = 'button'; + closeButton.className = 'webfront-inspector-close'; + closeButton.setAttribute('aria-label', 'Close the inspector'); + closeButton.title = 'Close the inspector'; + closeButton.textContent = '×'; + bar.append(title, detachButton, closeButton); + const notice = page.createElement('div'); + notice.className = 'webfront-inspector-notice'; + notice.setAttribute('role', 'status'); + notice.hidden = true; + const noticeText = page.createElement('span'); + const retry = page.createElement('button'); + retry.type = 'button'; + retry.textContent = 'Try again'; + notice.append(noticeText, retry); + // A frame is made for each panel shown, its address set before it enters the page: navigating a frame that is already + // in the page adds an entry to the window's history, and a window with a history may no longer close itself. + let frame = page.createElement('iframe'); + frame.className = 'webfront-inspector-frame'; + frame.title = 'Inspector'; + panel.append(bar, notice, frame); + page.body.append(panel); + + let shownPanel = null, retryPanel = null; + // Each action on the floating window (show, hide, attach, detach) takes a new number: a detached container that answers + // late only changes the window when no other action came meanwhile, so it never hides a panel shown since, nor shows + // one closed since. + let action = 0; + const shown = () => clampRect(preferences.rect ?? defaultInspectorRect(viewport()), viewport()); + function render() { + if (panel.hidden) return; + const rect = shown(); + Object.assign(panel.style, {left: `${rect.x}px`, top: `${rect.y}px`, width: `${rect.width}px`, height: `${rect.height}px`}); + } + function choose(rect) { + preferences.rect = clampRect(rect, viewport()); + store.place(preferences.rect); + render(); + } + windowControls({view, bar, panel, shown, choose, viewport, shownNow: () => !panel.hidden}); + view.addEventListener('resize', render); + + const reason = () => detachedContainer(containers, {embedded: isEmbedded}) ? '' : hostReasons.noDetached; + function say(text, again = null) { + noticeText.textContent = text; + retryPanel = again; + retry.hidden = !again; + notice.hidden = !text; + } + function showFloating(id, message = '') { + ++action; + shownPanel = id; + title.textContent = panelTitle(id); + panel.setAttribute('aria-label', `WebFront inspector: ${panelTitle(id)}`); + const why = reason(); + detachButton.setAttribute('aria-disabled', String(Boolean(why))); + detachButton.title = why || 'Open this panel in a window of its own'; + // The frame opens no connection of its own: the page reads ?frame and borrows this page's bridge. + const url = urlOf(id, {frame: '1'}); + if (frame.getAttribute('src') !== url) { + const next = page.createElement('iframe'); + next.className = 'webfront-inspector-frame'; + next.title = `Inspector: ${panelTitle(id)}`; + next.setAttribute('src', url); + frame.replaceWith(next); + frame = next; + } + say(message, message && retryPanel); + panel.hidden = false; + render(); + } + function hideFloating() { + ++action; + panel.hidden = true; + shownPanel = null; + const empty = page.createElement('iframe'); // unloads the panel without navigating + empty.className = 'webfront-inspector-frame'; + empty.title = 'Inspector'; + frame.replaceWith(empty); + frame = empty; + } + + /** + * Opens `id` in its detached container; resolves with whether it did. A failure leaves it in the floating window. A native + * window that is no longer wanted once C++ has answered every opening of the panel (attached again, or its floating + * window closed meanwhile) is closed then: the panel stays in the floating window, or closed. + */ + async function openDetached(id, container) { + if (container === 'window') { + const rect = shown(), started = action; + const attempt = {cancelled: false}; + if (!opening.has(id)) opening.set(id, {pending: new Set(), latest: null}); + const openings = opening.get(id); + openings.pending.add(attempt); + openings.latest = attempt; + let failure = null; + try { + // A close that an attach asked for is over first: the window opened now is never the one being closed. + if (closing.has(id)) await closing.get(id); + await bridge.cppFunction('webfront.inspector.openWindow')(id, self, rect.width, rect.height); + } catch (error) { + failure = error; + } + // A panel has one native window per host page, which every pending opening of it may reuse: whether it stays is + // decided once the last of them has answered, whatever their order, by the latest one asked for. + openings.pending.delete(attempt); + if (!openings.pending.size) { + opening.delete(id); + if (!preferences.detached.has(id) || openings.latest.cancelled) + await bridge.cppFunction('webfront.inspector.closeWindow')(id, self).catch(() => {}); + } + if (failure) { + // Shown as the fallback only if nothing was done with the window while the native one was being opened. + if (action === started) { + retryPanel = id; + showFloating(id, `${hostReasons.windowFailed}: ${failure?.message ?? failure}`); + } + return false; + } + return preferences.detached.has(id) && !attempt.cancelled; + } + // The target names the host too: a tab of another page of the same browsing group is never reused for this one. A tab + // that was asked to close itself may not be closed yet: a new name opens another tab instead of reusing that one. + const generation = selfClosing.get(id); + const name = `webfront-inspector-${self}-${id.replace('.', '-')}${generation ? `-${generation}` : ''}`; + const tab = openTab(urlOf(id), name); + if (tab) { + tabs.set(id, tab); + return true; + } + retryPanel = id; + showFloating(id, hostReasons.blocked); + return false; + } + + // The detached container of a panel attached again is closed by this page, ordered with its later detaches, and not by + // the detached window once it got the answer: a detach between that answer and the window's close would reuse the + // window, then lose it. `closing` holds the close of a native window still in progress, `tabs` the tabs this page opened, + // and `selfClosing` the generation of the panels whose tab closes itself (a tab this page did not open, before a reload). + const closing = new Map(), tabs = new Map(), selfClosing = new Map(); + let generation = 0; + // The openings of a native window that C++ has not answered yet, per panel (Detach clicked twice makes two), and the + // latest one asked for: closing the floating window that shows that panel meanwhile cancels all of them, and the + // window is closed once the last of them has answered, unless a later detach asked for it again. + const opening = new Map(); + /** Closes the floating window at the user's request, with the native windows still opening for its panel. */ + function closeFloating() { + for (const attempt of (shownPanel && opening.get(shownPanel)?.pending) || []) attempt.cancelled = true; + hideFloating(); + } + /** + * Closes the detached container of `id`; resolves with 'host' when this page closed it, 'self' when the window must close + * itself. A native window counts as closed only when C++ says so: a close that failed or found no window answers 'self', + * so that the window does not stay open waiting for a close that will not come. + */ + async function closeDetached(id) { + if (detachedContainer(containers, {embedded: isEmbedded}) === 'window') { + const closed = bridge.cppFunction('webfront.inspector.closeWindow')(id, self).then(Boolean, () => false); + closing.set(id, closed); + closed.then(() => { if (closing.get(id) === closed) closing.delete(id); }); + return await closed ? 'host' : 'self'; + } + const tab = tabs.get(id); + tabs.delete(id); + if (tab && !tab.closed) { + tab.close(); + return 'host'; + } + selfClosing.set(id, ++generation); + return 'self'; + } + + /** Hides the floating window's `id` now that its detached container opened, unless it was attached or changed since. */ + function hideIfStill(id, started) { + if (shownPanel === id && preferences.detached.has(id) && action === started) hideFloating(); + } + + const host = { + get containers() { return containers; }, + get embedded() { return isEmbedded; }, + /** The identifier that names this page in its detached windows. */ + get id() { return self; }, + /** The bridge this host was created with: the frame of the floating window borrows it (inspector.mjs, pageBridge). */ + get bridge() { return bridge; }, + get shownPanel() { return shownPanel; }, + get frame() { return frame; }, + panel, bar, detachButton, closeButton, notice, + reason, + /** Shows `id` where the project keeps it: its detached container, or this page's floating window. */ + async open(id) { + if (!panels.has(id)) throw new Error(`Unknown inspector panel ${id}`); + const container = containerFor(id, {containers, embedded: isEmbedded, detached: preferences.detached}); + if (!container) return null; + if (container === 'floating') { + retryPanel = null; + showFloating(id); + return 'floating'; + } + const started = action; + if (await openDetached(id, container)) { + hideIfStill(id, started); + return container; + } + return 'floating'; + }, + /** Moves `id` to its detached container, and remembers it there. */ + async detach(id) { + const container = detachedContainer(containers, {embedded: isEmbedded}); + if (!container) return null; + preferences.detached.add(id); + store.detached(id, true); + const started = action; + if (await openDetached(id, container)) { + hideIfStill(id, started); + return container; + } + return 'floating'; + }, + /** Moves `id` back to this page's floating window, and remembers it there. */ + attach(id) { + preferences.detached.delete(id); + store.detached(id, false); + retryPanel = null; + showFloating(id); + }, + close: closeFloating, + saved: () => store.saved(), + get preferences() { return {detached: new Set(preferences.detached), rect: preferences.rect}; }, + }; + + detachButton.addEventListener('click', () => { + if (shownPanel && !reason()) host.detach(shownPanel); + }); + closeButton.addEventListener('click', closeFloating); + retry.addEventListener('click', () => { if (retryPanel) host.detach(retryPanel); }); + + // A detached inspector asks to come back: the page that detached it shows the panel, closes the detached container when + // it can, and answers who closes it ('host', or 'self' for a tab this page did not open). + if (typeof view.BroadcastChannel === 'function') { + const channel = new view.BroadcastChannel(inspectorChannel); + channel.addEventListener('message', ({data}) => { + // Only the page that detached the panel takes it back: other pages of the same origin ignore the request. + if (data?.type !== 'attach' || data.host !== self || !panels.has(data.panel) || !containers?.host) return; + host.attach(data.panel); + closeDetached(data.panel).then(closer => channel.postMessage({type: 'attached', id: data.id, closer})); + }); + host.channel = channel; + } + // A place still waiting for its write is written when the page goes away (a detach is written at once). + view.addEventListener('pagehide', () => { store.saved().catch(() => {}); }); + // The frame of the floating window reaches its host here: the same origin, and no connection of its own. + view.webfrontInspectorHost = host; + return host; +} + +/** + * The inspectors of a page that holds the tab: `open(panel)` shows a panel, creating the host on first use. The host is also + * created as soon as `access` says that this page reaches the inspectors, without waiting for a panel to be opened: a panel + * detached before this page was reloaded carries the page's identifier, and its request to be attached again must find the + * host listening. `host()` is the promise of the host, null until it is created; a creation that failed is tried again on the + * next `open(panel)`. `create` replaces createInspectorHost (tests). + */ +export function prepareInspectors({create = createInspectorHost, ...options}) { + let made = null; + const host = () => made ??= Promise.resolve().then(() => create(options)).catch(error => { + made = null; + throw error; + }); + Promise.resolve(options.access).then(access => { if (access?.containers?.host) host().catch(() => {}); }, () => {}); + return { + open: panel => host().then(created => created.open(panel)), + host: () => made, + }; +} diff --git a/js/developer/environment/inspector.html b/js/developer/environment/inspector.html new file mode 100644 index 00000000..9305f078 --- /dev/null +++ b/js/developer/environment/inspector.html @@ -0,0 +1,14 @@ + + + + +WebFront inspector + +

Starting the inspector…

+ + + diff --git a/js/developer/environment/inspector.mjs b/js/developer/environment/inspector.mjs new file mode 100644 index 00000000..a024af1e --- /dev/null +++ b/js/developer/environment/inspector.mjs @@ -0,0 +1,383 @@ +// The page of the inspectors (#680, ADR-027 section 8): inspector.html?panel= shows one panel and talks to C++ through the +// bridge. In a window or a tab of its own it opens its own connection; in the floating window of a page (?frame=1) it opens +// none and borrows that page's bridge, since the adapters give the proof of the view to the main frame only. The panel of the +// watches lists them by webfront.inspector.watches and follows the registrations and removals (section 3, "Découverte"). +import {inspectorPanels as panels, panelTitle, inspectorChannel as channelName} from './menu.mjs'; + +// --- Bridge ---------------------------------------------------------------------------------------------------- + +/** + * The bridge of this page: the host page's when it is the frame of a floating window (`frame` set, and a parent of the + * same origin that has one), else its own, by loading WebFront.js, which connects when it loads. Resolves once ready. + */ +export async function pageBridge(view = window, {frame = false} = {}) { + if (frame && view.parent !== view) { + // The bridge the host was created with, which may not be the page's global webFront: the frame then reads the + // same connection as its host, whose access was checked, and never another one. + let borrowed = null; + try { borrowed = view.parent.webfrontInspectorHost?.bridge ?? null; } + catch { /* another origin: never borrowed */ } + if (!borrowed) throw new Error('The inspector\'s frame has no host page to borrow the bridge from'); + await borrowed.ready; + return borrowed; + } + if (!view.webFront) { + const page = view.document; + await new Promise((resolve, reject) => { + const script = page.createElement('script'); + script.src = '/WebFront.js'; + script.onload = resolve; + script.onerror = () => reject(new Error('Cannot load WebFront.js')); + page.head.append(script); + }); + } + await view.webFront.ready; + return view.webFront; +} + +// --- Watches --------------------------------------------------------------------------------------------------- + +export const watchesFunction = 'webfront.inspector.watches'; +/** The period of the discovery, as the inspector reads its watches (ADR-027: 250 ms by default). */ +export const defaultPeriod = 250; + +/** A descriptor of webfront.inspector.watches as an object; null when it is not one. */ +export function readDescriptor(tuple) { + if (!Array.isArray(tuple) || tuple.length !== 5) return null; + const [id, name, kind, location, writable] = tuple; + if (!Number.isSafeInteger(id) || id <= 0 || typeof name !== 'string' || typeof kind !== 'string' || typeof location !== 'string' + || typeof writable !== 'boolean') return null; + return {id, name, kind, location, writable}; +} + +/** A page of webfront.inspector.watches: {descriptors, next, revision, changed}; throws when it is not one. */ +export function readPage(answer) { + if (!Array.isArray(answer) || answer.length !== 4) throw new Error('The inspectors gave a page that this environment does not read'); + const [list, next, revision, changed] = answer; + const descriptors = (Array.isArray(list) ? list : []).map(readDescriptor); + if (descriptors.includes(null) || !Number.isSafeInteger(next) || !Number.isSafeInteger(revision) || typeof changed !== 'boolean') + throw new Error('The inspectors gave a page that this environment does not read'); + return {descriptors, next, revision, changed}; +} + +/** How many times a listing starts again because the registry changed while it was read, before it gives up. */ +export const listingAttempts = 8; + +/** + * Every live watch, page after page from the start, with the revision of the registry they describe. The pages give the + * revision of the first one: a page that answers "changed" means that a watch was registered or removed while the list was + * read, so the pages already read may name a removed watch, and the listing starts again. After `listingAttempts` such + * changes it gives up and resolves with null: the list shown stays, and the next poll, which finds the registry changed, + * tries again. Only a stable read gives a list, always a complete one. `active()` is asked before each page: once it is + * false (the inspector paused or closed) the listing stops and resolves with null, having read no further. + */ +export async function listWatches(bridge, revision = 0, {active = () => true} = {}) { + for (let attempt = 0; attempt < listingAttempts; ++attempt) { + if (!active()) return null; + const first = readPage(await bridge.cppFunction(watchesFunction)(revision, 0, 200)); + const watches = [...first.descriptors]; + let next = first.next, stable = true; + while (stable && next) { + if (!active()) return null; + const page = readPage(await bridge.cppFunction(watchesFunction)(first.revision, next, 200)); + watches.push(...page.descriptors); + stable = !page.changed; + next = page.next; + } + if (stable) return {watches, revision: first.revision}; + revision = 0; + } + return null; +} + +/** What changed between the watches shown (`known`, a Map by id) and a new list: the descriptors to add, the ids to remove. */ +export function reconcile(known, listed) { + const ids = new Set(listed.map(watch => watch.id)); + return {added: listed.filter(watch => !known.has(watch.id)), removed: [...known.keys()].filter(id => !ids.has(id))}; +} + +/** + * Follows the watches of the application: asks the revision of the registry every `period` with a count of 0, reads the + * list again when it changed, and calls `onChange({added, removed, watches})`. `forget(id)` removes a watch that a call + * found gone (a refusal `webfront.inspector.unknown`). `pause()` and `resume()` stop and restart the reads; `stop()` ends them. + * `onError(error)` receives a failed read; the discovery keeps trying at the next period. `onRead(watches)` follows every read + * that succeeds, changed or not, so that an error shown earlier can be cleared once the reads work again. + */ +export function createWatchDiscovery({bridge, onChange, onError = () => {}, onRead = () => {}, period = defaultPeriod, timers = globalThis}) { + const known = new Map(); + let revision = 0, timer = null, paused = false, stopped = false, running = null; + const apply = listed => { + const change = reconcile(known, listed); + for (const watch of change.added) known.set(watch.id, watch); + for (const id of change.removed) known.delete(id); + if (change.added.length || change.removed.length) onChange({...change, watches: [...known.values()]}); + }; + // Paused or stopped: no further request, and nothing read after the pause is shown. The revision moves only with a list + // that is shown, so that a resumption reads again from the one shown. + const active = () => !paused && !stopped; + async function poll() { + const {changed, revision: current} = readPage(await bridge.cppFunction(watchesFunction)(revision, 0, 0)); + if (!active()) return; + if (changed || current !== revision) { + const listed = await listWatches(bridge, current, {active}); + if (!active()) return; + if (listed) { + revision = listed.revision; + apply(listed.watches); + } + } + onRead([...known.values()]); + } + // One chain of reads at a time: a read in progress schedules the next one when it ends, so nothing else does meanwhile + // (a pause then a resumption during a read would start a second chain, whose results could overtake the first's). + function schedule() { + if (stopped || paused || timer !== null || running !== null) return; + timer = timers.setTimeout(() => { + timer = null; + running = poll().catch(onError).finally(() => { + running = null; + schedule(); + }); + }, period); + } + const discovery = { + get watches() { return [...known.values()]; }, + get paused() { return paused; }, + /** Reads now, then at each period. */ + async start() { + running = poll().catch(onError); + await running; + running = null; + schedule(); + }, + /** Forgets a watch that a call found gone, as a removal from the registry would. */ + forget(id) { + if (!known.delete(id)) return; + onChange({added: [], removed: [id], watches: [...known.values()]}); + }, + pause() { + paused = true; + timers.clearTimeout(timer); + timer = null; + }, + resume() { + paused = false; + schedule(); + }, + stop() { + stopped = true; + timers.clearTimeout(timer); + timer = null; + }, + /** Resolves once the read in progress, if any, is over. */ + settled: () => running ?? Promise.resolve(), + }; + return discovery; +} + +// --- Page ------------------------------------------------------------------------------------------------------ + +const styles = ` +:root{color-scheme:dark} +body{margin:0;background:#141821;color:#e8edf4;font:14px system-ui} +header{display:flex;align-items:center;gap:8px;padding:8px 12px;background:#202737;border-bottom:1px solid #46536a} +header h1{flex:1 1 auto;margin:0;font-size:14px;font-weight:600} +header button{min-height:32px;padding:0 10px;border:1px solid #46536a;border-radius:4px;background:#2f3a50;color:inherit;font:inherit;cursor:pointer} +header button:focus-visible{outline:2px solid #d7fa85;outline-offset:1px} +main{padding:8px 12px} +.status{color:#a9b3c4;font-size:12px;margin:4px 0 8px} +.status:empty{display:none} +.error{color:#ffbd2e} +ul.watches{list-style:none;margin:0;padding:0} +ul.watches li{display:grid;grid-template-columns:auto 1fr;gap:2px 12px;padding:8px;border-bottom:1px solid #2f3a50} +ul.watches .name{font-weight:600} +ul.watches .kind{color:#d7fa85;font-family:ui-monospace,monospace;font-size:12px;justify-self:end} +ul.watches .location{grid-column:1/3;color:#a9b3c4;font-size:12px;overflow-wrap:anywhere} +ul.watches .writable{color:#8fd0ff;font-size:12px}`; + +const placeholders = { + 'cpp.functions': 'The functions that the application registered come with the next versions of the environment.', + 'cpp.browsers': 'The connected browsers and the running tasks come with the next versions of the environment.', + 'typescript.packages': 'The tree of the locked packages comes with the next versions of the environment.', + 'typescript.bridge': 'The state of the bridge in the page comes with the next versions of the environment.', +}; + +/** Renders the list of the watches in `list`, one item per watch, kept by id so that a removal removes its item. */ +export function renderWatches(list, watches) { + const page = list.ownerDocument; + const items = new Map([...list.children].map(item => [Number(item.dataset.watch), item])); + const ids = new Set(watches.map(watch => watch.id)); + for (const [id, item] of items) if (!ids.has(id)) item.remove(); + for (const watch of watches) { + if (items.has(watch.id)) continue; + const item = page.createElement('li'); + item.dataset.watch = String(watch.id); + const cell = (className, text) => { + const element = page.createElement('span'); + element.className = className; + element.textContent = text; + return element; + }; + item.append(cell('name', watch.name), cell('kind', watch.kind), cell('location', watch.location)); + if (watch.writable) item.append(cell('writable', 'writable')); + list.append(item); + } +} + +/** Closes this window once the page that opened it is gone; nothing for a window that no page opened. */ +export function watchOpener(view, period = 1000) { + const opener = view.opener; + if (!opener) return null; + const watcher = view.setInterval(() => { if (opener.closed) view.close(); }, period); + view.addEventListener('pagehide', () => view.clearInterval(watcher)); + return watcher; +} + +/** + * Loads the page again when the browser restores it from its back-forward cache. The restored page is resumed without + * main(): the discovery of the watches and the watch of the opener, stopped when it was hidden, would not start again, and + * the connection of a tab may have been closed meanwhile. Loading it again starts all of them anew. + */ +export function reloadWhenRestored(view) { + view.addEventListener('pageshow', event => { if (event.persisted) view.location.reload(); }); +} + +/** + * Shows the panel named by the page's URL. In a frame it borrows the host page's bridge; elsewhere it has its own + * connection, offers to attach the panel to the host page again, and closes itself when the page that opened it is gone. + */ +export async function main(view = window) { + const page = view.document; + const params = new URL(view.location.href).searchParams; + const id = params.get('panel') ?? 'cpp.watches'; + const framed = params.get('frame') === '1'; + page.title = `WebFront inspector: ${panelTitle(id)}`; + reloadWhenRestored(view); + const style = page.createElement('style'); + style.textContent = styles; + page.head.append(style); + const header = page.createElement('header'); + const heading = page.createElement('h1'); + heading.textContent = panelTitle(id); + header.append(heading); + const body = page.createElement('main'); + const status = page.createElement('p'); + status.className = 'status'; + status.setAttribute('role', 'status'); + body.append(status); + page.body.replaceChildren(header, body); + if (!panels.has(id)) { + status.textContent = `Unknown inspector panel: ${id}`; + return null; + } + + // A tab that the main page opened closes with it, as a secondary window closes with the main window (#616): watched + // before the bridge is awaited, so that a tab whose connection fails or is still opening closes too. + if (!framed) watchOpener(view); + + let bridge; + try { bridge = await pageBridge(view, {frame: framed}); } + catch (error) { + status.textContent = `The inspector cannot reach the application: ${error?.message ?? error}`; + status.classList.add('error'); + return null; + } + + // Detached, the panel can go back to the floating window of the page that holds the tab. + if (!framed) { + const attach = page.createElement('button'); + attach.type = 'button'; + attach.className = 'attach'; + attach.textContent = 'Attach'; + attach.title = 'Show this panel in the floating window of the main page'; + header.append(attach); + // Its own status: the reads of the watches, which clear theirs, never clear why the panel could not be attached. + const attachStatus = page.createElement('p'); + attachStatus.className = 'status attach-status'; + attachStatus.setAttribute('role', 'status'); + body.prepend(attachStatus); + attach.addEventListener('click', () => attachAgain(view, bridge, id, attachStatus, {host: params.get('host')})); + } + + if (id !== 'cpp.watches') { + status.textContent = placeholders[id]; + return {bridge}; + } + const list = page.createElement('ul'); + list.className = 'watches'; + list.setAttribute('aria-label', 'Watches'); + body.append(list); + const pause = page.createElement('button'); + pause.type = 'button'; + pause.className = 'pause'; + pause.textContent = 'Pause'; + header.insertBefore(pause, header.children[1] ?? null); + const describe = watches => { + status.classList.remove('error'); + status.textContent = watches.length ? '' : 'The application declares no watch (app.watch).'; + }; + const discovery = createWatchDiscovery({ + bridge, + onChange: ({watches}) => renderWatches(list, watches), + // Every read that succeeds says so, also after an error and when nothing changed. + onRead: describe, + onError: error => { + status.classList.add('error'); + status.textContent = error?.code === 'webfront.inspector.denied' + ? 'The inspectors answer only a view of the application: this page is not admitted.' + : `The watches cannot be read: ${error?.message ?? error}`; + }, + timers: view, + }); + pause.addEventListener('click', () => { + if (discovery.paused) discovery.resume(); else discovery.pause(); + pause.textContent = discovery.paused ? 'Resume' : 'Pause'; + }); + view.addEventListener('pagehide', () => discovery.stop()); + await discovery.start(); + return {bridge, discovery, list}; +} + +/** + * Asks the page that detached the panel (`host`, the identifier its address carries) to show it again. That page closes this + * window itself when it can (a native window, or a tab it opened); otherwise it answers that this window closes itself: a tab + * by itself, a native window through C++. Another page of the same origin does not answer. Without an answer within `wait` + * the window stays and says why in `status`; an answer that comes later still closes it. + */ +export async function attachAgain(view, bridge, id, status, {host = null, wait = 1000} = {}) { + if (typeof view.BroadcastChannel !== 'function' || !host) { + status.textContent = 'This window cannot reach the page that opened it: close it and open the panel from the menu.'; + return false; + } + status.textContent = ''; + const channel = new view.BroadcastChannel(channelName); + const request = `${id}:${Date.now()}:${Math.random()}`; + // The channel listens until the answer, or until this page goes: an answer that comes after the wait still closes this + // window, since the host shows the panel again by then (else the panel would be shown twice). + const close = () => channel.close(); + view.addEventListener?.('pagehide', close, {once: true}); + const finish = async answer => { + close(); + status.textContent = ''; + // The host closes this window itself, ordered with a detach the user may make meanwhile, which reuses or reopens it: + // closing it from here could close the window of that newer detach. + if (answer.closer === 'host') return true; + if (view.opener) view.close(); + else await bridge.cppFunction('webfront.inspector.closeWindow')(id, host).catch(() => view.close()); + return true; + }; + return new Promise(resolve => { + let late = false; + const timer = view.setTimeout(() => { + late = true; + status.textContent = 'The main page did not answer: open the panel from the menu of its tab.'; + resolve(false); + }, wait); + channel.addEventListener('message', ({data}) => { + if (data?.type !== 'attached' || data.id !== request) return; + view.clearTimeout(timer); + finish(data).then(done => { if (!late) resolve(done); }); + }); + channel.postMessage({type: 'attach', panel: id, host, id: request}); + }); +} diff --git a/js/developer/environment/menu.mjs b/js/developer/environment/menu.mjs index 7fefec6a..e4f36ab3 100644 --- a/js/developer/environment/menu.mjs +++ b/js/developer/environment/menu.mjs @@ -18,6 +18,19 @@ export const inspectorMenus = [ ]}, ]; +/** The inspector panels by id, each with the label of its group. */ +export const inspectorPanels = new Map(inspectorMenus.flatMap(group => group.children.map(panel => [panel.id, {...panel, group: group.label}]))); + +/** The title of a panel's window: its group and its name ("C++ state: Watches"). */ +export const panelTitle = id => inspectorPanels.has(id) ? `${inspectorPanels.get(id).group}: ${inspectorPanels.get(id).label}` : 'Inspector'; + +/** + * The channel between the page that holds the tab and its detached inspectors, other windows of the same origin + * (inspector-host.mjs): a detached inspector asks to be attached again ({type: 'attach', panel, id}), and the page that + * takes it answers ({type: 'attached', id}) before the inspector closes its window. + */ +export const inspectorChannel = 'webfront-inspector'; + // --- Access to the inspectors ---------------------------------------------------------------------------------- /** The reserved function that says which containers would reach the inspectors; the only one that checks no access. */ @@ -29,7 +42,7 @@ export const accessReasons = { noContainer: 'The inspectors answer only a view of the application, and this page is not one: use an embedded frontend ' + '(WebKitGTK, WKWebView, WebView2 or CEF), or set WebFrontConfig::trustLoopbackClients, knowing that any local ' + 'process can then read the state of the application.', - noInspector: 'This version of the developer environment cannot open the inspectors yet.', + noInspector: 'This page cannot open the inspectors.', }; /** diff --git a/js/developer/environment/runtime.mjs b/js/developer/environment/runtime.mjs index aaea3bc7..980cfb05 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -18,6 +18,7 @@ import {generateProvider, applicationPage} from './embed.mjs'; import {typescriptPackage, parseCheckOptions, checkHost} from './typecheck.mjs'; import {pinnedStarters} from './bootstrap.mjs'; import {createWorkspace, isManaged, layoutState, State} from './workspace.mjs'; +import {prepareInspectors} from './inspector-host.mjs'; import {connectAutomation as connectAgent, clipText, automationHelp, onAutomationNotice} from './automation.mjs'; import {ls, cat, tree, mounts, fileCommandHelp, withheld, withheldReason} from './files.mjs'; import {dependencyTree, why as whyInstalled, info as packageInfo} from './dependencies.mjs'; @@ -665,7 +666,17 @@ export async function mount({bridge, config, terminal: element, preview, onExit, terminal.unicode.activeVersion = unicodeProvider.version; const fit = new FitAddon(); terminal.loadAddon(fit); - const workspace = layout && preview && !isManaged(preview) ? await createWorkspace({bridge, element, frame: preview}) : null; + // The inspectors (#680) open from the tab's menu, in the container that reaches C++ (inspector-host.mjs). + // The menu does not wait for the panel: a panel that cannot open is said in the terminal. + let inspectors = null, editor = null; + const openInspector = panel => inspectors.open(panel).catch(error => { + const text = `\x1b[31mThe inspector could not open: ${error?.message ?? error}\x1b[0m`; + if (editor) editor.notice(text); else terminal.write(`${text}\r\n`); + workspace?.open({focus: false}); // a collapsed terminal would hide the diagnostic; the keys stay where they are + }); + const workspace = layout && preview && !isManaged(preview) ? await createWorkspace({bridge, element, frame: preview, openInspector}) : null; + if (workspace) inspectors = prepareInspectors({bridge, page: element.ownerDocument, access: workspace.inspectorAccess, + inspectorUrl: new URL('./inspector.html', import.meta.url).href}); terminal.open(element); fit.fit(); const write = text => terminal.write(text); @@ -680,7 +691,7 @@ export async function mount({bridge, config, terminal: element, preview, onExit, readHistory(bridge).catch(() => [])]); earlyInput.dispose(); const context = {bridge, config, preview, cppCommands, onExit}; - const editor = new LineEditor({write, columns: () => terminal.cols, rows: () => terminal.rows, prompt: '> ', history, + editor = new LineEditor({write, columns: () => terminal.cols, rows: () => terminal.rows, prompt: '> ', history, remember: line => rememberLine(bridge, line), run: async (line, signal) => { workspace?.command(true); // the tab shows that a command runs, also while the terminal is collapsed @@ -744,5 +755,5 @@ export async function mount({bridge, config, terminal: element, preview, onExit, if (workspace.interfaceExists) showPreview(preview); workspace.attach({focus: () => terminal.focus(), fit: fitToElement ? fitTerminal : undefined}); } else terminal.focus(); - return {terminal, editor, workspace}; + return {terminal, editor, workspace, inspectors: () => inspectors?.host() ?? null}; } diff --git a/js/developer/environment/terminal.mjs b/js/developer/environment/terminal.mjs index 8ca1b884..371cb4bd 100644 --- a/js/developer/environment/terminal.mjs +++ b/js/developer/environment/terminal.mjs @@ -298,6 +298,18 @@ export class LineEditor { if (this.cells.length) this.redraw(); } + /** + * Prints `text` as lines of their own, for an event that no command reported: above the line being edited, which is + * drawn again below them (also while a completion is pending, which then acts on the line drawn again), or after the + * output of the command that runs. + */ + notice(text) { + const lines = text.endsWith('\n') ? text : `${text}\r\n`; + if (this.running || this.closed) return this.write((this.atLineStart ? '' : '\r\n') + lines); + this.write(ansi.up(this.row) + '\r' + ansi.clearBelow + lines); + this.showPrompt(); + } + handle(data) { if (this.closed) return data === '\r' ? this.reopen() : undefined; if (this.completing) return void this.completing.push(data); diff --git a/js/developer/environment/workspace.mjs b/js/developer/environment/workspace.mjs index 5fbaf94d..7b364ff9 100644 --- a/js/developer/environment/workspace.mjs +++ b/js/developer/environment/workspace.mjs @@ -164,6 +164,50 @@ export function placeStore(bridge, delay = 300) { }; } +// --- Floating window -------------------------------------------------------------------------------------------- + +/** + * Makes `panel` a window that its title `bar` moves: by dragging it (the pointer is captured, so that the interface under + * the window does not take the moves), or with the arrow keys on the focused bar, Shift resizing it; the corner handle of + * CSS `resize` resizes it with the pointer. A control of the bar (a button) does not start a move. `shown()` is the + * displayed rectangle, `choose(rect)` makes a new one the chosen place, `viewport()` gives the room, and `shownNow()` + * whether the window is displayed (a hidden one does not take the sizes its element reports). The terminal's window and + * the inspector's share it. + */ +export function windowControls({view, bar, panel, shown, choose, viewport, shownNow}) { + // One move at a time, by the pointer that started it: a second finger on the bar neither takes the move over nor ends it. + let grip = null; + bar.addEventListener('pointerdown', event => { + if (grip || event.button !== 0 || event.target.closest?.('button')) return; + const rect = shown(); + grip = {id: event.pointerId, x: event.clientX - rect.x, y: event.clientY - rect.y}; + try { bar.setPointerCapture(event.pointerId); } + catch { /* a pointer that is already gone: the move ends with it */ } + event.preventDefault(); + bar.focus(); + }); + bar.addEventListener('pointermove', event => { + if (grip?.id === event.pointerId) choose({...shown(), x: event.clientX - grip.x, y: event.clientY - grip.y}); + }); + const release = event => { if (grip?.id === event.pointerId) grip = null; }; + bar.addEventListener('pointerup', release); + bar.addEventListener('pointercancel', release); + bar.addEventListener('lostpointercapture', release); + bar.addEventListener('keydown', event => { + if (event.target !== bar) return; + const rect = keyboardRect(shown(), event, viewport()); + if (!rect) return; + event.preventDefault(); + choose(rect); + }); + // The corner handle (CSS resize) writes the size on the element: it becomes the chosen one. + new view.ResizeObserver(() => { + if (!shownNow()) return; + const rect = shown(), width = panel.offsetWidth, height = panel.offsetHeight; + if (width && height && (width !== rect.width || height !== rect.height)) choose({...rect, width, height}); + }).observe(panel); +} + // --- Page ------------------------------------------------------------------------------------------------------ // The WebFront swallow, shipped in the environment, in the colours of the tab. @@ -383,36 +427,7 @@ export async function createWorkspace({bridge, element, frame, openInspector = n // is installed ahead of the application's. A frame that the application embeds gets it once it is seen here. frame.addEventListener('webfront-preview-window', () => watchWindow(frame.contentWindow)); - // Moving: the pointer is captured, so that the interface under the window does not take the moves. - let grip = null; - bar.addEventListener('pointerdown', event => { - if (event.button !== 0 || event.target === closeButton) return; - const rect = shown(); - grip = {x: event.clientX - rect.x, y: event.clientY - rect.y}; - try { bar.setPointerCapture(event.pointerId); } - catch { /* a pointer that is already gone: the move ends with it */ } - event.preventDefault(); - bar.focus(); - }); - bar.addEventListener('pointermove', event => { - if (grip) choose({...shown(), x: event.clientX - grip.x, y: event.clientY - grip.y}); - }); - const release = () => { grip = null; }; - bar.addEventListener('pointerup', release); - bar.addEventListener('pointercancel', release); - bar.addEventListener('keydown', event => { - if (event.target !== bar) return; - const rect = keyboardRect(shown(), event, viewport()); - if (!rect) return; - event.preventDefault(); - choose(rect); - }); - // The corner handle (CSS resize) writes the size on the element: it becomes the chosen one. - new view.ResizeObserver(() => { - if (state !== State.floating) return; - const rect = shown(), width = panel.offsetWidth, height = panel.offsetHeight; - if (width && height && (width !== rect.width || height !== rect.height)) choose({...rect, width, height}); - }).observe(panel); + windowControls({view, bar, panel, shown, choose, viewport, shownNow: () => state === State.floating}); view.addEventListener('resize', render); render(); diff --git a/js/developer/scripts/build.mjs b/js/developer/scripts/build.mjs index 0d119a9a..74cbe8e8 100644 --- a/js/developer/scripts/build.mjs +++ b/js/developer/scripts/build.mjs @@ -64,8 +64,10 @@ export default async function (context) { const read = async path => written.get(path) ?? await project.read(path); const files = new Map(); - for (const name of ['runtime', 'compiler', 'script-worker', 'typecheck-worker']) + for (const name of ['runtime', 'compiler', 'script-worker', 'typecheck-worker', 'inspector']) files.set(`${name}.mjs`, await write(`${output}/${name}.mjs`, await bundle(`js/developer/environment/${name}.mjs`))); + // The page of the inspectors (#680): a window, a tab or the frame of a floating window loads it beside runtime.mjs. + files.set('inspector.html', await write(`${output}/inspector.html`, await project.read('js/developer/environment/inspector.html'))); files.set('esbuild.wasm', await write(`${output}/esbuild.wasm`, await project.read(lockedFile(lock, 'esbuild-wasm', 'esbuild.wasm')))); files.set('xterm.css', await write(`${output}/xterm.css`, await project.read(lockedFile(lock, '@xterm/xterm', 'css/xterm.css')))); @@ -111,7 +113,8 @@ export default async function (context) { files.set('package.json', await write(`${output}/package.json`, JSON.stringify({name: '@webfront/developer-environment', version, description: 'Browser-powered WebFront developer environment', type: 'module', license: '(Apache-2.0 OR CECILL-B)', - files: ['runtime.mjs', 'compiler.mjs', 'script-worker.mjs', 'typecheck-worker.mjs', 'esbuild.wasm', 'xterm.css', 'environment.json', 'LICENSES.txt']}, null, 2) + '\n')); + files: ['runtime.mjs', 'compiler.mjs', 'script-worker.mjs', 'typecheck-worker.mjs', 'inspector.mjs', 'inspector.html', 'esbuild.wasm', + 'xterm.css', 'environment.json', 'LICENSES.txt']}, null, 2) + '\n')); const bytes = compress(tar(new Map([...files].map(([name, content]) => [`package/${name}`, content])))); await write(`${output}/environment.tgz`, bytes); diff --git a/js/developer/tools/bundle-inputs.json b/js/developer/tools/bundle-inputs.json index 5c1b0560..999c8ca1 100644 --- a/js/developer/tools/bundle-inputs.json +++ b/js/developer/tools/bundle-inputs.json @@ -24,6 +24,9 @@ "js/developer/environment/terminal.mjs", "js/developer/environment/workspace.mjs", "js/developer/environment/menu.mjs", + "js/developer/environment/inspector-host.mjs", + "js/developer/environment/inspector.mjs", + "js/developer/environment/inspector.html", "js/developer/environment/tarball.mjs", "js/developer/environment/commands.mjs", "js/developer/environment/files.mjs", diff --git a/js/developer/webfront.project.json b/js/developer/webfront.project.json index df958a91..98ebdb78 100644 --- a/js/developer/webfront.project.json +++ b/js/developer/webfront.project.json @@ -32,6 +32,7 @@ "test/developer/specs/testing-specs.mjs", "test/developer/specs/timers-specs.mjs", "test/developer/specs/workspace-specs.mjs", + "test/developer/specs/inspector-specs.mjs", "test/developer/specs/files-specs.mjs", "test/developer/specs/dependencies-specs.mjs", "test/developer/specs/distribution-specs.mjs" diff --git a/test/developer/memory-bridge.mjs b/test/developer/memory-bridge.mjs index 4d2f5234..21c44ed7 100644 --- a/test/developer/memory-bridge.mjs +++ b/test/developer/memory-bridge.mjs @@ -17,7 +17,8 @@ export function memoryBridge(storage = new Map()) { const prefix = directory ? directory + '/' : ''; const names = new Set([...storage.keys()].filter(key => key.startsWith(prefix)) .map(key => key.slice(prefix.length)).map(rest => rest.includes('/') ? rest.split('/')[0] + '/' : rest)); - if (!names.size) throw new Error('Cannot list project directory: ' + directory); + // The project root always exists, even empty; another directory exists only through the files it holds. + if (!names.size && directory) throw new Error('Cannot list project directory: ' + directory); return new TextEncoder().encode(JSON.stringify([...names].sort())); }, // Like Store::entries: the same entries with their type and size; the memory project keeps no dates. @@ -55,6 +56,20 @@ export function memoryBridge(storage = new Map()) { } }, }; - const bridge = {cppFunction: name => async (...args) => operations[name.replace('webfront.developer.', '')](...args)}; + const bridge = {cppFunction: name => async (...args) => { + if (name === 'webfront.inspector.readPreferences') { + // Like Store::readWithState: the file and the token of exactly those bytes. + const path = '.webfront/developer/inspector-window.json'; + return [storage.has(path), storage.get(path) ?? new Uint8Array(), stateOf([path])]; + } + if (name === 'webfront.inspector.savePreferences') { + const path = '.webfront/developer/inspector-window.json'; + const [expected, bytes] = args; + if (stateOf([path]) !== expected) throw new Error('The project changed since it was read; run the command again'); + storage.set(path, bytes); + return; + } + return operations[name.replace('webfront.developer.', '')](...args); + }}; return {bridge, storage, pending: () => transactions.size}; } diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs new file mode 100644 index 00000000..aebf0dfb --- /dev/null +++ b/test/developer/specs/inspector-specs.mjs @@ -0,0 +1,1082 @@ +// Specs of the inspectors' host and page (#680, ADR-027 section 8): the container a panel opens in, the choices kept in the +// project, the floating window, detaching and attaching, and the discovery of the watches. The page in a real window, tab +// or frame is checked in test/web/developer-specs.mjs. +import {detachedContainer, containerFor, hostReasons, parsePreferences, formatPreferences, readPreferences, preferencesPath, + createInspectorHost, defaultInspectorRect, panelTitle, claimHostIdentifier, hostKey, prepareInspectors, + preferencesStore, applyPreferenceChanges} from '../../../js/developer/environment/inspector-host.mjs'; +import {readDescriptor, readPage, listWatches, listingAttempts, reconcile, watchOpener, createWatchDiscovery, renderWatches, pageBridge, attachAgain, + watchesFunction, reloadWhenRestored} from '../../../js/developer/environment/inspector.mjs'; +import {inspectorChannel, inspectorPanels} from '../../../js/developer/environment/menu.mjs'; +import {LineEditor} from '../../../js/developer/environment/terminal.mjs'; +import {memoryBridge} from '../memory-bridge.mjs'; + +const encode = text => new TextEncoder().encode(text); + +/** A registry of watches in memory, answering webfront.inspector.watches as C++ does (pages of `size`, revision, changed). */ +function memoryWatches(size = 200) { + const watches = new Map(); + let revision = 1, nextId = 1; + const calls = []; + return { + calls, + add(name, kind = 'integer') { + const id = nextId++; + watches.set(id, [id, name, kind, `app.cpp:${id}`, false]); + ++revision; + return id; + }, + remove(id) { + if (watches.delete(id)) ++revision; + }, + answer(known, after, count) { + calls.push([known, after, count]); + const served = [...watches.values()].filter(([id]) => id > after).slice(0, Math.min(count, size)); + const more = [...watches.values()].filter(([id]) => id > after).length > served.length; + return [served, more && count ? served.at(-1)[0] : 0, revision, known !== revision]; + }, + }; +} + +describe('The inspectors', () => { + describe('containers', () => { + it('detach a panel to a native window, else to a tab of the system browser, else nowhere', () => { + const containers = (secondaryWindow, host, newConnections) => ({secondaryWindow, host, newConnections}); + expect(detachedContainer(containers(true, true, false), {embedded: true})).toBe('window'); + expect(detachedContainer(containers(true, true, true), {embedded: false})).toBe('window'); + // A tab only for a page of the system browser, and only when new loopback connections are admitted. + expect(detachedContainer(containers(false, true, true), {embedded: false})).toBe('tab'); + expect(detachedContainer(containers(false, true, true), {embedded: true})).toBeNull(); + expect(detachedContainer(containers(false, true, false), {embedded: false})).toBeNull(); + // Nothing for a page that is not admitted, nor without an answer. + expect(detachedContainer(containers(false, false, true), {embedded: false})).toBeNull(); + expect(detachedContainer(null)).toBeNull(); + }); + + it('open a panel detached only when the project keeps it so and a detached container exists', () => { + const admitted = {secondaryWindow: false, host: true, newConnections: false}; + const detached = new Set(['cpp.watches']); + expect(containerFor('cpp.watches', {containers: admitted, embedded: true, detached})).toBe('floating'); + expect(containerFor('cpp.watches', {containers: {...admitted, secondaryWindow: true}, embedded: true, detached})).toBe('window'); + expect(containerFor('cpp.functions', {containers: {...admitted, secondaryWindow: true}, embedded: true, detached})).toBe('floating'); + expect(containerFor('cpp.watches', {containers: {...admitted, newConnections: true}, embedded: false, detached})).toBe('tab'); + expect(containerFor('cpp.watches', {containers: null, embedded: true, detached})).toBeNull(); + }); + }); + + describe('remembered choices', () => { + it('keep the detached panels and the floating window\'s place, and ignore what they do not know', () => { + const text = formatPreferences({detached: new Set(['cpp.watches', 'typescript.bridge']), rect: {x: 1, y: 2, width: 300, height: 200}}); + expect(JSON.parse(text)).toEqual({format: 1, detached: ['cpp.watches', 'typescript.bridge'], rect: {x: 1, y: 2, width: 300, height: 200}}); + const read = parsePreferences(text); + expect([...read.detached]).toEqual(['cpp.watches', 'typescript.bridge']); + expect(read.rect).toEqual({x: 1, y: 2, width: 300, height: 200}); + const odd = parsePreferences(JSON.stringify({format: 1, detached: ['nothing', 'cpp.browsers'], rect: {x: 0, y: 0, width: -1, height: 2}})); + expect([...odd.detached]).toEqual(['cpp.browsers']); + expect(odd.rect).toBeNull(); + for (const bad of ['', 'nope', JSON.stringify({format: 2, detached: ['cpp.watches']}), JSON.stringify({format: 1, detached: 'cpp.watches'})]) + expect([...parsePreferences(bad).detached]).toEqual([]); + }); + + it('are read from the project, and empty without a file', async () => { + const {bridge} = memoryBridge(new Map([[preferencesPath, encode(formatPreferences({detached: new Set(['cpp.watches']), rect: null}))]])); + expect([...(await readPreferences(bridge)).detached]).toEqual(['cpp.watches']); + expect([...(await readPreferences(memoryBridge().bridge)).detached]).toEqual([]); + }); + }); + + describe('choices kept by several pages', () => { + it('apply the changes of a page to the choices of the project, not its whole copy', () => { + const current = {detached: new Set(['cpp.watches']), rect: {x: 1, y: 2, width: 300, height: 200}}; + const next = applyPreferenceChanges(current, {panels: new Map([['cpp.functions', true]]), rect: undefined}); + expect([...next.detached].sort()).toEqual(['cpp.functions', 'cpp.watches']); + expect(next.rect).toEqual(current.rect); + expect([...applyPreferenceChanges(current, {panels: new Map([['cpp.watches', false]]), rect: null}).detached]).toEqual([]); + }); + + it('keep what another page wrote meanwhile, and write a detach at once', async () => { + jasmine.clock().install(); + try { + const {bridge, storage} = memoryBridge(); + const first = preferencesStore(bridge), second = preferencesStore(bridge); + // The first page detaches Watches: written at once, without waiting for the delay of the places. + first.detached('cpp.watches', true); + await first.saved(); + expect([...parsePreferences(new TextDecoder().decode(storage.get(preferencesPath))).detached]).toEqual(['cpp.watches']); + // The second page, which read the file before, moves its window: the detach of the first is kept. + second.place({x: 5, y: 6, width: 400, height: 300}); + jasmine.clock().tick(300); + await second.saved(); + const kept = parsePreferences(new TextDecoder().decode(storage.get(preferencesPath))); + expect([...kept.detached]).toEqual(['cpp.watches']); + expect(kept.rect).toEqual({x: 5, y: 6, width: 400, height: 300}); + } finally { jasmine.clock().uninstall(); } + }); + + it('rejects a failed save and can save again from a later action', async () => { + const {bridge: memory, storage} = memoryBridge(); + const calls = []; + let connected = false; + const bridge = {cppFunction: name => async (...args) => { + calls.push(name); + if (name === 'webfront.inspector.savePreferences' && !connected) throw new Error('Disconnected'); + return memory.cppFunction(name)(...args); + }}; + const store = preferencesStore(bridge); + store.detached('cpp.watches', true); + await expectAsync(store.saved()).toBeRejectedWithError('Disconnected'); + expect(storage.has(preferencesPath)).toBeFalse(); + // One read gives the file (absent here) and the token of exactly what it read. + expect(calls).toEqual(['webfront.inspector.readPreferences', 'webfront.inspector.savePreferences']); + expect(storage.has(preferencesPath)).toBeFalse(); + connected = true; + store.detached('cpp.watches', true); + await store.saved(); + expect([...parsePreferences(new TextDecoder().decode(storage.get(preferencesPath))).detached]).toEqual(['cpp.watches']); + }); + + it('do not commit over choices that could not be read', async () => { + const others = encode(formatPreferences({detached: new Set(['cpp.functions']), rect: {x: 1, y: 2, width: 300, height: 200}})); + const {bridge: memory, storage} = memoryBridge(new Map([[preferencesPath, others]])); + let failing = true; + const bridge = {cppFunction: name => async (...args) => { + if (name === 'webfront.inspector.readPreferences' && failing) throw new Error('Cannot read project file: ' + preferencesPath); + return memory.cppFunction(name)(...args); + }}; + const store = preferencesStore(bridge); + store.detached('cpp.watches', true); + await expectAsync(store.saved()).toBeRejectedWithError(/Cannot read project file/); + expect(storage.get(preferencesPath)).toBe(others); + // Shown, they are empty: the inspectors still open. + expect([...(await readPreferences(bridge)).detached]).toEqual([]); + failing = false; + store.detached('cpp.watches', true); + await store.saved(); + expect([...parsePreferences(new TextDecoder().decode(storage.get(preferencesPath))).detached].sort()) + .toEqual(['cpp.functions', 'cpp.watches']); + }); + + it('keep a change whose save failed, and write it with the next one without asking for it again', async () => { + const {bridge: memory, storage} = memoryBridge(); + let connected = false; + const bridge = {cppFunction: name => async (...args) => { + if (name === 'webfront.inspector.savePreferences' && !connected) throw new Error('Disconnected'); + return memory.cppFunction(name)(...args); + }}; + const store = preferencesStore(bridge); + store.detached('cpp.watches', true); + await expectAsync(store.saved()).toBeRejectedWithError('Disconnected'); + connected = true; + // Only a move after the reconnection: the detach that failed is written with it. + store.place({x: 5, y: 6, width: 400, height: 300}); + await store.saved(); + const written = parsePreferences(new TextDecoder().decode(storage.get(preferencesPath))); + expect([...written.detached]).toEqual(['cpp.watches']); + expect(written.rect).toEqual({x: 5, y: 6, width: 400, height: 300}); + }); + + it('let a newer change of a panel win over the failed one it replaces', async () => { + const {bridge: memory, storage} = memoryBridge(); + let connected = false; + const bridge = {cppFunction: name => async (...args) => { + if (name === 'webfront.inspector.savePreferences' && !connected) throw new Error('Disconnected'); + return memory.cppFunction(name)(...args); + }}; + const store = preferencesStore(bridge); + store.detached('cpp.watches', true); + await expectAsync(store.saved()).toBeRejectedWithError('Disconnected'); + connected = true; + store.detached('cpp.watches', false); // attached again since: the newer change is the one written + await store.saved(); + expect([...parsePreferences(new TextDecoder().decode(storage.get(preferencesPath))).detached]).toEqual([]); + }); + + it('fall back to the token then the file with a library that cannot read them together', async () => { + const {bridge: memory, storage} = memoryBridge(new Map([[preferencesPath, encode(formatPreferences({detached: new Set(['cpp.functions']), rect: null}))]])); + const calls = []; + const bridge = {cppFunction: name => async (...args) => { + calls.push(name); + if (name === 'webfront.inspector.readPreferences') + throw Object.assign(new Error("C++ function 'webfront.inspector.readPreferences' was not found"), {code: 'webfront.notFound'}); + return memory.cppFunction(name)(...args); + }}; + const store = preferencesStore(bridge); + store.detached('cpp.watches', true); + await store.saved(); + expect(calls.slice(0, 3)).toEqual(['webfront.inspector.readPreferences', 'webfront.developer.state', 'webfront.developer.read']); + expect([...parsePreferences(new TextDecoder().decode(storage.get(preferencesPath))).detached].sort()).toEqual(['cpp.functions', 'cpp.watches']); + }); + + it('write again a change whose file changed between its read and its commit', async () => { + const {bridge: memory, storage} = memoryBridge(); + let raced = false; + const bridge = {cppFunction: name => async (...args) => { + // Another page commits between this page's read and its commit, once. + if (name === 'webfront.inspector.savePreferences' && !raced) { + raced = true; + storage.set(preferencesPath, encode(formatPreferences({detached: new Set(['typescript.bridge']), rect: null}))); + } + return memory.cppFunction(name)(...args); + }}; + const store = preferencesStore(bridge); + store.detached('cpp.watches', true); + await store.saved(); + expect(raced).toBeTrue(); + expect([...parsePreferences(new TextDecoder().decode(storage.get(preferencesPath))).detached].sort()) + .toEqual(['cpp.watches', 'typescript.bridge']); + }); + }); + + describe('host', () => { + const hosts = []; + // A host of this page on a project in memory, whose inspector functions answer as `answers` says. + async function testHost({containers, embedded = true, files = new Map(), openWindow = async () => {}, closeWindow = async () => true, + windowOpen = () => ({}), hostId = 'host-a'} = {}) { + const {bridge: projectBridge, storage} = memoryBridge(files); + const calls = []; + const bridge = {cppFunction: name => async (...args) => { + calls.push([name, ...args]); + if (name === 'webfront.inspector.openWindow') return openWindow(...args); + if (name === 'webfront.inspector.closeWindow') return closeWindow(...args); + if (name === 'webfront.inspector.embedded') return embedded; + return projectBridge.cppFunction(name)(...args); + }}; + const opened = []; + const host = await createInspectorHost({bridge, page: document, inspectorUrl: '/webfront/developer/environment/inspector.html', + access: Promise.resolve({containers, reason: ''}), hostId, windowOpen: (url, name) => { opened.push([url, name]); return windowOpen(url, name); }}); + hosts.push(host); + return {host, bridge, calls, opened, storage}; + } + afterEach(() => { + for (const host of hosts.splice(0)) { + host.close(); + host.channel?.close(); + host.panel.remove(); + } + document.head.querySelectorAll('style').forEach(style => { if (style.textContent.includes('.webfront-inspector-window')) style.remove(); }); + delete window.webfrontInspectorHost; + }); + const admitted = (secondaryWindow, newConnections = false) => ({secondaryWindow, host: true, newConnections}); + const frameUrl = host => new URL(host.frame.getAttribute('src'), location.href); + + it('shows a panel in a floating window whose frame borrows this page\'s bridge', async () => { + const {host, bridge} = await testHost({containers: admitted(false)}); + expect(await host.open('cpp.watches')).toBe('floating'); + expect(host.panel.hidden).toBeFalse(); + expect(host.panel.getAttribute('role')).toBe('dialog'); + expect(host.bar.textContent).toContain(panelTitle('cpp.watches')); + expect(frameUrl(host).pathname).toBe('/webfront/developer/environment/inspector.html'); + expect(frameUrl(host).searchParams.get('panel')).toBe('cpp.watches'); + expect(frameUrl(host).searchParams.get('frame')).toBe('1'); + expect(window.webfrontInspectorHost).toBe(host); + expect(host.bridge).toBe(bridge); // the bridge its frame borrows + // Inside the viewport, at its default place. + const rect = host.panel.getBoundingClientRect(); + expect(rect.left).toBeGreaterThanOrEqual(0); + expect(rect.right).toBeLessThanOrEqual(document.documentElement.clientWidth + 1); + // Another panel replaces the shown one; closing hides the window and unloads its frame. + await host.open('cpp.functions'); + expect(frameUrl(host).searchParams.get('panel')).toBe('cpp.functions'); + host.closeButton.click(); + expect(host.panel.hidden).toBeTrue(); + expect(host.frame.hasAttribute('src')).toBeFalse(); + }); + + it('greys Detach with the reason when no detached container would reach the inspectors', async () => { + const {host, calls, opened} = await testHost({containers: admitted(false, true), embedded: true}); + await host.open('cpp.watches'); + expect(host.detachButton.getAttribute('aria-disabled')).toBe('true'); + expect(host.detachButton.title).toBe(hostReasons.noDetached); + host.detachButton.click(); + await host.saved(); + expect(calls.some(([name]) => name === 'webfront.inspector.openWindow')).toBeFalse(); + expect(opened).toEqual([]); + expect(host.panel.hidden).toBeFalse(); + }); + + it('detaches a panel to a native secondary window, and opens it there next time', async () => { + const {host, calls, storage} = await testHost({containers: admitted(true)}); + await host.open('cpp.watches'); + expect(host.detachButton.getAttribute('aria-disabled')).toBe('false'); + expect(await host.detach('cpp.watches')).toBe('window'); + const [, panel, hostId, width, height] = calls.find(([name]) => name === 'webfront.inspector.openWindow'); + expect(panel).toBe('cpp.watches'); + expect(hostId).toBe(host.id); + expect(width).toBeGreaterThan(0); + expect(height).toBeGreaterThan(0); + expect(host.panel.hidden).toBeTrue(); + await host.saved(); + expect([...parsePreferences(new TextDecoder().decode(storage.get(preferencesPath))).detached]).toEqual(['cpp.watches']); + // The project remembers it: the next opening goes to the window again (which C++ brings to the front). + calls.length = 0; + expect(await host.open('cpp.watches')).toBe('window'); + expect(calls.filter(([name]) => name === 'webfront.inspector.openWindow').length).toBe(1); + }); + + it('keeps a panel in the floating window when its native window fails, and says why', async () => { + const {host} = await testHost({containers: admitted(true), openWindow: async () => { throw new Error('no session'); }}); + expect(await host.detach('cpp.watches')).toBe('floating'); + expect(host.panel.hidden).toBeFalse(); + expect(host.notice.hidden).toBeFalse(); + expect(host.notice.textContent).toContain('no session'); + }); + + it('detaches a panel to a tab of the system browser, and falls back to the floating window when it is blocked', async () => { + let blocked = true; + const {host, opened} = await testHost({containers: admitted(false, true), embedded: false, windowOpen: () => blocked ? null : {}}); + expect(await host.detach('cpp.watches')).toBe('floating'); + expect(opened.length).toBe(1); + const [url, name] = opened[0]; + expect(new URL(url).searchParams.get('panel')).toBe('cpp.watches'); + expect(new URL(url).searchParams.has('frame')).toBeFalse(); + expect(new URL(url).searchParams.get('host')).toBe('host-a'); + expect(name).toBe('webfront-inspector-host-a-cpp-watches'); + expect(host.panel.hidden).toBeFalse(); + expect(host.notice.textContent).toContain(hostReasons.blocked); + const retry = host.notice.querySelector('button'); + expect(retry.hidden).toBeFalse(); + blocked = false; + retry.click(); + await new Promise(resolve => setTimeout(resolve)); + expect(opened.length).toBe(2); + expect(host.panel.hidden).toBeTrue(); + }); + + it('opens a tab of its own for each page, even for the same panel', async () => { + const {host: firstHost, opened: first} = await testHost({containers: admitted(false, true), embedded: false, hostId: 'host-a'}); + const {host: second, opened: other} = await testHost({containers: admitted(false, true), embedded: false, hostId: 'host-b'}); + await firstHost.detach('cpp.watches'); + await second.detach('cpp.watches'); + expect(first[0][1]).not.toBe(other[0][1]); + expect(new URL(other[0][0]).searchParams.get('host')).toBe('host-b'); + }); + + it('never opens a tab from an embedded view', async () => { + const {host, opened} = await testHost({containers: admitted(false, true), embedded: true}); + expect(await host.detach('cpp.watches')).toBeNull(); + expect(opened).toEqual([]); + }); + + it('opens nothing for a page that is not admitted', async () => { + const {host} = await testHost({containers: null}); + expect(await host.open('cpp.watches')).toBeNull(); + expect(host.panel.hidden).toBeTrue(); + }); + + it('attaches a detached panel again when its window asks, and answers it', async () => { + const {host, storage} = await testHost({containers: admitted(true), files: new Map([[preferencesPath, + encode(formatPreferences({detached: new Set(['cpp.watches']), rect: null}))]])}); + const inspector = new BroadcastChannel(inspectorChannel); + try { + const answered = new Promise(resolve => inspector.addEventListener('message', ({data}) => { + if (data?.type === 'attached') resolve(data.id); + })); + inspector.postMessage({type: 'attach', panel: 'cpp.watches', host: 'host-a', id: 'request-1'}); + expect(await answered).toBe('request-1'); + expect(host.shownPanel).toBe('cpp.watches'); + expect(host.panel.hidden).toBeFalse(); + await host.saved(); + expect([...parsePreferences(new TextDecoder().decode(storage.get(preferencesPath))).detached]).toEqual([]); + } finally { inspector.close(); } + }); + + it('attaches a panel again only in the page that detached it', async () => { + const {host: mine} = await testHost({containers: admitted(true), hostId: 'host-a'}); + const {host: other, storage: otherStorage} = await testHost({containers: admitted(true), hostId: 'host-b'}); + const inspector = new BroadcastChannel(inspectorChannel); + try { + const answers = []; + inspector.addEventListener('message', ({data}) => { if (data?.type === 'attached') answers.push(data.id); }); + inspector.postMessage({type: 'attach', panel: 'cpp.watches', host: 'host-a', id: 'request-a'}); + await new Promise(resolve => setTimeout(resolve, 50)); + expect(answers).toEqual(['request-a']); + expect(mine.shownPanel).toBe('cpp.watches'); + expect(other.shownPanel).toBeNull(); + expect(other.panel.hidden).toBeTrue(); + // A request without a host, or for a page that is gone, is taken by nobody. + inspector.postMessage({type: 'attach', panel: 'cpp.functions', id: 'request-none'}); + inspector.postMessage({type: 'attach', panel: 'cpp.functions', host: 'host-gone', id: 'request-gone'}); + await new Promise(resolve => setTimeout(resolve, 50)); + expect(answers).toEqual(['request-a']); + expect(mine.shownPanel).toBe('cpp.watches'); + await other.saved(); + expect(otherStorage.has(preferencesPath)).toBeFalse(); + } finally { inspector.close(); } + }); + + // The window that asked to be attached again, on the channel: resolves with the host's answer. + async function askAttach(panel, request) { + const inspector = new BroadcastChannel(inspectorChannel); + try { + return await new Promise(resolve => { + inspector.addEventListener('message', ({data}) => { if (data?.type === 'attached' && data.id === request) resolve(data); }); + inspector.postMessage({type: 'attach', panel, host: 'host-a', id: request}); + }); + } finally { inspector.close(); } + } + + it('closes the native window of a panel attached again itself, before a new detach opens one', async () => { + let closed; + const {host, calls} = await testHost({containers: admitted(true), closeWindow: () => new Promise(resolve => { closed = resolve; })}); + await host.detach('cpp.watches'); + const answer = askAttach('cpp.watches', 'request-close'); // answered once the close is over + await new Promise(resolve => setTimeout(resolve, 20)); + expect(host.preferences.detached.has('cpp.watches')).toBeFalse(); + // The user detaches it again while the close is in progress: the window opens only once the close is over. + const detaching = host.detach('cpp.watches'); + await new Promise(resolve => setTimeout(resolve)); + const names = () => calls.map(([name]) => name).filter(name => name.endsWith('Window')); + expect(names()).toEqual(['webfront.inspector.openWindow', 'webfront.inspector.closeWindow']); + closed(true); + expect((await answer).closer).toBe('host'); + expect(await detaching).toBe('window'); + expect(names()).toEqual(['webfront.inspector.openWindow', 'webfront.inspector.closeWindow', 'webfront.inspector.openWindow']); + expect(host.preferences.detached.has('cpp.watches')).toBeTrue(); + }); + + it('lets the native window close itself when the host could not close it', async () => { + for (const closeWindow of [async () => false, async () => { throw new Error('no session'); }]) { + const {host} = await testHost({containers: admitted(true), closeWindow}); + await host.detach('cpp.watches'); + // The window waits for the host only when the host closed it: else it would stay open. + expect((await askAttach('cpp.watches', `request-${hosts.length}`)).closer).toBe('self'); + expect(host.shownPanel).toBe('cpp.watches'); + host.close(); + host.channel?.close(); + } + }); + + it('closes a tab it opened when its panel is attached again, and opens a new one on the next detach', async () => { + const tabs = []; + const {host, opened} = await testHost({containers: admitted(false, true), embedded: false, windowOpen: () => { + const tab = {closed: false, close() { this.closed = true; }}; + tabs.push(tab); + return tab; + }}); + await host.detach('cpp.watches'); + expect((await askAttach('cpp.watches', 'request-tab')).closer).toBe('host'); + expect(tabs[0].closed).toBeTrue(); + expect(await host.detach('cpp.watches')).toBe('tab'); + expect(tabs[1].closed).toBeFalse(); + expect(opened.map(([, name]) => name)).toEqual(['webfront-inspector-host-a-cpp-watches', 'webfront-inspector-host-a-cpp-watches']); + }); + + it('lets a tab it did not open close itself, and never reuses that tab for a new detach', async () => { + // The tab was opened before this page was reloaded: this page has no reference to it. + const {host, opened} = await testHost({containers: admitted(false, true), embedded: false, files: new Map([[preferencesPath, + encode(formatPreferences({detached: new Set(['cpp.watches']), rect: null}))]])}); + expect((await askAttach('cpp.watches', 'request-orphan')).closer).toBe('self'); + expect(await host.detach('cpp.watches')).toBe('tab'); + expect(opened.map(([, name]) => name)).toEqual(['webfront-inspector-host-a-cpp-watches-1']); + }); + + // The Web Locks of an origin, shared by the pages of a test: a page holds a lock until it is released. + function originLocks() { + const held = new Set(); + return {held, locks: {request: async (name, options, callback) => { + const available = !held.has(name); + if (available) held.add(name); + const result = callback(available ? {name} : null); + if (available) await result; + return result; + }}}; + } + const pageOf = ({locks, store = new Map()}) => ({crypto, navigator: {locks}, + sessionStorage: {getItem: key => store.get(key) ?? null, setItem: (key, value) => store.set(key, value)}, store}); + + it('keeps a page\'s identifier across a reload of its tab', async () => { + const first = originLocks(), store = new Map(); + const id = await claimHostIdentifier(pageOf({locks: first.locks, store})); + expect(id).toMatch(/^[A-Za-z0-9_-]{1,64}$/); + expect(store.get(hostKey)).toBe(id); + // The reloaded page: the old one released its lock as it went away. + const reloaded = originLocks(); + expect(await claimHostIdentifier(pageOf({locks: reloaded.locks, store}))).toBe(id); + }); + + it('gives a page opened by another one, whose session storage is a copy, an identifier of its own', async () => { + const origin = originLocks(), store = new Map(); + const opener = await claimHostIdentifier(pageOf({locks: origin.locks, store})); + const copied = new Map(store); + const opened = await claimHostIdentifier(pageOf({locks: origin.locks, store: copied})); + expect(opened).not.toBe(opener); + expect(copied.get(hostKey)).toBe(opened); + expect(store.get(hostKey)).toBe(opener); + expect(origin.held.size).toBe(2); + }); + + it('takes a new identifier at each load without Web Locks or storage, and never keeps an invalid one', async () => { + const store = new Map([[hostKey, 'bad/value']]); + const view = {crypto, sessionStorage: {getItem: key => store.get(key) ?? null, setItem: (key, value) => store.set(key, value)}}; + const first = await claimHostIdentifier(view); + expect(first).toMatch(/^[0-9a-f]{24}$/); + expect(await claimHostIdentifier(view)).not.toBe(first); + const noStorage = {crypto, get sessionStorage() { throw new Error('denied'); }}; + expect(await claimHostIdentifier(noStorage)).toMatch(/^[0-9a-f]{24}$/); + }); + + it('listens for its detached panels as soon as the page reaches the inspectors, before any panel is opened', async () => { + // The page was reloaded: a window detached before the reload carries its identifier and asks to be attached. + const {bridge} = memoryBridge(); + const fullBridge = {cppFunction: name => name === 'webfront.inspector.embedded' ? async () => true : bridge.cppFunction(name)}; + const options = {bridge: fullBridge, page: document, inspectorUrl: '/webfront/developer/environment/inspector.html', + access: Promise.resolve({containers: admitted(true), reason: ''}), hostId: 'reloaded', windowOpen: () => ({})}; + const inspectors = prepareInspectors(options); + const host = await new Promise(resolve => { + const wait = () => inspectors.host() ? resolve(inspectors.host()) : setTimeout(wait); + wait(); + }); + hosts.push(host); + const inspector = new BroadcastChannel(inspectorChannel); + try { + const answered = new Promise(resolve => inspector.addEventListener('message', ({data}) => { + if (data?.type === 'attached') resolve(data.id); + })); + inspector.postMessage({type: 'attach', panel: 'cpp.watches', host: 'reloaded', id: 'after-reload'}); + expect(await answered).toBe('after-reload'); + expect(host.shownPanel).toBe('cpp.watches'); + } finally { inspector.close(); } + }); + + it('makes no host for a page that does not reach the inspectors until a panel is asked for', async () => { + const made = []; + const inspectors = prepareInspectors({access: Promise.resolve({containers: null, reason: 'no'}), create: options => { + made.push(options); + return Promise.resolve({open: panel => panel}); + }}); + await new Promise(resolve => setTimeout(resolve)); + expect(inspectors.host()).toBeNull(); + expect(await inspectors.open('cpp.watches')).toBe('cpp.watches'); + expect(made.length).toBe(1); + }); + + it('creates the host again on the next panel after a failed creation', async () => { + let attempts = 0; + const inspectors = prepareInspectors({access: Promise.resolve({containers: admitted(true), reason: ''}), create: async () => { + if (++attempts === 1) throw new Error('no host'); + return {open: panel => panel}; + }}); + await new Promise(resolve => setTimeout(resolve)); // the creation started by the access fails + expect(attempts).toBe(1); + expect(inspectors.host()).toBeNull(); + expect(await inspectors.open('cpp.watches')).toBe('cpp.watches'); + expect(attempts).toBe(2); + }); + + it('does not show a panel again when its native window fails after another action', async () => { + let fail; + const pending = new Promise((resolve, reject) => { fail = reject; }); + const {host} = await testHost({containers: admitted(true), openWindow: () => pending}); + await host.open('cpp.watches'); + const detaching = host.detach('cpp.watches'); + await host.open('cpp.functions'); // the user opens another panel meanwhile + fail(new Error('no session')); + expect(await detaching).toBe('floating'); + expect(host.shownPanel).toBe('cpp.functions'); + expect(host.notice.hidden).toBeTrue(); + }); + + it('keeps a panel attached while its detach was pending, and closes the native window that opened late', async () => { + let opened; + const pending = new Promise(resolve => { opened = resolve; }); + const {host, calls} = await testHost({containers: admitted(true), openWindow: () => pending}); + await host.open('cpp.watches'); + const detaching = host.detach('cpp.watches'); + host.attach('cpp.watches'); // the panel is attached again before C++ answered + expect(calls.some(([name]) => name === 'webfront.inspector.closeWindow')).toBeFalse(); + opened(); // the native window opens after all + expect(await detaching).toBe('floating'); + expect(host.panel.hidden).toBeFalse(); + expect(host.shownPanel).toBe('cpp.watches'); + expect(host.preferences.detached.has('cpp.watches')).toBeFalse(); + // Shown once: the stale native window is closed, the floating one stays. + expect(calls.filter(([name]) => name === 'webfront.inspector.closeWindow')).toEqual([['webfront.inspector.closeWindow', 'cpp.watches', 'host-a']]); + }); + + it('closes the native window that opens after the user closed the floating window', async () => { + let opened; + const {host, calls} = await testHost({containers: admitted(true), openWindow: () => new Promise(resolve => { opened = resolve; })}); + await host.open('cpp.watches'); + const detaching = host.detach('cpp.watches'); + host.closeButton.click(); // the user closes the inspector before C++ answered + opened(); + await detaching; + expect(host.panel.hidden).toBeTrue(); + expect(calls.filter(([name]) => name === 'webfront.inspector.closeWindow')).toEqual([['webfront.inspector.closeWindow', 'cpp.watches', 'host-a']]); + // The panel stays remembered detached: the next opening goes to its window. + expect(host.preferences.detached.has('cpp.watches')).toBeTrue(); + }); + + it('closes every native window still opening for the panel when the floating window is closed, after Detach clicked twice', async () => { + const answers = []; + const {host, calls} = await testHost({containers: admitted(true), openWindow: () => new Promise(resolve => answers.push(resolve))}); + await host.open('cpp.watches'); + const first = host.detach('cpp.watches'); + const second = host.detach('cpp.watches'); + expect(answers.length).toBe(2); + host.closeButton.click(); + answers[0](); // the first opening answers after the close too + answers[1](); + await Promise.all([first, second]); + expect(host.panel.hidden).toBeTrue(); + // Both aimed at the panel's one native window: the latest opening closes it. + expect(calls.filter(([name]) => name === 'webfront.inspector.closeWindow')).toEqual([['webfront.inspector.closeWindow', 'cpp.watches', 'host-a']]); + }); + + it('closes the window once every cancelled opening has answered, whatever their order', async () => { + const answers = []; + const {host, calls} = await testHost({containers: admitted(true), openWindow: () => new Promise(resolve => answers.push(resolve))}); + await host.open('cpp.watches'); + const first = host.detach('cpp.watches'); + const second = host.detach('cpp.watches'); + host.closeButton.click(); // cancels both + answers[1](); // the latest opening answers first: the first one may still create the window + await second; + expect(calls.some(([name]) => name === 'webfront.inspector.closeWindow')).toBeFalse(); + answers[0](); + expect(await first).toBe('floating'); + expect(calls.filter(([name]) => name === 'webfront.inspector.closeWindow')).toEqual([['webfront.inspector.closeWindow', 'cpp.watches', 'host-a']]); + expect(host.panel.hidden).toBeTrue(); + }); + + it('does not let a cancelled opening close the window that a later detach of the panel reuses', async () => { + const answers = []; + const {host, calls} = await testHost({containers: admitted(true), openWindow: () => new Promise(resolve => answers.push(resolve))}); + await host.open('cpp.watches'); + const cancelled = host.detach('cpp.watches'); + host.closeButton.click(); // cancels the first opening + const again = host.detach('cpp.watches'); // the user detaches it again at once + expect(answers.length).toBe(2); + answers[0](); // the cancelled opening answers first + await cancelled; + expect(calls.some(([name]) => name === 'webfront.inspector.closeWindow')).toBeFalse(); + answers[1](); + expect(await again).toBe('window'); + expect(calls.some(([name]) => name === 'webfront.inspector.closeWindow')).toBeFalse(); + expect(host.panel.hidden).toBeTrue(); + }); + + it('keeps the native window when another panel is opened in the floating window meanwhile', async () => { + let opened; + const {host, calls} = await testHost({containers: admitted(true), openWindow: () => new Promise(resolve => { opened = resolve; })}); + await host.open('cpp.watches'); + const detaching = host.detach('cpp.watches'); + await host.open('cpp.functions'); + host.closeButton.click(); // closes Functions, not the panel being detached + opened(); + expect(await detaching).toBe('window'); + expect(calls.some(([name]) => name === 'webfront.inspector.closeWindow')).toBeFalse(); + }); + + it('keeps the native window of a panel detached again while its first opening was pending', async () => { + const answers = []; + const {host, calls} = await testHost({containers: admitted(true), openWindow: () => new Promise(resolve => answers.push(resolve))}); + await host.open('cpp.watches'); + const first = host.detach('cpp.watches'); + host.attach('cpp.watches'); + const second = host.detach('cpp.watches'); // detached again: the window that opens is wanted + answers.forEach(resolve => resolve()); + expect(await first).toBe('window'); + expect(await second).toBe('window'); + expect(calls.some(([name]) => name === 'webfront.inspector.closeWindow')).toBeFalse(); + expect(host.panel.hidden).toBeTrue(); + }); + + it('says in the terminal that a panel could not open, above the line being edited', () => { + let output = ''; + const editor = new LineEditor({write: text => { output += text; }, run: async () => {}}); + editor.showPrompt(); + editor.handle('ls'); + output = ''; + editor.notice('The inspector could not open: no host'); + // The edited line is erased, the notice printed on its own line, then the prompt and the line drawn again. + expect(output.startsWith('\r\x1b[JThe inspector could not open: no host\r\n> ')).toBeTrue(); + expect(output).toContain('ls'); + }); + + it('draws the line again after a notice received while a completion is pending', async () => { + let output = '', answer; + const ran = []; + const editor = new LineEditor({write: text => { output += text; }, run: async line => { ran.push(line); }, + complete: () => new Promise(resolve => { answer = resolve; })}); + editor.showPrompt(); + editor.handle('ls'); + editor.handle('\t'); // the completion is pending + output = ''; + editor.notice('The inspector could not open: no host'); + expect(output.startsWith('\r\x1b[JThe inspector could not open: no host\r\n> ')).toBeTrue(); + expect(output).toContain('ls'); + answer({candidates: []}); // no candidate: the completion draws nothing + await new Promise(resolve => setTimeout(resolve)); + editor.handle('\r'); + await editor.whenIdle(); + expect(ran).toEqual(['ls']); + }); + + it('opens at a default place inside a small viewport', () => { + const rect = defaultInspectorRect({width: 400, height: 300}); + expect(rect.x + rect.width).toBeLessThanOrEqual(400); + expect(rect.y + rect.height).toBeLessThanOrEqual(300); + }); + }); + + describe('page', () => { + it('borrows the bridge of its host page in a frame, without loading WebFront.js', async () => { + const bridge = {ready: Promise.resolve()}; + // The host's bridge, not the page's global one: the environment may be mounted with another bridge. + const global = {ready: Promise.resolve()}; + const view = {parent: {webFront: global, webfrontInspectorHost: {bridge}}, document}; + expect(await pageBridge(view, {frame: true})).toBe(bridge); + // Without a host, the global bridge of the page is never borrowed. + await expectAsync(pageBridge({parent: {webFront: global}, document}, {frame: true})).toBeRejectedWithError(/borrow/); + await expectAsync(pageBridge({parent: {}, document}, {frame: true})).toBeRejectedWithError(/borrow/); + }); + + it('asks the main page to attach it again, and stays open when nobody answers', async () => { + const status = document.createElement('p'); + const closed = []; + const view = {BroadcastChannel, setTimeout: (run, delay) => setTimeout(run, delay), clearTimeout: id => clearTimeout(id), opener: {}, close: () => closed.push(true)}; + const host = new BroadcastChannel(inspectorChannel); + host.addEventListener('message', ({data}) => { + if (data?.type === 'attach' && data.host === 'host-a') host.postMessage({type: 'attached', id: data.id}); + }); + try { + expect(await attachAgain(view, null, 'cpp.watches', status, {host: 'host-b', wait: 50})).toBeFalse(); // another page + expect(closed).toEqual([]); + expect(await attachAgain(view, null, 'cpp.watches', status, {host: 'host-a'})).toBeTrue(); + } finally { host.close(); } + expect(closed).toEqual([true]); + expect(await attachAgain(view, null, 'cpp.watches', status, {host: 'host-a', wait: 50})).toBeFalse(); + expect(status.textContent).toContain('did not answer'); + expect(closed.length).toBe(1); + }); + + it('closes a tab once the page that opened it is gone, and watches nothing without an opener', () => { + jasmine.clock().install(); + try { + const opener = {closed: false}, closed = []; + const handlers = []; + const view = {opener, setInterval: (run, delay) => setInterval(run, delay), clearInterval: id => clearInterval(id), + close: () => closed.push(true), addEventListener: (name, handler) => handlers.push([name, handler])}; + expect(watchOpener(view, 1000)).not.toBeNull(); + jasmine.clock().tick(1000); + expect(closed).toEqual([]); + opener.closed = true; + jasmine.clock().tick(1000); + expect(closed).toEqual([true]); + handlers.find(([name]) => name === 'pagehide')[1](); + expect(watchOpener({...view, opener: null})).toBeNull(); + } finally { jasmine.clock().uninstall(); } + }); + + it('loads itself again when the browser restores it from its back-forward cache', () => { + const handlers = [], reloads = []; + const view = {addEventListener: (name, handler) => handlers.push([name, handler]), location: {reload: () => reloads.push(true)}}; + reloadWhenRestored(view); + const shown = handlers.find(([name]) => name === 'pageshow')[1]; + shown({persisted: false}); // the first load + expect(reloads).toEqual([]); + shown({persisted: true}); // back to a page that was kept: its discovery had stopped + expect(reloads).toEqual([true]); + }); + + it('closes itself on an answer that comes after the wait, which the host gave once it showed the panel again', async () => { + const status = document.createElement('p'); + const closed = []; + const view = {BroadcastChannel, setTimeout: (run, delay) => setTimeout(run, delay), clearTimeout: id => clearTimeout(id), opener: {}, + close: () => closed.push(true)}; + const host = new BroadcastChannel(inspectorChannel); + host.addEventListener('message', ({data}) => { + if (data?.type === 'attach') setTimeout(() => host.postMessage({type: 'attached', id: data.id, closer: 'self'}), 80); + }); + try { + expect(await attachAgain(view, null, 'cpp.watches', status, {host: 'host-a', wait: 20})).toBeFalse(); + expect(status.textContent).toContain('did not answer'); + expect(closed).toEqual([]); + await new Promise(resolve => setTimeout(resolve, 150)); + expect(closed).toEqual([true]); // the late answer closed it + expect(status.textContent).toBe(''); + } finally { host.close(); } + }); + + it('leaves its closing to the host page when the host answers that it closes it', async () => { + const status = document.createElement('p'); + const calls = [], closed = []; + const bridge = {cppFunction: name => async (...args) => { calls.push([name, ...args]); return true; }}; + for (const opener of [{}, null]) { + const view = {BroadcastChannel, setTimeout: (run, delay) => setTimeout(run, delay), clearTimeout: id => clearTimeout(id), opener, + close: () => closed.push(true)}; + const host = new BroadcastChannel(inspectorChannel); + host.addEventListener('message', ({data}) => host.postMessage({type: 'attached', id: data.id, closer: 'host'})); + try { expect(await attachAgain(view, bridge, 'cpp.functions', status, {host: 'host-a'})).toBeTrue(); } + finally { host.close(); } + } + // Neither a tab nor a native window closes itself: a detach meanwhile may have reused it. + expect(closed).toEqual([]); + expect(calls).toEqual([]); + }); + + it('closes its native window through C++ when it has no opener', async () => { + const status = document.createElement('p'); + const calls = []; + const bridge = {cppFunction: name => async (...args) => { calls.push([name, ...args]); return true; }}; + const view = {BroadcastChannel, setTimeout: (run, delay) => setTimeout(run, delay), clearTimeout: id => clearTimeout(id), opener: null, close: () => {}}; + const host = new BroadcastChannel(inspectorChannel); + host.addEventListener('message', ({data}) => host.postMessage({type: 'attached', id: data.id})); + try { expect(await attachAgain(view, bridge, 'cpp.functions', status, {host: 'host-a'})).toBeTrue(); } + finally { host.close(); } + expect(calls).toEqual([['webfront.inspector.closeWindow', 'cpp.functions', 'host-a']]); + // Without the identifier of its page, the window does not ask anybody. + expect(await attachAgain(view, bridge, 'cpp.functions', status)).toBeFalse(); + expect(calls.length).toBe(1); + }); + }); + + describe('watches', () => { + const bridgeOf = registry => ({cppFunction: name => async (...args) => { + expect(name).toBe(watchesFunction); + return registry.answer(...args); + }}); + + it('read the descriptors and pages that C++ sends, and refuse anything else', () => { + expect(readDescriptor([3, 'grid', 'sequence', 'life.cpp:12', true])).toEqual({id: 3, name: 'grid', kind: 'sequence', location: 'life.cpp:12', writable: true}); + expect(readDescriptor([0, 'grid', 'sequence', 'life.cpp:12', true])).toBeNull(); + expect(readDescriptor([1, 'grid', 'sequence', 'life.cpp:12'])).toBeNull(); + expect(readPage([[], 0, 4, true])).toEqual({descriptors: [], next: 0, revision: 4, changed: true}); + expect(() => readPage([[[1, 'a']], 0, 4, true])).toThrowError(/does not read/); + expect(() => readPage([[], 0, 4])).toThrowError(/does not read/); + }); + + it('are listed page after page, by identifier', async () => { + const registry = memoryWatches(2); + ['a', 'b', 'c', 'd', 'e'].forEach(name => registry.add(name)); + const {watches, revision} = await listWatches(bridgeOf(registry), 0); + expect(watches.map(watch => watch.name)).toEqual(['a', 'b', 'c', 'd', 'e']); + expect(revision).toBe(6); + expect(registry.calls.map(([, after]) => after)).toEqual([0, 2, 4]); + }); + + it('are listed again when the registry changes between two pages, so that a removed watch is not kept', async () => { + const registry = memoryWatches(2); + const ids = ['a', 'b', 'c', 'd'].map(name => registry.add(name)); + let removed = false; + const bridge = {cppFunction: () => async (...args) => { + const answer = registry.answer(...args); + // Between the first and the second page, a watch already read is removed. + if (!removed && args[1] === 0) { removed = true; registry.remove(ids[0]); } + return answer; + }}; + const {watches, revision} = await listWatches(bridge, 0); + expect(watches.map(watch => watch.name)).toEqual(['b', 'c', 'd']); + expect(revision).toBe(6); + // The next poll with that revision sees no change, and the list is right. + expect(registry.answer(revision, 0, 0)[3]).toBeFalse(); + }); + + it('give up a listing while the registry keeps changing, with a bounded number of reads', async () => { + const registry = memoryWatches(1); + ['a', 'b'].forEach(name => registry.add(name)); + // Each read adds a watch: no page can ever catch up with the registry. + const bridge = {cppFunction: () => async (...args) => { + const answer = registry.answer(...args); + registry.add(`x${registry.calls.length}`); + return answer; + }}; + expect(await listWatches(bridge, 0)).toBeNull(); + expect(registry.calls.filter(([, after]) => after === 0).length).toBe(listingAttempts); + expect(registry.calls.length).toBeLessThanOrEqual(2 * listingAttempts); // never reads to the end of a growing list + }); + + it('keep the watches shown when a listing gives up, and show the list once a read is stable', async () => { + const registry = memoryWatches(1); + registry.add('a'); + let churning = true; + const bridge = {cppFunction: () => async (...args) => { + const answer = registry.answer(...args); + if (churning) registry.add(`x${registry.calls.length}`); + return answer; + }}; + const changes = []; + const discovery = createWatchDiscovery({bridge, onChange: change => changes.push(change.watches.map(watch => watch.name)), timers: {setTimeout: () => 0, clearTimeout: () => {}}}); + await discovery.start(); + expect(changes).toEqual([]); // nothing shown from an unstable read + churning = false; + await discovery.start(); + expect(changes.length).toBe(1); + expect(changes[0][0]).toBe('a'); + expect(changes[0].length).toBe((await listWatches(bridge, 0)).watches.length); // the complete list + discovery.stop(); + }); + + it('send no further read and show nothing read after a pause', async () => { + const registry = memoryWatches(1); + ['a', 'b', 'c'].forEach(name => registry.add(name)); + let discovery, pauses = 1; + const bridge = {cppFunction: () => async (...args) => { + const answer = registry.answer(...args); + if (args[2] === 0 && pauses-- > 0) discovery.pause(); // the user pauses while the revision is asked + return answer; + }}; + const changes = []; + discovery = createWatchDiscovery({bridge, onChange: change => changes.push(change), timers: {setTimeout: () => 0, clearTimeout: () => {}}}); + await discovery.start(); + expect(registry.calls.length).toBe(1); // only the revision: no page after the pause + expect(changes).toEqual([]); + // Resumed, it reads again from the revision shown (none yet), and shows the list. + discovery.resume(); + await discovery.start(); + expect(changes.length).toBe(1); + expect(changes[0].watches.map(watch => watch.name)).toEqual(['a', 'b', 'c']); + discovery.stop(); + }); + + it('reconcile the watches shown with a new list', () => { + const known = new Map([[1, {id: 1}], [2, {id: 2}]]); + expect(reconcile(known, [{id: 2}, {id: 3}])).toEqual({added: [{id: 3}], removed: [1]}); + }); + + it('follow registrations and removals, asking only for the revision while nothing changes', async () => { + jasmine.clock().install(); + try { + const registry = memoryWatches(); + const grid = registry.add('grid', 'sequence'); + const changes = []; + const discovery = createWatchDiscovery({bridge: bridgeOf(registry), onChange: change => changes.push(change), period: 250}); + await discovery.start(); + expect(discovery.watches.map(watch => watch.name)).toEqual(['grid']); + registry.calls.length = 0; + // Nothing changed: one call with a count of 0 per period. + jasmine.clock().tick(250); + await discovery.settled(); + expect(registry.calls).toEqual([[2, 0, 0]]); + // A registration appears, a removal disappears. + const generations = registry.add('generations'); + jasmine.clock().tick(250); + await discovery.settled(); + expect(discovery.watches.map(watch => watch.name)).toEqual(['grid', 'generations']); + registry.remove(grid); + jasmine.clock().tick(250); + await discovery.settled(); + expect(discovery.watches.map(watch => watch.id)).toEqual([generations]); + expect(changes.at(-1).removed).toEqual([grid]); + // A call that finds a watch gone forgets it at once; paused, nothing is asked. + discovery.forget(generations); + expect(discovery.watches).toEqual([]); + discovery.pause(); + registry.calls.length = 0; + jasmine.clock().tick(1000); + expect(registry.calls).toEqual([]); + discovery.resume(); + jasmine.clock().tick(250); + await discovery.settled(); + expect(registry.calls.length).toBeGreaterThan(0); + discovery.stop(); + } finally { jasmine.clock().uninstall(); } + }); + + it('keep trying after a refused read', async () => { + jasmine.clock().install(); + try { + const registry = memoryWatches(); + let refuse = true; + const errors = []; + const bridge = {cppFunction: () => async (...args) => { + if (refuse) throw Object.assign(new Error('denied'), {code: 'webfront.inspector.denied'}); + return registry.answer(...args); + }}; + registry.add('grid'); + const discovery = createWatchDiscovery({bridge, onChange: () => {}, onError: error => errors.push(error.code), period: 250}); + await discovery.start(); + expect(errors).toEqual(['webfront.inspector.denied']); + refuse = false; + jasmine.clock().tick(250); + await discovery.settled(); + expect(discovery.watches.map(watch => watch.name)).toEqual(['grid']); + discovery.stop(); + } finally { jasmine.clock().uninstall(); } + }); + + it('report every successful read, so that an error is cleared once the reads work again', async () => { + jasmine.clock().install(); + try { + const registry = memoryWatches(); + registry.add('grid'); + let fail = false; + const events = []; + const bridge = {cppFunction: () => async (...args) => { + if (fail) throw new Error('lost'); + return registry.answer(...args); + }}; + const discovery = createWatchDiscovery({bridge, onChange: () => events.push('change'), onError: () => events.push('error'), + onRead: watches => events.push(`read ${watches.length}`), period: 250}); + await discovery.start(); + expect(events).toEqual(['change', 'read 1']); + fail = true; + jasmine.clock().tick(250); + await discovery.settled(); + fail = false; + // The registry has not changed: the read finds nothing new, and still says that it succeeded. + jasmine.clock().tick(250); + await discovery.settled(); + expect(events).toEqual(['change', 'read 1', 'error', 'read 1']); + discovery.stop(); + } finally { jasmine.clock().uninstall(); } + }); + + it('keep one read at a time when paused and resumed while a read is in progress', async () => { + jasmine.clock().install(); + try { + const registry = memoryWatches(); + registry.add('grid'); + let hold = null, inFlight = 0, most = 0; + const bridge = {cppFunction: () => async (...args) => { + ++inFlight; + most = Math.max(most, inFlight); + try { + if (hold) await hold.promise; + return registry.answer(...args); + } finally { --inFlight; } + }}; + const discovery = createWatchDiscovery({bridge, onChange: () => {}, period: 250}); + await discovery.start(); + // The next read waits for its answer; meanwhile the panel is paused and resumed, and time goes on. + let release; + hold = {promise: new Promise(resolve => { release = resolve; })}; + jasmine.clock().tick(250); + await Promise.resolve(); + expect(inFlight).toBe(1); + discovery.pause(); + discovery.resume(); + jasmine.clock().tick(1000); + await Promise.resolve(); + expect(inFlight).toBe(1); + hold = null; + release(); + await discovery.settled(); + // The read that ended schedules the next one: one chain, one read per period. + registry.calls.length = 0; + jasmine.clock().tick(250); + await discovery.settled(); + jasmine.clock().tick(250); + await discovery.settled(); + expect(registry.calls.length).toBe(2); + expect(most).toBe(1); + discovery.stop(); + } finally { jasmine.clock().uninstall(); } + }); + + it('render one item per watch, and remove the item of a watch that disappeared', () => { + const list = document.createElement('ul'); + renderWatches(list, [{id: 1, name: 'grid', kind: 'sequence', location: 'life.cpp:12', writable: false}, + {id: 2, name: 'speed', kind: 'integer', location: 'life.cpp:20', writable: true}]); + expect([...list.children].map(item => item.dataset.watch)).toEqual(['1', '2']); + expect(list.children[1].textContent).toContain('writable'); + const first = list.children[0]; + renderWatches(list, [{id: 1, name: 'grid', kind: 'sequence', location: 'life.cpp:12', writable: false}]); + expect([...list.children]).toEqual([first]); + }); + + it('name every panel of the menu', () => { + expect([...inspectorPanels.keys()]).toEqual(['cpp.functions', 'cpp.browsers', 'cpp.watches', 'typescript.packages', 'typescript.bridge']); + }); + }); +}); diff --git a/test/developer/specs/workspace-specs.mjs b/test/developer/specs/workspace-specs.mjs index 3b7bec85..5404259e 100644 --- a/test/developer/specs/workspace-specs.mjs +++ b/test/developer/specs/workspace-specs.mjs @@ -1,7 +1,7 @@ // Specs of the developer page's layout (workspace.mjs): what counts as an existing interface, the states of the display, // and the place of the floating terminal window. The page itself is checked in test/web/developer-specs.mjs. import {hasInterface, previewDirectory, State, initialState, nextState, clampRect, defaultRect, keyboardRect, minimumSize, step, - isToggleKey, Status, tabStatus, statusText, defaultShortcut, shortcutText, readShortcut, parsePlace, formatPlace, readPlace, placeStore, placePath, + windowControls, isToggleKey, Status, tabStatus, statusText, defaultShortcut, shortcutText, readShortcut, parsePlace, formatPlace, readPlace, placeStore, placePath, createWorkspace} from '../../../js/developer/environment/workspace.mjs'; import {publish} from '../../../js/developer/environment/io.mjs'; import {inspectorAccess, readInspectorAccess, accessReasons, containersFunction, placeMenu, createTabMenu, longPress, inspectorMenus, @@ -12,6 +12,31 @@ describe('The developer page layout', () => { const encode = text => new TextEncoder().encode(text); const page = text => new Map([['index.html', encode(text)], ['app.js', encode('')]]); + describe('window controls', () => { + it('move the window by the pointer that started the move only', () => { + const bar = document.createElement('div'), panel = document.createElement('div'); + document.body.append(bar, panel); + try { + let rect = {x: 100, y: 100, width: 400, height: 200}; + windowControls({view: window, bar, panel, shown: () => rect, choose: next => { rect = next; }, viewport: () => ({width: 2000, height: 2000}), + shownNow: () => false}); + const pointer = (type, pointerId, x, y) => bar.dispatchEvent(new PointerEvent(type, {bubbles: true, cancelable: true, pointerId, clientX: x, clientY: y, button: 0})); + pointer('pointerdown', 1, 110, 110); + pointer('pointerdown', 2, 300, 110); // a second finger: ignored + pointer('pointermove', 1, 160, 130); + expect([rect.x, rect.y]).toEqual([150, 120]); + pointer('pointermove', 2, 900, 900); // the second finger does not move the window + expect([rect.x, rect.y]).toEqual([150, 120]); + pointer('pointerup', 2, 900, 900); // nor does lifting it end the move + pointer('pointermove', 1, 170, 140); + expect([rect.x, rect.y]).toEqual([160, 130]); + pointer('pointerup', 1, 170, 140); + pointer('pointermove', 1, 500, 500); + expect([rect.x, rect.y]).toEqual([160, 130]); + } finally { bar.remove(); panel.remove(); } + }); + }); + describe('existing interface', () => { it('is a published preview page, which wf create and wf build do not produce', async () => { const {bridge, storage} = memoryBridge(); diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index a43ae095..8a6d1881 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -80,7 +80,7 @@ list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServe list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp DomBatchTests.cpp JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesTests.cpp IndexFSTests.cpp) list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp StorageTests.cpp NativeStorageTests.cpp PtyTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp ProfileLeaseTests.cpp SafePathTests.cpp UISubscribersTests.cpp) -list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp BroadcastTests.cpp SpaceTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) +list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp WatchTests.cpp BroadcastTests.cpp SpaceTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationDiscoveryTests.cpp AutomationMcpHttpTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp HostLoopTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp DeferredCallTests.cpp) list(APPEND TESTS_LIST Main.cpp ScenarioIsolation.cpp FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp UIExecutorTests.cpp NativeWindowTests.cpp WindowRegistryTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) if(WEBFRONT_USE_MDDLOG) diff --git a/test/unit/DeveloperTests.cpp b/test/unit/DeveloperTests.cpp index 20481d43..74ac166b 100644 --- a/test/unit/DeveloperTests.cpp +++ b/test/unit/DeveloperTests.cpp @@ -893,6 +893,60 @@ const Scenario publicationPrepared{"A publication prepared from stale state is r }); }}; +const Scenario conditionalFilePublication{"A failed single-file publication releases its destination", [] { + TemporaryDirectory project; + developer::Store store{project.path()}; + const std::string path = "preferences.json"; + const auto absent = store.state({path}); + store.publishFile(path, bytes("first"), absent); + then("a conflicting save leaves the file intact and the next save can use the same path", [&] { + requireThrows([&] { + store.publishFile(path, bytes("stale"), absent); + }); + requireEqual(store.read(path, 0), bytes("first")); + store.publishFile(path, bytes("next"), store.state({path})); + requireEqual(store.read(path, 0), bytes("next")); + }); + }}; + +const Scenario readWithState{"A small file is read with the token of exactly its bytes, so that a save applies only to that content", [] { + TemporaryDirectory project; + developer::Store store{project.path()}; + const std::string path = ".webfront/developer/inspector-window.json"; + given("no file", [&] { + const auto [present, content, token] = store.readWithState(path, 1024); + then("it is absent, with the token of its absence, and a save from it creates the file", [&] { + require(!present); + require(content.empty()); + requireEqual(token, store.state({path})); + store.publishFile(path, bytes("first"), token); + requireEqual(store.read(path, 0), bytes("first")); + }); + }); + given("a file whose content changes and comes back after it was read", [&] { + store.publishFile(path, bytes("A"), store.state({path})); + store.publishFile(path, bytes("B"), store.state({path})); + const auto [present, content, token] = store.readWithState(path, 1024); + require(present && content == bytes("B")); + requireEqual(token, store.state({path})); + store.publishFile(path, bytes("A"), store.state({path})); // back to an earlier content + then("a save from what was read is refused: the token is that of the bytes read, not of the earlier content", [&] { + requireThrows([&] { + store.publishFile(path, bytes("merged"), token); + }); + requireEqual(store.read(path, 0), bytes("A")); + }); + }); + given("a file larger than the limit", [&] { + store.publishFile(path, bytes("0123456789"), store.state({path})); + then("it is refused rather than cut", [&] { + requireThrows([&] { + static_cast(store.readWithState(path, 4)); + }); + }); + }); + }}; + const Scenario newDirectories{ "New directories are durable once their parents are synchronized", [] { diff --git a/test/unit/InspectorDistribution.cpp b/test/unit/InspectorDistribution.cpp index dab5658f..c854f58f 100644 --- a/test/unit/InspectorDistribution.cpp +++ b/test/unit/InspectorDistribution.cpp @@ -33,7 +33,21 @@ const Scenario inspectorsAbsent{"A distribution build registers no inspector fun app.bootstrap("developer", {.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}); then("the environment's callbacks exist, and no webfront.inspector.* function", [&] { require(app.hasCppFunction("webfront.developer.config")); - require(!app.hasCppFunction("webfront.inspector.containers")); + for (const auto* name : {"webfront.inspector.containers", + "webfront.inspector.embedded", + "webfront.inspector.watches", + "webfront.inspector.readPreferences", + "webfront.inspector.savePreferences", + "webfront.inspector.openWindow", + "webfront.inspector.closeWindow"}) + require(!app.hasCppFunction(name)); + }); + then("a watch registers nothing: its handle is empty", [&] { + int value = 0; + auto watch = app.watch("value", [&value]() -> const int& { + return value; + }); + require(!watch); }); }); }}; diff --git a/test/unit/SpaceTests.cpp b/test/unit/SpaceTests.cpp index 59765355..b381dc2d 100644 --- a/test/unit/SpaceTests.cpp +++ b/test/unit/SpaceTests.cpp @@ -1057,6 +1057,34 @@ const Scenario deferredKeeps{"A deferred function of a space keeps its callable }); }}; +const Scenario spaceReservedNames{ + "A space refuses the names reserved to the inspectors (ADR-027, section 1)", + {"spaces", "inspector"}, + [] { + SpaceApp app{WebFrontConfig{.port = "0"}}; + app.spaces("/s/", [](std::string_view) -> std::optional { + return std::nullopt; + }); + SpaceApp::Space space{app, "/s/", "alpha"}; + then("its pages cannot be given a function that hides or poses as one of the inspectors", [&] { + checkThrows([&] { + space.cppFunction("webfront.inspector.watches", [] { + return true; + }); + }); + checkThrows([&] { + space.cppFunction("webfront.inspector.containers", [] { + return true; + }); + }); + require(!space.hasCppFunction("webfront.inspector.watches")); + require(space.cppFunction("whoAmI", [] { + return true; + })); + }); + } +}; + const Scenario upgradePath{"The path of a WebSocket upgrade reaches the application, and a target a file request refuses is refused (#672)", {"spaces"}, [] { SpaceApp app{WebFrontConfig{.port = "0"}}; std::map> spaces; diff --git a/test/unit/ViewAssociationTests.cpp b/test/unit/ViewAssociationTests.cpp index c704b4ad..00b305dd 100644 --- a/test/unit/ViewAssociationTests.cpp +++ b/test/unit/ViewAssociationTests.cpp @@ -11,6 +11,7 @@ #include "InjectableNetworking.hpp" #include "TemporaryDirectory.hpp" +#include #include #include #include @@ -391,3 +392,270 @@ const Scenario inspectorContainersScenario{"The inspectors' containers follow th }); }); }}; + +namespace { +/// A frontend that opens secondary windows (WebKitGTK, WKWebView, WebView2 in this respect), counting the windows it opens. +struct InspectorWindowFrontend { + static constexpr bool providesViewProof() noexcept { + return true; + } + static constexpr frontend::Action action{frontend::Action::keepServerRunning}; + static void initialize() { } + static void open(std::string_view, std::string_view) { } + static inline int opened = 0; + static void openSecondaryWindow(std::string_view, std::string_view, std::string_view, const ContentPolicy&, const WindowOptions&, const ViewLaunch&) { + ++opened; + } + [[nodiscard]] static frontend::UIExecutor uiExecutor() { + return {}; + } +}; +using InspectorWindowApp = DeveloperAppWithNetwork; + +/// The browser calls `name` with `arguments`; the answer is among the socket's writes. +template +void callWith(const std::string& name, msg::CallId callId, Arguments... arguments) { + msg::FunctionCall<> message; + message.setCallId(callId); + websocket::Frame frame{std::span(reinterpret_cast(message.header().data()), message.header().size())}; + message.encodeParameter(name, frame); + (message.encodeParameter(arguments, frame), ...); + frame.freeze(); + ViewSocket::receive(testing::clientFrame(testing::messagePayload(frame))); +} + +/// The encoded answer of a call that returns a boolean: the header of the return, then the boolean. +std::string booleanAnswer(msg::CallId callId, bool value) { + const msg::FunctionCallHeader header{.parametersCount = 1, .callId = callId, .parametersDataSize = 1}; + std::string bytes(reinterpret_cast(&header), sizeof header); + bytes += static_cast(value ? msg::CodedType::booleanTrue : msg::CodedType::booleanFalse); + return bytes; +} + +/// A bootstrapped developer application of `Frontend`, with one browser that presented `proof` (or not). +template +struct AdmittedBrowser { + AdmittedBrowser(bool trustLoopback, bool proven) : app(project.path(), inspectorConfig(trustLoopback)) { + app.bootstrap("developer", {.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}); + connect(app, proven ? testing::LaunchSecret::of(app) : std::string{}, inspectorUpgradeRequest); + } + webfront::test::TemporaryDirectory project; + Application app; +}; +} // namespace + +const Scenario inspectorContainersWithWindows{ + "A frontend that opens windows offers one only to an admitted page (ADR-027, section 8)", + {"view-association", "inspector"}, + [] { + given("the proven view", [&] { + freshNetwork(); + AdmittedBrowser browser{false, true}; + callWithoutArgument("webfront.inspector.containers", 7); + then("a secondary window and the page are admitted, no new connection", [&] { + require(ViewSocket::wrote(containersAnswer(true, true, false))); + }); + }); + given("a page that is not proven, on the loopback, without trustLoopbackClients", [&] { + freshNetwork(); + ViewSocket::peerIsLoopback = true; + AdmittedBrowser browser{false, false}; + callWithoutArgument("webfront.inspector.containers", 7); + then("no container: the window would be opened by a page that is refused", [&] { + require(ViewSocket::wrote(containersAnswer(false, false, false))); + }); + }); + given("a page that is not proven, on the loopback, with trustLoopbackClients", [&] { + freshNetwork(); + ViewSocket::peerIsLoopback = true; + AdmittedBrowser browser{true, false}; + callWithoutArgument("webfront.inspector.containers", 7); + then("the trusted page may open a window, and new connections are admitted", [&] { + require(ViewSocket::wrote(containersAnswer(true, true, true))); + }); + }); + } +}; + +const Scenario developerWriteAccess{ + "Developer writes and commands require an admitted client when the frontend proves its view", + {"view-association", "inspector"}, + [] { + const std::string path = "protected.txt"; + const std::vector bytes{'o', 'k'}; + given("an unproven client of an embedded frontend", [&] { + freshNetwork(); + AdmittedBrowser browser{false, false}; + Commands commands{browser.app}; + const auto denied = [&](auto name, auto... arguments) { + const auto offset = ViewSocket::writtenText().size(); + callWith(name, 7, arguments...); + require(ViewSocket::writtenText().find(inspect::code::denied, offset) != std::string::npos); + }; + denied("webfront.developer.begin", path, false); + denied("webfront.developer.beginNew", path, false); + denied("webfront.developer.write", path, std::string{"output"}, std::uint64_t{0}, bytes); + denied("webfront.developer.commit", path); + denied("webfront.developer.abort", path); + denied("webfront.developer.commitGroup", path, path, path); + denied("webfront.commands.start", std::uint32_t{1}, path, std::string{"[]"}); + denied("webfront.commands.cancel", std::uint32_t{1}); + denied("webfront.inspector.savePreferences", path, bytes); + const auto offset = ViewSocket::writtenText().size(); + callWith("webfront.developer.state", 7, path); + const auto response = ViewSocket::writtenText().substr(offset); + require(!response.empty() && !response.contains(inspect::code::denied)); + require(!std::filesystem::exists(browser.project.path() / ".webfront/developer/staging")); + }); + given("a proven client", [&] { + freshNetwork(); + AdmittedBrowser browser{false, true}; + callWith("webfront.developer.begin", 7, path, false); + require(!ViewSocket::wrote(inspect::code::denied)); + require(std::filesystem::is_directory(browser.project.path() / ".webfront/developer/staging")); + }); + given("a system browser with the default trust policy", [&] { + freshNetwork(); + AdmittedBrowser browser{false, false}; + callWith("webfront.developer.begin", 7, path, false); + require(!ViewSocket::wrote(inspect::code::denied)); + require(std::filesystem::is_directory(browser.project.path() / ".webfront/developer/staging")); + }); + } +}; + +const Scenario inspectorWindowAccess{ + "webfront.inspector.openWindow opens a panel's window only for an admitted page (ADR-027, sections 2 and 8)", + {"view-association", "inspector"}, + [] { + given("a page that is not admitted, with a frontend that opens windows", [&] { + freshNetwork(); + InspectorWindowFrontend::opened = 0; + AdmittedBrowser browser{false, false}; + callWith("webfront.inspector.openWindow", 9, std::string{"cpp.watches"}, std::string{"host-1"}, 720.0, 560.0); + then("the call is refused as denied, and no window opens", [&] { + require(ViewSocket::wrote(inspect::code::denied)); + requireEqual(InspectorWindowFrontend::opened, 0); + }); + }); + given("the proven view and an unknown panel", [&] { + freshNetwork(); + InspectorWindowFrontend::opened = 0; + AdmittedBrowser browser{false, true}; + callWith("webfront.inspector.openWindow", 9, std::string{"../../etc/passwd"}, std::string{"host-1"}, 720.0, 560.0); + then("the call is refused before any window", [&] { + require(ViewSocket::wrote("Unknown inspector panel")); + requireEqual(InspectorWindowFrontend::opened, 0); + }); + }); + given("the proven view of a frontend that opens no secondary window", [&] { + freshNetwork(); + AdmittedBrowser browser{false, true}; + callWith("webfront.inspector.openWindow", 9, std::string{"cpp.watches"}, std::string{"host-1"}, 720.0, 560.0); + then("the call is refused as unavailable", [&] { + require(ViewSocket::wrote(inspect::code::unavailable)); + }); + }); + given("the pages of a panel", [&] { + then("each panel of each host page has its own window, and only the panels of the menu have one", [&] { + requireEqual(developer::inspectorPage("cpp.watches", "a1_b-2"), + std::string{"webfront/developer/environment/inspector.html?panel=cpp.watches&host=a1_b-2"}); + checkThrows([] { + static_cast(developer::inspectorPage("cpp", "host")); + }); + // The host page names itself in the window's address: no other text reaches the page string. + for (const auto* host : {"", "a/b", "a&panel=x", "é", "x x"}) + checkThrows([host] { + static_cast(developer::inspectorPage("cpp.watches", host)); + }); + require(developer::inspectorHostIdentifier(std::string(64, 'a')) && !developer::inspectorHostIdentifier(std::string(65, 'a'))); + requireEqual(developer::inspectorWindowExtent(10.0, 720), 720); + requireEqual(developer::inspectorWindowExtent(800.5, 720), 800); + }); + }); + } +}; + +const Scenario inspectorWatchesAccess{ + "webfront.inspector.watches lists the application's watches to an admitted page only (ADR-027, sections 2 and 3)", + {"view-association", "inspector"}, + [] { + std::vector grid{1, 2, 3}; + given("the proven view and a watch declared after bootstrap", [&] { + freshNetwork(); + AdmittedBrowser browser{false, true}; + auto watch = browser.app.watch("grid", [&grid]() -> const std::vector& { + return grid; + }); + require(static_cast(watch)); + callWith("webfront.inspector.watches", 11, 0.0, 0.0, 200.0); + then("the page names the watch, its kind and where it was declared", [&] { + require(ViewSocket::wrote("grid")); + require(ViewSocket::wrote("sequence")); + require(ViewSocket::wrote("ViewAssociationTests.cpp:")); + }); + then("the proven view is told that it is an embedded view, which never offers it a tab", [&] { + callWithoutArgument("webfront.inspector.embedded", 12); + require(ViewSocket::wrote(booleanAnswer(12, true))); + }); + then("a second watch of the same name is refused while the first lives", [&] { + checkThrows([&] { + static_cast(browser.app.watch("grid", [&grid]() -> const std::vector& { + return grid; + })); + }); + }); + }); + given("a page that is not admitted", [&] { + freshNetwork(); + AdmittedBrowser browser{false, false}; + auto watch = browser.app.watch("secret", [&grid]() -> const std::vector& { + return grid; + }); + callWith("webfront.inspector.watches", 11, 0.0, 0.0, 200.0); + then("the call is refused as denied, before any read of the table", [&] { + require(ViewSocket::wrote(inspect::code::denied)); + require(!ViewSocket::wrote("secret")); + }); + }); + given("a page that is not admitted asks whether it is an embedded view", [&] { + freshNetwork(); + AdmittedBrowser browser{false, false}; + callWithoutArgument("webfront.inspector.embedded", 12); + then("the call is refused as denied, without an answer", [&] { + require(ViewSocket::wrote(inspect::code::denied)); + require(!ViewSocket::wrote(booleanAnswer(12, false)) && !ViewSocket::wrote(booleanAnswer(12, true))); + }); + }); + given("a trusted loopback page that is not proven asks whether it is an embedded view", [&] { + freshNetwork(); + ViewSocket::peerIsLoopback = true; + AdmittedBrowser browser{true, false}; + callWithoutArgument("webfront.inspector.embedded", 12); + then("under a frontend without the proof, it is told that it is not one: a tab of the system browser may be offered", [&] { + require(ViewSocket::wrote(booleanAnswer(12, false))); + }); + }); + given("a trusted loopback page that is not proven, under a frontend that gives its views the proof", [&] { + freshNetwork(); + ViewSocket::peerIsLoopback = true; + AdmittedBrowser browser{true, false}; + callWithoutArgument("webfront.inspector.embedded", 12); + then("it is told that it may be one (a frame of an embedded view), which never offers it a tab", [&] { + require(ViewSocket::wrote(booleanAnswer(12, true))); + }); + }); + given("a trusted loopback page", [&] { + freshNetwork(); + ViewSocket::peerIsLoopback = true; + AdmittedBrowser browser{true, false}; + auto watch = browser.app.watch("trusted", [&grid]() -> const std::vector& { + return grid; + }); + callWith("webfront.inspector.watches", 11, 0.0, 0.0, 200.0); + then("it is admitted by trustLoopbackClients", [&] { + require(ViewSocket::wrote("trusted")); + }); + }); + } +}; diff --git a/test/unit/WatchTests.cpp b/test/unit/WatchTests.cpp new file mode 100644 index 00000000..22155adb --- /dev/null +++ b/test/unit/WatchTests.cpp @@ -0,0 +1,427 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-25 +// +// WebFront — tests/unit +// Role: The registry of the watches and its discovery page (ADR-027, section 3), their handle, kinds and bounded texts. +// Thread: worker-safe | Alloc: unrestricted +// LLM: unit tests of include/webfront/Watches.hpp; the bridge side is in ViewAssociationTests.cpp + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace webfront::bdd; +using namespace webfront; + +namespace { +using inspect::WatchRegistry; + +std::uint64_t addWatch(WatchRegistry& registry, std::string name) { + return registry.add(std::move(name), "integer", "app.cpp:1", false, nullptr); +} + +std::vector namesOf(const inspect::WatchPage& page) { + std::vector names; + for (const auto& descriptor : std::get<0>(page)) + names.push_back(std::get<1>(descriptor)); + return names; +} + +struct Unprintable { }; + +const std::vector& sharedValues() { + static const std::vector values{1, 2}; + return values; +} +} // namespace + +const Scenario watchTexts{"The texts of a watch are bounded and made visible (ADR-027, sections 3 and 4)", {"inspector"}, [] { + given("texts of the application", [&] { + then("control characters become their visible pictures", [&] { + requireEqual(inspect::boundedText("a\nb\x7f"), std::string{"a␊b␡"}); + }); + then("a short text is kept whole", [&] { + requireEqual(inspect::boundedText("grid"), std::string{"grid"}); + }); + then("a long text is cut on a character boundary and ends with an ellipsis", [&] { + const std::string long_(255, 'x'); + const auto cut = inspect::boundedText(long_ + "\xC3\xA9\xC3\xA9"); // the é crosses 256 bytes + require(cut.size() <= inspect::maxTextBytes); + require(cut.ends_with("\xE2\x80\xA6")); + requireEqual(inspect::utf8Prefix("a\xC3\xA9", 2), std::string_view{"a"}); + }); + then("a bound smaller than the ellipsis keeps the prefix that fits, without it", [&] { + requireEqual(inspect::boundedText("abc", 1), std::string{"a"}); + requireEqual(inspect::boundedText("\xC3\xA9t\xC3\xA9", 2), std::string{"\xC3\xA9"}); + requireEqual(inspect::boundedText("abc", 0), std::string{}); + }); + then("an unbounded limit keeps the whole text", [&] { + requireEqual(inspect::boundedText("abcdef", std::string_view::npos), std::string{"abcdef"}); + }); + then("a long location keeps the end of the path", [&] { + const auto text = inspect::locationText(std::source_location::current()); + require(text.size() <= inspect::maxTextBytes); + require(text.contains("WatchTests.cpp:")); + }); + then("a path that its visible form makes too long still ends with its file and line", [&] { + const auto text = inspect::locationText(std::string(90, '\t') + "/app.cpp", 17); + require(text.size() <= inspect::maxTextBytes); + require(text.ends_with("/app.cpp:17")); + require(text.starts_with("\xE2\x80\xA6\xE2\x90\x89")); // cut between two pictures, never inside one + }); + }); + }}; + +const Scenario watchKinds{"The kind of a watch's root follows the order of ADR-027, section 4", {"inspector"}, [] { + then("scalars, strings and bitsets", [&] { + requireEqual(inspect::kindOf(), std::string_view{"bool"}); + requireEqual(inspect::kindOf(), std::string_view{"integer"}); + requireEqual(inspect::kindOf(), std::string_view{"real"}); + requireEqual(inspect::kindOf(), std::string_view{"string"}); + requireEqual(inspect::kindOf>(), std::string_view{"bitset"}); + }); + then("wrappers, containers, formattable and opaque types", [&] { + requireEqual(inspect::kindOf>(), std::string_view{"optional"}); + requireEqual(inspect::kindOf>(), std::string_view{"variant"}); + requireEqual(inspect::kindOf>(), std::string_view{"tuple"}); + requireEqual(inspect::kindOf>(), std::string_view{"tuple"}); + requireEqual(inspect::kindOf>(), std::string_view{"map"}); + requireEqual(inspect::kindOf>(), std::string_view{"sequence"}); + requireEqual(inspect::kindOf>(), std::string_view{"sequence"}); + requireEqual(inspect::kindOf(), std::string_view{"formatted"}); + requireEqual(inspect::kindOf(), std::string_view{"opaque"}); + }); + then("a source's object and whether it writes come from its form", [&] { + int value = 0; + auto reader = [](inspect::Visit) { }; + auto writer = [](inspect::Visit>) { }; + auto reference = [&value]() -> int& { + return value; + }; + auto copy = [] { + return std::string{}; + }; + using ReaderShape = inspect::SourceShape; + static_assert(std::is_same_v && !ReaderShape::writable); + static_assert(inspect::SourceShape::writable); + // A reference read on the server thread is not writable, nor is a copy (section 6). + static_assert(!inspect::SourceShape::writable); + static_assert(std::is_same_v::Object, std::string>); + static_assert(!inspect::WatchSource); + // A visitor callable on an lvalue only, as the stored source is called, is a visitor. + struct LvalueVisitor { + void operator()(inspect::Visit) & { } + }; + struct ConstLvalueVisitor { + void operator()(inspect::Visit>) const& { } + }; + static_assert(std::is_same_v::Object, const int>); + static_assert(inspect::SourceShape::writable); + // An accessor that returns nothing gives nothing to show: it is refused. + auto nothing = [] { }; + static_assert(!inspect::WatchSource); + // A function given by name is a source too, kept as a pointer. + static_assert(inspect::WatchSource); + static_assert(std::is_same_v>::Object, const std::vector>); + require(value == 0); + }); + }}; + +const Scenario watchRegistry{"The registry of the watches gives stable identifiers and a revision (ADR-027, section 3)", {"inspector"}, [] { + given("a registry with three watches", [&] { + WatchRegistry registry; + const auto initial = registry.revision(); + const auto a = addWatch(registry, "a"), b = addWatch(registry, "b"), c = addWatch(registry, "c"); + then("identifiers follow the registrations and the revision changed at each", [&] { + require(a < b && b < c); + requireEqual(registry.revision(), initial + 3); + }); + then("a second watch of the same name, or an empty or long name, is refused", [&] { + bool duplicate = false, empty = false, long_ = false; + try { + static_cast(addWatch(registry, "b")); + } catch (const std::invalid_argument&) { + duplicate = true; + } + try { + static_cast(addWatch(registry, "")); + } catch (const std::invalid_argument&) { + empty = true; + } + try { + static_cast(addWatch(registry, std::string(257, 'x'))); + } catch (const std::invalid_argument&) { + long_ = true; + } + require(duplicate && empty && long_); + requireEqual(registry.size(), std::size_t{3}); + }); + when("one is removed and registered again under its name", [&] { + registry.remove(b); + const auto again = addWatch(registry, "b"); + then("it gets a new identifier, and the old one is gone", [&] { + require(again > c); + require(!registry.contains(b)); + requireEqual(registry.revision(), initial + 5); + }); + then("removing an unknown identifier changes nothing", [&] { + const auto revision = registry.revision(); + registry.remove(b); + requireEqual(registry.revision(), revision); + }); + }); + }); + }}; + +const Scenario watchPages{ + "The discovery page lists the live watches by identifier, within the budget (ADR-027, section 3)", + {"inspector"}, + [] { + given("a registry of five watches", [&] { + WatchRegistry registry; + std::vector ids; + for (const auto* name : {"a", "b", "c", "d", "e"}) + ids.push_back(addWatch(registry, name)); + const auto revision = static_cast(registry.revision()); + then("a page with a count of 0 gives only the revision and whether it changed", [&] { + const auto [list, next, current, changed] = registry.page(0, 0, 0, 32768); + require(list.empty()); + requireEqual(next, 0.0); + requireEqual(current, revision); + require(changed); + require(!std::get<3>(registry.page(revision, 0, 0, 32768))); + }); + then("pages follow the identifiers, and the last one ends with 0", [&] { + const auto first = registry.page(revision, 0, 2, 32768); + requireEqual(namesOf(first), std::vector{"a", "b"}); + requireEqual(std::get<1>(first), static_cast(ids[1])); + const auto last = registry.page(revision, static_cast(ids[3]), 2, 32768); + requireEqual(namesOf(last), std::vector{"e"}); + requireEqual(std::get<1>(last), 0.0); + }); + then("a removal and a registration during the listing skip and repeat nothing", [&] { + const auto first = registry.page(revision, 0, 2, 32768); + registry.remove(ids[0]); // already served + registry.remove(ids[3]); // not served yet + static_cast(addWatch(registry, "f")); + const auto rest = registry.page(revision, std::get<1>(first), 10, 32768); + requireEqual(namesOf(rest), std::vector{"c", "e", "f"}); + require(std::get<3>(rest)); // the registry changed meanwhile + }); + then("a page holds no more than the budget, and the next one resumes after it", [&] { + // Each descriptor takes 2 + 9 + 4 + 10 + 12 + 1 bytes: 38, and the header 64. + const auto narrow = registry.page(revision, 0, 200, inspect::responseHeaderBytes + 80); + requireEqual(namesOf(narrow), std::vector{"a", "b"}); + const auto next = registry.page(revision, std::get<1>(narrow), 200, inspect::responseHeaderBytes + 80); + requireEqual(namesOf(next), std::vector{"c", "d"}); + }); + then("a budget that cannot hold the next watch is refused, not answered as the end of the list", [&] { + checkThrows([&] { + static_cast(registry.page(revision, 0, 200, inspect::responseHeaderBytes + 10)); + }); + // Only the revision is asked for: no descriptor has to fit. + require(std::get<0>(registry.page(revision, 0, 0, 0)).empty()); + }); + then("a count above 1 000 is read as 1 000, and numbers that are not whole are refused", [&] { + WatchRegistry many; + for (int index = 0; index < 1001; ++index) + static_cast(addWatch(many, "w" + std::to_string(index))); + const auto all = static_cast(many.revision()); + const auto first = many.page(all, 0, 5000, 1 << 20); // a budget that holds every entry + requireEqual(std::get<0>(first).size(), std::size_t{1000}); + const auto rest = many.page(all, std::get<1>(first), 5000, 1 << 20); + requireEqual(namesOf(rest), std::vector{"w1000"}); + requireEqual(std::get<1>(rest), 0.0); + for (const double bad : {-1.0, 0.5, 1e300}) + checkThrows([&] { + static_cast(registry.page(bad, 0, 0, 32768)); + }); + checkThrows([&] { + static_cast(registry.page(revision, 0, 2.5, 32768)); + }); + }); + }); + given("a watch whose texts are at their bounds", [&] { + WatchRegistry registry; + static_cast(registry.add(std::string(inspect::maxTextBytes, 'n'), "formatted", std::string(inspect::maxTextBytes, 'l'), true, nullptr)); + then("a page of it fits the smallest budget", [&] { + requireEqual(std::get<0>(registry.page(0, 0, 1, inspect::minPageBytes)).size(), std::size_t{1}); + }); + then("a longer location is bounded when it is registered, and a longer kind refused", [&] { + WatchRegistry bounded; + static_cast(bounded.add("long", "formatted", std::string(4096, 'l'), false, nullptr)); + const auto page = bounded.page(0, 0, 200, inspect::minPageBytes); + requireEqual(std::get<0>(page).size(), std::size_t{1}); + require(std::get<3>(std::get<0>(page)[0]).size() <= inspect::maxTextBytes); + checkThrows([&] { + static_cast(bounded.add("kind", std::string(inspect::maxKindBytes + 1, 'k'), "app.cpp:1", false, nullptr)); + }); + }); + }); + given("watches whose names hold control characters", [&] { + WatchRegistry registry; + static_cast(addWatch(registry, "line\none")); + // Its visible form is another name: the names the application gave are what must be unique. + static_cast(addWatch(registry, "line\xE2\x90\x8Aone")); + static_cast(addWatch(registry, std::string(inspect::maxTextBytes - 1, 'n') + "\t")); // the picture crosses the bound + const auto names = namesOf(registry.page(0, 0, 10, 32768)); + then("the page shows them with their control characters visible", [&] { + requireEqual(names.size(), std::size_t{3}); // before any index: an omitted name fails here + requireEqual(names[0], std::string{"line\xE2\x90\x8Aone"}); + requireEqual(names[1], std::string{"line\xE2\x90\x8Aone"}); + }); + then("a name that its visible form makes longer is cut within the bound", [&] { + requireEqual(names.size(), std::size_t{3}); + require(names[2].size() <= inspect::maxTextBytes); + require(names[2].ends_with("\xE2\x80\xA6")); + }); + then("a second watch of the same name is still refused", [&] { + checkThrows([&] { + static_cast(addWatch(registry, "line\none")); + }); + }); + }); + }}; + +const Scenario watchHandles{ + "A watch exists while its handle lives, and the handle outlives the application (ADR-027, section 5)", + {"inspector"}, + [] { + given("a handle on a registry", [&] { + auto registry = std::make_shared(); + auto source = std::make_shared(7); + std::weak_ptr observed = source; + inspect::Watch handle{registry, registry->add("grid", "integer", "app.cpp:1", false, std::move(source))}; + then("the watch is registered and the registry keeps its source", [&] { + require(static_cast(handle)); + require(registry->contains(handle.id())); + require(!observed.expired()); + }); + when("the handle is moved, then reset", [&] { + const auto id = handle.id(); + inspect::Watch moved = std::move(handle); + require(!handle); + require(moved.id() == id && registry->contains(id)); + moved.reset(); + then("the watch and its source are gone", [&] { + require(!registry->contains(id)); + require(observed.expired()); + }); + }); + when("the registry goes first", [&] { + registry.reset(); + then("the handle is destroyed without touching it", [&] { + handle.reset(); + require(!handle); + }); + }); + }); + given("a source whose release assigns its own handle to a new watch", [&] { + auto registry = std::make_shared(); + inspect::Watch handle; + // The destructor of the source registers a new watch in the same handle, as a source + // owning an object that watches itself again would. + struct Reassigning { + WatchRegistry& registry; + inspect::Watch& handle; + std::weak_ptr owner; + ~Reassigning() { + handle = inspect::Watch{owner, registry.add("again", "integer", "app.cpp:2", false, nullptr)}; + } + }; + const auto first = registry->add("first", "integer", "app.cpp:1", false, std::make_shared(*registry, handle, registry)); + handle = inspect::Watch{registry, first}; + when("the handle is reset", [&] { + handle.reset(); + then("the new watch stays registered and its handle can still remove it", [&] { + require(!registry->contains(first)); + require(static_cast(handle)); + const auto again = handle.id(); + require(registry->contains(again)); + handle.reset(); + require(!registry->contains(again)); + require(!handle); + }); + }); + when("the handle is assigned another watch", [&] { + handle = inspect::Watch{registry, addWatch(*registry, "other")}; + then("the assignment made by the released source is the one kept, still removable", [&] { + require(!registry->contains(first)); + // The one watch left is the source's "again", not "other", and the handle holds it. + requireEqual(namesOf(registry->page(0, 0, 10, 32768)), std::vector{"again"}); + const auto kept = handle.id(); + require(registry->contains(kept)); + handle.reset(); + requireEqual(registry->size(), std::size_t{0}); + }); + }); + }); + given("a source whose release assigns its handle while the handle is destroyed", [&] { + auto registry = std::make_shared(); + // Destroyed with delete once released, so that the source's reference stays on the handle while its destructor runs. + auto owned = std::make_unique(); + auto* handle = owned.get(); + struct Reassigning { + WatchRegistry& registry; + inspect::Watch& handle; + std::weak_ptr owner; + ~Reassigning() { + handle = inspect::Watch{owner, registry.add("again", "integer", "app.cpp:2", false, nullptr)}; + } + }; + *handle = inspect::Watch{registry, + registry->add("first", "integer", "app.cpp:1", false, std::make_shared(*registry, *handle, registry))}; + when("the handle is destroyed", [&] { + delete owned.release(); + then("the handle takes no new watch, and the one the source registered is removed with its temporary", [&] { + requireEqual(registry->size(), std::size_t{0}); + }); + }); + }); + given("an application outside the developer environment", [&] { + BasicWF app{WebFrontConfig{.port = "0"}}; + int value = 0; + then("watch() registers nothing and returns an empty handle", [&] { + auto handle = app.watch("value", [&value]() -> const int& { + return value; + }); + require(!handle); + require(!app.watch("byName", sharedValues)); // a function given by name + requireEqual(handle.id(), std::uint64_t{0}); + }); + then("an invalid name is refused all the same", [&] { + checkThrows([&] { + static_cast(app.watch("", [&value]() -> const int& { + return value; + })); + }); + }); + then("cppFunction refuses the names reserved to the inspectors", [&] { + checkThrows([&] { + app.cppFunction("webfront.inspector.containers", [] { + return true; + }); + }); + checkThrows([&] { + app.cppFunction("webfront.inspector.watches", [] { + return true; + }); + }); + require(!app.hasCppFunction("webfront.inspector.containers")); + require(app.cppFunction("webfront.inspectorish", [] { + return true; + })); + }); + }); + }}; diff --git a/test/web/DeveloperTest.cpp b/test/web/DeveloperTest.cpp index 9e1654b1..4b13376b 100644 --- a/test/web/DeveloperTest.cpp +++ b/test/web/DeveloperTest.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include namespace { @@ -288,10 +289,34 @@ class Part { app.cppFunction("test.part", [part = mode.part] { return part; }); + // What the inspectors must offer this page, known from the frontend type and not from webfront.inspector.containers(), + // which the spec checks against it: the view of an embedded frontend is admitted, and a frontend that has secondary + // windows offers one (ADR-027, sections 2 and 8). + app.cppFunction("test.expectedContainers", [] { + return std::tuple{App::supportsSecondaryWindow, true}; + }); app.cppFunction("test.browsers", [this] { return static_cast(app.connectedBrowsers()); }); + // The connections that proved they are a view of the application: the window of show() and its secondary windows. + app.cppFunction("test.views", [this] { + double views = 0; + app.forEachUI([&views](App::UI ui) { + if (ui.isEmbeddedView()) + ++views; + }); + return views; + }); bootstrapApp(app, mode, readIntegrity(project.path() / "fixtures/provision.json")); + // A watch that the page declares and removes while an inspector shows the watches (#680): it appears, then disappears. + app.cppFunction("test.watch", [this](std::string name) { + watches.insert_or_assign(name, app.watch(name, [this]() -> const std::string& { + return mode.part; + })); + }); + app.cppFunction("test.unwatch", [this](std::string name) { + watches.erase(name); + }); subscription = app.subscribeUIStarted([injected = false](App::UI ui) mutable { if (!std::exchange(injected, true)) ui.addScript(runScript); @@ -299,6 +324,7 @@ class Part { } ~Part() { + watches.clear(); states->releaseAll(); app.stop(); // Drain while the commands, callback state and project are still alive. @@ -351,12 +377,13 @@ class Part { return config; } - std::atomic passed{false}; - bool reported = false; - std::mutex reportMutex; - std::shared_ptr states; - webfront::Commands commands; - webfront::UISubscription subscription; + std::atomic passed{false}; + bool reported = false; + std::mutex reportMutex; + std::shared_ptr states; + webfront::Commands commands; + webfront::UISubscription subscription; + std::map watches; // used on the server thread only }; } // namespace diff --git a/test/web/developer-session.html b/test/web/developer-session.html index f531ff7b..06287edf 100644 --- a/test/web/developer-session.html +++ b/test/web/developer-session.html @@ -3,6 +3,5 @@ Second developer session
- diff --git a/test/web/developer-session.mjs b/test/web/developer-session.mjs index 77c8d0fb..9e4dfb31 100644 --- a/test/web/developer-session.mjs +++ b/test/web/developer-session.mjs @@ -1,6 +1,21 @@ -// A second browser session for developer-specs.mjs: its own WebFront connection, the same environment runtime. +// A second session made by the proven top-level test view, with its own connection and its own copy of the runtime. +class SessionBridge extends parent.WebFrontBridge { + cppFunction(name) { + const call = super.cppFunction(name); + return (...args) => call(...args.map(value => value instanceof Uint8Array ? new parent.Uint8Array(value) : value)); + } + + executeFunction(name, args) { + if (name === 'webfront.commands.output') return globalThis.webfront.commands.output(...args); + if (name === 'webfront.commands.exit') return globalThis.webfront.commands.exit(...args); + return super.executeFunction(name, args); + } +} + globalThis.session = (async () => { - await webFront.ready; + const bridge = new SessionBridge(); + globalThis.addEventListener('pagehide', () => bridge.socket.close(), {once: true}); + await bridge.ready; const runtime = await import('/webfront/developer/environment/runtime.mjs'); - return {runtime, bridge: webFront, cppCommands: await runtime.discoverCommands(webFront)}; + return {runtime, bridge, cppCommands: await runtime.discoverCommands(bridge)}; })(); diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index 36f9e956..311bed2f 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -859,11 +859,14 @@ try { rightClick: (target, x, y) => target.dispatchEvent(new view.MouseEvent('contextmenu', {bubbles: true, cancelable: true, button: 2, clientX: x, clientY: y})), }; }; - // The reason the inspector entries give, from what webfront.inspector.containers() answered to the page's bridge: - // an admitted page has no inspector to open yet (#680), another one is told how to be admitted (ADR-027, section 8). - const inspectorReason = async bridge => { - const [, host] = await bridge.cppFunction('webfront.inspector.containers')(); - return host ? /cannot open the inspectors yet/ : /trustLoopbackClients/; + // Opens the submenu of `group` until its entries are available: the page is admitted and the menu read its access. + const availableEntries = async (layoutOf, group) => { + await until(() => { + layoutOf.menus().slice(1).forEach(() => layoutOf.press(layoutOf.entries(1)[0], {key: 'ArrowLeft'})); + layoutOf.press(layoutOf.entries(0)[group], {key: 'ArrowRight'}); + return layoutOf.entries(1).length > 0 && layoutOf.entries(1).every(entry => entry.getAttribute('aria-disabled') !== 'true'); + }, 'The inspector entries of an admitted page must be available'); + return layoutOf.entries(1); }; // Opens the submenu of `group` (1: C++ state, 2: TypeScript state) until the menu has read the page's access. const inspectorEntries = async (layoutOf, group, expected) => { @@ -922,13 +925,80 @@ try { 'A displayed interface must fill the window, with the icon'); if (part === 'workspace') { // This page's own menu: the inspector entries follow what its connection is admitted to. + // The containers come from the frontend type, known to the test program: a containers() that wrongly answered + // no window, or no admission, would otherwise run a shorter path and still pass. + const [secondaryWindow, admitted] = await webFront.cppFunction('test.expectedContainers')(); + const [offeredWindow, offeredAdmission] = await webFront.cppFunction('webfront.inspector.containers')(); + assert(offeredWindow === secondaryWindow && offeredAdmission === admitted, + `The inspectors must offer what the frontend gives: ${[offeredWindow, offeredAdmission]} instead of ${[secondaryWindow, admitted]}`); const tabBox = here.box('.webfront-terminal-toggle'); here.rightClick(here.button(), tabBox.left + 10, tabBox.top + 10); - const entries = await inspectorEntries(here, 1, await inspectorReason(webFront)); - assert(entries.length === 3 && entries.every(entry => entry.getAttribute('aria-disabled') === 'true'), - 'Without an inspector to open, the entries of this page must be greyed'); - here.press(entries[0], {key: 'Escape'}); - assert(here.menus().length === 0 && document.activeElement === here.button(), 'Escape in a submenu must close the whole menu and give the focus back to the tab'); + if (!admitted) { + const entries = await inspectorEntries(here, 1, /trustLoopbackClients/); + assert(entries.length === 3 && entries.every(entry => entry.getAttribute('aria-disabled') === 'true'), + 'The inspector entries of a page that is not admitted must be greyed'); + here.press(entries[0], {key: 'Escape'}); + assert(document.activeElement === here.button(), 'Escape in a submenu must give the focus back to the tab'); + } else { + // The view of an embedded frontend is admitted: its Watches entry opens the inspector (#680, ADR-027 section 8). + const opened = []; + const open = window.open; + window.open = (...args) => { opened.push(args); return null; }; + try { + const entries = await availableEntries(here, 1); + here.press(entries[2], {key: 'Enter'}); + const floating = () => document.querySelector('.webfront-inspector-window'); + await until(() => floating() && !floating().hidden, 'The Watches entry must open the inspector in a floating window'); + assert(here.menus().length === 0 && here.inside('.webfront-inspector-window'), 'The inspector window must stay inside the page, with the menu closed'); + const frame = floating().querySelector('iframe'); + const listed = () => [...(frame.contentDocument?.querySelectorAll('ul.watches li .name') ?? [])].map(item => item.textContent); + await until(() => frame.contentDocument?.querySelector('ul.watches'), 'The floating inspector must show the watches'); + // The frame borrows this page's bridge: it opens no connection and loads no WebFront.js of its own. + assert(!Object.hasOwn(frame.contentWindow, 'webFront') && !frame.contentDocument.querySelector('script[src="/WebFront.js"]'), + 'The inspector\'s frame must not open a connection of its own'); + // A watch registered while the inspector is open appears, and disappears once removed (ADR-027, section 3). + await webFront.cppFunction('test.watch')('integration'); + await until(() => listed().includes('integration'), `A registered watch must appear in the inspector: ${listed()}`); + // The list that showed it must be the one that loses it: the same document, still shown. + const shownDocument = frame.contentDocument, shownList = shownDocument.querySelector('ul.watches'); + const inShownList = () => [...shownList.querySelectorAll('li .name')].map(item => item.textContent).includes('integration'); + await webFront.cppFunction('test.unwatch')('integration'); + await until(() => !inShownList(), `A removed watch must disappear from the inspector: ${listed()}`); + assert(shownList.isConnected && frame.isConnected && frame.contentDocument === shownDocument, + 'The watch must have disappeared from the list that showed it, still in the inspector'); + const detach = floating().querySelector('.webfront-inspector-detach'); + if (secondaryWindow) { + // A frontend that opens windows: Detach moves the panel to a native window with its own proven connection. + const views = await webFront.cppFunction('test.views')(); + assert(detach.getAttribute('aria-disabled') === 'false', 'A frontend that opens windows must offer to detach the panel'); + detach.click(); + await until(() => floating().hidden, 'A detached panel must leave the floating window'); + await until(async () => await webFront.cppFunction('test.views')() === views + 1, + 'The detached inspector must be a secondary window, connected as a proven view'); + await window.webfrontInspectorHost.saved(); + const kept = JSON.parse(new TextDecoder().decode(await call('read', '.webfront/developer/inspector-window.json', 0))); + assert(kept.detached.includes('cpp.watches'), `The project must remember the detached panel: ${JSON.stringify(kept)}`); + assert(await webFront.cppFunction('webfront.inspector.closeWindow')('cpp.watches', window.webfrontInspectorHost.id) === true, 'The panel\'s window must close'); + assert(await webFront.cppFunction('webfront.inspector.closeWindow')('cpp.watches', window.webfrontInspectorHost.id) === false, + 'The closed inspector window must be gone'); + // A closed view's connection ends when its engine releases the page: WKWebView may take seconds. + await eventually(async () => await webFront.cppFunction('test.views')() === views, 'The closed inspector window must disconnect', + {attempts: 1200}); + window.webfrontInspectorHost.attach('cpp.watches'); + await window.webfrontInspectorHost.saved(); + } else { + // CEF, or a view without a secondary window: the floating window is the only container, and Detach says why. + assert(detach.getAttribute('aria-disabled') === 'true' && /No detached window/.test(detach.title), + `Without a detached container, Detach must be greyed with its reason: ${detach.title}`); + detach.click(); + assert(!floating().hidden, 'A greyed Detach must leave the panel in the floating window'); + } + assert(opened.length === 0, 'An embedded view must never open a tab of the inspectors'); + floating().querySelector('.webfront-inspector-close').click(); + assert(floating().hidden, 'The inspector window must close'); + } finally { window.open = open; } + } + assert(here.menus().length === 0, 'The menu must be closed'); } // Launching again: the bootstrap page of the same project, in a window of its own size. @@ -1042,12 +1112,25 @@ try { assert(again.inside('.webfront-terminal-window') && again.box('.webfront-terminal-window').right > again.viewport().width - 1, 'A drag must stay inside the window'); pointer('pointermove', 0, 0); assert(left() > 0, 'A released bar must not follow the pointer'); - // The place is remembered in the project. + // The unproven bootstrap frame can move its terminal, and its project writes are refused. + const framePlace = {x: left(), y: top()}; const placePath = '.webfront/developer/terminal-window.json'; + const frameWrite = await failure(relaunched.contentWindow.webFront.cppFunction('webfront.developer.begin')(placePath, false)); + assert(frameWrite?.code === 'webfront.inspector.denied', 'An unproven bootstrap frame must not publish its terminal place'); + + // Move the proven main view's terminal and check that a later session will read its place. + if (here.state() === 'interface') here.button().click(); + for (let count = 0; count < 100; ++count) { + key(here.bar(), {key: 'ArrowLeft'}); + key(here.bar(), {key: 'ArrowUp'}); + } + key(here.bar(), {key: 'ArrowRight'}); + key(here.bar(), {key: 'ArrowDown'}); + const mainPlace = here.box('.webfront-terminal-window'); const place = async () => { try { return JSON.parse(new TextDecoder().decode(await readFile(placePath))); } catch { return null; } }; - await until(async () => (await place())?.x === left(), 'The place of the terminal window must be remembered in the project'); + await until(async () => (await place())?.x === mainPlace.x, 'The place of the proven view must be remembered in the project'); const remembered = await place(); - assert(remembered.format === 1 && remembered.width === again.box('.webfront-terminal-window').width, `The size must be remembered too: ${JSON.stringify(remembered)}`); + assert(remembered.format === 1 && remembered.width === mainPlace.width, `The size must be remembered too: ${JSON.stringify(remembered)}`); // A smaller window keeps the icon and the terminal window; the remembered place comes back with the room. const columns = () => Math.round(page.querySelector('#terminal .xterm-screen')?.getBoundingClientRect().width ?? 0); @@ -1064,7 +1147,7 @@ try { assert(again.inside('.webfront-terminal-window') && again.inside('.webfront-terminal-toggle'), 'A small window must keep the icon and the terminal window'); await until(() => columns() < wideScreen, 'xterm.js must be fitted to a smaller terminal window'); resize(900, 600); - await until(() => left() === remembered.x && top() === remembered.y, 'A window enlarged again must give the terminal window its place back'); + await until(() => left() === framePlace.x && top() === framePlace.y, 'A window enlarged again must give the terminal window its place back'); await until(() => columns() === wideScreen, 'xterm.js must be fitted to the terminal window again'); // The close button and the shortcut collapse and open it, wherever the focus is.