Skip to content

Latest commit

 

History

History
143 lines (102 loc) · 25 KB

AGENTS.md

File metadata and controls

143 lines (102 loc) · 25 KB

WebFront contributor and agent guide

Project goal and current maturity

WebFront is a C++23 header-only library for serving a browser UI from a C++ application. It embeds an HTTP/WebSocket server and exposes an asynchronous binary bridge for calls in both directions. The two directions are not symmetric:

  • JavaScript calls registered C++ callbacks with webFront.cppFunction(name)(...). This always returns a Promise, even for a void C++ callback, and the Promise rejects on failure, so an ignored Promise can cause an unhandled rejection.
  • C++ calls browser functions with ui.jsFunction(name)(arguments...), which is fire-and-forget and ignores the result, or with ui.jsFunction<R>(name)(arguments...), which returns a std::future<R>. Only the untyped C++ form is fire-and-forget.
  • webFront.ready resolves after the WebSocket handshake acknowledgement and rejects if the initial connection fails or closes.

WebFront also ships a standalone developer environment (NativeApp::bootstrap("developer")): a terminal whose wf commands (init, create, install, restore, run, exec, check, test, build, dev, preview, embed, list, why, info, help) manage a project manifest and lock, compile TS/TSX, type-check, run Jasmine specs and generate the application's embedded provider, with no JavaScript runtime or package manager on the developer's machine. It is not a sandbox. See docs/DEVELOPER_ENVIRONMENT.md.

The README introduces WebFront through the Game of Life walkthrough, demonstrating the developer bootstrap, reactive TypeScript UI and embedded distribution. The minimal HelloWorld example remains available under examples/hello-world/. Native modules and the bridge are covered by the Jasmine browser integration test. The optional ui.document() API provides per-connection DOM islands, batched writes, events (callbacks or awaitable node.next(name)) and grouped sender reads; see docs/DOM.md. The optional React store and Island adapter, including its support policy and coordinated unmount contract, is described in docs/REACT.md; examples/life/react/ demonstrates it. app.spaces(prefix, resolver) serves several independent users from one process, each WebFront::Space under prefix/<segment>/ with its own functions, handlers, broadcasts and routes (docs/SPACES.md). Application coroutines use webfront::Task and app.spawn(task)/ui.spawn(task); retain a TaskHandle to request individual cancellation. WebFront owns and drains these tasks. Spawn is callable from any thread while the application lives; a call rejected during shutdown returns a stopped handle. Destructors wait for outstanding operations; explicit shutdown reports a stalled join. Typed C++ sender calls support local cancellation; futures and JavaScript Promises do not expose cancellation.

