Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ The README introduces WebFront through the Game of Life walkthrough, demonstrati
- `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/`: only 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).
- `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](docs/PTY.md) 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 `test/unit/Bdd.hpp` (a single-header BDD framework); `test/web/`: real-browser integration (`suite/` is the WebFront project of the Jasmine specs, run by `webtest` through `wf test`); `test/driver/`: `webfront-wf`, the non-interactive `wf` driver for tests; `test/fuzz/`, `test/fixtures/`; `test/cmake/`: CMake test scripts and sub-projects. The `RepositoryLayout` CTest case pins the tracked root.
Expand Down Expand Up @@ -116,7 +117,7 @@ Exception: a purely C++ change that reuses an existing encoding, introduces no n
## Coding and testing conventions

- Use C++23, four-space indentation, the `.clang-format` of the directory (`include/webfront/`, `test/`, `examples/`), and the naming rules in `.github/CONTRIBUTING.md`.
- Keep production implementation header-only under `include/`; `examples/` contains the three public examples; browser resources live in `js/`.
- Keep production implementation header-only under `include/`; browser resources live in `js/`.
- Prefer standard-library facilities and explicit ownership. Keep public headers ODR-safe (`inline`/templates as appropriate).
- Unit tests are named `const Scenario` objects whose `given`/`when`/`then` sections are lambdas, checked with `require`/`check` (`test/unit/Bdd.hpp`), and use deterministic mocks.
- 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.
Expand Down
1 change: 1 addition & 0 deletions README.fr.md
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ L'installation de CMake elle-même ne demande pas de droits root. Répétez l'ex
- Les appels JavaScript vers C++ renvoient toujours des Promises. En C++, `ui.jsFunction(name)(...)` est sans retour ; `ui.jsFunction<R>(name)(...)` renvoie un `std::future<R>`. Fonction absente, exception, réponse mal formée et déconnexion font échouer l'appel typé. Les futures et Promises n'exposent pas d'annulation ; les senders typés proposent une annulation locale.
- Le pont transporte scalaires, chaînes, tuples, tableaux numériques typés, bitsets et listes homogènes de valeurs composées prises en charge. Il ne transporte pas d'objets arbitraires. Chaînes et messages sont bornés par la politique de taille (64 Mio par défaut) ; à partir de 65 536 octets, les chaînes utilisent l'encodage long.
- L'environnement de développement et l'accès aux fichiers du projet sont destinés au code local de confiance, sans sandbox. Seuls les paquets compatibles navigateur sont pris en charge ; ni scripts d'installation ni extensions natives ne sont exécutés. `wf check` vérifie les types séparément de la compilation.
- Le [pseudo-terminal natif](docs/PTY.md) relie un programme choisi par l’application à xterm.js sous Linux, macOS et Windows, après activation explicite.
- L'adaptateur optionnel [`@webfront/react`](docs/REACT.md) apporte stores C++ avec regroupement des mises à jour et îlots React. `WebFrontLifeReact` montre un panneau C++ dans React ; son archive est préparée localement pour publication au registre.
- Linux embarqué dispose d'une CI ARM64 et de preuves sur Orin Nano. Les autres cartes, cibles sans OS et microcontrôleurs ne sont pas qualifiés globalement. Le transport local ne fournit ni TLS ni authentification client ; un accès distant demande une conception de sécurité propre à l'application.
- Packaging, accessibilité et déploiement des moteurs natifs restent propres au produit. L'[état du projet](docs/PROJECT_STATUS.md) fait référence pour les validations et limites ; l'[historique](docs/CHANGELOG.md) décrit les migrations et ruptures de compatibilité.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ CI exercises C++ and native-browser paths on Windows, macOS and Linux. Extended
- JavaScript calls to C++ always return Promises. C++ `ui.jsFunction(name)(...)` is fire-and-forget; `ui.jsFunction<R>(name)(...)` returns `std::future<R>`. Missing functions, exceptions, malformed replies and disconnects fail the typed call.
- The binary bridge supports scalars, strings, tuples, numeric typed arrays, packed bitsets and homogeneous lists of supported compound values. Arbitrary objects do not cross it. Strings and messages are bounded by the message-size policy (64 MiB by default); strings of 65,536 bytes or more use the long-string encoding. See [the bridge contract](docs/adr/ADR-003-protocole-binaire-et-bornes.md).
- Development project access is explicit and intended for trusted local code. Downloaded tools run with the application's bridge authority, and script permissions frame only the `context` API: neither is a sandbox. Only packages that run in a browser are supported; installation scripts and native add-ons are not executed. Builds transform TypeScript without type checking; `wf check` type-checks with the compiler the project locks.
- An opt-in [native pseudoterminal](docs/PTY.md) connects an application-selected program to xterm.js on Linux, macOS and Windows.
- The optional [`@webfront/react` adapter](docs/REACT.md) supplies coalesced C++ stores and empty React islands. `WebFrontLifeReact` demonstrates a C++ panel within the Game of Life React UI; its package archive is prepared locally for registry publication.
- Embedded Linux has ARM64 CI coverage and specific Orin Nano board evidence; other boards, bare-metal targets and microcontrollers are not generally qualified. Check C++23, memory, networking and browser requirements for your target. The default local transport supplies neither TLS nor client authentication; remote deployment needs an application-specific security design.
- Packaging, accessibility and native-engine deployment still need application-specific work. The optional [`ui.document()` API](docs/DOM.md) provides DOM islands, automatically batched writes, event callbacks and grouped sender reads. See [project status](docs/PROJECT_STATUS.md) for known limitations.
Expand Down
1 change: 1 addition & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ these entries stays in the GitHub releases and the Git history.
## Unreleased

### Added
- Run application-selected programs in a native pseudoterminal with an optional xterm.js page adapter and replay across reloads (#613, `docs/PTY.md`).
- Skip GStreamer's initialization, and its plugin scan, in WebKitGTK for an application whose pages never use audio or video, with `WindowOptions::media = false`; the default keeps media (#611, `docs/WEBKITGTK.md`).
- WKWebView supports `WindowOptions::background`, translucent colours included, and `WEBFRONT_STARTUP_TRACE=1` (#611, `docs/WKWEBVIEW.md`).
- WebView2 supports `WindowOptions::background` and `WEBFRONT_STARTUP_TRACE=1` (#611, `docs/WEBVIEW2.md`).
Expand Down
3 changes: 2 additions & 1 deletion docs/PROJECT_STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer
system browser, `app.requestClose()` from another thread, or `webfront::UIThread` where the frontend
accepts a secondary thread (WebView2); a host loop cannot share the main thread with an embedded
window. See [host integration](HOST_INTEGRATION.md).
- **Native pseudoterminals (opt-in).** `webfront::Pty` uses a Unix PTY on Linux and macOS or ConPTY on Windows 10 version 1809 and later. The page adapter requires a loopback bind and the application’s own browser origin. See the [PTY guide and standalone example](PTY.md).
- **Developer environment.** `NativeApp::bootstrap("developer")` loads the verified, pinned
environment selected by `DeveloperReleaseData.hpp`. Its terminal provides `wf init`, `create`,
`install`, `restore`, `run`, `exec`, `check`, `test`, `build`, `dev`, `preview`, `embed`, `list`, `why`, `info` and `help`, beside the terminal's own read-only `ls`, `cat`, `tree` and `mounts` (ADR-023). The manifest and lock describe
Expand All @@ -40,7 +41,7 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer
Native-engine deployment remains application work. The [README walkthrough](../README.md)
covers the console, developer and embedded Game of Life stages; Hello World and the host loop
(`examples/host-loop/`, a Boing Ball ray-traced by the host on the CPU or with optional CUDA; see
[the host-loop example](HOST_LOOP_EXAMPLE.md) for its measurements and limits) are the other public examples.
[the host-loop example](HOST_LOOP_EXAMPLE.md) for its measurements and limits) are also in the default build.
- **Developer automation (opt-in).** `webfront-agent` provides local stdio MCP and a JSON CLI
for an explicitly launched developer window. Native grants select check/build/test/preview,
bounded inspection and semantic actions. [Automation](AUTOMATION.md) documents provisioning,
Expand Down
46 changes: 46 additions & 0 deletions docs/PTY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Native pseudoterminals

Include `<webfront/Pty.hpp>` to run a program in a native terminal from C++. The child receives the requested argument vector, working directory, environment and initial terminal dimensions. Linux and macOS use a Unix PTY. Windows uses ConPTY, available since Windows 10 version 1809 and Windows Server 2019. [Microsoft's ConPTY documentation](https://learn.microsoft.com/en-us/windows/console/creating-a-pseudoconsole-session)

```cpp
webfront::Pty terminal({
.argv = {"sh", "-i"},
.directory = "/path/to/project",
.environment = {{"PATH", "/usr/bin:/bin"}},
.size = {100, 32}
});
```

Use UTF-8 strings for arguments and environment entries. The environment comes from `PtyOptions::environment`, with defaults for `TERM` (`xterm-256color`), `COLORTERM` (`truecolor`) and Windows `SystemRoot`. Supply any other variables the program needs, such as `HOME`, `USERPROFILE` or `PATH`. Relative paths are resolved against the child's directory. Bare executable names are searched in the supplied `PATH` or, when it is absent, in `/usr/bin:/bin` on Unix and the system directory on Windows. Windows also resolves `.cmd` and `.bat` shims and runs them through the system `cmd.exe`. Paths and arguments passed to batch scripts must omit double quotes, percent signs and line breaks.

- `write(bytes)` queues a whole chunk if there is room. It returns `false` immediately when the 64 KiB queue is full, the chunk exceeds capacity or the terminal is closing.
- `read(cursor, stopToken)` waits for data, exit, cancellation or hangup. `tryRead(cursor)` takes a snapshot without waiting for terminal I/O. Start at cursor zero and use the returned `next` for the following read. Each snapshot contains at most 16 KiB. `truncated` means the cursor fell behind the latest 1 MiB of retained output. The final snapshot carries the exit code.
- `resize({columns, rows})` schedules a resize on the terminal worker. Consecutive requests may be coalesced.
- `hangUp()` wakes readers and requests cleanup. `exitCode()` becomes available after cleanup. Destruction joins the worker. On Unix, cleanup signals the child and the foreground process group with SIGHUP and then escalates to SIGKILL. The host must leave the PTY child available for WebFront to reap. Cleanup also looks for remaining processes in the same session, including after the session leader exits. A process that creates a separate session may outlive it. On Linux with pidfds, cleanup uses a stable reference when signalling a member of a secondary group. Other Unix configurations check session and process group membership immediately before signalling by PID. On Windows, a job object terminates the entire process tree and ConPTY is closed. Ctrl+C follows the child console mode and the Windows control-handler policy. If the host was launched with Ctrl+C ignored, a child can inherit that setting. The example enables normal processing for its own process with `SetConsoleCtrlHandler(nullptr, FALSE)` before launch.

After natural exit, the worker drains terminal output to EOF or until a three-second deadline when another process holds the terminal open. Unix waits on the terminal and a wake pipe, with a 250 ms backstop for child exit. Windows checks its output pipe every 40 ms while idle and every 10 ms when input is pending or final output is draining. ConPTY keeps accepting output from descendants until its job empties or the drainage deadline expires. The launch pipe closes on exec. On Unix, coordinate host forks that retain inherited descriptors with PTY startup. A concurrent child that keeps the writer open can cause the PTY launch to fail at the ten-second startup deadline.

## Connect a browser page

Set `WebFrontConfig::allowPtyPages = true` and call `webfront::registerPtyPage(app, options)` from `<webfront/PtyPage.hpp>` before starting the server. Use a literal IPv4 loopback address or `::1` and set `contentPolicy.allowMissingOrigin = false`. Leave `allowAnyBridgeOrigin` disabled and `bridgeAllowedOrigins` empty. WebFront rejects incompatible configurations before binding. The application configures the executable, directory and environment. A dedicated worker starts the native process, so its startup wait leaves the server available. A page can open the configured session, send terminal input, resize, read output or hang up.

Every page of that origin shares access to the registered terminal. Serve trusted content and keep the loopback port private to the local application. A local native client can supply its own `Origin` header, and forwarding the port can extend access beyond the local machine. The terminal runs with the host application's privileges.

Bundle [the adapter](../js/pty/index.mjs) from the `@webfront/pty` package with your page and call `mount(element, {terminal, fit})` with your xterm.js `Terminal` and `FitAddon`. The adapter writes byte chunks to xterm so UTF-8 sequences can span reads. It forwards input and resizes the PTY when the container changes size. `onError` reports a rejected input or bridge failure, `onExit` receives the process status and `onTruncated` reports when some history has expired. The adapter rejects paste events that exceed the 64 KiB browser input queue, measured in UTF-8 bytes and reduced by pending input. If the native queue fills, the adapter reports the rejection and discards unsent input. The child may already have received earlier chunks.

Each registration owns one session, opened on first attach and retained across page reloads, including after the child exits. Pass `restart: true` to `mount` to start a fresh session after the old process has finished. The old replay is discarded and pending calls for the old session are refused. A different callback name selects another application-configured session. Call `dispose()` when unmounting the adapter to stop its output requests and listeners. Call `hangUp()` to close the process. Application shutdown also closes the process. The adapter keeps one output request pending, for up to one second while idle. The server checks for output every 40 ms during that wait, in addition to the native worker and bridge latency. Reattachment replays the retained bytes, so after truncation a full-screen program may need to redraw.

Prepare a publishable `@webfront/pty` archive with `wf run pty-package` from the repository developer project. The example below uses the same adapter source directly.

## Run the example

The [standalone example](../examples/pty/) opens the system shell in the application's working directory. Run the following commands from the repository root in a POSIX shell with the WebFront developer environment available for the `wf` commands.

```sh
cmake -S examples/pty -B build-pty-example -DWEBFRONT_AUTODETECT_NATIVE=OFF
cmake --build build-pty-example
(cd build-pty-example/page && wf restore && wf build)
./build-pty-example/WebFrontPtyExample build-pty-example/page/.webfront/developer/build
```

CMake stages the browser sources, pinned packages and adapter in `build-pty-example/page`. On Windows, pass the same build output directory to `WebFrontPtyExample.exe` in the chosen CMake configuration's output directory.
3 changes: 2 additions & 1 deletion docs/adr/ADR-010-composants-et-outils-optionnels.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ personnalisés des services ([ADR-020](ADR-020-services-systeme.md)) s'y ajouter
`wf run services-package` écrivent une archive déterministe (`js/developer/scripts/package-archive.mjs`) et son
SHA-512 ; le registre de test sert ces mêmes octets, et la suite installe puis importe l'archive. Aucun de ces
paquets n'entre dans les ressources du cœur (`MinimalCoreAssets` inchangé) ; la publication reste une action de
mainteneur distincte.
mainteneur distincte. `@webfront/pty` (#613) suit le même modèle avec `wf run pty-package`.
Son adaptateur reçoit les instances de xterm.js et de FitAddon de l’application.

## Prescriptions d’implémentation et de génération de code

Expand Down
1 change: 1 addition & 0 deletions examples/pty/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/terminal.mjs
Loading
Loading