From 9b6df718223e2b41b34f9e2bf25f898c64f7a39e Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:50:19 +0100 Subject: [PATCH 01/21] Detachable inspector host and discovery of the watches (#680) The tab's menu opens inspector.html of the environment in the container that reaches C++ (ADR-027, section 8): a floating window of the page whose frame borrows the page's bridge, a native secondary window (webfront.inspector.openWindow) or, with trustLoopbackClients, a tab of the system browser. Each panel can be detached and attached again; the choice and the place are kept in .webfront/developer/inspector-window.json. app.watch(name, source) registers a watch while its handle lives, only in the developer environment; webfront.inspector.watches pages the registry by identifier with its revision, and the Watches panel follows registrations and removals. cppFunction refuses the names reserved to the inspectors. webfront.inspector.embedded and closeWindow are recorded in ADR-027 1.1. The floating window makes a new frame for each panel instead of navigating it: a navigation adds a history entry, after which WebKitGTK refuses window.close(). --- docs/CHANGELOG.md | 5 + docs/DEVELOPER_ENVIRONMENT.md | 21 +- ...-inspecteurs-de-l-etat-de-l-application.md | 10 + include/webfront/DeveloperApp.hpp | 93 +++- include/webfront/Watches.hpp | 445 ++++++++++++++++++ include/webfront/WebFront.hpp | 137 ++++-- js/developer/environment/bundles.json | 13 +- js/developer/environment/inspector-host.mjs | 328 +++++++++++++ js/developer/environment/inspector.html | 14 + js/developer/environment/inspector.mjs | 317 +++++++++++++ js/developer/environment/menu.mjs | 15 +- js/developer/environment/runtime.mjs | 12 +- js/developer/environment/workspace.mjs | 73 +-- js/developer/scripts/build.mjs | 7 +- js/developer/tools/bundle-inputs.json | 3 + js/developer/webfront.project.json | 1 + test/developer/specs/inspector-specs.mjs | 373 +++++++++++++++ test/unit/CMakeLists.txt | 2 +- test/unit/InspectorDistribution.cpp | 14 +- test/unit/ViewAssociationTests.cpp | 183 +++++++ test/unit/WatchTests.cpp | 288 ++++++++++++ test/web/DeveloperTest.cpp | 32 +- test/web/developer-specs.mjs | 76 ++- 23 files changed, 2365 insertions(+), 97 deletions(-) create mode 100644 include/webfront/Watches.hpp create mode 100644 js/developer/environment/inspector-host.mjs create mode 100644 js/developer/environment/inspector.html create mode 100644 js/developer/environment/inspector.mjs create mode 100644 test/developer/specs/inspector-specs.mjs create mode 100644 test/unit/WatchTests.cpp diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e3c91636..262e717f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -11,12 +11,17 @@ these entries stays in the GitHub releases and the Git history. ## Unreleased ### 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). - Compile test files faster: include ``, free of ``, `` and ``, and only the parts a file uses (`bdd/Matchers.hpp`, `bdd/Approx.hpp`, `bdd/Eventually.hpp`, `bdd/Runner.hpp` for `main()`); `Bdd.hpp` still includes them all (#669, `docs/BDD.md`). - See both operands of a failed comparison with `checkEqual(a, b)`/`requireEqual(a, b)`, and write your own types in reports by specializing `webfront::bdd::Printer` (#669, `docs/BDD.md`). - Compare floating-point values within a tolerance with `approx(v)`, `.epsilon()` and `.margin()`, Catch2's `Approx` semantics, with the expected value and tolerances in the failure (#669, `docs/BDD.md`). - Run code after the last scenario with the third, optional `runEnding` function of `webfront::bdd::Listener`, called before the summary and the JUnit report whatever the outcome, even when a run- or scenario-starting listener threw; an exception of a run listener fails the run and appears in the JUnit report (#669, `docs/BDD.md`). - The test helpers, `webfront_add_jasmine_test` included, export the real `XDG_DATA_HOME` and `XDG_CACHE_HOME` as `WEBFRONT_TEST_REAL_XDG_DATA_HOME` and `WEBFRONT_TEST_REAL_XDG_CACHE_HOME`, so an application under test can keep the throwaway WebKitGTK profile away from the programs it starts ([#664](https://github.com/ambroise-leclerc/WebFront/issues/664), `docs/CONSUMER_TESTING.md`). +### Changed +- `cppFunction` refuses the names starting with `webfront.inspector.`, which belong to the inspectors, with `std::invalid_argument` (#680, ADR-027). + ### Fixed - `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`). diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index b1a263ae..cb4fa259 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -442,8 +442,25 @@ 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 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: the adapters give the proof of the view to the main frame only. **Detach** moves the + panel to a window of its own, and **Attach**, in that window, brings it back to the floating window: + + | 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) | + + The project keeps the detached panels and the floating window's place in `.webfront/developer/inspector-window.json`. + 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/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..da9e2acc 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 est la vue d'un frontend intégré, ce qui décide de l'onglet du navigateur système ; `webfront.inspector.closeWindow(panneau)` ferme la fenêtre d'un panneau rattaché ; une fenêtre par panneau ; choix et place conservés dans `inspector-window.json`. | À 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 @@ -670,6 +671,15 @@ 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 rend +`UI::isEmbeddedView()` de l'appelant ; un échec compte comme une vue intégrée, ce qui n'essaie jamais d'onglet. Chaque +panneau détaché a sa propre fenêtre, nommée par la page `inspector.html?panel=` : `openWindow(panneau, largeur, +hauteur)` n'accepte que les panneaux du menu, et `webfront.inspector.closeWindow(panneau)` 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 à la page +hôte par un `BroadcastChannel` de même origine, et ne se ferme qu'après sa réponse. + 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/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 373da32d..79c087f7 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,24 @@ 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 page of the environment that shows an inspector panel, as openSecondaryWindow() names its window: one window per +/// panel, so that opening a panel again brings its window to the front. Throws std::invalid_argument for an unknown panel. +inline std::string inspectorPage(std::string_view panel) { + if (std::ranges::find(inspectorPanels, panel) == inspectorPanels.end()) + throw std::invalid_argument("Unknown inspector panel"); + return "webfront/developer/environment/inspector.html?panel=" + std::string(panel); +} + +/// 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) { @@ -141,15 +162,77 @@ class DeveloperAppWithNetwork : public BasicWF("webfront.developer.state"); expose<&Store::commitGroupLines, void, std::string, std::string, std::string>("webfront.developer.commitGroup"); #if !(defined(WEBFRONT_DISTRIBUTION) && WEBFRONT_DISTRIBUTION) - // The inspectors exist only in the developer environment and never in a distribution build (ADR-027, section 1). + 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). 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 is the view of an embedded frontend: a tab of the system browser is offered only to a page + // that is not (ADR-027, section 8), since window.open() in an embedded view would open a frame without the proof. + this->template reservedCppFunction("webfront.inspector.embedded", [](Caller ui) { + admit(ui); + return ui.isEmbeddedView(); }); -#endif + // 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, 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, double, double>( + "webfront.inspector.openWindow", + [this](Caller ui, std::string panel, double width, double height) -> ResultTask { + admit(ui); + auto page = developer::inspectorPage(panel); + 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)}; + // 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(), [&] { + this->openSecondaryWindow(page, std::move(options)); + }); + }); + // Closes the panel's secondary window, when it is attached again; false when none is open. + this->template reservedCppFunction, Caller, std::string>( + "webfront.inspector.closeWindow", + [this](Caller ui, std::string panel) -> ResultTask { + admit(ui); + auto page = developer::inspectorPage(panel); + if (!Base::canShowSecondaryWindow()) + co_return false; + co_return co_await networking::ex::then(this->uiExecutor().schedule(), [&] { + return this->requestClose(page); + }); + }); } + /// 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)"); + } +#endif + /// Registers a store operation as a bridge callback; the store stays alive as long as the callback. template void expose(std::string name) { diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp new file mode 100644 index 00000000..794e61a0 --- /dev/null +++ b/include/webfront/Watches.hpp @@ -0,0 +1,445 @@ +// 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: heap-init +// 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); +} + +/// 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. +[[nodiscard]] inline std::string boundedText(std::string_view text, std::size_t limit = maxTextBytes) { + std::string visible; + visible.reserve(std::min(text.size(), limit + 4)); + for (const char c : text) { + 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; + if (visible.size() > limit + 4) + break; // enough to know that it is cut + } + if (visible.size() <= limit) + return visible; + constexpr std::string_view ellipsis = "…"; + std::string cut{utf8Prefix(visible, limit - ellipsis.size())}; + cut += ellipsis; + return cut; +} + +/// Where a watch was declared, "file:line", keeping the end of a long path (the file's name) within the bound. +[[nodiscard]] inline std::string locationText(const std::source_location& location) { + const std::string full = std::string(location.file_name()) + ':' + std::to_string(location.line()); + if (full.size() <= maxTextBytes) + return boundedText(full); + constexpr std::string_view ellipsis = "…"; + std::size_t start = full.size() - (maxTextBytes - ellipsis.size()); + while (start < full.size() && (static_cast(full[start]) & 0xC0u) == 0x80u) + ++start; + return boundedText(std::string(ellipsis) + full.substr(start)); +} + +// --- 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 { }; + +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; +}; + +template + requires(!detail::visitor_source && std::invocable) +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; + 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, or the name + /// of a watch that is still registered. + std::uint64_t add(std::string name, std::string_view kind, std::string location, bool writable, std::shared_ptr source) { + checkName(name); + 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::string(kind), std::move(location), 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. + */ + [[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) { + more = true; + break; + } + used += bytes; + last = entry->first; + served.emplace_back(static_cast(entry->first), entry->second.name, 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.name.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 { + if (this != &other) { + reset(); + registry = std::move(other.registry); + watchId = std::exchange(other.watchId, 0); + } + return *this; + } + ~Watch() { + reset(); + } + + /// Removes the watch now; the handle becomes empty. + void reset() noexcept { + if (const auto id = std::exchange(watchId, 0); id != 0) + if (const auto owner = registry.lock()) + owner->remove(id); + registry.reset(); + } + + /// 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; +}; + +} // namespace webfront::inspect diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 4fb7115f..86d72405 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -25,6 +25,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" @@ -40,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -1112,23 +1114,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) { - if constexpr (detail::deferred_result) - return registerDeferred(std::move(functionName), std::forward(function)); - else if constexpr (detail::takes_caller::value) - return registerWithCaller(std::move(functionName), std::forward(function)); - else { - auto callable = detail::makeCppFunctionHandler(std::forward(function)); - auto responder = detail::makeCppFunctionResponder(std::move(callable)); - return cppFunctions - .try_emplace(std::move(functionName), - [responder](std::span data, WebLink& link, msg::CallId callId, UI) mutable { - responder(data, link, callId); - }) - .second; - } + refuseReservedName(functionName); + return registerCppFunction(std::move(functionName), std::forward(function)); } /** @@ -1143,6 +1134,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) { @@ -1156,6 +1148,64 @@ 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) { + if constexpr (detail::deferred_result) + return registerDeferred(std::move(functionName), std::forward(function)); + else if constexpr (detail::takes_caller::value) + return registerWithCaller(std::move(functionName), std::forward(function)); + else { + auto callable = detail::makeCppFunctionHandler(std::forward(function)); + auto responder = detail::makeCppFunctionResponder(std::move(callable)); + return cppFunctions + .try_emplace(std::move(functionName), + [responder](std::span data, WebLink& link, msg::CallId callId, UI) mutable { + responder(data, link, callId); + }) + .second; + } + } + +public: enum class WindowAction { none, closeWindow }; #ifdef _MSC_VER // A Frontend::open() that unconditionally throws (e.g. CEFFrontend::open() when CEF support @@ -1488,6 +1538,27 @@ class BasicWF { windowOptions.background = "#141821"; } + /// Registers one of WebFront's own reserved functions (`webfront.inspector.*`), which cppFunction refuses to the application. + template + bool reservedCppFunction(std::string functionName, auto&& function) { + return registerCppFunction(std::move(functionName), std::forward(function)); + } + + /// For the developer environment: from now on, watch() registers in the table that the inspectors read (ADR-027). + /// Returns that table. A distribution build never calls it. + std::shared_ptr enableInspectors() { + std::scoped_lock lock{watchRegistryMutex}; + if (!watchRegistry) + watchRegistry = std::make_shared(); + return watchRegistry; + } + + /// The table of the watches, null until enableInspectors(). + [[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 { @@ -1696,24 +1767,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/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 5a7329ce..38d7bb2e 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": "ed8a2a4d10dadc110a0083a2bf63fa7ed721c980a512e4446e5c0559b5e43671", "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/workspace.mjs": "81c1d7550fcb70cc5f6ebd8e431ffc3d332de2ae6c8df83ed65b737b512519ac", + "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", + "js/developer/environment/inspector-host.mjs": "d9a5bf10b5d2715f8b9348631ed43fe8516459ec9aca2a177b6e48f62d280528", + "js/developer/environment/inspector.mjs": "e7d346957d6aa28bb693e58a83c850d6a7face70f16b72e5fb6c27eba93fea3c", + "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..2cbf7004 --- /dev/null +++ b/js/developer/environment/inspector-host.mjs @@ -0,0 +1,328 @@ +// 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, publish} 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'; + +export async function readPreferences(bridge) { + try { return parsePreferences(decoder.decode(await readProject(bridge, preferencesPath))); } + catch { return parsePreferences(''); } +} + +/** Writes the choices shortly after they stop changing; a failed write keeps the inspector usable. */ +export function preferencesStore(bridge, delay = 300) { + let timer = null, pending = null, writes = Promise.resolve(), written = null; + const flush = () => { + clearTimeout(timer); + timer = null; + if (!pending) return writes; + const text = formatPreferences(pending); + pending = null; + writes = writes.then(async () => { + if (text === written) return; + await publish(bridge, preferencesPath, new Map([['output', encoder.encode(text)]]), {directory: false}); + written = text; + }).catch(() => {}); + return writes; + }; + return { + remember(preferences) { + pending = {detached: new Set(preferences.detached), rect: preferences.rect}; + clearTimeout(timer); + timer = setTimeout(flush, 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}`; + +/** + * 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 is an embedded view (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). + */ +export async function createInspectorHost({bridge, page, inspectorUrl, access, embedded = null, windowOpen = null}) { + const view = page.defaultView, root = page.documentElement; + 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 remember = () => store.remember(preferences); + 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); + 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; + 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()); + remember(); + 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 = '') { + 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() { + 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. */ + async function openDetached(id, container) { + if (container === 'window') { + const rect = shown(); + try { + await bridge.cppFunction('webfront.inspector.openWindow')(id, rect.width, rect.height); + return true; + } catch (error) { + retryPanel = id; + showFloating(id, `${hostReasons.windowFailed}: ${error?.message ?? error}`); + return false; + } + } + const tab = openTab(urlOf(id), `webfront-inspector-${id.replace('.', '-')}`); + if (tab) return true; + retryPanel = id; + showFloating(id, hostReasons.blocked); + return false; + } + + const host = { + get containers() { return containers; }, + get embedded() { return isEmbedded; }, + 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'; + } + if (await openDetached(id, container)) { + if (shownPanel === id) hideFloating(); + 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); + remember(); + if (await openDetached(id, container)) { + if (shownPanel === id) hideFloating(); + return container; + } + return 'floating'; + }, + /** Moves `id` back to this page's floating window, and remembers it there. */ + attach(id) { + preferences.detached.delete(id); + remember(); + retryPanel = null; + showFloating(id); + }, + close: hideFloating, + 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', hideFloating); + retry.addEventListener('click', () => { if (retryPanel) host.detach(retryPanel); }); + + // A detached inspector asks to come back: the first host that takes it answers, so that the inspector closes its window. + if (typeof view.BroadcastChannel === 'function') { + const channel = new view.BroadcastChannel(inspectorChannel); + channel.addEventListener('message', ({data}) => { + if (data?.type !== 'attach' || !panels.has(data.panel) || !containers?.host) return; + host.attach(data.panel); + channel.postMessage({type: 'attached', id: data.id}); + }); + host.channel = channel; + } + // The frame of the floating window reaches its host here: the same origin, and no connection of its own. + view.webfrontInspectorHost = host; + return host; +} 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..d9a26c80 --- /dev/null +++ b/js/developer/environment/inspector.mjs @@ -0,0 +1,317 @@ +// 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) { + let borrowed = null; + try { borrowed = view.parent.webFront; } + 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}; +} + +/** Every live watch, page after page from the start, with the revision of the registry that the last page gave. */ +export async function listWatches(bridge, revision = 0) { + const watches = []; + let after = 0, latest = revision; + for (;;) { + const page = readPage(await bridge.cppFunction(watchesFunction)(revision, after, 200)); + watches.push(...page.descriptors); + latest = page.revision; + if (!page.next) return {watches, revision: latest}; + after = page.next; + } +} + +/** 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. + */ +export function createWatchDiscovery({bridge, onChange, onError = () => {}, 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()]}); + }; + async function poll() { + const {changed, revision: current} = readPage(await bridge.cppFunction(watchesFunction)(revision, 0, 0)); + if (!changed && current === revision) return; + const listed = await listWatches(bridge, current); + revision = listed.revision; + apply(listed.watches); + } + function schedule() { + if (stopped || paused || timer !== 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])); + for (const [id, item] of items) if (!watches.some(watch => watch.id === 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); + } +} + +/** + * 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)}`; + 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; + } + + 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); + attach.addEventListener('click', () => attachAgain(view, bridge, id, status)); + // A tab that the main page opened closes with it, as a secondary window closes with the main window (#616). + if (view.opener) { + const opener = view.opener; + const watcher = view.setInterval(() => { if (opener.closed) view.close(); }, 1000); + view.addEventListener('pagehide', () => view.clearInterval(watcher)); + } + } + + 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); + describe(watches); + }, + 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(); + if (!discovery.watches.length && !status.classList.contains('error')) describe([]); + return {bridge, discovery, list}; +} + +/** + * Asks the main page to show the panel again, and closes this window once it answered: a native window through C++, a tab + * by itself. Without an answer the window stays, and says why. + */ +export async function attachAgain(view, bridge, id, status, wait = 1000) { + if (typeof view.BroadcastChannel !== 'function') { + status.textContent = 'This browser cannot reach the main page from here: close this window and open the panel from the menu.'; + return false; + } + const channel = new view.BroadcastChannel(channelName); + const request = `${id}:${Date.now()}:${Math.random()}`; + const answered = await new Promise(resolve => { + const timer = view.setTimeout(() => resolve(false), wait); + channel.addEventListener('message', ({data}) => { + if (data?.type !== 'attached' || data.id !== request) return; + view.clearTimeout(timer); + resolve(true); + }); + channel.postMessage({type: 'attach', panel: id, id: request}); + }); + channel.close(); + if (!answered) { + status.textContent = 'The main page did not answer: open the panel from the menu of its tab.'; + return false; + } + if (view.opener) view.close(); + else await bridge.cppFunction('webfront.inspector.closeWindow')(id).catch(() => view.close()); + return true; +} 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..9c741c82 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 {createInspectorHost} 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,14 @@ 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++: their host is made at the first use. + let inspectors = null; + const openInspector = panel => { + inspectors ??= createInspectorHost({bridge, page: element.ownerDocument, access: workspace.inspectorAccess, + inspectorUrl: new URL('./inspector.html', import.meta.url).href}); + return inspectors.then(host => host.open(panel)); + }; + const workspace = layout && preview && !isManaged(preview) ? await createWorkspace({bridge, element, frame: preview, openInspector}) : null; terminal.open(element); fit.fit(); const write = text => terminal.write(text); @@ -744,5 +752,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}; } diff --git a/js/developer/environment/workspace.mjs b/js/developer/environment/workspace.mjs index 5fbaf94d..c74b00be 100644 --- a/js/developer/environment/workspace.mjs +++ b/js/developer/environment/workspace.mjs @@ -164,6 +164,48 @@ 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}) { + let grip = null; + bar.addEventListener('pointerdown', event => { + if (event.button !== 0 || event.target.closest?.('button')) 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 (!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 +425,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/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs new file mode 100644 index 00000000..912f5e45 --- /dev/null +++ b/test/developer/specs/inspector-specs.mjs @@ -0,0 +1,373 @@ +// 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} from '../../../js/developer/environment/inspector-host.mjs'; +import {readDescriptor, readPage, listWatches, reconcile, createWatchDiscovery, renderWatches, pageBridge, attachAgain, + watchesFunction} from '../../../js/developer/environment/inspector.mjs'; +import {inspectorChannel, inspectorPanels} from '../../../js/developer/environment/menu.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('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 () => {}, windowOpen = () => ({})} = {}) { + 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.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: ''}), windowOpen: (url, name) => { opened.push([url, name]); return windowOpen(url, name); }}); + hosts.push(host); + return {host, 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} = 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); + // 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, width, height] = calls.find(([name]) => name === 'webfront.inspector.openWindow'); + expect(panel).toBe('cpp.watches'); + 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(name).toBe('webfront-inspector-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('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', 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('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()}; + const view = {parent: {webFront: bridge}, document}; + expect(await pageBridge(view, {frame: true})).toBe(bridge); + 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') host.postMessage({type: 'attached', id: data.id}); + }); + try { expect(await attachAgain(view, null, 'cpp.watches', status)).toBeTrue(); } + finally { host.close(); } + expect(closed).toEqual([true]); + expect(await attachAgain(view, null, 'cpp.watches', status, 50)).toBeFalse(); + expect(status.textContent).toContain('did not answer'); + expect(closed.length).toBe(1); + }); + + 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)).toBeTrue(); } + finally { host.close(); } + expect(calls).toEqual([['webfront.inspector.closeWindow', 'cpp.functions']]); + }); + }); + + 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('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('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/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 95234207..71e6d0df 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 WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) +list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp WatchTests.cpp BroadcastTests.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/InspectorDistribution.cpp b/test/unit/InspectorDistribution.cpp index dab5658f..32d52aa6 100644 --- a/test/unit/InspectorDistribution.cpp +++ b/test/unit/InspectorDistribution.cpp @@ -33,7 +33,19 @@ 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.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/ViewAssociationTests.cpp b/test/unit/ViewAssociationTests.cpp index c704b4ad..c89e33b9 100644 --- a/test/unit/ViewAssociationTests.cpp +++ b/test/unit/ViewAssociationTests.cpp @@ -391,3 +391,186 @@ 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 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))); +} + +/// 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 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"}, 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"}, 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"}, 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 has its own window, and only the panels of the menu have one", [&] { + requireEqual(developer::inspectorPage("cpp.watches"), std::string{"webfront/developer/environment/inspector.html?panel=cpp.watches"}); + checkThrows([] { + static_cast(developer::inspectorPage("cpp")); + }); + 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 page asks whether this page is an embedded view", [&] { + callWithoutArgument("webfront.inspector.embedded", 12); + require(!ViewSocket::wrote(inspect::code::denied)); + }); + 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", [&] { + require(ViewSocket::wrote(inspect::code::denied)); + }); + }); + 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..61afb3be --- /dev/null +++ b/test/unit/WatchTests.cpp @@ -0,0 +1,288 @@ +// 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_ + "éé"); // the é crosses 256 bytes + require(cut.size() <= inspect::maxTextBytes); + require(cut.ends_with("…")); + requireEqual(inspect::utf8Prefix("aé", 2), std::string_view{"a"}); + }); + 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:")); + }); + }); + }}; + +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 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 small = registry.page(revision, 0, 200, inspect::responseHeaderBytes + 80); + requireEqual(namesOf(small), std::vector{"a", "b"}); + const auto next = registry.page(revision, std::get<1>(small), 200, inspect::responseHeaderBytes + 80); + requireEqual(namesOf(next), std::vector{"c", "d"}); + }); + then("a count above 1 000 is read as 1 000, and numbers that are not whole are refused", [&] { + requireEqual(std::get<0>(registry.page(revision, 0, 5000, 32768)).size(), std::size_t{5}); + 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}); + }); + }); + }}; + +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("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..59aa82e7 100644 --- a/test/web/DeveloperTest.cpp +++ b/test/web/DeveloperTest.cpp @@ -291,7 +291,25 @@ class Part { 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 +317,7 @@ class Part { } ~Part() { + watches.clear(); states->releaseAll(); app.stop(); // Drain while the commands, callback state and project are still alive. @@ -351,12 +370,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-specs.mjs b/test/web/developer-specs.mjs index 36f9e956..77a04227 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,66 @@ 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. + const [secondaryWindow, admitted] = await webFront.cppFunction('webfront.inspector.containers')(); 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()}`); + await webFront.cppFunction('test.unwatch')('integration'); + await until(() => !listed().includes('integration'), `A removed watch must disappear from the inspector: ${listed()}`); + 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') === true, 'The panel\'s window must close'); + await until(async () => await webFront.cppFunction('test.views')() === views, 'The closed inspector window must disconnect'); + 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. From 5f0105a26d18f6fb62c51ba9ce489092c33cc4f7 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:09:31 +0100 Subject: [PATCH 02/21] List the watches again when they change between pages, and attach a panel to its own page only (#680) listWatches read the pages after the first one without noticing a change of the registry, and kept the revision of the last page: a watch removed between two pages stayed in the list under a revision that no poll found changed. The pages now carry the revision of the first one, and a page that answers "changed" starts the listing again; after eight such changes the list is given with the revision 0, which the next poll reads again. Every host page had taken the attach request of any detached panel of the same origin. Each host page now has an identifier, kept in its tab's session storage, that the address of its detached windows carries (inspector.html?panel=&host=, checked by C++ in openWindow and closeWindow); only the page named in the request takes the panel back. --- docs/DEVELOPER_ENVIRONMENT.md | 4 +- ...-inspecteurs-de-l-etat-de-l-application.md | 21 ++-- include/webfront/DeveloperApp.hpp | 35 +++--- js/developer/environment/bundles.json | 4 +- js/developer/environment/inspector-host.mjs | 34 +++++- js/developer/environment/inspector.mjs | 53 ++++++--- test/developer/specs/inspector-specs.mjs | 102 +++++++++++++++--- test/unit/ViewAssociationTests.cpp | 19 ++-- test/web/developer-specs.mjs | 2 +- 9 files changed, 215 insertions(+), 59 deletions(-) diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index cb4fa259..051db9dd 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -456,7 +456,9 @@ environment's `mount`, not to the embedded bootstrap page): | 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) | - The project keeps the detached panels and the floating window's place in `.webfront/developer/inspector-window.json`. + 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. The project keeps the detached panels and the floating window's place in + `.webfront/developer/inspector-window.json`. 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. 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 da9e2acc..9bc8385f 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,7 +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 est la vue d'un frontend intégré, ce qui décide de l'onglet du navigateur système ; `webfront.inspector.closeWindow(panneau)` ferme la fenêtre d'un panneau rattaché ; une fenêtre par panneau ; choix et place conservés dans `inspector-window.json`. | À renseigner après intégration. | +| 1.1 | 2026-11-25 | Proposée | Ambroise Leclerc | Hôte détachable (#680) : `webfront.inspector.embedded()` dit à la page hôte si elle est la vue d'un frontend intégré, 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`. | À 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 @@ -673,12 +673,19 @@ La page se charge dans le premier conteneur qui convient : 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 rend -`UI::isEmbeddedView()` de l'appelant ; un échec compte comme une vue intégrée, ce qui n'essaie jamais d'onglet. Chaque -panneau détaché a sa propre fenêtre, nommée par la page `inspector.html?panel=` : `openWindow(panneau, largeur, -hauteur)` n'accepte que les panneaux du menu, et `webfront.inspector.closeWindow(panneau)` 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 à la page -hôte par un `BroadcastChannel` de même origine, et ne se ferme qu'après sa réponse. +`UI::isEmbeddedView()` de l'appelant ; un échec compte 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. 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, et la fenêtre ne +se ferme qu'après cette réponse. + +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. La même règle désactive « Détacher » quand aucun conteneur détaché ne donnerait l'accès. diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 79c087f7..c2521dd9 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -86,12 +86,23 @@ inline constexpr std::tuple inspectorContainers(bool frontendO /// 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 page of the environment that shows an inspector panel, as openSecondaryWindow() names its window: one window per -/// panel, so that opening a panel again brings its window to the front. Throws std::invalid_argument for an unknown panel. -inline std::string inspectorPage(std::string_view panel) { +/// 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 == '_'; + }); +} + +/// 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"); - return "webfront/developer/environment/inspector.html?panel=" + std::string(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. @@ -194,13 +205,13 @@ class DeveloperAppWithNetwork : public BasicWFpage(revision, after, count, inspect::responseBudget); }); - // A secondary window of the panel, with the proof of the view (section 8); opening it again brings it to the front. + // 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, double, double>( + this->template reservedCppFunction, Caller, std::string, std::string, double, double>( "webfront.inspector.openWindow", - [this](Caller ui, std::string panel, double width, double height) -> ResultTask { + [this](Caller ui, std::string panel, std::string host, double width, double height) -> ResultTask { admit(ui); - auto page = developer::inspectorPage(panel); + 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", @@ -211,12 +222,12 @@ class DeveloperAppWithNetwork : public BasicWFopenSecondaryWindow(page, std::move(options)); }); }); - // Closes the panel's secondary window, when it is attached again; false when none is open. - this->template reservedCppFunction, Caller, std::string>( + // 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) -> ResultTask { + [this](Caller ui, std::string panel, std::string host) -> ResultTask { admit(ui); - auto page = developer::inspectorPage(panel); + auto page = developer::inspectorPage(panel, host); if (!Base::canShowSecondaryWindow()) co_return false; co_return co_await networking::ex::then(this->uiExecutor().schedule(), [&] { diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 38d7bb2e..d87b9b03 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -24,8 +24,8 @@ "js/developer/environment/terminal.mjs": "1d81a28a6e6cfd5bdb1ff8854e17a273b7bcfebf2c97d469b8706db636f3799e", "js/developer/environment/workspace.mjs": "81c1d7550fcb70cc5f6ebd8e431ffc3d332de2ae6c8df83ed65b737b512519ac", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "d9a5bf10b5d2715f8b9348631ed43fe8516459ec9aca2a177b6e48f62d280528", - "js/developer/environment/inspector.mjs": "e7d346957d6aa28bb693e58a83c850d6a7face70f16b72e5fb6c27eba93fea3c", + "js/developer/environment/inspector-host.mjs": "46b6a2bfc22c63a3f78349b939102089291d800a71a832e71a877c32ad4b20fd", + "js/developer/environment/inspector.mjs": "a8815c23ea618fbf061bf1ac028fba86848e47c820730d6e535edcfe1285b347", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index 2cbf7004..d13bc1d5 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -118,15 +118,37 @@ const styles = ` .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'; + +/** + * The identifier of this host page: the one its tab already has, else a new random one (1 to 64 letters, digits, `-` or + * `_`, which webfront.inspector.openWindow checks). Each tab has its own, so a detached panel is attached again only to + * the page that detached it, even when several pages of the application are open on the same origin. + */ +export function hostIdentifier(view) { + const valid = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value); + let stored = null; + try { stored = view.sessionStorage?.getItem(hostKey); } + catch { /* no storage: a new identifier for this load */ } + if (valid(stored)) return stored; + const bytes = view.crypto.getRandomValues(new Uint8Array(12)); + const made = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''); + try { view.sessionStorage?.setItem(hostKey, made); } + catch { /* kept for this load only */ } + return made; +} + /** * 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 is an embedded view (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). + * can). `windowOpen` replaces window.open (tests). `hostId` names this page in its detached windows (hostIdentifier()). */ -export async function createInspectorHost({bridge, page, inspectorUrl, access, embedded = null, windowOpen = null}) { +export async function createInspectorHost({bridge, page, inspectorUrl, access, embedded = null, windowOpen = null, hostId = null}) { const view = page.defaultView, root = page.documentElement; + const self = hostId ?? hostIdentifier(view); const viewport = () => ({width: root.clientWidth, height: root.clientHeight}); const [preferences, containers, isEmbedded] = await Promise.all([ readPreferences(bridge), @@ -139,6 +161,7 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e 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; }; @@ -244,7 +267,7 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e if (container === 'window') { const rect = shown(); try { - await bridge.cppFunction('webfront.inspector.openWindow')(id, rect.width, rect.height); + await bridge.cppFunction('webfront.inspector.openWindow')(id, self, rect.width, rect.height); return true; } catch (error) { retryPanel = id; @@ -262,6 +285,8 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e const host = { get containers() { return containers; }, get embedded() { return isEmbedded; }, + /** The identifier that names this page in its detached windows. */ + get id() { return self; }, get shownPanel() { return shownPanel; }, get frame() { return frame; }, panel, bar, detachButton, closeButton, notice, @@ -316,7 +341,8 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e if (typeof view.BroadcastChannel === 'function') { const channel = new view.BroadcastChannel(inspectorChannel); channel.addEventListener('message', ({data}) => { - if (data?.type !== 'attach' || !panels.has(data.panel) || !containers?.host) return; + // 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); channel.postMessage({type: 'attached', id: data.id}); }); diff --git a/js/developer/environment/inspector.mjs b/js/developer/environment/inspector.mjs index d9a26c80..42da5bea 100644 --- a/js/developer/environment/inspector.mjs +++ b/js/developer/environment/inspector.mjs @@ -58,15 +58,39 @@ export function readPage(answer) { return {descriptors, next, revision, changed}; } -/** Every live watch, page after page from the start, with the revision of the registry that the last page gave. */ +/** 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, the list is given with the revision 0, which the next poll always finds changed. + */ export async function listWatches(bridge, revision = 0) { + for (let attempt = 0; attempt < listingAttempts; ++attempt) { + const first = readPage(await bridge.cppFunction(watchesFunction)(revision, 0, 200)); + const watches = [...first.descriptors]; + let next = first.next, stable = true; + while (stable && next) { + 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; + } + const {watches} = await listWatchesOnce(bridge); + return {watches, revision: 0}; +} + +async function listWatchesOnce(bridge) { const watches = []; - let after = 0, latest = revision; - for (;;) { - const page = readPage(await bridge.cppFunction(watchesFunction)(revision, after, 200)); + for (let after = 0;;) { + const page = readPage(await bridge.cppFunction(watchesFunction)(0, after, 200)); watches.push(...page.descriptors); - latest = page.revision; - if (!page.next) return {watches, revision: latest}; + if (!page.next) return {watches}; after = page.next; } } @@ -236,7 +260,7 @@ export async function main(view = window) { attach.textContent = 'Attach'; attach.title = 'Show this panel in the floating window of the main page'; header.append(attach); - attach.addEventListener('click', () => attachAgain(view, bridge, id, status)); + attach.addEventListener('click', () => attachAgain(view, bridge, id, status, {host: params.get('host')})); // A tab that the main page opened closes with it, as a secondary window closes with the main window (#616). if (view.opener) { const opener = view.opener; @@ -287,12 +311,13 @@ export async function main(view = window) { } /** - * Asks the main page to show the panel again, and closes this window once it answered: a native window through C++, a tab - * by itself. Without an answer the window stays, and says why. + * Asks the page that detached the panel (`host`, the identifier its address carries) to show it again, and closes this + * window once that page answered: a native window through C++, a tab by itself. Another page of the same origin does not + * answer. Without an answer the window stays, and says why. */ -export async function attachAgain(view, bridge, id, status, wait = 1000) { - if (typeof view.BroadcastChannel !== 'function') { - status.textContent = 'This browser cannot reach the main page from here: close this window and open the panel from the menu.'; +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; } const channel = new view.BroadcastChannel(channelName); @@ -304,7 +329,7 @@ export async function attachAgain(view, bridge, id, status, wait = 1000) { view.clearTimeout(timer); resolve(true); }); - channel.postMessage({type: 'attach', panel: id, id: request}); + channel.postMessage({type: 'attach', panel: id, host, id: request}); }); channel.close(); if (!answered) { @@ -312,6 +337,6 @@ export async function attachAgain(view, bridge, id, status, wait = 1000) { return false; } if (view.opener) view.close(); - else await bridge.cppFunction('webfront.inspector.closeWindow')(id).catch(() => view.close()); + else await bridge.cppFunction('webfront.inspector.closeWindow')(id, host).catch(() => view.close()); return true; } diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index 912f5e45..caacb2ec 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -2,8 +2,8 @@ // 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} from '../../../js/developer/environment/inspector-host.mjs'; -import {readDescriptor, readPage, listWatches, reconcile, createWatchDiscovery, renderWatches, pageBridge, attachAgain, + createInspectorHost, defaultInspectorRect, panelTitle, hostIdentifier, hostKey} from '../../../js/developer/environment/inspector-host.mjs'; +import {readDescriptor, readPage, listWatches, listingAttempts, reconcile, createWatchDiscovery, renderWatches, pageBridge, attachAgain, watchesFunction} from '../../../js/developer/environment/inspector.mjs'; import {inspectorChannel, inspectorPanels} from '../../../js/developer/environment/menu.mjs'; import {memoryBridge} from '../memory-bridge.mjs'; @@ -85,7 +85,7 @@ describe('The inspectors', () => { 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 () => {}, windowOpen = () => ({})} = {}) { + async function testHost({containers, embedded = true, files = new Map(), openWindow = async () => {}, windowOpen = () => ({}), hostId = 'host-a'} = {}) { const {bridge: projectBridge, storage} = memoryBridge(files); const calls = []; const bridge = {cppFunction: name => async (...args) => { @@ -96,7 +96,7 @@ describe('The inspectors', () => { }}; const opened = []; const host = await createInspectorHost({bridge, page: document, inspectorUrl: '/webfront/developer/environment/inspector.html', - access: Promise.resolve({containers, reason: ''}), windowOpen: (url, name) => { opened.push([url, name]); return windowOpen(url, name); }}); + access: Promise.resolve({containers, reason: ''}), hostId, windowOpen: (url, name) => { opened.push([url, name]); return windowOpen(url, name); }}); hosts.push(host); return {host, calls, opened, storage}; } @@ -151,8 +151,9 @@ describe('The inspectors', () => { await host.open('cpp.watches'); expect(host.detachButton.getAttribute('aria-disabled')).toBe('false'); expect(await host.detach('cpp.watches')).toBe('window'); - const [, panel, width, height] = calls.find(([name]) => name === 'webfront.inspector.openWindow'); + 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(); @@ -180,6 +181,7 @@ describe('The inspectors', () => { 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-cpp-watches'); expect(host.panel.hidden).toBeFalse(); expect(host.notice.textContent).toContain(hostReasons.blocked); @@ -212,7 +214,7 @@ describe('The inspectors', () => { const answered = new Promise(resolve => inspector.addEventListener('message', ({data}) => { if (data?.type === 'attached') resolve(data.id); })); - inspector.postMessage({type: 'attach', panel: 'cpp.watches', id: 'request-1'}); + 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(); @@ -221,6 +223,45 @@ describe('The inspectors', () => { } 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(); } + }); + + it('names each tab\'s page by an identifier its tab keeps', () => { + const store = new Map(); + const view = {crypto, sessionStorage: {getItem: key => store.get(key) ?? null, setItem: (key, value) => store.set(key, value)}}; + const first = hostIdentifier(view); + expect(first).toMatch(/^[A-Za-z0-9_-]{1,64}$/); + expect(hostIdentifier(view)).toBe(first); // a reload of the same tab + expect(store.get(hostKey)).toBe(first); + const otherTab = {crypto, sessionStorage: {getItem: () => null, setItem: () => {}}}; + expect(hostIdentifier(otherTab)).not.toBe(first); + const noStorage = {crypto, get sessionStorage() { throw new Error('denied'); }}; + expect(hostIdentifier(noStorage)).toMatch(/^[0-9a-f]{24}$/); + store.set(hostKey, 'bad/value'); + expect(hostIdentifier(view)).not.toBe('bad/value'); + }); + it('opens at a default place inside a small viewport', () => { const rect = defaultInspectorRect({width: 400, height: 300}); expect(rect.x + rect.width).toBeLessThanOrEqual(400); @@ -242,12 +283,15 @@ describe('The inspectors', () => { 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') host.postMessage({type: 'attached', id: data.id}); + if (data?.type === 'attach' && data.host === 'host-a') host.postMessage({type: 'attached', id: data.id}); }); - try { expect(await attachAgain(view, null, 'cpp.watches', status)).toBeTrue(); } - finally { host.close(); } + 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, 50)).toBeFalse(); + 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); }); @@ -259,9 +303,12 @@ describe('The inspectors', () => { 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)).toBeTrue(); } + try { expect(await attachAgain(view, bridge, 'cpp.functions', status, {host: 'host-a'})).toBeTrue(); } finally { host.close(); } - expect(calls).toEqual([['webfront.inspector.closeWindow', 'cpp.functions']]); + 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); }); }); @@ -289,6 +336,37 @@ describe('The inspectors', () => { 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 the revision when the registry keeps changing, so that the next poll reads the list again', async () => { + const registry = memoryWatches(1); + ['a', 'b'].forEach(name => registry.add(name)); + const bridge = {cppFunction: () => async (...args) => { + const answer = registry.answer(...args); + if (args[1] === 0) registry.add(`x${registry.calls.length}`); + return answer; + }}; + const {watches, revision} = await listWatches(bridge, 0); + expect(revision).toBe(0); + expect(watches.length).toBeGreaterThan(0); + expect(registry.calls.filter(([, after]) => after === 0).length).toBeGreaterThanOrEqual(listingAttempts); + }); + 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]}); diff --git a/test/unit/ViewAssociationTests.cpp b/test/unit/ViewAssociationTests.cpp index c89e33b9..a53718e7 100644 --- a/test/unit/ViewAssociationTests.cpp +++ b/test/unit/ViewAssociationTests.cpp @@ -473,7 +473,7 @@ const Scenario inspectorWindowAccess{ freshNetwork(); InspectorWindowFrontend::opened = 0; AdmittedBrowser browser{false, false}; - callWith("webfront.inspector.openWindow", 9, std::string{"cpp.watches"}, 720.0, 560.0); + 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); @@ -483,7 +483,7 @@ const Scenario inspectorWindowAccess{ freshNetwork(); InspectorWindowFrontend::opened = 0; AdmittedBrowser browser{false, true}; - callWith("webfront.inspector.openWindow", 9, std::string{"../../etc/passwd"}, 720.0, 560.0); + 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); @@ -492,17 +492,24 @@ const Scenario inspectorWindowAccess{ 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"}, 720.0, 560.0); + 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 has its own window, and only the panels of the menu have one", [&] { - requireEqual(developer::inspectorPage("cpp.watches"), std::string{"webfront/developer/environment/inspector.html?panel=cpp.watches"}); + 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")); + 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); }); diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index 77a04227..0d33a387 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -968,7 +968,7 @@ try { 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') === true, 'The panel\'s window must close'); + assert(await webFront.cppFunction('webfront.inspector.closeWindow')('cpp.watches', window.webfrontInspectorHost.id) === true, 'The panel\'s window must close'); await until(async () => await webFront.cppFunction('test.views')() === views, 'The closed inspector window must disconnect'); window.webfrontInspectorHost.attach('cpp.watches'); await window.webfrontInspectorHost.saved(); From 4338ae4db20e918c5410f7f67b73bcbf26b4131a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:14:36 +0100 Subject: [PATCH 03/21] Listen for detached panels at load, and clear a read error once reads work again (#680) The inspectors' host was made at the first opening of a panel: after a reload of the page, a window detached before it still offered Attach, and its request found no host listening. prepareInspectors() now makes the host as soon as the page is known to reach the inspectors. A successful poll that found the registry unchanged told the panel nothing, so an error shown after a failed read stayed while the reads worked again. The discovery now reports every successful read (onRead), which clears the error. --- js/developer/environment/bundles.json | 6 +- js/developer/environment/inspector-host.mjs | 16 ++++++ js/developer/environment/inspector.mjs | 23 ++++---- js/developer/environment/runtime.mjs | 14 ++--- test/developer/specs/inspector-specs.mjs | 64 ++++++++++++++++++++- 5 files changed, 100 insertions(+), 23 deletions(-) diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index d87b9b03..64a3e624 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -17,15 +17,15 @@ "js/developer/environment/packages.mjs": "37fe2a410e211264cfeaedbff3df50f7e62b02f8088130127d94f92081e2a5ad", "js/developer/environment/starter.mjs": "fd43db1861121577c48a0327436ce39cb9076d7cad0e9e273d40955747cc6a48", "js/developer/environment/paths.mjs": "3b6114df78eb193161c5c84499dda084cb7ff91c56a4496371c30295d00880e3", - "js/developer/environment/runtime.mjs": "ed8a2a4d10dadc110a0083a2bf63fa7ed721c980a512e4446e5c0559b5e43671", + "js/developer/environment/runtime.mjs": "c40fe190028f1e2781467de9bf960578b53f735587c3b806ea678fe48b75271a", "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": "81c1d7550fcb70cc5f6ebd8e431ffc3d332de2ae6c8df83ed65b737b512519ac", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "46b6a2bfc22c63a3f78349b939102089291d800a71a832e71a877c32ad4b20fd", - "js/developer/environment/inspector.mjs": "a8815c23ea618fbf061bf1ac028fba86848e47c820730d6e535edcfe1285b347", + "js/developer/environment/inspector-host.mjs": "5ef464cf54395a1307651b5f49d8cccc2a0c0fec9f94776e9a93e8979526d9d3", + "js/developer/environment/inspector.mjs": "59a2d0288fe5f1f441a1318be519776cab25bbf5442a27af73bc230f741850a1", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index d13bc1d5..e7548cca 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -352,3 +352,19 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e 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. `create` replaces createInspectorHost (tests). + */ +export function prepareInspectors({create = createInspectorHost, ...options}) { + let made = null; + const host = () => made ??= create(options); + 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.mjs b/js/developer/environment/inspector.mjs index 42da5bea..fc71d426 100644 --- a/js/developer/environment/inspector.mjs +++ b/js/developer/environment/inspector.mjs @@ -105,9 +105,10 @@ export function reconcile(known, listed) { * 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. + * `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 = () => {}, period = defaultPeriod, timers = globalThis}) { +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 => { @@ -118,10 +119,12 @@ export function createWatchDiscovery({bridge, onChange, onError = () => {}, peri }; async function poll() { const {changed, revision: current} = readPage(await bridge.cppFunction(watchesFunction)(revision, 0, 0)); - if (!changed && current === revision) return; - const listed = await listWatches(bridge, current); - revision = listed.revision; - apply(listed.watches); + if (changed || current !== revision) { + const listed = await listWatches(bridge, current); + revision = listed.revision; + apply(listed.watches); + } + onRead([...known.values()]); } function schedule() { if (stopped || paused || timer !== null) return; @@ -288,10 +291,9 @@ export async function main(view = window) { }; const discovery = createWatchDiscovery({ bridge, - onChange: ({watches}) => { - renderWatches(list, watches); - describe(watches); - }, + 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' @@ -306,7 +308,6 @@ export async function main(view = window) { }); view.addEventListener('pagehide', () => discovery.stop()); await discovery.start(); - if (!discovery.watches.length && !status.classList.contains('error')) describe([]); return {bridge, discovery, list}; } diff --git a/js/developer/environment/runtime.mjs b/js/developer/environment/runtime.mjs index 9c741c82..b9fb072b 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -18,7 +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 {createInspectorHost} from './inspector-host.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'; @@ -666,14 +666,12 @@ export async function mount({bridge, config, terminal: element, preview, onExit, terminal.unicode.activeVersion = unicodeProvider.version; const fit = new FitAddon(); terminal.loadAddon(fit); - // The inspectors (#680) open from the tab's menu, in the container that reaches C++: their host is made at the first use. + // The inspectors (#680) open from the tab's menu, in the container that reaches C++ (inspector-host.mjs). let inspectors = null; - const openInspector = panel => { - inspectors ??= createInspectorHost({bridge, page: element.ownerDocument, access: workspace.inspectorAccess, - inspectorUrl: new URL('./inspector.html', import.meta.url).href}); - return inspectors.then(host => host.open(panel)); - }; + const openInspector = panel => inspectors.open(panel); 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); @@ -752,5 +750,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, inspectors: () => inspectors}; + return {terminal, editor, workspace, inspectors: () => inspectors?.host() ?? null}; } diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index caacb2ec..5f92983e 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -2,7 +2,7 @@ // 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, hostIdentifier, hostKey} from '../../../js/developer/environment/inspector-host.mjs'; + createInspectorHost, defaultInspectorRect, panelTitle, hostIdentifier, hostKey, prepareInspectors} from '../../../js/developer/environment/inspector-host.mjs'; import {readDescriptor, readPage, listWatches, listingAttempts, reconcile, createWatchDiscovery, renderWatches, pageBridge, attachAgain, watchesFunction} from '../../../js/developer/environment/inspector.mjs'; import {inspectorChannel, inspectorPanels} from '../../../js/developer/environment/menu.mjs'; @@ -262,6 +262,41 @@ describe('The inspectors', () => { expect(hostIdentifier(view)).not.toBe('bad/value'); }); + 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('opens at a default place inside a small viewport', () => { const rect = defaultInspectorRect({width: 400, height: 300}); expect(rect.x + rect.width).toBeLessThanOrEqual(400); @@ -433,6 +468,33 @@ describe('The inspectors', () => { } 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('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}, From 9cf1494da892790674156363ab8943f12f2f9aa8 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:21:16 +0100 Subject: [PATCH 04/21] Give each host page an identifier of its own, and name its tabs by it (#680) A page opened by another one starts with a copy of its session storage, so it took the same host identifier, and both pages answered the same request to attach a panel. A page now uses the identifier only while it holds the exclusive Web Lock of that identifier, released when the page goes away: a reload keeps it, a copied storage gets a new one. Without Web Locks every load takes a new identifier. The target name of a detached panel's tab named the panel only: another host page of the same browsing group could navigate that tab. It now names the host. --- ...-inspecteurs-de-l-etat-de-l-application.md | 5 +- js/developer/environment/bundles.json | 2 +- js/developer/environment/inspector-host.mjs | 47 ++++++++++---- test/developer/specs/inspector-specs.mjs | 65 +++++++++++++++---- 4 files changed, 91 insertions(+), 28 deletions(-) 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 9bc8385f..413569f0 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 @@ -676,7 +676,10 @@ vue. Elle le demande à `webfront.inspector.embedded()`, qui vérifie l'accès c `UI::isEmbeddedView()` de l'appelant ; un échec compte 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. Un panneau détaché a sa propre fenêtre, nommée par la page `inspector.html?panel=&host=` : +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 diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 64a3e624..dd89c2f9 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -24,7 +24,7 @@ "js/developer/environment/terminal.mjs": "1d81a28a6e6cfd5bdb1ff8854e17a273b7bcfebf2c97d469b8706db636f3799e", "js/developer/environment/workspace.mjs": "81c1d7550fcb70cc5f6ebd8e431ffc3d332de2ae6c8df83ed65b737b512519ac", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "5ef464cf54395a1307651b5f49d8cccc2a0c0fec9f94776e9a93e8979526d9d3", + "js/developer/environment/inspector-host.mjs": "5168025e9b8e3fdbde8e4f89983cc5aa7d2c46875644c5eae94a660c39f06544", "js/developer/environment/inspector.mjs": "59a2d0288fe5f1f441a1318be519776cab25bbf5442a27af73bc230f741850a1", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index e7548cca..580e6f91 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -121,22 +121,42 @@ const styles = ` /** 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: the one its tab already has, else a new random one (1 to 64 letters, digits, `-` or - * `_`, which webfront.inspector.openWindow checks). Each tab has its own, so a detached panel is attached again only to - * the page that detached it, even when several pages of the application are open on the same origin. + * 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 function hostIdentifier(view) { - const valid = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value); +export async function claimHostIdentifier(view) { let stored = null; try { stored = view.sessionStorage?.getItem(hostKey); } catch { /* no storage: a new identifier for this load */ } - if (valid(stored)) return stored; - const bytes = view.crypto.getRandomValues(new Uint8Array(12)); - const made = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''); - try { view.sessionStorage?.setItem(hostKey, made); } + 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 made; + return claimed; } /** @@ -144,11 +164,11 @@ export function hostIdentifier(view) { * the menu read (menu.mjs, inspectorAccess), and `embedded` to whether this page is an embedded view (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 (hostIdentifier()). + * 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 ?? hostIdentifier(view); + const self = hostId ?? await claimHostIdentifier(view); const viewport = () => ({width: root.clientWidth, height: root.clientHeight}); const [preferences, containers, isEmbedded] = await Promise.all([ readPreferences(bridge), @@ -275,7 +295,8 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e return false; } } - const tab = openTab(urlOf(id), `webfront-inspector-${id.replace('.', '-')}`); + // The target names the host too: a tab of another page of the same browsing group is never reused for this one. + const tab = openTab(urlOf(id), `webfront-inspector-${self}-${id.replace('.', '-')}`); if (tab) return true; retryPanel = id; showFloating(id, hostReasons.blocked); diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index 5f92983e..d178e772 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -2,7 +2,7 @@ // 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, hostIdentifier, hostKey, prepareInspectors} from '../../../js/developer/environment/inspector-host.mjs'; + createInspectorHost, defaultInspectorRect, panelTitle, claimHostIdentifier, hostKey, prepareInspectors} from '../../../js/developer/environment/inspector-host.mjs'; import {readDescriptor, readPage, listWatches, listingAttempts, reconcile, createWatchDiscovery, renderWatches, pageBridge, attachAgain, watchesFunction} from '../../../js/developer/environment/inspector.mjs'; import {inspectorChannel, inspectorPanels} from '../../../js/developer/environment/menu.mjs'; @@ -182,7 +182,7 @@ describe('The inspectors', () => { 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-cpp-watches'); + 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'); @@ -194,6 +194,15 @@ describe('The inspectors', () => { 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(); @@ -247,19 +256,49 @@ describe('The inspectors', () => { } finally { inspector.close(); } }); - it('names each tab\'s page by an identifier its tab keeps', () => { - const store = new Map(); + // 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 = hostIdentifier(view); - expect(first).toMatch(/^[A-Za-z0-9_-]{1,64}$/); - expect(hostIdentifier(view)).toBe(first); // a reload of the same tab - expect(store.get(hostKey)).toBe(first); - const otherTab = {crypto, sessionStorage: {getItem: () => null, setItem: () => {}}}; - expect(hostIdentifier(otherTab)).not.toBe(first); + 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(hostIdentifier(noStorage)).toMatch(/^[0-9a-f]{24}$/); - store.set(hostKey, 'bad/value'); - expect(hostIdentifier(view)).not.toBe('bad/value'); + 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 () => { From 68e2e18f3515ee25f009d95f5301b6367691b722 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:35:08 +0100 Subject: [PATCH 05/21] Keep one chain of watch reads, and show watch names with visible control characters (#680) Pausing and resuming the Watches panel while a read was in progress scheduled another read beside it: two chains of polling then ran, and their results could apply out of order. Nothing is scheduled while a read is in progress; the read schedules the next one when it ends. The discovery page sent the names of the watches as the application gave them, control characters included, unlike the other texts of the application (ADR-027, sections 3 and 4). The registry keeps the given name for uniqueness and sends its bounded, visible form. --- include/webfront/Watches.hpp | 12 ++++--- js/developer/environment/bundles.json | 2 +- js/developer/environment/inspector.mjs | 4 ++- test/developer/specs/inspector-specs.mjs | 42 ++++++++++++++++++++++++ test/unit/WatchTests.cpp | 21 ++++++++++++ 5 files changed, 74 insertions(+), 7 deletions(-) diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index 794e61a0..51e32015 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -288,7 +288,8 @@ inline constexpr double maxExactNumber = 9007199254740992.0; class WatchRegistry { public: struct Entry { - std::string name; + 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; @@ -303,8 +304,9 @@ class WatchRegistry { 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::string(kind), std::move(location), writable, std::move(source)}); + const auto id = nextId++; + auto label = boundedText(name); + entries.emplace(id, Entry{std::move(name), std::move(label), std::string(kind), std::move(location), writable, std::move(source)}); ++currentRevision; return id; } @@ -362,7 +364,7 @@ class WatchRegistry { } used += bytes; last = entry->first; - served.emplace_back(static_cast(entry->first), entry->second.name, entry->second.kind, entry->second.location, entry->second.writable); + 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}; @@ -381,7 +383,7 @@ class WatchRegistry { /// 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.name.size()) + (3 + entry.kind.size()) + (3 + entry.location.size()) + 1; + 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) { diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index dd89c2f9..c4d7d731 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -25,7 +25,7 @@ "js/developer/environment/workspace.mjs": "81c1d7550fcb70cc5f6ebd8e431ffc3d332de2ae6c8df83ed65b737b512519ac", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", "js/developer/environment/inspector-host.mjs": "5168025e9b8e3fdbde8e4f89983cc5aa7d2c46875644c5eae94a660c39f06544", - "js/developer/environment/inspector.mjs": "59a2d0288fe5f1f441a1318be519776cab25bbf5442a27af73bc230f741850a1", + "js/developer/environment/inspector.mjs": "2174fec457d76ec8283501e35e845974f86d29689c0d6a306ea60c67d31216e8", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", diff --git a/js/developer/environment/inspector.mjs b/js/developer/environment/inspector.mjs index fc71d426..57446d14 100644 --- a/js/developer/environment/inspector.mjs +++ b/js/developer/environment/inspector.mjs @@ -126,8 +126,10 @@ export function createWatchDiscovery({bridge, onChange, onError = () => {}, onRe } 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) return; + if (stopped || paused || timer !== null || running !== null) return; timer = timers.setTimeout(() => { timer = null; running = poll().catch(onError).finally(() => { diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index d178e772..a1fac1f3 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -534,6 +534,48 @@ describe('The inspectors', () => { } 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}, diff --git a/test/unit/WatchTests.cpp b/test/unit/WatchTests.cpp index 61afb3be..8d7dc607 100644 --- a/test/unit/WatchTests.cpp +++ b/test/unit/WatchTests.cpp @@ -218,6 +218,27 @@ const Scenario watchPages{ requireEqual(std::get<0>(registry.page(0, 0, 1, inspect::minPageBytes)).size(), std::size_t{1}); }); }); + 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\u240Aone")); + 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[0], std::string{"line\u240Aone"}); + requireEqual(names[1], std::string{"line\u240Aone"}); + }); + then("a name that its visible form makes longer is cut within the bound", [&] { + require(names[2].size() <= inspect::maxTextBytes); + require(names[2].ends_with("\u2026")); + }); + 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"}, [] { From 1c4f7001e2e8963548f033b6738c3d3759cff80e Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:41:32 +0100 Subject: [PATCH 06/21] Build the watch tests with MSVC, and give WKWebView time to release a closed window (#680) The Windows headers define `small` as `char`: the watch tests named a variable so and did not compile with MSVC. Watches.hpp also parenthesizes std::min for the headers that define min. Under WKWebView the connection of a closed secondary window may end seconds after the window: the developer test now checks that the inspector's window is gone (closeWindow answers false), then waits up to 30 s for its connection. --- include/webfront/Watches.hpp | 2 +- test/unit/WatchTests.cpp | 6 +++--- test/web/developer-specs.mjs | 6 +++++- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index 51e32015..e42fb848 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -85,7 +85,7 @@ inline constexpr std::string_view reservedPrefix = "webfront.inspector."; /// to U+241F, U+2421 for DEL), then the text is cut to `limit` bytes on a character boundary, ending with "…" when cut. [[nodiscard]] inline std::string boundedText(std::string_view text, std::size_t limit = maxTextBytes) { std::string visible; - visible.reserve(std::min(text.size(), limit + 4)); + visible.reserve((std::min)(text.size(), limit + 4)); // parenthesized: Windows headers may define min for (const char c : text) { const auto byte = static_cast(c); if (byte < 0x20u || byte == 0x7Fu) { diff --git a/test/unit/WatchTests.cpp b/test/unit/WatchTests.cpp index 8d7dc607..0be113dc 100644 --- a/test/unit/WatchTests.cpp +++ b/test/unit/WatchTests.cpp @@ -195,9 +195,9 @@ const Scenario watchPages{ }); 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 small = registry.page(revision, 0, 200, inspect::responseHeaderBytes + 80); - requireEqual(namesOf(small), std::vector{"a", "b"}); - const auto next = registry.page(revision, std::get<1>(small), 200, inspect::responseHeaderBytes + 80); + 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 count above 1 000 is read as 1 000, and numbers that are not whole are refused", [&] { diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index 0d33a387..39dc78d9 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -969,7 +969,11 @@ try { 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'); - await until(async () => await webFront.cppFunction('test.views')() === views, 'The closed inspector window must disconnect'); + 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 { From 3569faee26f6fc82f72f3accc83c9b5ff7055091 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:18:56 +0100 Subject: [PATCH 07/21] Answer the review of #692 (#680) Bounded texts below the ellipsis' size, locations cut from the end of their visible form, kind and location bounded at registration, a source never released under the registry's lock, reservedCppFunction private to the developer environment and strict. Choices written as changes with a conditional commit, a detach written at once, late native-window answers that no longer undo a newer action, the opener watched before the bridge, one pointer per window move. Breaking entry in the changelog; the ADR and the guide say where a panel opens. --- docs/CHANGELOG.md | 4 +- docs/DEVELOPER_ENVIRONMENT.md | 10 +- ...-inspecteurs-de-l-etat-de-l-application.md | 12 ++- include/webfront/Watches.hpp | 70 ++++++++----- include/webfront/WebFront.hpp | 17 ++-- js/developer/environment/bundles.json | 6 +- js/developer/environment/inspector-host.mjs | 98 ++++++++++++++----- js/developer/environment/inspector.mjs | 22 +++-- js/developer/environment/workspace.mjs | 10 +- test/developer/specs/inspector-specs.mjs | 98 ++++++++++++++++++- test/developer/specs/workspace-specs.mjs | 27 ++++- test/unit/ViewAssociationTests.cpp | 24 ++++- test/unit/WatchTests.cpp | 31 +++++- test/web/developer-specs.mjs | 7 +- 14 files changed, 354 insertions(+), 82 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 64467c5f..81e56867 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -10,6 +10,9 @@ these entries stays in the GitHub releases and the Git history. ## Unreleased +### Breaking +- `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). @@ -21,7 +24,6 @@ these entries stays in the GitHub releases and the Git history. - The test helpers, `webfront_add_jasmine_test` included, export the real `XDG_DATA_HOME` and `XDG_CACHE_HOME` as `WEBFRONT_TEST_REAL_XDG_DATA_HOME` and `WEBFRONT_TEST_REAL_XDG_CACHE_HOME`, so an application under test can keep the throwaway WebKitGTK profile away from the programs it starts ([#664](https://github.com/ambroise-leclerc/WebFront/issues/664), `docs/CONSUMER_TESTING.md`). ### Changed -- `cppFunction` refuses the names starting with `webfront.inspector.`, which belong to the inspectors, with `std::invalid_argument` (#680, ADR-027). - `WebFront.js` opens its WebSocket on the directory of the page (`ws://host/dir/` instead of `ws://host`), which tells the server a page's space; the server still ignores that path outside the spaces (#671). ### Fixed diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 051db9dd..7d1c1647 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -445,10 +445,12 @@ environment's `mount`, not to the embedded bootstrap page): `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 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: the adapters give the proof of the view to the main frame only. **Detach** moves the - panel to a window of its own, and **Attach**, in that window, brings it back to the floating window: + 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 | | --- | --- | 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 413569f0..1c580183 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 @@ -219,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.*`). @@ -653,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 @@ -690,6 +693,11 @@ se ferme qu'après cette réponse. 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. Un détachement ou un rattachement est écrit aussitôt, la +place après une courte pause. + 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/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index e42fb848..5821a391 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -81,41 +81,56 @@ inline constexpr std::string_view reservedPrefix = "webfront.inspector."; 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 = "\u2026"; +} // 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 + 4)); // parenthesized: Windows headers may define min for (const char c : text) { - 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; + detail::appendVisible(visible, c); if (visible.size() > limit + 4) break; // enough to know that it is cut } if (visible.size() <= limit) return visible; - constexpr std::string_view ellipsis = "…"; - std::string cut{utf8Prefix(visible, limit - ellipsis.size())}; - cut += ellipsis; + 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", keeping the end of a long path (the file's name) within the bound. +/// 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) { - const std::string full = std::string(location.file_name()) + ':' + std::to_string(location.line()); - if (full.size() <= maxTextBytes) - return boundedText(full); - constexpr std::string_view ellipsis = "…"; - std::size_t start = full.size() - (maxTextBytes - ellipsis.size()); - while (start < full.size() && (static_cast(full[start]) & 0xC0u) == 0x80u) - ++start; - return boundedText(std::string(ellipsis) + full.substr(start)); + return locationText(location.file_name(), location.line()); } // --- Kinds (ADR-027, section 4) -------------------------------------------------------------------------------- @@ -296,17 +311,22 @@ class WatchRegistry { 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, or the name - /// of a watch that is still registered. + /// 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++; - auto label = boundedText(name); - entries.emplace(id, Entry{std::move(name), std::move(label), std::string(kind), std::move(location), writable, std::move(source)}); + 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; } diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index ee5246a8..87604f3c 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -1038,6 +1038,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 @@ -1592,12 +1603,6 @@ class BasicWF { windowOptions.background = "#141821"; } - /// Registers one of WebFront's own reserved functions (`webfront.inspector.*`), which cppFunction refuses to the application. - template - bool reservedCppFunction(std::string functionName, auto&& function) { - return registerCppFunction(std::move(functionName), std::forward(function)); - } - /// For the developer environment: from now on, watch() registers in the table that the inspectors read (ADR-027). /// Returns that table. A distribution build never calls it. std::shared_ptr enableInspectors() { diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index c4d7d731..91588bb1 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -22,10 +22,10 @@ "js/developer/environment/development.mjs": "1f32f911610c72ad3e935de1c2b138fa275ce9eda04bb63c824d5e09923305a6", "js/developer/environment/testing.mjs": "aeb584505fab5957b9c02e78536e12f7d7f3d12f8adb2e17f1a1a6e395e43f3c", "js/developer/environment/terminal.mjs": "1d81a28a6e6cfd5bdb1ff8854e17a273b7bcfebf2c97d469b8706db636f3799e", - "js/developer/environment/workspace.mjs": "81c1d7550fcb70cc5f6ebd8e431ffc3d332de2ae6c8df83ed65b737b512519ac", + "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "5168025e9b8e3fdbde8e4f89983cc5aa7d2c46875644c5eae94a660c39f06544", - "js/developer/environment/inspector.mjs": "2174fec457d76ec8283501e35e845974f86d29689c0d6a306ea60c67d31216e8", + "js/developer/environment/inspector-host.mjs": "c9b398e5a3cd40d959dfda92b0dad8f35d505c18e431222145abbac64abf3179", + "js/developer/environment/inspector.mjs": "fe0a6a3844426485b1d1f70f0710ca7557eb824e0bcb4bac62a9a2180197549f", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index 580e6f91..5a863ae6 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -3,7 +3,7 @@ // 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, publish} from './io.mjs'; +import {readProject, call, writeChunks} from './io.mjs'; import {clampRect, step, minimumSize, windowControls} from './workspace.mjs'; import {inspectorPanels as panels, panelTitle, inspectorChannel} from './menu.mjs'; @@ -71,25 +71,62 @@ export async function readPreferences(bridge) { catch { return parsePreferences(''); } } -/** Writes the choices shortly after they stop changing; a failed write keeps the inspector usable. */ +/** 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. */ +async function writePreferenceChanges(bridge, changes) { + for (let attempt = 1; ; ++attempt) { + let id = null; + try { + const token = await call(bridge, 'state', preferencesPath); + const text = formatPreferences(applyPreferenceChanges(await readPreferences(bridge), changes)); + id = await call(bridge, 'begin', preferencesPath, false); + await writeChunks(bridge, {id, path: 'output', bytes: encoder.encode(text)}); + await call(bridge, 'commitGroup', id, preferencesPath, token); + return; + } catch (error) { + if (id !== null) await call(bridge, 'abort', id).catch(() => {}); + 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. + */ export function preferencesStore(bridge, delay = 300) { - let timer = null, pending = null, writes = Promise.resolve(), written = null; + let timer = null, pending = {panels: new Map(), rect: undefined}, writes = Promise.resolve(); const flush = () => { clearTimeout(timer); timer = null; - if (!pending) return writes; - const text = formatPreferences(pending); - pending = null; - writes = writes.then(async () => { - if (text === written) return; - await publish(bridge, preferencesPath, new Map([['output', encoder.encode(text)]]), {directory: false}); - written = text; - }).catch(() => {}); + if (!pending.panels.size && pending.rect === undefined) return writes; + const changes = pending; + pending = {panels: new Map(), rect: undefined}; + writes = writes.then(() => writePreferenceChanges(bridge, changes)).catch(() => {}); return writes; }; return { - remember(preferences) { - pending = {detached: new Set(preferences.detached), rect: preferences.rect}; + /** Remembers whether `id` is detached, at once: a page closed just after a detach keeps it. */ + detached(id, away) { + pending.panels.set(id, away); + flush(); + }, + /** Remembers the floating window's place once it stops changing. */ + place(rect) { + pending.rect = rect; clearTimeout(timer); timer = setTimeout(flush, delay); }, @@ -176,7 +213,6 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e Promise.resolve(embedded ?? bridge.cppFunction('webfront.inspector.embedded')()).then(Boolean, () => true), ]); const store = preferencesStore(bridge); - const remember = () => store.remember(preferences); const openTab = windowOpen ?? ((url, name) => view.open(url, name)); const urlOf = (panel, extra = {}) => { const url = new URL(inspectorUrl, view.location.href); @@ -230,6 +266,10 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e 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; @@ -238,7 +278,7 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e } function choose(rect) { preferences.rect = clampRect(rect, viewport()); - remember(); + store.place(preferences.rect); render(); } windowControls({view, bar, panel, shown, choose, viewport, shownNow: () => !panel.hidden}); @@ -252,6 +292,7 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e notice.hidden = !text; } function showFloating(id, message = '') { + ++action; shownPanel = id; title.textContent = panelTitle(id); panel.setAttribute('aria-label', `WebFront inspector: ${panelTitle(id)}`); @@ -273,6 +314,7 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e render(); } function hideFloating() { + ++action; panel.hidden = true; shownPanel = null; const empty = page.createElement('iframe'); // unloads the panel without navigating @@ -285,13 +327,16 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e /** Opens `id` in its detached container; resolves with whether it did. A failure leaves it in the floating window. */ async function openDetached(id, container) { if (container === 'window') { - const rect = shown(); + const rect = shown(), started = action; try { await bridge.cppFunction('webfront.inspector.openWindow')(id, self, rect.width, rect.height); return true; } catch (error) { - retryPanel = id; - showFloating(id, `${hostReasons.windowFailed}: ${error?.message ?? error}`); + // 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}: ${error?.message ?? error}`); + } return false; } } @@ -303,6 +348,11 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e return false; } + /** 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; }, @@ -322,8 +372,9 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e showFloating(id); return 'floating'; } + const started = action; if (await openDetached(id, container)) { - if (shownPanel === id) hideFloating(); + hideIfStill(id, started); return container; } return 'floating'; @@ -333,9 +384,10 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e const container = detachedContainer(containers, {embedded: isEmbedded}); if (!container) return null; preferences.detached.add(id); - remember(); + store.detached(id, true); + const started = action; if (await openDetached(id, container)) { - if (shownPanel === id) hideFloating(); + hideIfStill(id, started); return container; } return 'floating'; @@ -343,7 +395,7 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e /** Moves `id` back to this page's floating window, and remembers it there. */ attach(id) { preferences.detached.delete(id); - remember(); + store.detached(id, false); retryPanel = null; showFloating(id); }, @@ -369,6 +421,8 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e }); 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(); }); // The frame of the floating window reaches its host here: the same origin, and no connection of its own. view.webfrontInspectorHost = host; return host; diff --git a/js/developer/environment/inspector.mjs b/js/developer/environment/inspector.mjs index 57446d14..451da935 100644 --- a/js/developer/environment/inspector.mjs +++ b/js/developer/environment/inspector.mjs @@ -204,7 +204,8 @@ const placeholders = { export function renderWatches(list, watches) { const page = list.ownerDocument; const items = new Map([...list.children].map(item => [Number(item.dataset.watch), item])); - for (const [id, item] of items) if (!watches.some(watch => watch.id === id)) item.remove(); + 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'); @@ -221,6 +222,15 @@ export function renderWatches(list, watches) { } } +/** 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; +} + /** * 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. @@ -249,6 +259,10 @@ export async function main(view = window) { 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) { @@ -266,12 +280,6 @@ export async function main(view = window) { attach.title = 'Show this panel in the floating window of the main page'; header.append(attach); attach.addEventListener('click', () => attachAgain(view, bridge, id, status, {host: params.get('host')})); - // A tab that the main page opened closes with it, as a secondary window closes with the main window (#616). - if (view.opener) { - const opener = view.opener; - const watcher = view.setInterval(() => { if (opener.closed) view.close(); }, 1000); - view.addEventListener('pagehide', () => view.clearInterval(watcher)); - } } if (id !== 'cpp.watches') { diff --git a/js/developer/environment/workspace.mjs b/js/developer/environment/workspace.mjs index c74b00be..7b364ff9 100644 --- a/js/developer/environment/workspace.mjs +++ b/js/developer/environment/workspace.mjs @@ -175,22 +175,24 @@ export function placeStore(bridge, delay = 300) { * 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 (event.button !== 0 || event.target.closest?.('button')) return; + if (grip || event.button !== 0 || event.target.closest?.('button')) return; const rect = shown(); - grip = {x: event.clientX - rect.x, y: event.clientY - rect.y}; + 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) choose({...shown(), x: event.clientX - grip.x, y: event.clientY - grip.y}); + if (grip?.id === event.pointerId) choose({...shown(), x: event.clientX - grip.x, y: event.clientY - grip.y}); }); - const release = () => { grip = null; }; + 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()); diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index a1fac1f3..be3465fa 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -2,8 +2,9 @@ // 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} from '../../../js/developer/environment/inspector-host.mjs'; -import {readDescriptor, readPage, listWatches, listingAttempts, reconcile, createWatchDiscovery, renderWatches, pageBridge, attachAgain, + 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} from '../../../js/developer/environment/inspector.mjs'; import {inspectorChannel, inspectorPanels} from '../../../js/developer/environment/menu.mjs'; import {memoryBridge} from '../memory-bridge.mjs'; @@ -82,6 +83,54 @@ describe('The inspectors', () => { }); }); + 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('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.developer.commitGroup' && !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. @@ -336,6 +385,33 @@ describe('The inspectors', () => { expect(made.length).toBe(1); }); + 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', async () => { + let opened; + const pending = new Promise(resolve => { opened = resolve; }); + const {host} = await testHost({containers: admitted(true), openWindow: () => pending}); + await host.open('cpp.watches'); + const detaching = host.detach('cpp.watches'); + host.attach('cpp.watches'); // the window asks to come back before C++ answered + opened(); + await detaching; + expect(host.panel.hidden).toBeFalse(); + expect(host.shownPanel).toBe('cpp.watches'); + expect(host.preferences.detached.has('cpp.watches')).toBeFalse(); + }); + it('opens at a default place inside a small viewport', () => { const rect = defaultInspectorRect({width: 400, height: 300}); expect(rect.x + rect.width).toBeLessThanOrEqual(400); @@ -370,6 +446,24 @@ describe('The inspectors', () => { 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('closes its native window through C++ when it has no opener', async () => { const status = document.createElement('p'); const calls = []; 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/ViewAssociationTests.cpp b/test/unit/ViewAssociationTests.cpp index a53718e7..c3ff8dd5 100644 --- a/test/unit/ViewAssociationTests.cpp +++ b/test/unit/ViewAssociationTests.cpp @@ -420,6 +420,14 @@ void callWith(const std::string& name, msg::CallId callId, Arguments... argument 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 { @@ -535,9 +543,9 @@ const Scenario inspectorWatchesAccess{ require(ViewSocket::wrote("sequence")); require(ViewSocket::wrote("ViewAssociationTests.cpp:")); }); - then("the page asks whether this page is an embedded view", [&] { + 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(inspect::code::denied)); + require(ViewSocket::wrote(booleanAnswer(12, true))); }); then("a second watch of the same name is refused while the first lives", [&] { checkThrows([&] { @@ -563,8 +571,18 @@ const Scenario inspectorWatchesAccess{ freshNetwork(); AdmittedBrowser browser{false, false}; callWithoutArgument("webfront.inspector.embedded", 12); - then("the call is refused as denied", [&] { + 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("it is admitted and told that it is not one: a tab of the system browser may be offered to it", [&] { + require(ViewSocket::wrote(booleanAnswer(12, false))); }); }); given("a trusted loopback page", [&] { diff --git a/test/unit/WatchTests.cpp b/test/unit/WatchTests.cpp index 0be113dc..41a8b1bb 100644 --- a/test/unit/WatchTests.cpp +++ b/test/unit/WatchTests.cpp @@ -61,11 +61,22 @@ const Scenario watchTexts{"The texts of a watch are bounded and made visible (AD require(cut.ends_with("…")); requireEqual(inspect::utf8Prefix("aé", 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("\u00e9t\u00e9", 2), std::string{"\u00e9"}); + requireEqual(inspect::boundedText("abc", 0), std::string{}); + }); 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("\u2026\u2409")); // cut between two pictures, never inside one + }); }); }}; @@ -201,7 +212,15 @@ const Scenario watchPages{ requireEqual(namesOf(next), std::vector{"c", "d"}); }); then("a count above 1 000 is read as 1 000, and numbers that are not whole are refused", [&] { - requireEqual(std::get<0>(registry.page(revision, 0, 5000, 32768)).size(), std::size_t{5}); + 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)); @@ -217,6 +236,16 @@ const Scenario watchPages{ 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; diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index 39dc78d9..292a7c72 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -954,8 +954,13 @@ try { // 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(() => !listed().includes('integration'), `A removed watch must disappear from the inspector: ${listed()}`); + 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. From 982427356b0005d889bd613078e6ee22a7eae5fb Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:59:21 +0100 Subject: [PATCH 08/21] Guard developer writes and finish inspector saves on the server (#680) --- docs/DEVELOPER_ENVIRONMENT.md | 5 +- ...-inspecteurs-de-l-etat-de-l-application.md | 4 +- include/webfront/Commands.hpp | 9 ++++ include/webfront/DeveloperApp.hpp | 32 +++++++++--- include/webfront/Watches.hpp | 2 +- .../webfront/frontend/EmbeddedFrontend.hpp | 3 ++ include/webfront/frontend/Frontend.hpp | 14 +++++ include/webfront/system/DeveloperStore.hpp | 17 +++++++ js/developer/environment/inspector-host.mjs | 18 +++---- test/developer/memory-bridge.mjs | 11 +++- test/developer/specs/inspector-specs.mjs | 22 +++++++- test/unit/DeveloperTests.cpp | 16 ++++++ test/unit/InspectorDistribution.cpp | 1 + test/unit/ViewAssociationTests.cpp | 51 +++++++++++++++++++ test/unit/WatchTests.cpp | 18 +++---- 15 files changed, 191 insertions(+), 32 deletions(-) diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 7d1c1647..22f30be2 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -460,7 +460,10 @@ environment's `mount`, not to the embedded bootstrap page): 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. The project keeps the detached panels and the floating window's place in - `.webfront/developer/inspector-window.json`. + `.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. 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 1c580183..796b8288 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 @@ -696,7 +696,9 @@ recommencer la liste, pour qu'un observateur retiré entre deux pages ne reste p 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. Un détachement ou un rattachement est écrit aussitôt, la -place après une courte pause. +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. 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. diff --git a/include/webfront/Commands.hpp b/include/webfront/Commands.hpp index 20cf04c7..bf17280d 100644 --- a/include/webfront/Commands.hpp +++ b/include/webfront/Commands.hpp @@ -395,9 +395,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 +429,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 c2521dd9..c7c1df7d 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -165,13 +165,13 @@ 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 @@ -198,6 +198,12 @@ class DeveloperAppWithNetwork : public BasicWFtemplate reservedCppFunction>( + "webfront.inspector.savePreferences", + [owned = store](Caller ui, std::string expected, std::vector bytes) { + admit(ui); + owned->publishFile(".webfront/developer/inspector-window.json", 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", @@ -236,13 +242,14 @@ class DeveloperAppWithNetwork : public BasicWF @@ -252,6 +259,17 @@ 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 { + if (frontend::providesViewProof()) + admit(ui); + return ((*owned).*Member)(std::move(arguments)...); + }); + } + std::filesystem::path project; std::shared_ptr store; }; diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index 5821a391..10b8099c 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -93,7 +93,7 @@ inline void appendVisible(std::string& visible, char c) { } else visible += c; } -inline constexpr std::string_view ellipsis = "\u2026"; +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 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..631fe6c9 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,16 @@ concept FrontendType = requires(std::string_view port, std::string_view file) { { Frontend::open(port, file) } -> std::same_as; } && std::same_as, Action>; +/// Whether the active frontend gives the application window the bridge's launch proof. +template +[[nodiscard]] bool providesViewProof() { + if constexpr (requires { + { Frontend::providesViewProof() } -> std::same_as; + }) + return Frontend::providesViewProof(); + 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. @@ -303,6 +314,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/DeveloperStore.hpp b/include/webfront/system/DeveloperStore.hpp index 88913c9c..e4f208b5 100644 --- a/include/webfront/system/DeveloperStore.hpp +++ b/include/webfront/system/DeveloperStore.hpp @@ -254,6 +254,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/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index 5a863ae6..7c648331 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -3,7 +3,7 @@ // 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, writeChunks} from './io.mjs'; +import {readProject, call} from './io.mjs'; import {clampRect, step, minimumSize, windowControls} from './workspace.mjs'; import {inspectorPanels as panels, panelTitle, inspectorChannel} from './menu.mjs'; @@ -84,16 +84,12 @@ 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. */ async function writePreferenceChanges(bridge, changes) { for (let attempt = 1; ; ++attempt) { - let id = null; try { const token = await call(bridge, 'state', preferencesPath); const text = formatPreferences(applyPreferenceChanges(await readPreferences(bridge), changes)); - id = await call(bridge, 'begin', preferencesPath, false); - await writeChunks(bridge, {id, path: 'output', bytes: encoder.encode(text)}); - await call(bridge, 'commitGroup', id, preferencesPath, token); + await bridge.cppFunction('webfront.inspector.savePreferences')(token, encoder.encode(text)); return; } catch (error) { - if (id !== null) await call(bridge, 'abort', id).catch(() => {}); if (attempt === 20 || !preferenceConflict.test(error?.message)) throw error; await new Promise(resolve => setTimeout(resolve, 10 + Math.random() * 40)); } @@ -115,20 +111,20 @@ export function preferencesStore(bridge, delay = 300) { if (!pending.panels.size && pending.rect === undefined) return writes; const changes = pending; pending = {panels: new Map(), rect: undefined}; - writes = writes.then(() => writePreferenceChanges(bridge, changes)).catch(() => {}); + writes = writes.catch(() => {}).then(() => writePreferenceChanges(bridge, changes)); return writes; }; return { - /** Remembers whether `id` is detached, at once: a page closed just after a detach keeps it. */ + /** Starts saving the new detached state immediately. */ detached(id, away) { pending.panels.set(id, away); - flush(); + flush().catch(() => {}); }, /** Remembers the floating window's place once it stops changing. */ place(rect) { pending.rect = rect; clearTimeout(timer); - timer = setTimeout(flush, delay); + timer = setTimeout(() => flush().catch(() => {}), delay); }, saved: () => flush(), }; @@ -422,7 +418,7 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e 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(); }); + 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; diff --git a/test/developer/memory-bridge.mjs b/test/developer/memory-bridge.mjs index 4d2f5234..87f2a8da 100644 --- a/test/developer/memory-bridge.mjs +++ b/test/developer/memory-bridge.mjs @@ -55,6 +55,15 @@ 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.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 index be3465fa..2f7003e5 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -111,12 +111,32 @@ describe('The inspectors', () => { } 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(calls).toEqual(['webfront.developer.state', 'webfront.developer.read', '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('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.developer.commitGroup' && !raced) { + if (name === 'webfront.inspector.savePreferences' && !raced) { raced = true; storage.set(preferencesPath, encode(formatPreferences({detached: new Set(['typescript.bridge']), rect: null}))); } diff --git a/test/unit/DeveloperTests.cpp b/test/unit/DeveloperTests.cpp index 20481d43..e6f38547 100644 --- a/test/unit/DeveloperTests.cpp +++ b/test/unit/DeveloperTests.cpp @@ -893,6 +893,22 @@ 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 newDirectories{ "New directories are durable once their parents are synchronized", [] { diff --git a/test/unit/InspectorDistribution.cpp b/test/unit/InspectorDistribution.cpp index 32d52aa6..5b5c881d 100644 --- a/test/unit/InspectorDistribution.cpp +++ b/test/unit/InspectorDistribution.cpp @@ -36,6 +36,7 @@ const Scenario inspectorsAbsent{"A distribution build registers no inspector fun for (const auto* name : {"webfront.inspector.containers", "webfront.inspector.embedded", "webfront.inspector.watches", + "webfront.inspector.savePreferences", "webfront.inspector.openWindow", "webfront.inspector.closeWindow"}) require(!app.hasCppFunction(name)); diff --git a/test/unit/ViewAssociationTests.cpp b/test/unit/ViewAssociationTests.cpp index c3ff8dd5..7ce4e8ef 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 @@ -395,6 +396,9 @@ 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) { } @@ -473,6 +477,53 @@ const Scenario inspectorContainersWithWindows{ } }; +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"}, diff --git a/test/unit/WatchTests.cpp b/test/unit/WatchTests.cpp index 41a8b1bb..6dbcdd7a 100644 --- a/test/unit/WatchTests.cpp +++ b/test/unit/WatchTests.cpp @@ -56,14 +56,14 @@ const Scenario watchTexts{"The texts of a watch are bounded and made visible (AD }); 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_ + "éé"); // the é crosses 256 bytes + const auto cut = inspect::boundedText(long_ + "\xC3\xA9\xC3\xA9"); // the é crosses 256 bytes require(cut.size() <= inspect::maxTextBytes); - require(cut.ends_with("…")); - requireEqual(inspect::utf8Prefix("aé", 2), std::string_view{"a"}); + 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("\u00e9t\u00e9", 2), std::string{"\u00e9"}); + requireEqual(inspect::boundedText("\xC3\xA9t\xC3\xA9", 2), std::string{"\xC3\xA9"}); requireEqual(inspect::boundedText("abc", 0), std::string{}); }); then("a long location keeps the end of the path", [&] { @@ -75,7 +75,7 @@ const Scenario watchTexts{"The texts of a watch are bounded and made visible (AD 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("\u2026\u2409")); // cut between two pictures, never inside one + require(text.starts_with("\xE2\x80\xA6\xE2\x90\x89")); // cut between two pictures, never inside one }); }); }}; @@ -251,16 +251,16 @@ const Scenario watchPages{ 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\u240Aone")); + 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[0], std::string{"line\u240Aone"}); - requireEqual(names[1], std::string{"line\u240Aone"}); + 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", [&] { require(names[2].size() <= inspect::maxTextBytes); - require(names[2].ends_with("\u2026")); + require(names[2].ends_with("\xE2\x80\xA6")); }); then("a second watch of the same name is still refused", [&] { checkThrows([&] { From 664349b0fe24de454bbe6f6ba082aa240e2683ad Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:04:47 +0100 Subject: [PATCH 09/21] Keep the command header self-contained (#680) --- include/webfront/Commands.hpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/include/webfront/Commands.hpp b/include/webfront/Commands.hpp index bf17280d..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 From 19841c85a6be5c0ed05550e82cf14eb1c2150d17 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:11:35 +0100 Subject: [PATCH 10/21] Exercise developer writes from admitted browser sessions (#680) --- js/developer/environment/bundles.json | 2 +- test/web/developer-session.html | 1 - test/web/developer-session.mjs | 21 ++++++++++++++++++--- test/web/developer-specs.mjs | 21 +++++++++++++++++---- 4 files changed, 36 insertions(+), 9 deletions(-) diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 91588bb1..8c24ee71 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -24,7 +24,7 @@ "js/developer/environment/terminal.mjs": "1d81a28a6e6cfd5bdb1ff8854e17a273b7bcfebf2c97d469b8706db636f3799e", "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "c9b398e5a3cd40d959dfda92b0dad8f35d505c18e431222145abbac64abf3179", + "js/developer/environment/inspector-host.mjs": "2b884675202d79382b6b2d62a312ef559a734870cd9a56c2922c26eea9b9daba", "js/developer/environment/inspector.mjs": "fe0a6a3844426485b1d1f70f0710ca7557eb824e0bcb4bac62a9a2180197549f", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", 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 292a7c72..d1a61aef 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -1107,12 +1107,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); @@ -1129,7 +1142,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. From 8dceb1fcf9edde1b488458d891c69c52a5aad5b4 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:23:52 +0100 Subject: [PATCH 11/21] Fix MSVC warnings and Windows macro collisions (#680) --- include/webfront/frontend/Frontend.hpp | 3 ++- include/webfront/weblink/Messages.hpp | 14 +++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/include/webfront/frontend/Frontend.hpp b/include/webfront/frontend/Frontend.hpp index 631fe6c9..ae7d585c 100644 --- a/include/webfront/frontend/Frontend.hpp +++ b/include/webfront/frontend/Frontend.hpp @@ -92,7 +92,8 @@ template { Frontend::providesViewProof() } -> std::same_as; }) return Frontend::providesViewProof(); - return false; + else + return false; } // `action` describes what BasicWF should do after `open()` returns. 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) { From b255cabde4b27a4eaf57a9ebd114374175bd9de9 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:11:24 +0100 Subject: [PATCH 12/21] Keep unreadable inspector choices, refuse a page budget too small, retry a failed host (#680) - A preferences file that exists but cannot be read now fails the write instead of being replaced by this page's changes alone; only an absent file counts as empty. - WatchRegistry::page() throws std::length_error when the next watch does not fit the budget, instead of answering an empty page that ends the listing. - Refused project writes say what was refused; the code stays webfront.inspector.denied (ADR-027). - A failed creation of the inspectors' host is tried again on the next panel, and a panel that cannot open is reported in the terminal (LineEditor.notice) instead of an unhandled rejection. --- include/webfront/DeveloperApp.hpp | 6 ++- include/webfront/Watches.hpp | 5 +- js/developer/environment/bundles.json | 6 +-- js/developer/environment/inspector-host.mjs | 45 ++++++++++++++++-- js/developer/environment/runtime.mjs | 10 ++-- js/developer/environment/terminal.mjs | 11 +++++ test/developer/memory-bridge.mjs | 3 +- test/developer/specs/inspector-specs.mjs | 51 ++++++++++++++++++++- test/unit/WatchTests.cpp | 7 +++ 9 files changed, 128 insertions(+), 16 deletions(-) diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index c7c1df7d..ec625cd7 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -264,8 +264,10 @@ class DeveloperAppWithNetwork : public BasicWFtemplate cppFunction(std::move(name), [owned = store](Caller ui, Args... arguments) -> Result { - if (frontend::providesViewProof()) - admit(ui); + // 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)...); }); } diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index 10b8099c..9476f6a5 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -365,7 +365,8 @@ class WatchRegistry { * 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. + * 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"); @@ -379,6 +380,8 @@ class WatchRegistry { 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; } diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 8c24ee71..8ad65c27 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -17,14 +17,14 @@ "js/developer/environment/packages.mjs": "37fe2a410e211264cfeaedbff3df50f7e62b02f8088130127d94f92081e2a5ad", "js/developer/environment/starter.mjs": "fd43db1861121577c48a0327436ce39cb9076d7cad0e9e273d40955747cc6a48", "js/developer/environment/paths.mjs": "3b6114df78eb193161c5c84499dda084cb7ff91c56a4496371c30295d00880e3", - "js/developer/environment/runtime.mjs": "c40fe190028f1e2781467de9bf960578b53f735587c3b806ea678fe48b75271a", + "js/developer/environment/runtime.mjs": "b67e898c7d40dbf5dab1d0486d39d035c7a740c564e418675ca244206f23bb00", "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/terminal.mjs": "3b74d1a4d0466ce06af4df2bd9727c2ecb933780dc52de94abc153c1e60d48e7", "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "2b884675202d79382b6b2d62a312ef559a734870cd9a56c2922c26eea9b9daba", + "js/developer/environment/inspector-host.mjs": "be8a3adfae655c02961bd8e2b866c6d55be5dd34cbf76ae700704d728694f289", "js/developer/environment/inspector.mjs": "fe0a6a3844426485b1d1f70f0710ca7557eb824e0bcb4bac62a9a2180197549f", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index 7c648331..3c348e8a 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -66,8 +66,36 @@ export function parsePreferences(text) { 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; + } +} + +/** The choices the project has: empty ones without a file; a file that exists but cannot be read throws. */ +async function readStoredPreferences(bridge) { + let bytes; + try { bytes = await readProject(bridge, preferencesPath); } + catch (error) { + if (await projectFileMissing(bridge, preferencesPath).catch(() => false)) return parsePreferences(''); + throw error; + } + return parsePreferences(decoder.decode(bytes)); +} + +/** 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 parsePreferences(decoder.decode(await readProject(bridge, preferencesPath))); } + try { return await readStoredPreferences(bridge); } catch { return parsePreferences(''); } } @@ -81,12 +109,15 @@ export function applyPreferenceChanges(current, {panels, 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. */ +/** + * 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 token = await call(bridge, 'state', preferencesPath); - const text = formatPreferences(applyPreferenceChanges(await readPreferences(bridge), changes)); + const text = formatPreferences(applyPreferenceChanges(await readStoredPreferences(bridge), changes)); await bridge.cppFunction('webfront.inspector.savePreferences')(token, encoder.encode(text)); return; } catch (error) { @@ -428,11 +459,15 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e * 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. `create` replaces createInspectorHost (tests). + * 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 ??= create(options); + 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)), diff --git a/js/developer/environment/runtime.mjs b/js/developer/environment/runtime.mjs index b9fb072b..dfa0325e 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -667,8 +667,12 @@ export async function mount({bridge, config, terminal: element, preview, onExit, const fit = new FitAddon(); terminal.loadAddon(fit); // The inspectors (#680) open from the tab's menu, in the container that reaches C++ (inspector-host.mjs). - let inspectors = null; - const openInspector = panel => inspectors.open(panel); + // 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`); + }); 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}); @@ -686,7 +690,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 diff --git a/js/developer/environment/terminal.mjs b/js/developer/environment/terminal.mjs index 8ca1b884..29024448 100644 --- a/js/developer/environment/terminal.mjs +++ b/js/developer/environment/terminal.mjs @@ -298,6 +298,17 @@ 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, 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 || this.completing) 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/test/developer/memory-bridge.mjs b/test/developer/memory-bridge.mjs index 87f2a8da..62e1f3fc 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. diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index 2f7003e5..c978792d 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -7,6 +7,7 @@ import {detachedContainer, containerFor, hostReasons, parsePreferences, formatPr import {readDescriptor, readPage, listWatches, listingAttempts, reconcile, watchOpener, createWatchDiscovery, renderWatches, pageBridge, attachAgain, watchesFunction} 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); @@ -123,7 +124,9 @@ describe('The inspectors', () => { const store = preferencesStore(bridge); store.detached('cpp.watches', true); await expectAsync(store.saved()).toBeRejectedWithError('Disconnected'); - expect(calls).toEqual(['webfront.developer.state', 'webfront.developer.read', 'webfront.inspector.savePreferences']); + // Without a file, the read fails and listing the directories shows that the file is absent. + expect(calls).toEqual(['webfront.developer.state', 'webfront.developer.read', 'webfront.developer.list', 'webfront.developer.list', + 'webfront.developer.list', 'webfront.inspector.savePreferences']); expect(storage.has(preferencesPath)).toBeFalse(); connected = true; store.detached('cpp.watches', true); @@ -131,6 +134,27 @@ describe('The inspectors', () => { 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.developer.read' && failing) throw new Error('Cannot read project file: ' + args[0]); + 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('write again a change whose file changed between its read and its commit', async () => { const {bridge: memory, storage} = memoryBridge(); let raced = false; @@ -405,6 +429,19 @@ describe('The inspectors', () => { 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; }); @@ -432,6 +469,18 @@ describe('The inspectors', () => { expect(host.preferences.detached.has('cpp.watches')).toBeFalse(); }); + 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('opens at a default place inside a small viewport', () => { const rect = defaultInspectorRect({width: 400, height: 300}); expect(rect.x + rect.width).toBeLessThanOrEqual(400); diff --git a/test/unit/WatchTests.cpp b/test/unit/WatchTests.cpp index 6dbcdd7a..5cdd76fe 100644 --- a/test/unit/WatchTests.cpp +++ b/test/unit/WatchTests.cpp @@ -211,6 +211,13 @@ const Scenario watchPages{ 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) From 2fa35787d1392f609cf574c62493e6d037069128 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:38:22 +0100 Subject: [PATCH 13/21] Reload a restored inspector page, and offer no tab under an embedded frontend (#680) - inspector.html loads itself again when the browser restores it from its back-forward cache: the discovery of the watches, the watch of the opener and the tab's connection were stopped when it was hidden, and main() does not run again. - webfront.inspector.embedded() also answers true while the active frontend gives its views the proof: an admitted page without it (a frame of an embedded view, under trustLoopbackClients) may run inside one, where window.open() would open a frame without the proof (ADR-027, section 8). --- ...DR-027-inspecteurs-de-l-etat-de-l-application.md | 9 ++++++--- include/webfront/DeveloperApp.hpp | 8 +++++--- js/developer/environment/bundles.json | 4 ++-- js/developer/environment/inspector-host.mjs | 2 +- js/developer/environment/inspector.mjs | 10 ++++++++++ test/developer/specs/inspector-specs.mjs | 13 ++++++++++++- test/unit/ViewAssociationTests.cpp | 11 ++++++++++- 7 files changed, 46 insertions(+), 11 deletions(-) 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 796b8288..1b563ba3 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,7 +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 est la vue d'un frontend intégré, 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`. | À renseigner après intégration. | +| 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`. | À 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 @@ -675,8 +675,11 @@ flottante sert de repli). L'ordre qui suit choisit le conteneur d'un panneau **d 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 rend -`UI::isEmbeddedView()` de l'appelant ; un échec compte comme une vue intégrée, ce qui n'essaie jamais d'onglet. +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 diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index ec625cd7..161dec2f 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -192,11 +192,13 @@ class DeveloperAppWithNetwork : public BasicWFtrustsLoopbackClients()](Caller ui) { return developer::inspectorContainers(Base::canShowSecondaryWindow(), ui.isLocalClient(), trust); }); - // Whether the calling page is the view of an embedded frontend: a tab of the system browser is offered only to a page - // that is not (ADR-027, section 8), since window.open() in an embedded view would open a frame without the proof. + // 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(); + return ui.isEmbeddedView() || frontend::providesViewProof(); }); this->template reservedCppFunction>( "webfront.inspector.savePreferences", diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 8ad65c27..6e5f360d 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -24,8 +24,8 @@ "js/developer/environment/terminal.mjs": "3b74d1a4d0466ce06af4df2bd9727c2ecb933780dc52de94abc153c1e60d48e7", "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "be8a3adfae655c02961bd8e2b866c6d55be5dd34cbf76ae700704d728694f289", - "js/developer/environment/inspector.mjs": "fe0a6a3844426485b1d1f70f0710ca7557eb824e0bcb4bac62a9a2180197549f", + "js/developer/environment/inspector-host.mjs": "a6e8de0d6a2db1ec4b74cb312b4118883278bac4489ee707e70d2c5ff963b325", + "js/developer/environment/inspector.mjs": "5c68c94b722a891b4d4b4be0d30a018e91615201c754cb0973d745c4ba311a88", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index 3c348e8a..e02279db 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -225,7 +225,7 @@ export async function claimHostIdentifier(view) { /** * 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 is an embedded view (by default asked to + * 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()). diff --git a/js/developer/environment/inspector.mjs b/js/developer/environment/inspector.mjs index 451da935..fa45bbfc 100644 --- a/js/developer/environment/inspector.mjs +++ b/js/developer/environment/inspector.mjs @@ -231,6 +231,15 @@ export function watchOpener(view, period = 1000) { 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. @@ -241,6 +250,7 @@ export async function main(view = window) { 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); diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index c978792d..42b1354b 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -5,7 +5,7 @@ import {detachedContainer, containerFor, hostReasons, parsePreferences, formatPr 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} from '../../../js/developer/environment/inspector.mjs'; + 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'; @@ -533,6 +533,17 @@ describe('The inspectors', () => { } 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 its native window through C++ when it has no opener', async () => { const status = document.createElement('p'); const calls = []; diff --git a/test/unit/ViewAssociationTests.cpp b/test/unit/ViewAssociationTests.cpp index 7ce4e8ef..00b305dd 100644 --- a/test/unit/ViewAssociationTests.cpp +++ b/test/unit/ViewAssociationTests.cpp @@ -632,10 +632,19 @@ const Scenario inspectorWatchesAccess{ ViewSocket::peerIsLoopback = true; AdmittedBrowser browser{true, false}; callWithoutArgument("webfront.inspector.embedded", 12); - then("it is admitted and told that it is not one: a tab of the system browser may be offered to it", [&] { + 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; From bed092c18d826ce5e7621bbdf38fe0b809729414 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:58:01 +0100 Subject: [PATCH 14/21] Close a native inspector window that opens after its panel was attached again (#680) When openWindow answers after attach() brought the panel back to the floating window, the host asks webfront.inspector.closeWindow for that stale window instead of leaving the panel shown twice. A panel detached again meanwhile keeps its window. Both orders are covered with a deferred openWindow answer. --- js/developer/environment/bundles.json | 2 +- js/developer/environment/inspector-host.mjs | 10 +++++++- test/developer/specs/inspector-specs.mjs | 28 +++++++++++++++++---- 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 6e5f360d..cdebe2ab 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -24,7 +24,7 @@ "js/developer/environment/terminal.mjs": "3b74d1a4d0466ce06af4df2bd9727c2ecb933780dc52de94abc153c1e60d48e7", "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "a6e8de0d6a2db1ec4b74cb312b4118883278bac4489ee707e70d2c5ff963b325", + "js/developer/environment/inspector-host.mjs": "80b370935ac9b14d278160d8989c1384ac99d0933ce66339419621b76814c184", "js/developer/environment/inspector.mjs": "5c68c94b722a891b4d4b4be0d30a018e91615201c754cb0973d745c4ba311a88", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index e02279db..374bdeb3 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -351,12 +351,20 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e frame = empty; } - /** Opens `id` in its detached container; resolves with whether it did. A failure leaves it in the floating window. */ + /** + * Opens `id` in its detached container; resolves with whether it did. A failure leaves it in the floating window. A native + * window that opens after the panel was attached again (while C++ was opening it) is closed at once: the panel stays in + * the floating window that attach() showed. + */ async function openDetached(id, container) { if (container === 'window') { const rect = shown(), started = action; try { await bridge.cppFunction('webfront.inspector.openWindow')(id, self, rect.width, rect.height); + if (!preferences.detached.has(id)) { + await bridge.cppFunction('webfront.inspector.closeWindow')(id, self).catch(() => {}); + return false; + } return true; } catch (error) { // Shown as the fallback only if nothing was done with the window while the native one was being opened. diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index 42b1354b..fa99f43c 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -184,6 +184,7 @@ describe('The inspectors', () => { const bridge = {cppFunction: name => async (...args) => { calls.push([name, ...args]); if (name === 'webfront.inspector.openWindow') return openWindow(...args); + if (name === 'webfront.inspector.closeWindow') return true; if (name === 'webfront.inspector.embedded') return embedded; return projectBridge.cppFunction(name)(...args); }}; @@ -455,18 +456,35 @@ describe('The inspectors', () => { expect(host.notice.hidden).toBeTrue(); }); - it('keeps a panel attached while its detach was pending', async () => { + 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} = await testHost({containers: admitted(true), openWindow: () => pending}); + 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 window asks to come back before C++ answered - opened(); - await detaching; + 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('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', () => { From e30f19ca1899a9763a0bd0a1c22cad72b78082e8 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:04:48 +0100 Subject: [PATCH 15/21] Borrow the host's bridge in the floating inspector's frame (#680) The frame read parent.webFront, the page's global bridge, although mount() and createInspectorHost() receive a bridge explicitly: mounted with another bridge, the inspector could show the watches of another connection or be refused while its host is admitted. The host now exposes the bridge it was created with, and the frame borrows only that one. --- js/developer/environment/bundles.json | 4 ++-- js/developer/environment/inspector-host.mjs | 2 ++ js/developer/environment/inspector.mjs | 4 +++- test/developer/specs/inspector-specs.mjs | 11 ++++++++--- 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index cdebe2ab..7a1879ee 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -24,8 +24,8 @@ "js/developer/environment/terminal.mjs": "3b74d1a4d0466ce06af4df2bd9727c2ecb933780dc52de94abc153c1e60d48e7", "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "80b370935ac9b14d278160d8989c1384ac99d0933ce66339419621b76814c184", - "js/developer/environment/inspector.mjs": "5c68c94b722a891b4d4b4be0d30a018e91615201c754cb0973d745c4ba311a88", + "js/developer/environment/inspector-host.mjs": "b680ec52a70f4d1f77dea3c6bfe2726bb96732fe0a2d36a05f59f405e8d95b92", + "js/developer/environment/inspector.mjs": "577d8873682a27b49fd3784f9c630ec99712ebfe1cf38e6109b4a79eac17cc7b", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index 374bdeb3..4e2081b6 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -393,6 +393,8 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e 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, diff --git a/js/developer/environment/inspector.mjs b/js/developer/environment/inspector.mjs index fa45bbfc..4c27ef0b 100644 --- a/js/developer/environment/inspector.mjs +++ b/js/developer/environment/inspector.mjs @@ -12,8 +12,10 @@ import {inspectorPanels as panels, panelTitle, inspectorChannel as channelName} */ 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.webFront; } + 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; diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index fa99f43c..d12af006 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -192,7 +192,7 @@ describe('The inspectors', () => { 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, calls, opened, storage}; + return {host, bridge, calls, opened, storage}; } afterEach(() => { for (const host of hosts.splice(0)) { @@ -207,7 +207,7 @@ describe('The inspectors', () => { 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} = await testHost({containers: admitted(false)}); + 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'); @@ -216,6 +216,7 @@ describe('The inspectors', () => { 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); @@ -509,8 +510,12 @@ describe('The inspectors', () => { describe('page', () => { it('borrows the bridge of its host page in a frame, without loading WebFront.js', async () => { const bridge = {ready: Promise.resolve()}; - const view = {parent: {webFront: bridge}, document}; + // 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/); }); From 3626717b7e73b2d0c0bf92c74bf223e55e7d4ba8 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:12:16 +0100 Subject: [PATCH 16/21] Let the host page close the window of a panel attached again (#680) A detached window closed itself once the host answered its request to be attached again; a detach made between that answer and the close reused the window, which the late close then removed while the panel was remembered detached. The host now closes it, ordered with its own detaches: a native window through closeWindow on its connection, a new openWindow waiting for that close; a tab it opened through its reference. A tab it has no reference to (opened before a reload) still closes itself, and the next detach opens a tab under another name. The answer says who closes the window, and a window the host closes no longer closes itself. --- ...-inspecteurs-de-l-etat-de-l-application.md | 8 +- js/developer/environment/bundles.json | 4 +- js/developer/environment/inspector-host.mjs | 43 +++++++++-- js/developer/environment/inspector.mjs | 18 +++-- test/developer/specs/inspector-specs.mjs | 74 ++++++++++++++++++- 5 files changed, 129 insertions(+), 18 deletions(-) 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 1b563ba3..8a6655b6 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 @@ -690,8 +690,12 @@ autre page du même groupe de navigation ne réutilise pas son onglet. Un pannea `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, et la fenêtre ne -se ferme qu'après cette réponse. +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. diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 7a1879ee..e041336c 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -24,8 +24,8 @@ "js/developer/environment/terminal.mjs": "3b74d1a4d0466ce06af4df2bd9727c2ecb933780dc52de94abc153c1e60d48e7", "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "b680ec52a70f4d1f77dea3c6bfe2726bb96732fe0a2d36a05f59f405e8d95b92", - "js/developer/environment/inspector.mjs": "577d8873682a27b49fd3784f9c630ec99712ebfe1cf38e6109b4a79eac17cc7b", + "js/developer/environment/inspector-host.mjs": "791958b7558db830de74898c162479b9e3f4862ac5019947a8fda37aec6c64cc", + "js/developer/environment/inspector.mjs": "dc253099f207d29e0c86d815e545212a548c1eed7ff2fba0e9195ff0d40f21c3", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index 4e2081b6..94569855 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -360,6 +360,8 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e if (container === 'window') { const rect = shown(), started = action; 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); if (!preferences.detached.has(id)) { await bridge.cppFunction('webfront.inspector.closeWindow')(id, self).catch(() => {}); @@ -375,14 +377,44 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e return false; } } - // The target names the host too: a tab of another page of the same browsing group is never reused for this one. - const tab = openTab(urlOf(id), `webfront-inspector-${self}-${id.replace('.', '-')}`); - if (tab) return true; + // 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; + /** Closes the detached container of `id`; 'host' when this page closes it, 'self' when the window must close itself. */ + function closeDetached(id) { + if (detachedContainer(containers, {embedded: isEmbedded}) === 'window') { + const closed = bridge.cppFunction('webfront.inspector.closeWindow')(id, self).catch(() => false); + closing.set(id, closed); + closed.then(() => { if (closing.get(id) === closed) closing.delete(id); }); + return 'host'; + } + 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(); @@ -447,14 +479,15 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e closeButton.addEventListener('click', hideFloating); retry.addEventListener('click', () => { if (retryPanel) host.detach(retryPanel); }); - // A detached inspector asks to come back: the first host that takes it answers, so that the inspector closes its window. + // 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); - channel.postMessage({type: 'attached', id: data.id}); + channel.postMessage({type: 'attached', id: data.id, closer: closeDetached(data.panel)}); }); host.channel = channel; } diff --git a/js/developer/environment/inspector.mjs b/js/developer/environment/inspector.mjs index 4c27ef0b..4fd98158 100644 --- a/js/developer/environment/inspector.mjs +++ b/js/developer/environment/inspector.mjs @@ -334,9 +334,10 @@ export async function main(view = window) { } /** - * Asks the page that detached the panel (`host`, the identifier its address carries) to show it again, and closes this - * window once that page answered: a native window through C++, a tab by itself. Another page of the same origin does not - * answer. Without an answer the window stays, and says why. + * 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 the window + * stays, and says why. */ export async function attachAgain(view, bridge, id, status, {host = null, wait = 1000} = {}) { if (typeof view.BroadcastChannel !== 'function' || !host) { @@ -345,20 +346,23 @@ export async function attachAgain(view, bridge, id, status, {host = null, wait = } const channel = new view.BroadcastChannel(channelName); const request = `${id}:${Date.now()}:${Math.random()}`; - const answered = await new Promise(resolve => { - const timer = view.setTimeout(() => resolve(false), wait); + const answer = await new Promise(resolve => { + const timer = view.setTimeout(() => resolve(null), wait); channel.addEventListener('message', ({data}) => { if (data?.type !== 'attached' || data.id !== request) return; view.clearTimeout(timer); - resolve(true); + resolve(data); }); channel.postMessage({type: 'attach', panel: id, host, id: request}); }); channel.close(); - if (!answered) { + if (!answer) { status.textContent = 'The main page did not answer: open the panel from the menu of its tab.'; return false; } + // 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; diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index d12af006..6dc96eed 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -178,13 +178,14 @@ describe('The inspectors', () => { 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 () => {}, windowOpen = () => ({}), hostId = 'host-a'} = {}) { + 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 true; + if (name === 'webfront.inspector.closeWindow') return closeWindow(...args); if (name === 'webfront.inspector.embedded') return embedded; return projectBridge.cppFunction(name)(...args); }}; @@ -351,6 +352,58 @@ describe('The inspectors', () => { } 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'); + expect((await askAttach('cpp.watches', 'request-close')).closer).toBe('host'); + 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 detaching).toBe('window'); + expect(names()).toEqual(['webfront.inspector.openWindow', 'webfront.inspector.closeWindow', 'webfront.inspector.openWindow']); + expect(host.preferences.detached.has('cpp.watches')).toBeTrue(); + }); + + 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(); @@ -567,6 +620,23 @@ describe('The inspectors', () => { expect(reloads).toEqual([true]); }); + 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 = []; From 55c0ac5eea5fa6a3f4067dbb640a1b0798b4d3be Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:26:01 +0100 Subject: [PATCH 17/21] Close a native inspector window that opens after its floating window was closed (#680) Closing the floating window while C++ is opening the native window of the panel it shows now cancels that opening: once openWindow answers, the stale window is closed, as for a panel attached again meanwhile. Opening another panel in the floating window does not cancel it. Both are covered with a deferred openWindow answer. --- js/developer/environment/bundles.json | 2 +- js/developer/environment/inspector-host.mjs | 20 +++++++++++++--- test/developer/specs/inspector-specs.mjs | 26 +++++++++++++++++++++ 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index e041336c..c24e3b94 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -24,7 +24,7 @@ "js/developer/environment/terminal.mjs": "3b74d1a4d0466ce06af4df2bd9727c2ecb933780dc52de94abc153c1e60d48e7", "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "791958b7558db830de74898c162479b9e3f4862ac5019947a8fda37aec6c64cc", + "js/developer/environment/inspector-host.mjs": "70b5c9fefc39b649ad8202d23075520e76329a74db706f861a4609f541491d55", "js/developer/environment/inspector.mjs": "dc253099f207d29e0c86d815e545212a548c1eed7ff2fba0e9195ff0d40f21c3", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index 94569855..86f65a21 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -359,11 +359,14 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e async function openDetached(id, container) { if (container === 'window') { const rect = shown(), started = action; + const attempt = {cancelled: false}; + opening.set(id, attempt); 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); - if (!preferences.detached.has(id)) { + // Attached again, or its floating window closed by the user, while C++ was opening it: no longer wanted. + if (!preferences.detached.has(id) || attempt.cancelled) { await bridge.cppFunction('webfront.inspector.closeWindow')(id, self).catch(() => {}); return false; } @@ -375,6 +378,8 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e showFloating(id, `${hostReasons.windowFailed}: ${error?.message ?? error}`); } return false; + } finally { + if (opening.get(id) === attempt) opening.delete(id); } } // The target names the host too: a tab of another page of the same browsing group is never reused for this one. A tab @@ -397,6 +402,15 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e // 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 native window of each panel that C++ is opening: closing the floating window that shows that panel meanwhile + // cancels it, and the window is closed once it opens. + const opening = new Map(); + /** Closes the floating window at the user's request, with the native window still opening for its panel. */ + function closeFloating() { + const attempt = shownPanel && opening.get(shownPanel); + if (attempt) attempt.cancelled = true; + hideFloating(); + } /** Closes the detached container of `id`; 'host' when this page closes it, 'self' when the window must close itself. */ function closeDetached(id) { if (detachedContainer(containers, {embedded: isEmbedded}) === 'window') { @@ -468,7 +482,7 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e retryPanel = null; showFloating(id); }, - close: hideFloating, + close: closeFloating, saved: () => store.saved(), get preferences() { return {detached: new Set(preferences.detached), rect: preferences.rect}; }, }; @@ -476,7 +490,7 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e detachButton.addEventListener('click', () => { if (shownPanel && !reason()) host.detach(shownPanel); }); - closeButton.addEventListener('click', hideFloating); + 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 diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index 6dc96eed..9acf3aff 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -527,6 +527,32 @@ describe('The inspectors', () => { 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('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))}); From 1c664a4b760cc975495e78065869f8517f705c11 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:12:58 +0100 Subject: [PATCH 18/21] Cancel every pending native opening of a panel when its floating window closes (#680) A second Detach of the same panel replaced the first pending opening, so closing the floating window cancelled only the second one and the first could leave a native window open. The host now keeps every opening C++ has not answered yet, per panel, and closing the floating window cancels all of them. Covered with two deferred openWindow answers. --- js/developer/environment/bundles.json | 2 +- js/developer/environment/inspector-host.mjs | 16 +++++++++------- test/developer/specs/inspector-specs.mjs | 15 +++++++++++++++ 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index c24e3b94..8f5f7d43 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -24,7 +24,7 @@ "js/developer/environment/terminal.mjs": "3b74d1a4d0466ce06af4df2bd9727c2ecb933780dc52de94abc153c1e60d48e7", "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "70b5c9fefc39b649ad8202d23075520e76329a74db706f861a4609f541491d55", + "js/developer/environment/inspector-host.mjs": "a6a5eea8aa10bcbb71c477fd0c7731514e3ba80caff3cc47e02fde6e10c769ac", "js/developer/environment/inspector.mjs": "dc253099f207d29e0c86d815e545212a548c1eed7ff2fba0e9195ff0d40f21c3", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index 86f65a21..5634cc78 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -360,7 +360,8 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e if (container === 'window') { const rect = shown(), started = action; const attempt = {cancelled: false}; - opening.set(id, attempt); + if (!opening.has(id)) opening.set(id, new Set()); + opening.get(id).add(attempt); 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); @@ -379,7 +380,9 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e } return false; } finally { - if (opening.get(id) === attempt) opening.delete(id); + const pending = opening.get(id); + pending?.delete(attempt); + if (pending?.size === 0) opening.delete(id); } } // The target names the host too: a tab of another page of the same browsing group is never reused for this one. A tab @@ -402,13 +405,12 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e // 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 native window of each panel that C++ is opening: closing the floating window that shows that panel meanwhile - // cancels it, and the window is closed once it opens. + // The openings of a native window that C++ has not answered yet, per panel (Detach clicked twice makes two): closing the + // floating window that shows that panel meanwhile cancels all of them, and the window is closed once it opens. const opening = new Map(); - /** Closes the floating window at the user's request, with the native window still opening for its panel. */ + /** Closes the floating window at the user's request, with the native windows still opening for its panel. */ function closeFloating() { - const attempt = shownPanel && opening.get(shownPanel); - if (attempt) attempt.cancelled = true; + for (const attempt of (shownPanel && opening.get(shownPanel)) || []) attempt.cancelled = true; hideFloating(); } /** Closes the detached container of `id`; 'host' when this page closes it, 'self' when the window must close itself. */ diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index 9acf3aff..ba695d92 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -541,6 +541,21 @@ describe('The inspectors', () => { 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(); + expect(calls.filter(([name]) => name === 'webfront.inspector.closeWindow').length).toBe(2); + }); + 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; })}); From d658276c4e4c083fbfbb0dfd48db94621332dcf8 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:50:28 +0100 Subject: [PATCH 19/21] Let only a panel's latest opening close its window, and keep a watch reassigned by its source (#680) - A panel has one native window per host page: a cancelled opening now closes it only while it is the latest opening asked for that panel, so it no longer closes the window that a detach made meanwhile reuses. The latest opening decides, and closes the window if it was cancelled too. - Watch::reset() empties the handle before removing the watch and does not touch it afterwards, and the move assignment installs the new watch before removing the previous one: a source whose release assigns the same handle to a new watch no longer leaves a handle that cannot remove it. --- include/webfront/Watches.hpp | 15 +- js/developer/environment/bundles.json | 2 +- js/developer/environment/inspector-host.mjs | 10 +- test/developer/specs/inspector-specs.mjs | 20 ++- test/unit/WatchTests.cpp | 174 ++++++++++++-------- 5 files changed, 145 insertions(+), 76 deletions(-) diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index 9476f6a5..bbfa8d76 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -435,7 +435,9 @@ class Watch { Watch(Watch&& other) noexcept : registry(std::move(other.registry)), watchId(std::exchange(other.watchId, 0)) { } Watch& operator=(Watch&& other) noexcept { if (this != &other) { - reset(); + // 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); } @@ -445,12 +447,13 @@ class Watch { reset(); } - /// Removes the watch now; the handle becomes empty. + /// 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 { - if (const auto id = std::exchange(watchId, 0); id != 0) - if (const auto owner = registry.lock()) - owner->remove(id); - registry.reset(); + 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. diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 8f5f7d43..5cb2db4e 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -24,7 +24,7 @@ "js/developer/environment/terminal.mjs": "3b74d1a4d0466ce06af4df2bd9727c2ecb933780dc52de94abc153c1e60d48e7", "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "a6a5eea8aa10bcbb71c477fd0c7731514e3ba80caff3cc47e02fde6e10c769ac", + "js/developer/environment/inspector-host.mjs": "20a28dd403861a1492f4b2590ebd1b2da71a185498e58ee7fe434597f51b2c0c", "js/developer/environment/inspector.mjs": "dc253099f207d29e0c86d815e545212a548c1eed7ff2fba0e9195ff0d40f21c3", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index 5634cc78..652ab2b4 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -362,13 +362,17 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e const attempt = {cancelled: false}; if (!opening.has(id)) opening.set(id, new Set()); opening.get(id).add(attempt); + latest.set(id, attempt); 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); // Attached again, or its floating window closed by the user, while C++ was opening it: no longer wanted. if (!preferences.detached.has(id) || attempt.cancelled) { - await bridge.cppFunction('webfront.inspector.closeWindow')(id, self).catch(() => {}); + // A panel has one native window per host page: a later opening of it, which may reuse that window, + // decides whether it stays (and closes it in turn if it was cancelled too). + if (latest.get(id) === attempt) + await bridge.cppFunction('webfront.inspector.closeWindow')(id, self).catch(() => {}); return false; } return true; @@ -383,6 +387,7 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e const pending = opening.get(id); pending?.delete(attempt); if (pending?.size === 0) opening.delete(id); + if (latest.get(id) === attempt) latest.delete(id); } } // The target names the host too: a tab of another page of the same browsing group is never reused for this one. A tab @@ -407,7 +412,8 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e let generation = 0; // The openings of a native window that C++ has not answered yet, per panel (Detach clicked twice makes two): closing the // floating window that shows that panel meanwhile cancels all of them, and the window is closed once it opens. - const opening = new Map(); + // `latest` holds the last opening asked for each panel while it is pending: only that one closes a window it cancels. + const opening = new Map(), latest = 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)) || []) attempt.cancelled = true; diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index ba695d92..0172dcf6 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -553,7 +553,25 @@ describe('The inspectors', () => { answers[1](); await Promise.all([first, second]); expect(host.panel.hidden).toBeTrue(); - expect(calls.filter(([name]) => name === 'webfront.inspector.closeWindow').length).toBe(2); + // 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('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 () => { diff --git a/test/unit/WatchTests.cpp b/test/unit/WatchTests.cpp index 5cdd76fe..324125ce 100644 --- a/test/unit/WatchTests.cpp +++ b/test/unit/WatchTests.cpp @@ -277,69 +277,111 @@ const Scenario watchPages{ }); }}; -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("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; - })); - }); - }); - }}; +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(Reassigning{*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)); + requireEqual(registry->size(), std::size_t{1}); + const auto kept = handle.id(); + require(registry->contains(kept)); + handle.reset(); + 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; + })); + }); + }); + }}; From 8b26b4000b55ba44a259b9f0c47497dc7ef233b5 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:51:33 +0100 Subject: [PATCH 20/21] Decide whether a panel's native window stays once all its openings have answered (#680) With two openings of a panel pending and both cancelled, the latest one answering first closed the window and forgot the cancellation, so the first one could create the window afterwards and leave it open. The decision is now taken once the last pending opening of the panel has answered, whatever their order: the window is closed when the panel is no longer detached or the latest opening asked for was cancelled. Covered in both orders of the answers. --- js/developer/environment/bundles.json | 2 +- js/developer/environment/inspector-host.mjs | 50 ++++++++++----------- test/developer/specs/inspector-specs.mjs | 16 +++++++ 3 files changed, 42 insertions(+), 26 deletions(-) diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 5cb2db4e..c110a699 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -24,7 +24,7 @@ "js/developer/environment/terminal.mjs": "3b74d1a4d0466ce06af4df2bd9727c2ecb933780dc52de94abc153c1e60d48e7", "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "20a28dd403861a1492f4b2590ebd1b2da71a185498e58ee7fe434597f51b2c0c", + "js/developer/environment/inspector-host.mjs": "36c2045efd0bda50eee6f19f1ff426ebf1569f66113e1d2c530b7bed20192471", "js/developer/environment/inspector.mjs": "dc253099f207d29e0c86d815e545212a548c1eed7ff2fba0e9195ff0d40f21c3", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index 652ab2b4..af3c2dcb 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -353,42 +353,42 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e /** * Opens `id` in its detached container; resolves with whether it did. A failure leaves it in the floating window. A native - * window that opens after the panel was attached again (while C++ was opening it) is closed at once: the panel stays in - * the floating window that attach() showed. + * 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, new Set()); - opening.get(id).add(attempt); - latest.set(id, attempt); + 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); - // Attached again, or its floating window closed by the user, while C++ was opening it: no longer wanted. - if (!preferences.detached.has(id) || attempt.cancelled) { - // A panel has one native window per host page: a later opening of it, which may reuse that window, - // decides whether it stays (and closes it in turn if it was cancelled too). - if (latest.get(id) === attempt) - await bridge.cppFunction('webfront.inspector.closeWindow')(id, self).catch(() => {}); - return false; - } - return true; } 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}: ${error?.message ?? error}`); + showFloating(id, `${hostReasons.windowFailed}: ${failure?.message ?? failure}`); } return false; - } finally { - const pending = opening.get(id); - pending?.delete(attempt); - if (pending?.size === 0) opening.delete(id); - if (latest.get(id) === attempt) latest.delete(id); } + 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. @@ -410,13 +410,13 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e // 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): closing the - // floating window that shows that panel meanwhile cancels all of them, and the window is closed once it opens. - // `latest` holds the last opening asked for each panel while it is pending: only that one closes a window it cancels. - const opening = new Map(), latest = new Map(); + // 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)) || []) attempt.cancelled = true; + for (const attempt of (shownPanel && opening.get(shownPanel)?.pending) || []) attempt.cancelled = true; hideFloating(); } /** Closes the detached container of `id`; 'host' when this page closes it, 'self' when the window must close itself. */ diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index 0172dcf6..4d3219db 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -557,6 +557,22 @@ describe('The inspectors', () => { 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))}); From 170e02071f18844e9ba09967d88fc17ff75d520a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:21:17 +0100 Subject: [PATCH 21/21] Answer the review of #692 (#680) - Read the inspectors' choices and their token together (webfront.inspector.readPreferences, Store::readWithState): the token is that of the bytes read, so a save never applies to a content that changed and came back; a save that failed is kept for the next one. - Bound the listing of the watches, stop it on Pause, give Attach its own status, close a window on a late answer, and answer 'host' only when the native close succeeded. - Show the terminal when an inspector cannot open, and draw the edited line again after a notice during a completion. - Watches: lvalue-qualified visitors, accessors returning nothing refused, a truncation limit that cannot wrap, and a handle being destroyed takes no new watch; enableInspectors() private. - Bind the inspector window requests to the interface session that admitted them. - Require providesViewProof() of any frontend whose open() receives ViewLaunch. - The integration spec checks the containers against the frontend type; docs and ADR index. --- docs/CHANGELOG.md | 1 + docs/DEVELOPER_ENVIRONMENT.md | 4 +- docs/FRONTENDS.md | 6 +- ...-inspecteurs-de-l-etat-de-l-application.md | 14 +- docs/adr/README.md | 2 +- include/webfront/DeveloperApp.hpp | 21 ++- include/webfront/Watches.hpp | 27 ++- include/webfront/WebFront.hpp | 48 +++-- include/webfront/frontend/Frontend.hpp | 27 ++- include/webfront/system/DeveloperJournal.hpp | 22 +++ include/webfront/system/DeveloperStore.hpp | 29 +++ js/developer/environment/bundles.json | 8 +- js/developer/environment/inspector-host.mjs | 51 ++++-- js/developer/environment/inspector.mjs | 82 +++++---- js/developer/environment/runtime.mjs | 1 + js/developer/environment/terminal.mjs | 5 +- test/developer/memory-bridge.mjs | 5 + test/developer/specs/inspector-specs.mjs | 168 ++++++++++++++++-- test/unit/DeveloperTests.cpp | 38 ++++ test/unit/InspectorDistribution.cpp | 1 + test/unit/WatchTests.cpp | 44 ++++- test/web/DeveloperTest.cpp | 7 + test/web/developer-specs.mjs | 7 +- 23 files changed, 521 insertions(+), 97 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 057ad917..41e781cd 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -11,6 +11,7 @@ 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 diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 22f30be2..f77fc9bd 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -459,7 +459,9 @@ environment's `mount`, not to the embedded bootstrap page): | 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. The project keeps the detached panels and the floating window's place in + 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 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 8a6655b6..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,7 +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`. | À renseigner après intégration. | +| 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 @@ -702,10 +702,14 @@ recommencer la liste, pour qu'un observateur retiré entre deux pages ne reste p 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. 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. Si la page ferme avant que cet appel arrive, -le dernier changement peut être perdu. +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. 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/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 161dec2f..24b02746 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -94,6 +94,9 @@ inline bool inspectorHostIdentifier(std::string_view host) noexcept { }); } +/// 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. @@ -200,11 +203,19 @@ class DeveloperAppWithNetwork : public BasicWF(); }); + // 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(".webfront/developer/inspector-window.json", std::move(bytes), expected); + 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( @@ -225,8 +236,13 @@ class DeveloperAppWithNetwork : public BasicWFcurrentShowSession(); // 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)); }); }); @@ -238,8 +254,9 @@ class DeveloperAppWithNetwork : public BasicWFcurrentShowSession(); // as openWindow: never a window of a later session co_return co_await networking::ex::then(this->uiExecutor().schedule(), [&] { - return this->requestClose(page); + return this->isCurrentShowSession(bound) && this->requestClose(page); }); }); } diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index bbfa8d76..624d171a 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -4,7 +4,7 @@ // // WebFront — core // Role: The registry of the watches an application declares for the inspectors (ADR-027), and its discovery page. -// Thread: thread-safe | Alloc: heap-init +// 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 @@ -101,11 +101,11 @@ inline constexpr std::string_view ellipsis = "\xE2\x80\xA6"; /// 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 + 4)); // parenthesized: Windows headers may define min + 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 + 4) - break; // enough to know that it is cut + 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; @@ -241,6 +241,15 @@ 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 { @@ -274,8 +283,9 @@ struct SourceShape { 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) + requires(!detail::visitor_source && std::invocable && !std::is_void_v>) struct SourceShape { using Object = std::remove_reference_t>; static constexpr bool visitor = false; @@ -434,7 +444,8 @@ class Watch { 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 { - if (this != &other) { + // 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)}; @@ -444,6 +455,7 @@ class Watch { return *this; } ~Watch() { + destroying = true; // a source released by reset() may assign this handle: the assignment is refused reset(); } @@ -467,7 +479,8 @@ class Watch { private: std::weak_ptr registry; - std::uint64_t watchId = 0; + std::uint64_t watchId = 0; + bool destroying = false; }; } // namespace webfront::inspect diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 741d8f54..daa955ce 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -1628,16 +1628,7 @@ class BasicWF { windowOptions.background = "#141821"; } - /// For the developer environment: from now on, watch() registers in the table that the inspectors read (ADR-027). - /// Returns that table. A distribution build never calls it. - std::shared_ptr enableInspectors() { - std::scoped_lock lock{watchRegistryMutex}; - if (!watchRegistry) - watchRegistry = std::make_shared(); - return watchRegistry; - } - - /// The table of the watches, null until enableInspectors(). + /// 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; @@ -1650,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() { diff --git a/include/webfront/frontend/Frontend.hpp b/include/webfront/frontend/Frontend.hpp index ae7d585c..39eeba47 100644 --- a/include/webfront/frontend/Frontend.hpp +++ b/include/webfront/frontend/Frontend.hpp @@ -85,15 +85,29 @@ concept FrontendType = requires(std::string_view port, std::string_view file) { { Frontend::open(port, file) } -> std::same_as; } && std::same_as, Action>; -/// Whether the active frontend gives the application window the bridge's launch proof. +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 + 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. @@ -103,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 @@ -151,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; 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 e4f208b5..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); diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index c110a699..d7588dd6 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -17,15 +17,15 @@ "js/developer/environment/packages.mjs": "37fe2a410e211264cfeaedbff3df50f7e62b02f8088130127d94f92081e2a5ad", "js/developer/environment/starter.mjs": "fd43db1861121577c48a0327436ce39cb9076d7cad0e9e273d40955747cc6a48", "js/developer/environment/paths.mjs": "3b6114df78eb193161c5c84499dda084cb7ff91c56a4496371c30295d00880e3", - "js/developer/environment/runtime.mjs": "b67e898c7d40dbf5dab1d0486d39d035c7a740c564e418675ca244206f23bb00", + "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": "3b74d1a4d0466ce06af4df2bd9727c2ecb933780dc52de94abc153c1e60d48e7", + "js/developer/environment/terminal.mjs": "e7c3ca8f9833f10e07939277996eb01fb989c986420c96052271ff469fa59062", "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", - "js/developer/environment/inspector-host.mjs": "36c2045efd0bda50eee6f19f1ff426ebf1569f66113e1d2c530b7bed20192471", - "js/developer/environment/inspector.mjs": "dc253099f207d29e0c86d815e545212a548c1eed7ff2fba0e9195ff0d40f21c3", + "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", diff --git a/js/developer/environment/inspector-host.mjs b/js/developer/environment/inspector-host.mjs index af3c2dcb..ca8c7ced 100644 --- a/js/developer/environment/inspector-host.mjs +++ b/js/developer/environment/inspector-host.mjs @@ -82,20 +82,35 @@ async function projectFileMissing(bridge, path) { } } -/** The choices the project has: empty ones without a file; a file that exists but cannot be read throws. */ +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 parsePreferences(''); + if (await projectFileMissing(bridge, preferencesPath).catch(() => false)) return {preferences: parsePreferences(''), token}; throw error; } - return parsePreferences(decoder.decode(bytes)); + 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); } + try { return (await readStoredPreferences(bridge)).preferences; } catch { return parsePreferences(''); } } @@ -116,8 +131,8 @@ const preferenceConflict = /changed since it was read|already being written/; async function writePreferenceChanges(bridge, changes) { for (let attempt = 1; ; ++attempt) { try { - const token = await call(bridge, 'state', preferencesPath); - const text = formatPreferences(applyPreferenceChanges(await readStoredPreferences(bridge), changes)); + 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) { @@ -132,7 +147,8 @@ async function writePreferenceChanges(bridge, changes) { * 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. + * 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(); @@ -142,7 +158,12 @@ export function preferencesStore(bridge, delay = 300) { 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)); + 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 { @@ -419,13 +440,17 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e for (const attempt of (shownPanel && opening.get(shownPanel)?.pending) || []) attempt.cancelled = true; hideFloating(); } - /** Closes the detached container of `id`; 'host' when this page closes it, 'self' when the window must close itself. */ - function closeDetached(id) { + /** + * 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).catch(() => false); + 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 'host'; + return await closed ? 'host' : 'self'; } const tab = tabs.get(id); tabs.delete(id); @@ -509,7 +534,7 @@ export async function createInspectorHost({bridge, page, inspectorUrl, access, e // 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); - channel.postMessage({type: 'attached', id: data.id, closer: closeDetached(data.panel)}); + closeDetached(data.panel).then(closer => channel.postMessage({type: 'attached', id: data.id, closer})); }); host.channel = channel; } diff --git a/js/developer/environment/inspector.mjs b/js/developer/environment/inspector.mjs index 4fd98158..a024af1e 100644 --- a/js/developer/environment/inspector.mjs +++ b/js/developer/environment/inspector.mjs @@ -67,14 +67,18 @@ 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, the list is given with the revision 0, which the next poll always finds changed. + * 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) { +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; @@ -83,18 +87,7 @@ export async function listWatches(bridge, revision = 0) { if (stable) return {watches, revision: first.revision}; revision = 0; } - const {watches} = await listWatchesOnce(bridge); - return {watches, revision: 0}; -} - -async function listWatchesOnce(bridge) { - const watches = []; - for (let after = 0;;) { - const page = readPage(await bridge.cppFunction(watchesFunction)(0, after, 200)); - watches.push(...page.descriptors); - if (!page.next) return {watches}; - after = page.next; - } + 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. */ @@ -119,12 +112,19 @@ export function createWatchDiscovery({bridge, onChange, onError = () => {}, onRe 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); - revision = listed.revision; - apply(listed.watches); + const listed = await listWatches(bridge, current, {active}); + if (!active()) return; + if (listed) { + revision = listed.revision; + apply(listed.watches); + } } onRead([...known.values()]); } @@ -291,7 +291,12 @@ export async function main(view = window) { attach.textContent = 'Attach'; attach.title = 'Show this panel in the floating window of the main page'; header.append(attach); - attach.addEventListener('click', () => attachAgain(view, bridge, id, status, {host: params.get('host')})); + // 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') { @@ -336,34 +341,43 @@ export async function main(view = window) { /** * 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 the window - * stays, and says why. + * 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()}`; - const answer = await new Promise(resolve => { - const timer = view.setTimeout(() => resolve(null), wait); + // 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); - resolve(data); + finish(data).then(done => { if (!late) resolve(done); }); }); channel.postMessage({type: 'attach', panel: id, host, id: request}); }); - channel.close(); - if (!answer) { - status.textContent = 'The main page did not answer: open the panel from the menu of its tab.'; - return false; - } - // 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; } diff --git a/js/developer/environment/runtime.mjs b/js/developer/environment/runtime.mjs index dfa0325e..980cfb05 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -672,6 +672,7 @@ export async function mount({bridge, config, terminal: element, preview, onExit, 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, diff --git a/js/developer/environment/terminal.mjs b/js/developer/environment/terminal.mjs index 29024448..371cb4bd 100644 --- a/js/developer/environment/terminal.mjs +++ b/js/developer/environment/terminal.mjs @@ -300,11 +300,12 @@ export class LineEditor { /** * 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, or after the output of the command that runs. + * 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 || this.completing) return this.write((this.atLineStart ? '' : '\r\n') + lines); + 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(); } diff --git a/test/developer/memory-bridge.mjs b/test/developer/memory-bridge.mjs index 62e1f3fc..21c44ed7 100644 --- a/test/developer/memory-bridge.mjs +++ b/test/developer/memory-bridge.mjs @@ -57,6 +57,11 @@ export function memoryBridge(storage = new Map()) { }, }; 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; diff --git a/test/developer/specs/inspector-specs.mjs b/test/developer/specs/inspector-specs.mjs index 4d3219db..aebf0dfb 100644 --- a/test/developer/specs/inspector-specs.mjs +++ b/test/developer/specs/inspector-specs.mjs @@ -124,9 +124,9 @@ describe('The inspectors', () => { const store = preferencesStore(bridge); store.detached('cpp.watches', true); await expectAsync(store.saved()).toBeRejectedWithError('Disconnected'); - // Without a file, the read fails and listing the directories shows that the file is absent. - expect(calls).toEqual(['webfront.developer.state', 'webfront.developer.read', 'webfront.developer.list', 'webfront.developer.list', - 'webfront.developer.list', 'webfront.inspector.savePreferences']); + 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); @@ -139,7 +139,7 @@ describe('The inspectors', () => { const {bridge: memory, storage} = memoryBridge(new Map([[preferencesPath, others]])); let failing = true; const bridge = {cppFunction: name => async (...args) => { - if (name === 'webfront.developer.read' && failing) throw new Error('Cannot read project file: ' + args[0]); + if (name === 'webfront.inspector.readPreferences' && failing) throw new Error('Cannot read project file: ' + preferencesPath); return memory.cppFunction(name)(...args); }}; const store = preferencesStore(bridge); @@ -155,6 +155,57 @@ describe('The inspectors', () => { .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; @@ -367,7 +418,8 @@ describe('The inspectors', () => { let closed; const {host, calls} = await testHost({containers: admitted(true), closeWindow: () => new Promise(resolve => { closed = resolve; })}); await host.detach('cpp.watches'); - expect((await askAttach('cpp.watches', 'request-close')).closer).toBe('host'); + 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'); @@ -375,11 +427,24 @@ describe('The inspectors', () => { 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: () => { @@ -628,6 +693,25 @@ describe('The inspectors', () => { 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); @@ -695,6 +779,25 @@ describe('The inspectors', () => { 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 = []; @@ -769,18 +872,61 @@ describe('The inspectors', () => { expect(registry.answer(revision, 0, 0)[3]).toBeFalse(); }); - it('give up the revision when the registry keeps changing, so that the next poll reads the list again', async () => { + 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); - if (args[1] === 0) registry.add(`x${registry.calls.length}`); + registry.add(`x${registry.calls.length}`); return answer; }}; - const {watches, revision} = await listWatches(bridge, 0); - expect(revision).toBe(0); - expect(watches.length).toBeGreaterThan(0); - expect(registry.calls.filter(([, after]) => after === 0).length).toBeGreaterThanOrEqual(listingAttempts); + 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', () => { diff --git a/test/unit/DeveloperTests.cpp b/test/unit/DeveloperTests.cpp index e6f38547..74ac166b 100644 --- a/test/unit/DeveloperTests.cpp +++ b/test/unit/DeveloperTests.cpp @@ -909,6 +909,44 @@ const Scenario conditionalFilePublication{"A failed single-file publication rele }); }}; +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 5b5c881d..c854f58f 100644 --- a/test/unit/InspectorDistribution.cpp +++ b/test/unit/InspectorDistribution.cpp @@ -36,6 +36,7 @@ const Scenario inspectorsAbsent{"A distribution build registers no inspector fun 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"}) diff --git a/test/unit/WatchTests.cpp b/test/unit/WatchTests.cpp index 324125ce..22155adb 100644 --- a/test/unit/WatchTests.cpp +++ b/test/unit/WatchTests.cpp @@ -66,6 +66,9 @@ const Scenario watchTexts{"The texts of a watch are bounded and made visible (AD 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); @@ -116,6 +119,18 @@ const Scenario watchKinds{"The kind of a watch's root follows the order of ADR-0 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>); @@ -262,10 +277,12 @@ const Scenario watchPages{ 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")); }); @@ -323,7 +340,7 @@ const Scenario watchHandles{ 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(Reassigning{*registry, handle, registry})); + 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(); @@ -341,7 +358,8 @@ const Scenario watchHandles{ 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)); - requireEqual(registry->size(), std::size_t{1}); + // 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(); @@ -349,6 +367,28 @@ const Scenario watchHandles{ }); }); }); + 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; diff --git a/test/web/DeveloperTest.cpp b/test/web/DeveloperTest.cpp index 59aa82e7..4b13376b 100644 --- a/test/web/DeveloperTest.cpp +++ b/test/web/DeveloperTest.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include namespace { @@ -288,6 +289,12 @@ 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()); }); diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index d1a61aef..311bed2f 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -925,7 +925,12 @@ 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. - const [secondaryWindow, admitted] = await webFront.cppFunction('webfront.inspector.containers')(); + // 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); if (!admitted) {