Repository map

  • include/webfront/: public header-only library, included as <webfront/...>. WebFront.hpp is the main orchestration API; Commands.hpp adds an application's C++ commands to the developer environment's terminal.
  • include/webfront/components/react/: optional C++ snapshot stores coalesced per browser; the React adapter is installed separately with wf and documented in docs/REACT.md.
  • include/webfront/components/forms/: optional type descriptors (C++23), forms, inspectors and TypeScript declarations generated from them, and an optional C++26 reflection layer (Reflection.hpp, GCC 16 only) documented in docs/FORMS.md.
  • include/webfront/http/: HTTP and WebSocket protocol implementation.
  • include/webfront/weblink/: bridge message encoding and routing.
  • include/webfront/system/: layered virtual filesystems and the embedded web resources, a closed list guarded by the MinimalCoreAssets CTest case (normative list and 150 KiB decoded budget in ADR-016; changing it means amending the ADR and test/cmake/CheckMinimalCoreAssets.cmake together).
  • include/webfront/frontend/: system-browser, CEF, optional Windows WebView2 and macOS WKWebView frontend adapters.
  • examples/: the default build includes Hello World (hello-world/), the host loop (host-loop/: an application that keeps its own loop, app.start() or a host thread beside a native window; it ray-traces a Boing Ball on the CPU or with an optional CUDA unit, see docs/HOST_LOOP_EXAMPLE.md) and Game of Life (life/, with console, developer and embedded stages, plus the life/react/ variant with a C++ panel inside React). The standalone PTY example has its own CMake entry point.
  • js/core/: readable browser bridge, fallback and bootstrap loader compiled into include/webfront/, plus the embedding CMake modules; js/developer/: developer environment (its terminal and wf), the wf scripts that build it (scripts/), build and publication tools. The repository is itself a wf project (js/developer/webfront.project.json and its lock, selected with --manifest-dir js/developer): the environment builds itself, and its pure JavaScript specs (test/developer/) run with wf test. Production C++ remains header-only in include/webfront/.
  • js/developer/starters/: the sources of the app starter and agent-guide.md, the AGENTS.md that wf create puts beside a starter and that webfront_write_agent_guide() (cmake/WebFrontAgentGuide.cmake) writes in a consuming project.
  • js/services/: optional @webfront/services package, the browser side of the system services (ADR-020; a skeleton so far), built like @webfront/react by wf run services-package; outside the core's embedded resource list.
  • js/pty/: optional @webfront/pty adapter for native pseudoterminals. wf run pty-package assembles the archive used by the browser tests. See docs/PTY.md.
  • js/react/: optional @webfront/react package (createStore, useStore, Island), declarations and package-local license. wf run react-package assembles it; tests verify the exact archive installed by the registry. It is outside the core's embedded resource list.
  • test/fixtures/, test/web/fixtures/: retained regression fixtures, not public example applications.
  • test/unit/: C++ unit tests, written with include/webfront/testing/Bdd.hpp (a header-only BDD framework whose light core bdd/Core.hpp and optional parts bdd/Matchers.hpp, bdd/Approx.hpp, bdd/Eventually.hpp and bdd/Runner.hpp can be included separately, a public maintained interface with the WebFront::Bdd target and webfront_bdd_discover_tests, docs/BDD.md; cmake/WebFrontBdd*.cmake); test/web/: real-browser integration (suite/ is the WebFront project of the Jasmine specs, run by webtest through wf test); test/driver/: webfront-wf, the non-interactive wf driver for tests; test/fuzz/, test/fixtures/; test/cmake/: CMake test scripts and sub-projects. The RepositoryLayout CTest case pins the tracked root.
  • cmake/: build modules (frontends, CEF, CPM, compiler options) and public helpers such as webfront_embed_directory() (WebFrontEmbedDirectory.cmake, an interface directory embedded in pure CMake, docs/EMBEDDED_ASSETS.md); .github/: workflows, .github/CONTRIBUTING.md.
  • docs/: current reference guides, architecture decisions and docs/CHANGELOG.md.
  • docs/PROJECT_STATUS.md: current supported paths, validation scope and known limitations; completed work belongs in the changelog and Git history.
  • docs/adr/README.md: architecture decision index, Git history, tradeoffs and implementation rules; read the relevant ADRs before changing their contracts.
  • docs/DEVELOPING_WITH_AGENTS.md: what an agent developing a consuming application reads first (the model, the loop, each wf command in JSON and MCP); the README section, wf help agents, the starters' AGENTS.md and the AgentGuidance CTest case keep to it.
  • docs/WATCHES.md: the watches an application declares for the inspectors with app.watch (sources and their lock or executor, kinds rendered, writes, destruction of the handle, bounds); include/webfront/Watches.hpp, WatchMemory.hpp and WatchValues.hpp implement ADR-027 sections 3 to 6.
  • docs/DEVELOPER_ENVIRONMENT.md: the reference of the developer environment (wf commands, manifest and lock, TypeScript and wf check, tests, limits, distribution); docs/EMBEDDED_ASSETS.md: the core's embedded resources and their regeneration.

The historical webfront/ prototype and the former top-level webtest/ are gone: use test/unit/ for current C++ tests and test/web/ for browser tests. Do not revive legacy code without a specific issue and regression coverage.

Build and test commands

Use out-of-source builds. CPM downloads dependencies during first configure, so network access may be required.

# Newcomer quick start: no options, no CEF, no tests
mkdir build
cd build
cmake ..
cmake --build . --parallel 2
./examples/HelloWorld

# Fast, portable C++ baseline (no CEF download)
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \
  -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_ENABLE_TESTING=ON
cmake --build build --parallel
ctest --test-dir build --output-on-failure --parallel 4

# Run one unit-test scenario directly (`tests --help` lists the filters)
./build/test/unit/tests "Scenario: JsFunction"

# Linux real-browser integration test: configure downloads and verifies the pinned bootstrap environment and the packages
# of the local npm registry; the tests build the rest with wf
cmake -S . -B build-cef -DCMAKE_BUILD_TYPE=Release \
  -DWEBFRONT_EMBED_CEF=ON -DWEBFRONT_ENABLE_TESTING=ON
cmake --build build-cef --target webtest developer_integration webfront-wf --parallel
ctest --test-dir build-cef -L web-integration --output-on-failure --parallel 4

Build the developer environment with wf (the driver comes from any build with WEBFRONT_ENABLE_TESTING=ON), as js/developer/tools/PUBLISHING.md describes:

wf() { build/test/web/webfront-wf --project "$PWD" --manifest-dir js/developer -- "$@"; }
wf restore && wf run build build-distribution

On Linux, configuring tests with an enabled browser frontend requires xvfb-run, even if the subsequent CTest invocation selects only -L fast. Install Xvfb for the browser suite, or explicitly disable browser frontends (-DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_EMBED_WEBKITGTK=OFF) for a C++-only workflow. Missing Xvfb may skip only the optional Automation window tests; it must not silently remove the required Jasmine, developer journey or WfDriver coverage.

Important CMake options:

The headers of the embedded assets are generated, and checked by CTest, in pure CMake (js/core/EmbedAsset.cmake; the webfront-embedded-assets target regenerates them). Normal C++ builds consume the versioned headers. Configuring with WEBFRONT_ENABLE_TESTING=ON downloads the pinned bootstrap environment and the packages of the test registry, each verified against its SHA-512, tried three times and kept once per machine (WEBFRONT_DOWNLOAD_CACHE, by default in CPM's cache or the user's cache directory), so a new build tree links them instead of downloading them again; -DWEBFRONT_BOOTSTRAP_DIR and -DWEBFRONT_REGISTRY_DIR replace those downloads on a machine without network access.

  • WEBFRONT_EMBED_CEF=OFF (default): CEF is unavailable; this is the normal unit-test build. ON downloads/links CEF and enables the automated browser test; it makes CEFFrontend available but does not select it: webfront::WebFront always uses the system browser.

  • WEBFRONT_EMBED_WEBVIEW2=OFF (default): Windows-only opt-in SDK and static loader for WebView2Frontend; requires the separately installed Evergreen runtime. Select it explicitly with WebFrontWithFrontend<frontend::WebView2Frontend>. With tests enabled, WEBFRONT_WEBTEST_FRONTEND=WebView2 runs the shared Jasmine suite and lifecycle cases.

  • WEBFRONT_EMBED_WKWEBVIEW=OFF (default): macOS 13.3+ opt-in Cocoa/WebKit frontend, with no engine download. Select WebFrontWithFrontend<frontend::WKWebViewFrontend> on the main thread; WEBFRONT_WEBTEST_FRONTEND=WKWebView runs Jasmine and lifecycle coverage.

  • WEBFRONT_ENABLE_TESTING=ON (default OFF): build the C++ unit-test and Jasmine test targets. CI and contributor commands must pass it explicitly. The test, fuzzing, coverage and sanitizer options (WEBFRONT_ENABLE_SANITIZER_*) carry the WEBFRONT_ prefix so that a parent's own ENABLE_TESTING or ENABLE_SANITIZER_ADDRESS never builds or instruments WebFront's tests; the former unprefixed names no longer configure WebFront (cmake/WebFrontTestOptions.cmake documents the options).

  • WEBFRONT_BUILD_EXAMPLES (default ON only for the top-level project): build the examples. As a subproject (add_subdirectory), link WebFront::WebFront; no examples, tests or global compiler settings are added.

  • WEBFRONT_ENABLE_COVERAGE=ON: add GCC/Clang coverage instrumentation to the C++ tests.

  • The project has no CMake presets: the defaults are the quick local build (WEBFRONT_TEST_UNITY_BATCH=4, WEBFRONT_MSVC_ANALYZE=OFF, WEBFRONT_TEST_REPRODUCIBILITY=OFF) and every CI job passes these options explicitly (docs/TEST_TIERS.md).

If the environment provides a read-only default ccache directory, set CCACHE_DIR to a writable temporary directory for local builds. Do not encode machine-specific cache paths in project files. In CI, ENABLE_CACHE=OFF disables automatic cache discovery while CMAKE_CXX_COMPILER_LAUNCHER=sccache explicitly enables sccache; a PATH/version probe runs on all three platforms. The combined Linux job uses Debug with GCC coverage on every PR; Windows and macOS use Release. WebKitGTK defaults to development mode, with its sandbox disabled only while constructing the native view context; the environment is restored afterward. Distribution builds require the sandbox (WEBFRONT_DISTRIBUTION=ON or explicitly selected native UI targets). See docs/WEBKITGTK.md.

Architecture and invariants

BasicWF<NetProvider, Filesystem, Policy, Frontend> owns the HTTP server, connected WebLink objects, registered C++ callbacks, and server thread. BasicUI identifies one connected browser. onUIStarted sets the application's single handler for connected browsers; reusable code must use subscribeUIStarted, which adds a handler for as long as the returned UISubscription lives (the handle stays safe after the application is destroyed). A callback whose first parameter is the application's UI type receives the calling browser instead of reading it from the call data. A frontend must satisfy frontend::FrontendType and decides whether the server stops when open() returns.

The HTTP server connections and the WebSocket read/write loops are coroutines (networking::Task) awaiting the senders a network provider returns (Receive, Send, Accept; networking::TCPStdnet forwards them to stdnet). A stop request cancels them from any thread and they unwind on the io_context thread, so I/O objects are never closed from another thread. The server owns a counting_scope for HTTP, WebSocket and application tasks. shutdown() stops and joins owned work; call it outside server callbacks, after external run callers have returned. Whoever owns the objects the tasks use must run Server::drain() before destroying them (~BasicWF does): it closes, stops and joins the scope while pumping the context. Low-level WebSocket/WebLink users pass an external TaskScope& and drain it before releasing dependencies.

webfront::WebFront is default-constructible (WebFrontConfig: loopback address, port 9002, no document root) and show(page = "index.html") opens a page. show() keeps its calling thread; an application with its own loop uses start() (system browser, returns at once), requestClose() (ends show() from any thread) or webfront::UIThread (secondary thread, refused at compile time for main-thread frontends), as docs/HOST_INTEGRATION.md describes. Without a document root no local file access happens; WebFrontConfig::documentRoot serves local files for development only, after the embedded WebFront.js (which a root can never override) and before the embedded fallback page.

Filesystems implement open(std::filesystem::path) -> std::optional<fs::File> and are composed with fs::Multi<>; the first provider returning a file wins. NativeDebugFS is development-only and must not be presented as a production sandbox.

Bridge calls are asynchronous, and the two directions differ. webFront.cppFunction(name)(...) always returns a JavaScript Promise (also for void callbacks), so tests and examples must await or handle it. On the C++ side, only the untyped ui.jsFunction(name)(...) is fire-and-forget; ui.jsFunction<R>(name)(...) returns a std::future<R>. ui.jsFunctionSender<R>(name)(...) owns encoded arguments and dispatches at sender start; co_await propagates the receiver stop token. Cancellation completes stopped locally and discards a late reply; JavaScript continues running. See docs/ASYNC_EXECUTION.md for lifetime and completion-thread rules. On missing functions, callback exceptions, malformed returns, and disconnects, a C++ future completes exceptionally (get() throws) and a JavaScript Promise rejects. Result types are limited to the bridge's scalar, string, tuple, numeric typed-array, packed std::bitset<N> and list types. A list is a std::vector of strings, tuples, typed arrays or bitsets (JavaScript: webFront.list(items) of strings, typed arrays or tuples, received as an Array; numbers go as typed arrays; a plain short array is a tuple that a std::vector destination also accepts); elements are homogeneous and lists do not nest. Bitsets use Uint8Array with exactly ceil(N / 8) bytes, least-significant bit first in each byte, and zero high padding bits; decoding rejects wrong types, sizes and padding. JavaScript must know the logical bit count from the application contract. Strings of 65,536 bytes or more use the longString code (32-bit length), chosen by the encoder; the only bound is the buffers policy's maxMessageSize (64 MiB by default, JavaScript's maxMessageBytes): beyond it C++ throws std::length_error when it encodes, which rejects the Promise when it is a callback's result, and JavaScript throws a RangeError before sending. A cppFunction callback may return a sender (a webfront::ResultTask<R> coroutine): the Promise settles when it completes, the browser's disconnection stops it and drops its answer, and shutdown joins it. Callback signatures are deduced for ordinary lambdas, function pointers, and std::function; generic lambdas and overloaded call operators need explicit cppFunction<R, Args...>. Do not write tests or documentation that present JavaScript calls as fire-and-forget, imply an untyped C++ call returns a value, or suggest that richer objects cross the bridge (only the types above do). Registered callback objects must outlive their registration through owned storage; never capture a forwarding-reference parameter by reference in a stored handler. Names starting with webfront.inspector. are reserved to the inspectors (ADR-027). WebFront guards only its own reserved functions: an example or test callback that writes the project or what the server serves, starts a process or exposes a sensitive state takes the calling UI and checks ui.isLocalClient(), and documentation must not present the application's callbacks as guarded by WebFront.

The embedded WebFront.js wire format and C++ Messages.hpp implementation must evolve together. Any protocol change requires encoding/decoding unit tests and a real-browser regression test.

Exception: a purely C++ change that reuses an existing encoding, introduces no new wire type code and does not modify the binary wire format may leave the JavaScript codec and IndexFS.hpp unchanged. Encoding/decoding unit tests and a real-browser regression must still demonstrate compatibility with the existing JavaScript codec. See ADR-003.

Coding and testing conventions

  • Use C++23, four-space indentation, the .clang-format of the directory (include/webfront/, test/, examples/), and the naming rules in .github/CONTRIBUTING.md.
  • Every tracked C++ source starts with the normalized file header (SPDX, Author, Created, subsystem, Role, Thread, Alloc, LLM) described in .github/CONTRIBUTING.md; read it first, keep it true when you change the file, and give a new file one. The SourceHeaders CTest case checks it, and CI checks the format with .github/scripts/check-clang-format.sh (pinned clang-format); generated headers are exempt.
  • Keep production implementation header-only under include/; browser resources live in js/.
  • Prefer standard-library facilities and explicit ownership. Keep public headers ODR-safe (inline/templates as appropriate).
  • Unit tests are named const Scenario objects whose given/when/then sections are lambdas, checked with require/check, requireEqual/checkEqual (which report both operands) and approx for floating-point values (include/webfront/testing/Bdd.hpp), and use deterministic mocks.
  • Jasmine specs are the project test/web/suite/, built by esbuild-wasm and run by wf test under the locked jasmine-core (installed from the local registry by WebSuiteInstall); webtest is the webfront-wf driver plus the C++ callbacks of the specs. The specs tell C++ they are done (specsFinished), the process status is that of wf test (or 1 when C++ did not observe every call), and the CTest case has a timeout. The registry the suite installs from is built by wf run test-registry (the TestRegistry case), from the packages that configure downloaded.
  • Every bug fix needs a failing regression test at the lowest useful level. Bridge changes also need the browser integration test.
  • Tests must not require user input, a fixed pre-existing browser session, or public network access after dependencies are configured.

Tests are organized in three tiers selected by CTest labels (fast, standard, portability; see docs/TEST_TIERS.md). ctest -L fast is the quick check while working; a local run before declaring work complete runs everything. CI runs the fast tier first on each desktop job, the standard tier (everything but portability) on every pull request, and the advanced tier (three repetitions of the complete desktop suite, the portability job, sanitizers, fuzzers and the GCC/Clang CEF test) weekly and on every pull request into master, where those checks are required for the merge once marked required in the branch protection rules. A new test with no label belongs to the standard tier; label a test portability only if it verifies the library from another project or toolchain.

Before declaring work complete, run the CEF-off build and CTest suite. Run the CEF/Xvfb test when changing the bridge, browser lifecycle, module serving, Jasmine assets, or CEF frontend. These PRs, when they target develop, must also dispatch BuildAndTest.yml on the PR head branch before merging (gh workflow run BuildAndTest.yml --ref <pr-branch>), then wait for both GCC and Clang CEF jobs to pass; a PR into master runs this advanced tier on its own. Manual dispatch runs the extended CEF/sanitizer checks without repeating the desktop matrix by default. To also run the complete desktop CTest suite three times, resetting its fixtures on each pass, dispatch with -f repeat_desktop_tests=true. It is the required per-PR CEF validation for these changes; the weekly run is a backstop, not a substitute. Update README/status documentation when commands, public behavior, or limitations change. The NewcomerDocsMatchExamples CTest case fails when the README quick-start commands or snippets drift from the examples, CMake targets, or CI commands, and AddSubdirectoryConsumer builds a minimal parent project linking WebFront::WebFront.

Git and workspace safety

The workspace may contain user-owned untracked documents and large build directories. Never delete, move, format, stage, or overwrite unrelated files. In particular, names such as A_faire*, Texte*, calendar SVGs, data/, local batch files, and existing build* trees are not automatically project work.

Inspect git status --short before and after changes. Preserve overlapping user edits and use targeted patches. Never use destructive reset/checkout commands. Feature branches follow the issue-number convention and target develop; master is the release branch. GitHub issue changes require explicit user authorization and evidence from code/tests/history.

Never add AI-assistance attribution or advertising anywhere: not in commits, PR titles or descriptions, issue or PR comments, reviews, or documentation. This holds even when a tool, harness or template offers a "Generated by ..." footer or a session link; omit it, and strip it if a server appends it. Commits and pull requests must never contain AI-assistance attribution. Do not add Co-authored-by trailers for an AI tool, generated-by notices, bot attribution, or statements crediting Codex, Claude, Copilot, Vibe, or another assistant in commit messages, commit trailers, PR titles, or PR descriptions.

Definition of done

A change is done only when its intended behavior is demonstrated, relevant unit and integration tests pass, failure paths return nonzero or throw as documented, CI/build instructions match reality, public limitations are not overstated, and the final diff contains no unrelated workspace files.