From 91049abe601dceda19943f70e66d5ec5e30be517 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 2 Nov 2026 15:33:46 +0100 Subject: [PATCH 01/18] Make and downloads work in the embedded frontends (#451) WebKitGTK saves downloads to the user's download folder and answers the file chooser through an injection point; WKWebView implements the open panel and WKDownload; CEF gets the same injection points. A blob: URL of an admitted origin now passes the navigation policy. Scenarios capture their final state and CI assembles a per-platform qualification report. --- .github/workflows/BuildAndTest.yml | 54 ++++++ cmake/WebKitGTKSupport.cmake | 2 +- docs/CHANGELOG.md | 7 + docs/FRONTENDS.md | 28 +++ docs/adr/ADR-020-services-systeme.md | 4 + include/webfront/ContentPolicy.hpp | 18 ++ include/webfront/frontend/CEF.hpp | 55 +++++- include/webfront/frontend/Downloads.hpp | 26 +++ include/webfront/frontend/WKWebView.hpp | 142 ++++++++++++++- include/webfront/frontend/WebKitGTK.hpp | 115 ++++++++++++ include/webfront/frontend/WebKitGTKPolicy.hpp | 2 +- test/tools/Qualification.py | 158 ++++++++++++++++ test/unit/ContentPolicyTests.cpp | 8 + test/web/CEFFileServices.cpp | 169 ++++++++++++++++++ test/web/CMakeLists.txt | 16 ++ test/web/QualificationEvidence.hpp | 46 +++++ test/web/WebKitGTKLifecycle.cpp | 159 +++++++++++++++- test/web/file-services.html | 30 ++++ .../jasmine-consumer/file-services.spec.js | 55 ++++++ 19 files changed, 1089 insertions(+), 5 deletions(-) create mode 100644 include/webfront/frontend/Downloads.hpp create mode 100644 test/tools/Qualification.py create mode 100644 test/web/CEFFileServices.cpp create mode 100644 test/web/QualificationEvidence.hpp create mode 100644 test/web/file-services.html create mode 100644 test/web/jasmine-consumer/file-services.spec.js diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index 73981f0b..a9276b3b 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -181,6 +181,10 @@ jobs: Write-Host "WebView2 runtime $version at $($executable.FullName)" } # The fast tier (docs/TEST_TIERS.md): unit tests only, so a plain regression is reported before the browser suite starts. + # The file-service scenarios write their captures here (#451); see test/tools/Qualification.py. + - name: Choose the qualification evidence folder + shell: bash + run: echo "WEBFRONT_QUALIFICATION_DIR=$GITHUB_WORKSPACE/qualification-evidence" >> "$GITHUB_ENV" - name: Fast tests shell: bash run: ctest --test-dir build -C ${{ matrix.build_type }} -L fast --parallel 4 --output-on-failure --no-tests=error @@ -196,6 +200,17 @@ jobs: -DREPEAT=${{ (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master') || (github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests)) && '3' || '1' }} -DLABEL_EXCLUDE=${{ (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master') || (github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests)) && 'none' || 'portability' }} -P test/cmake/RunTestSuite.cmake + - name: Collect the qualification evidence + if: always() + shell: bash + run: python3 test/tools/Qualification.py collect --build build --evidence qualification-evidence --platform ${{ matrix.platform }} --output qualification/${{ matrix.platform }} + - name: Retain the qualification evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: qualification-${{ matrix.platform }} + path: qualification/${{ matrix.platform }}/ + if-no-files-found: ignore - name: Analyze CTest timings if: always() shell: bash @@ -496,6 +511,8 @@ jobs: sudo ip6tables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT sudo ip6tables -A OUTPUT ! -o lo -j REJECT - name: Run Jasmine bridge test + env: + WEBFRONT_QUALIFICATION_DIR: ${{ github.workspace }}/qualification-evidence run: >- ctest --test-dir ${{github.workspace}}/build-cef -L web-integration --output-on-failure --no-tests=error --parallel 4 --output-junit "${{ github.workspace }}/build-cef/test-results.xml" @@ -504,6 +521,16 @@ jobs: run: | sudo iptables -F OUTPUT sudo ip6tables -F OUTPUT + - name: Collect the qualification evidence + if: always() + run: python3 test/tools/Qualification.py collect --build build-cef --evidence qualification-evidence --platform linux-cef-${{ matrix.compiler }} --output qualification/linux-cef-${{ matrix.compiler }} + - name: Retain the qualification evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: qualification-linux-cef-${{ matrix.compiler }} + path: qualification/linux-cef-${{ matrix.compiler }}/ + if-no-files-found: ignore - name: Compiler cache statistics if: always() shell: bash @@ -517,3 +544,30 @@ jobs: build-cef/test-results.xml build-cef/Testing/Temporary/LastTest.log if-no-files-found: ignore + + # One document for every platform, built from the captures the jobs above retained (#451). It runs even when a job failed: + # a failing or missing platform is then written into the report instead of being left out. + qualification-report: + needs: [desktop, desktop-native, web-integration] + if: ${{ !cancelled() }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + - uses: actions/download-artifact@v4 + with: + pattern: qualification-* + path: qualification-input + - name: Assemble the qualification document + shell: bash + run: | + # Each artifact holds one platform's folder; give it that platform's name. + for directory in qualification-input/qualification-*; do + [ -d "$directory" ] && mv "$directory" "qualification-input/${directory#qualification-input/qualification-}" + done + python3 test/tools/Qualification.py report --input qualification-input --output qualification-report/QUALIFICATION.md + cat qualification-report/QUALIFICATION.md >> "$GITHUB_STEP_SUMMARY" + - uses: actions/upload-artifact@v4 + with: + name: qualification-report + path: qualification-report/ diff --git a/cmake/WebKitGTKSupport.cmake b/cmake/WebKitGTKSupport.cmake index 0d0d7385..c73c604c 100644 --- a/cmake/WebKitGTKSupport.cmake +++ b/cmake/WebKitGTKSupport.cmake @@ -25,7 +25,7 @@ function(webfront_add_webkitgtk_tests) target_link_libraries(webkitgtk_lifecycle PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) add_dependencies(webtest webkitgtk_lifecycle) webfront_find_xvfb(display_runner) - foreach(mode no-display worker-thread native-close repeated-show http-error pre-run-failure profile-permissions window-title) + foreach(mode no-display worker-thread native-close repeated-show http-error pre-run-failure profile-permissions window-title download choose-file cancel-choose) if(mode MATCHES "^(no-display|worker-thread|pre-run-failure|profile-permissions)$") add_test(NAME WebKitGTKAdapter-${mode} COMMAND webkitgtk_lifecycle ${mode}) elseif(display_runner) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 44cb6d35..13641d83 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- Embedded frontends: `` and downloads (#451, ADR-020 rule 6). WebKitGTK saves downloads to the user's + download folder (name reduced to its last component, never overwritten); WKWebView gets `runOpenPanelWithParameters` and + `WKDownload` (not yet run on a Mac); CEF and WebView2 use the engine's own handling. A `blob:` URL of an admitted origin + now passes the navigation policy, so a generated Blob can be downloaded. Test injection points answer the chooser and the + download without a dialog; CI builds a per-platform qualification report with window captures + (`test/tools/Qualification.py`, `docs/FRONTENDS.md`). + - Developer environment: the distribution is served from `https://dist.webfront.fr/` (#478, ADR-021). The sources advance to 0.6.5, the first version published under that address; `site.mjs` writes the `CNAME` file of the Pages branch and `wf run pin` checks the pinned archive where it is served now. Libraries and environments up to 0.6.4 pin the former diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 718e1135..77a3e550 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -45,6 +45,34 @@ startup failures before any window is created. Coordination waits have a 30-seco `test/unit/WebFrontTests.cpp` also checks initialization once per frontend type, retry after failed initialization, frontend selection and unavailable-engine diagnostics. These tests need no GUI. +## File chooser and downloads + +`` (single, multiple, `accept`, `webkitdirectory`) and downloads (``, generated `blob:` URLs) +work in every embedded frontend with the engine's own dialog, without a WebFront API (ADR-020, rule 6). A `blob:` URL of an +admitted origin passes the navigation policy (`webfront::detail::blobOriginUrl`); a `blob:` URL of any other origin does not. + +| Frontend | Chooser | Download | Test injection | +| --- | --- | --- | --- | +| WebKitGTK | default `run-file-chooser` dialog (portal under Flatpak) | `download-started` / `decide-destination`: the user's XDG download folder, the page's name reduced to its last component, never overwriting (`name (1).ext`) | `Session::chooseFiles`, `downloadDirectory`, `downloadFinished` | +| CEF (Chrome runtime) | the runtime's dialog | the runtime's download handling | `SimpleCEFClient::chooseFiles` (`CefDialogHandler::OnFileDialog`), `downloadDirectory`, `downloadFinished`. The runtime itself turns a suggested name `../x` into `_x` | +| WKWebView | `runOpenPanelWithParameters` shows an `NSOpenPanel` sheet of the window; only frames admitted by the policy | `WKDownload` (macOS 11.3+): a save panel proposes the name | `WKWebViewOptions::chooseFiles`, `downloadDirectory`, `downloadFinished` | +| WebView2 | the engine's native chooser | the engine's native download UI | none yet | + +WKWebView is written but has not been run on a Mac by its author: the qualification report below is the first check. The +engines require a user gesture to open a chooser, so the native scenarios click with a real pointer event (XTest under +Xvfb for WebKitGTK) or a `Runtime.evaluate` with `userGesture` (CEF). + +### Qualification report + +`ConsumerJasmine-file-services` (all engines) checks that files reach the page as `File` objects, that `accept` and +`webkitdirectory` are honoured, and that offering a generated Blob leaves the page and the bridge working. +`WebKitGTKAdapter-download|choose-file|cancel-choose` and `CEFFileServices-download|choose|cancel` drive the dialog and +the download through the injection points. Every scenario captures its final state with WebFront's own window capture +(`QualificationEvidence.hpp`, `ConsumerJasmine` captures). In CI each platform job retains a `qualification-` +artifact (`test/tools/Qualification.py collect`) and the `qualification-report` job assembles them into +`QUALIFICATION.md` with the images, for Linux (WebKitGTK; CEF on pull requests into `master` and on the weekly run), +Windows (WebView2) and macOS (WKWebView). A platform that did not report is written as missing. + ## Adding a frontend 1. Implement the type in `include/webfront/frontend/` following the contract above and include it from `Frontend.hpp`. Keep platform headers behind the option's macro. diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 745ebcd3..125a6d5d 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -352,6 +352,10 @@ Le code vérifié le 2026-10-31 ne permet pas encore d'implémenter ces règles. | 4 | [#449](https://github.com/ambroise-leclerc/WebFront/issues/449) Stockage modifiable et livraison des services | [#460](https://github.com/ambroise-leclerc/WebFront/issues/460) stockage sous racines déclarées, confiné pendant la résolution (révision de l'ADR-002) ; [#461](https://github.com/ambroise-leclerc/WebFront/issues/461) paquet `@webfront/services` | sélecteur HTML et écritures (règles 2 à 4) | | 5 | [#450](https://github.com/ambroise-leclerc/WebFront/issues/450) Intégration native des frontends | [#462](https://github.com/ambroise-leclerc/WebFront/issues/462) exécuteur du thread d'interface, y compris le navigateur système ; [#463](https://github.com/ambroise-leclerc/WebFront/issues/463) fenêtre native et correspondance avec les connexions | backend natif seulement | +État de l'étape 1 (#451) : sélecteur et téléchargements qualifiés sous WebKitGTK et CEF (Linux), implémentés sous +WKWebView, laissés au comportement natif sous WebView2 ; le rapport de qualification de la CI (`docs/FRONTENDS.md`) documente +chaque moteur. #452 reste à faire. + Après l'étape 4, le premier service (sélecteur HTML, poignées, import et export côté client) fera l'objet de sa propre épique ; les dialogues natifs suivront l'étape 5. `PUT`/`POST` ne sont pas des préalables : les écritures passent par des tableaux typés en morceaux ; leur ajout au serveur, utile aux très gros envois en flux et aux formulaires sans diff --git a/include/webfront/ContentPolicy.hpp b/include/webfront/ContentPolicy.hpp index c9822843..edf263c2 100644 --- a/include/webfront/ContentPolicy.hpp +++ b/include/webfront/ContentPolicy.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -130,6 +131,21 @@ inline std::optional contentOrigin(std::string_view url, bool origi return serializedContentOrigin(parts->scheme, authority->host, *port, defaultPort); } +/** + * @brief The URL a `blob:` URL was minted for (`blob:http://host:port/id` gives `http://host:port/id`), or empty. + * + * A page downloads a generated `Blob` by navigating to such a URL; its content always belongs to the page's own origin, + * so the origin it names is the one the navigation policy must judge. + */ +inline std::string_view blobOriginUrl(std::string_view url) { + constexpr std::string_view scheme = "blob:"; + if (url.size() <= scheme.size() || !std::ranges::equal(url.substr(0, scheme.size()), scheme, [](char a, char b) { + return std::tolower(static_cast(a)) == b; + })) + return {}; + return url.substr(scheme.size()); +} + /** @brief Validated snapshot shared by the HTTP and embedded-frontend policy hooks. */ class BoundContentPolicy { public: @@ -147,6 +163,8 @@ class BoundContentPolicy { } bool allowsNavigation(std::string_view url) const { + if (const auto inner = blobOriginUrl(url); !inner.empty()) + url = inner; // A Blob of an admitted origin (a generated download) is that origin's own content. const auto origin = contentOrigin(url); return origin && (policy.allowAnyNavigation || *origin == applicationOrigin || contains(policy.navigationAllowedOrigins, *origin)); } diff --git a/include/webfront/frontend/CEF.hpp b/include/webfront/frontend/CEF.hpp index ad5f4ed0..817843e7 100644 --- a/include/webfront/frontend/CEF.hpp +++ b/include/webfront/frontend/CEF.hpp @@ -6,12 +6,14 @@ #include "CEFPaths.hpp" #include "Capture.hpp" #include "DefaultBrowser.hpp" +#include "Downloads.hpp" #include "Url.hpp" #include "Window.hpp" #include #include #include +#include #include #include #include @@ -493,7 +495,9 @@ class SimpleCEFClient : public CefClient, public CefLoadHandler, public CefRequestHandler, public CefContextMenuHandler, - public CefCommandHandler { + public CefCommandHandler, + public CefDownloadHandler, + public CefDialogHandler { public: explicit SimpleCEFClient(webfront::detail::BoundContentPolicy policy = webfront::detail::BoundContentPolicy{}, browser::Launcher launch = browser::launch) : contentPolicy(std::move(policy)), popupLauncher(launch) { } @@ -512,6 +516,55 @@ class SimpleCEFClient : public CefClient, return this; } + /// The Chrome runtime already shows its own file dialog and saves downloads; these two hooks only exist for tests. + /// Test injection: answers without a dialog (an empty list cancels). Unset keeps the engine's dialog. + std::function()> chooseFiles; + /// Test injection: a non-empty folder receives downloads without a "save as" dialog. + std::filesystem::path downloadDirectory; + /// Test injection: called with the full path of each completed download. + std::function downloadFinished; + + CefRefPtr GetDownloadHandler() override { + return this; + } + CefRefPtr GetDialogHandler() override { + return this; + } + bool OnFileDialog(CefRefPtr, + FileDialogMode, + const CefString&, + const CefString&, + const std::vector&, + const std::vector&, + const std::vector&, + CefRefPtr callback) override { + if (!chooseFiles) + return false; + std::vector files; + try { + for (const auto& file : chooseFiles()) + files.emplace_back(file); + } catch (...) { + files.clear(); + } + if (files.empty()) + callback->Cancel(); + else + callback->Continue(files); + return true; + } + bool OnBeforeDownload(CefRefPtr, CefRefPtr, const CefString& suggested, CefRefPtr callback) override { + if (downloadDirectory.empty()) + return false; + const auto result = frontend::detail::uniqueDownloadPath(downloadDirectory, suggested.ToString()); + callback->Continue(result.string(), false); + return true; + } + void OnDownloadUpdated(CefRefPtr, CefRefPtr item, CefRefPtr) override { + if (item->IsComplete() && downloadFinished) + downloadFinished(item->GetFullPath().ToString()); + } + bool OnBeforeBrowse(CefRefPtr, CefRefPtr frame, CefRefPtr request, bool, bool) override { // Frame navigations and subresources remain outside this top-level navigation policy. return frame->IsMain() && !contentPolicy.allowsNavigation(request->GetURL().ToString()); diff --git a/include/webfront/frontend/Downloads.hpp b/include/webfront/frontend/Downloads.hpp new file mode 100644 index 00000000..156c6bf1 --- /dev/null +++ b/include/webfront/frontend/Downloads.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include + +namespace webfront::frontend::detail { + +/** + * @brief A path in `folder` that does not exist yet, for a download whose name the page suggested. + * + * Only the final component of the suggested name is kept (a page can neither choose a folder nor climb out of it), an + * empty name becomes "download", and an existing file is kept: "name", then "name (1).ext", "name (2).ext", and so on. + */ +inline std::filesystem::path uniqueDownloadPath(const std::filesystem::path& folder, std::string_view suggested) { + auto name = std::filesystem::path(std::string(suggested)).filename(); + if (name.empty() || name == "." || name == "..") + name = "download"; + auto result = folder / name; + std::error_code error; + for (int index = 1; std::filesystem::exists(result, error) && index < 10'000; ++index) + result = folder / (name.stem().string() + " (" + std::to_string(index) + ")" + name.extension().string()); + return result; +} + +} // namespace webfront::frontend::detail diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index ba822366..cb489f4d 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -3,14 +3,20 @@ #include "../ContentPolicy.hpp" #include "Action.hpp" #include "Capture.hpp" +#include "Downloads.hpp" #include "Url.hpp" #include "Window.hpp" #include #include #include +#include +#include +#include #include +#include #include +#include #include namespace webfront::frontend { @@ -23,6 +29,12 @@ struct WKWebViewOptions { WindowOptions window{}; /** @brief Keep the native window hidden and avoid activating the application. A WindowServer is still required. */ bool visible{true}; + /** @brief Test injection: answers `` without a dialog (an empty list cancels). Unset shows the system panel. */ + std::function()> chooseFiles{}; + /** @brief Test injection: a non-empty folder receives downloads without a save panel. */ + std::filesystem::path downloadDirectory{}; + /** @brief Test injection: called with the destination of each finished download. */ + std::function downloadFinished{}; }; } // namespace webfront::frontend @@ -277,6 +289,7 @@ struct Session { WKWebViewOptions options; webfront::detail::BoundContentPolicy contentPolicy; std::function navigationCancelled; + std::map downloadDestinations; // WKDownload -> destination, until it finishes. id app = nullptr, window = nullptr, view = nullptr, delegate = nullptr, timer = nullptr; id previousDelegate = nullptr, previousMenu = nullptr; long previousActivationPolicy = 0; @@ -499,12 +512,93 @@ struct Session { const auto destination = utf8(send(send(send(action, "request"), "URL"), "absoluteString")); if (contentPolicy.allowsNavigation(destination)) { policy = 1; // WKNavigationActionPolicyAllow + // and generated Blobs: WKNavigationActionPolicyDownload (macOS 11.3). + if (send(action, "respondsToSelector:", sel_registerName("shouldPerformDownload")) && send(action, "shouldPerformDownload")) + policy = 2; } else rejectNavigation("initial navigation was denied by contentPolicy"); }); decision(policy); // Exactly once, including after a C++ exception. } + /// : the system panel as a sheet of the window, or the test injection. The handler runs exactly once. + void chooseFilesForPage(id parameters, id frame, void (^completion)(id)) noexcept { + id result = nullptr; // NSArray*; nil cancels. + bool deferred = false; + guard([&] { + // Only the frames the policy admits may open a chooser. + if (!contentPolicy.allowsNavigation(utf8(send(send(send(frame, "request"), "URL"), "absoluteString")))) + return; + if (options.chooseFiles) { + const auto files = options.chooseFiles(); + if (files.empty()) + return; + const auto urls = send(type("NSMutableArray"), "array"); + for (const auto& file : files) { + Object path(text(file)); + send(urls, "addObject:", send(type("NSURL"), "fileURLWithPath:", path.get())); + } + result = urls; + return; + } + const auto panel = send(type("NSOpenPanel"), "openPanel"); + send(panel, "setAllowsMultipleSelection:", send(parameters, "allowsMultipleSelection")); + send(panel, "setCanChooseDirectories:", send(parameters, "allowsDirectories")); + send(panel, "setCanChooseFiles:", static_cast(true)); + auto handler = Block_copy(completion); + void (^finished)(long) = ^(long response) { + handler(response == 1 ? send(panel, "URLs") : nullptr); // NSModalResponseOK + Block_release(handler); + }; + deferred = true; + send(panel, "beginSheetModalForWindow:completionHandler:", window, finished); + }); + if (!deferred) + completion(result); + } + + /// A WKDownload needs a destination that does not exist: the test folder, or the user's choice in a save panel. + void chooseDownloadDestination(id download, const std::string& suggested, void (^completion)(id)) noexcept { + id result = nullptr; // NSURL*; nil cancels the download. + bool deferred = false; + guard([&] { + if (!options.downloadDirectory.empty()) { + const auto destination = frontend::detail::uniqueDownloadPath(options.downloadDirectory, suggested); + downloadDestinations[download] = destination.string(); + Object path(text(destination.string())); + result = send(type("NSURL"), "fileURLWithPath:", path.get()); + return; + } + const auto panel = send(type("NSSavePanel"), "savePanel"); + Object name(text(std::filesystem::path(suggested).filename().string())); + send(panel, "setNameFieldStringValue:", name.get()); + auto handler = Block_copy(completion); + void (^finished)(long) = ^(long response) { + id url = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK + if (url) + downloadDestinations[download] = utf8(send(url, "path")); + handler(url); + Block_release(handler); + }; + deferred = true; + send(panel, "beginSheetModalForWindow:completionHandler:", window, finished); + }); + if (!deferred) + completion(result); + } + + void downloadEnded(id download, bool completed) noexcept { + const auto found = downloadDestinations.find(download); + if (found == downloadDestinations.end()) + return; + const auto destination = std::move(found->second); + downloadDestinations.erase(found); + if (completed && options.downloadFinished) + guard([&] { + options.downloadFinished(destination); + }); + } + void navigationResponse(id response, void (^decision)(long)) noexcept { long policy = 1; // WKNavigationResponsePolicyAllow guard([&] { @@ -517,8 +611,12 @@ struct Session { rejectNavigation("initial navigation response was denied by contentPolicy"); return; } - if (committed) + // A response the engine cannot display (an attachment, an archive) is saved, not shown. + if (committed) { + if (!send(response, "canShowMIMEType")) + policy = 2; // WKNavigationResponsePolicyDownload return; + } if (send(http, "respondsToSelector:", sel_registerName("statusCode"))) { const auto status = send(http, "statusCode"); if (!successfulHttpStatus(status)) { @@ -620,6 +718,48 @@ inline void addNavigationMethods(Class cls) { return nullptr; }, "@@:@@@@"); + // File chooser (WKUIDelegate) and downloads (WKNavigationDelegate, WKDownloadDelegate), issue #451. + addMethod( + cls, + "webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:", + +[](id self, SEL, id, id parameters, id frame, void (^completion)(id)) { + if (auto s = session(self)) + s->chooseFilesForPage(parameters, frame, completion); + else + completion(nullptr); + }, + "v@:@@@@?"); + const auto becameDownload = +[](id self, SEL, id, id, id download) { + send(download, "setDelegate:", self); + }; + addMethod(cls, "webView:navigationAction:didBecomeDownload:", becameDownload, "v@:@@@"); + addMethod(cls, "webView:navigationResponse:didBecomeDownload:", becameDownload, "v@:@@@"); + addMethod( + cls, + "download:decideDestinationUsingResponse:suggestedFilename:completionHandler:", + +[](id self, SEL, id download, id, id suggested, void (^completion)(id)) { + if (auto s = session(self)) + s->chooseDownloadDestination(download, utf8(suggested), completion); + else + completion(nullptr); + }, + "v@:@@@@?"); + addMethod( + cls, + "downloadDidFinish:", + +[](id self, SEL, id download) { + if (auto s = session(self)) + s->downloadEnded(download, true); + }, + "v@:@"); + addMethod( + cls, + "download:didFailWithError:resumeData:", + +[](id self, SEL, id download, id, id) { + if (auto s = session(self)) + s->downloadEnded(download, false); + }, + "v@:@@@"); addMethod(cls, "webView:didFinishNavigation:", navigationFinished, "v@:@@"); addMethod(cls, "webView:didCommitNavigation:", navigationCommitted, "v@:@@"); const auto failed = +[](id self, SEL, id, id, id error) { diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 8ddedf77..5ce2f730 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -5,6 +5,7 @@ #include "Action.hpp" #include "Capture.hpp" #include "DefaultBrowser.hpp" +#include "Downloads.hpp" #include "Url.hpp" #include "Window.hpp" #include "WebKitGTKPolicy.hpp" @@ -90,6 +91,7 @@ class Api { Object (*settings)(Object) = symbol("webkit_web_view_get_settings"); void (*load)(Object, const char*) = symbol("webkit_web_view_load_uri"); const char* (*viewUri)(Object) = symbol("webkit_web_view_get_uri"); + const char* (*viewTitle)(Object) = symbol("webkit_web_view_get_title"); void (*windowClose)(Object) = symbol("gtk_window_close"); void (*stop)(Object) = symbol("webkit_web_view_stop_loading"); Object (*navigationAction)(Object) = symbol("webkit_navigation_policy_decision_get_navigation_action"); @@ -113,6 +115,11 @@ class Api { const void* (*bytesData)(Object, std::size_t*) = symbol("g_bytes_get_data"); void (*bytesUnref)(Object) = symbol("g_bytes_unref"); void (*errorFree)(Error*) = symbol("g_error_free"); + void (*downloadDestination)(Object, const char*) = symbol("webkit_download_set_destination"); + void (*downloadCancel)(Object) = symbol("webkit_download_cancel"); + const char* (*downloadGetDestination)(Object) = symbol("webkit_download_get_destination"); + void (*chooserSelect)(Object, const char* const*) = symbol("webkit_file_chooser_request_select_files"); + void (*chooserCancel)(Object) = symbol("webkit_file_chooser_request_cancel"); }; inline Api& api() { @@ -274,6 +281,18 @@ struct Session : FailureState { webfront::detail::BoundContentPolicy policy; WindowOptions windowOptions; std::function navigationCancelled; + /// Download folder; empty selects the user's XDG download folder, else the home folder. + std::filesystem::path downloadDirectory; + /// Test injection: answers without a dialog (an empty list cancels). Unset shows the system dialog. + std::function()> chooseFiles; + /// Test injection: called with the destination of each finished download. + std::function downloadFinished; + struct Download { + Api::Object object; + std::vector handlers; + }; + std::vector downloads; + unsigned long downloadStartedHandler = 0; bool closed = false; bool initialNavigation = true; unsigned navigationTimer = 0; @@ -288,6 +307,7 @@ struct Session : FailureState { Session& operator=(const Session&) = delete; ~Session() { stopNavigationTimer(); + releaseDownloads(); releaseView(); destroyWindow(); release(network); @@ -312,6 +332,17 @@ struct Session : FailureState { a.stop(view); release(view); } + void releaseDownloads() { + if (downloadStartedHandler && network) + a.disconnect(network, std::exchange(downloadStartedHandler, 0)); + for (auto& download : downloads) { + for (auto handler : download.handlers) + a.disconnect(download.object, handler); + a.downloadCancel(download.object); + a.unref(download.object); + } + downloads.clear(); + } void destroyWindow() { if (!window) return; @@ -356,6 +387,7 @@ struct Session : FailureState { a.windowChild(window, view); configureSettings(); registerHandlers(); + downloadStartedHandler = a.connect(network, "download-started", reinterpret_cast(onDownloadStarted), this, nullptr, 0); captureTarget->view = view; captureTarget->pending.open(); captureRegistration = CaptureRegistration{captureProvider(captureTarget)}; @@ -381,6 +413,42 @@ struct Session : FailureState { on("load-failed", onLoadFailed, 2); on("web-process-terminated", onProcessTerminated); on("decide-policy", onDecidePolicy); + on("run-file-chooser", onRunFileChooser); + } + + std::filesystem::path destinationFolder() const { + if (!downloadDirectory.empty()) + return downloadDirectory; + if (const auto* xdg = std::getenv("XDG_DOWNLOAD_DIR"); xdg && *xdg) + return xdg; + if (const auto* home = std::getenv("HOME"); home && *home) { + std::error_code error; + const auto folder = std::filesystem::path(home) / "Downloads"; + if (std::filesystem::is_directory(folder, error)) + return folder; + return home; + } + return std::filesystem::temp_directory_path(); + } + std::filesystem::path uniqueDestination(std::string_view suggested) const { + return uniqueDownloadPath(destinationFolder(), suggested); + } + void trackDownload(Api::Object download) { + Download entry{download, {}}; + a.refSink(download); + entry.handlers.push_back(a.connect(download, "decide-destination", reinterpret_cast(onDecideDestination), this, nullptr, 0)); + entry.handlers.push_back(a.connect(download, "finished", reinterpret_cast(onDownloadFinished), this, nullptr, 0)); + entry.handlers.push_back(a.connect(download, "failed", reinterpret_cast(onDownloadFailed), this, nullptr, 0)); + downloads.push_back(std::move(entry)); + } + void forgetDownload(Api::Object download) { + const auto found = std::ranges::find(downloads, download, &Download::object); + if (found == downloads.end()) + return; + for (auto handler : found->handlers) + a.disconnect(download, handler); + a.unref(found->object); + downloads.erase(found); } bool initialDocumentFailed() const { @@ -478,6 +546,53 @@ struct Session : FailureState { return 1; } } + static void onDownloadStarted(Api::Object, Api::Object download, Session* self) noexcept { + self->guard([self, download] { + self->trackDownload(download); + }); + } + static int onDecideDestination(Api::Object download, const char* suggested, Session* self) noexcept { + try { + const auto destination = self->uniqueDestination(suggested ? suggested : ""); + api().downloadDestination(download, destination.c_str()); + } catch (...) { + api().downloadCancel(download); + } + return 1; + } + static void onDownloadFinished(Api::Object download, Session* self) noexcept { + std::string destination; + if (const auto* path = api().downloadGetDestination(download)) + destination = path; + self->guard([self, download, destination] { + self->forgetDownload(download); + if (self->downloadFinished) + self->downloadFinished(destination); + }); + } + static void onDownloadFailed(Api::Object download, Api::Error*, Session* self) noexcept { + self->guard([self, download] { + self->forgetDownload(download); + }); + } + static int onRunFileChooser(Api::Object, Api::Object request, Session* self) noexcept { + if (!self->chooseFiles) + return 0; // The system dialog, attached to the window by WebKitGTK. + try { + const auto files = self->chooseFiles(); + std::vector pointers; + for (const auto& file : files) + pointers.push_back(file.c_str()); + pointers.push_back(nullptr); + if (files.empty()) + api().chooserCancel(request); + else + api().chooserSelect(request, pointers.data()); + } catch (...) { + api().chooserCancel(request); + } + return 1; + } static int onNavigationTimeout(void* data) noexcept { auto* self = static_cast(data); self->navigationTimer = 0; diff --git a/include/webfront/frontend/WebKitGTKPolicy.hpp b/include/webfront/frontend/WebKitGTKPolicy.hpp index 37c6671e..436fb753 100644 --- a/include/webfront/frontend/WebKitGTKPolicy.hpp +++ b/include/webfront/frontend/WebKitGTKPolicy.hpp @@ -24,7 +24,7 @@ struct PolicyRequest { inline bool navigationSchemeAllowed(const char* uri) { if (!uri) return false; - if (webfront::detail::contentOrigin(uri)) + if (webfront::detail::contentOrigin(uri) || webfront::detail::contentOrigin(webfront::detail::blobOriginUrl(uri))) return true; return std::string_view(uri) == "about:blank" || std::string_view(uri) == "about:srcdoc"; } diff --git a/test/tools/Qualification.py b/test/tools/Qualification.py new file mode 100644 index 00000000..b8470356 --- /dev/null +++ b/test/tools/Qualification.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Qualification report of the file services of the embedded frontends (issue #451). + +Two steps, both pure standard library: + + Qualification.py collect --build DIR --evidence DIR --platform NAME --output DIR + Gathers, on one CI platform, the CTest results of the file-service tests, the captures the specs wrote and the + evidence of the native scenarios (WEBFRONT_QUALIFICATION_DIR) into one folder with a manifest. + + Qualification.py report --input DIR --output FILE + Assembles the manifests of every platform (one sub-folder each) into a Markdown document that embeds the captures. + A platform that did not report, or a scenario nobody ran, is written as such rather than left out. +""" +import argparse +import datetime +import json +import pathlib +import shutil +import sys +import xml.etree.ElementTree as ET + +# Scenario -> (title, what it proves). The CTest names carry the platform-independent part. +GENERIC = ("ConsumerJasmine-file-services", "Files and Blob download offered to the page (File API, ``, ``)") +NATIVE = { + "choose-file": "``: the chooser answers with a fixture file, the page reads it", + "cancel-choose": "``: cancelling the chooser emits `cancel`, no error", + "download": "`` of a generated Blob lands in the download folder, inside it", +} +NATIVE_TESTS = { # engine -> CTest name pattern of a native scenario + "WebKitGTK": "WebKitGTKAdapter-{}", + "CEF": {"choose-file": "CEFFileServices-choose", "cancel-choose": "CEFFileServices-cancel", "download": "CEFFileServices-download"}, +} +ENGINES = ["WebKitGTK", "CEF", "WKWebView", "WebView2"] +NOT_INJECTED = { + "WKWebView": "chooser and download are implemented (`runOpenPanelWithParameters`, `WKDownloadDelegate`) with a test injection, but no native scenario drives them yet", + "WebView2": "the engine's own chooser and download UI are used; no injection point exists yet", +} + + +def engine_of(platform: str) -> str: + lowered = platform.lower() + for engine in ENGINES: + if engine.lower() in lowered: + return engine + return platform + + +def junit_results(build: pathlib.Path) -> dict[str, str]: + results: dict[str, str] = {} + for path in sorted(build.glob("test-results-*.xml")) + sorted(build.glob("test-results.xml")): + for case in ET.parse(path).getroot().iter("testcase"): + name = case.get("name", "") + if "file-services" not in name and "FileServices" not in name and not name.startswith("WebKitGTKAdapter-"): + continue + if case.find("failure") is not None or case.find("error") is not None: + status = "failed" + elif case.find("skipped") is not None: + status = "skipped" + else: + status = "passed" + # Several passes (repeated runs): any failure wins. + if results.get(name) != "failed": + results[name] = status + return results + + +def collect(args: argparse.Namespace) -> int: + build, out = pathlib.Path(args.build), pathlib.Path(args.output) + out.mkdir(parents=True, exist_ok=True) + manifest = {"platform": args.platform, "engine": engine_of(args.platform), "tests": junit_results(build), "images": []} + sources = [(p, "spec") for p in build.glob("test/web/webfront-jasmine/ConsumerJasmine-file-services/captures/*.png")] + evidence = pathlib.Path(args.evidence) if args.evidence else None + if evidence and evidence.is_dir(): + sources += [(p, "native") for p in evidence.glob("*.png")] + for source, kind in sources: + target = f"{kind}-{source.name}" + shutil.copyfile(source, out / target) + manifest["images"].append({"file": target, "kind": kind, "name": source.stem}) + if evidence and evidence.is_dir(): + manifest["native"] = [json.loads(p.read_text()) for p in sorted(evidence.glob("*.json"))] + (out / "manifest.json").write_text(json.dumps(manifest, indent=2)) + print(f"{args.platform}: {len(manifest['tests'])} results, {len(manifest['images'])} captures") + return 0 + + +def native_test(engine: str, scenario: str): + entry = NATIVE_TESTS.get(engine) + if isinstance(entry, str): + return entry.format(scenario) + return entry.get(scenario) if entry else None + + +def mark(status): + return {"passed": "✅ passed", "failed": "❌ failed", "skipped": "⏭ skipped"}.get(status, "⚪ not run") + + +def report(args: argparse.Namespace) -> int: + root, out = pathlib.Path(args.input), pathlib.Path(args.output) + manifests = {} + for path in sorted(root.glob("*/manifest.json")): + data = json.loads(path.read_text()) + manifests[path.parent.name] = (path.parent, data) + out.parent.mkdir(parents=True, exist_ok=True) + images = out.parent / "images" + images.mkdir(exist_ok=True) + lines = ["# Qualification of the file services of the embedded frontends", "", + f"Generated by CI on {datetime.date.today().isoformat()} from the run's platform artifacts (issue #451). " + "Captures are taken by WebFront's own window capture (`webfront::frontend::capturePng`): web content only, " + "native dialogs are not part of them.", "", + "## Summary", "", "| Platform | Engine | Spec: files and Blob download | " + " | ".join(NATIVE.values()) + " |", + "| --- | --- | --- | " + " | ".join("---" for _ in NATIVE) + " |"] + for name, (_, data) in manifests.items(): + engine = data["engine"] + row = [name, engine, mark(data["tests"].get(GENERIC[0]))] + for scenario in NATIVE: + test = native_test(engine, scenario) + row.append(mark(data["tests"].get(test)) if test else "⚪ not injected") + lines.append("| " + " | ".join(row) + " |") + missing = [e for e in ENGINES if not any(d["engine"] == e for _, d in manifests.values())] + if missing: + lines += ["", "No report from: " + ", ".join(missing) + " (the job did not run in this workflow, or failed before reporting)."] + lines += ["", "## Limits by engine", ""] + for engine, reason in NOT_INJECTED.items(): + lines.append(f"- **{engine}**: {reason}.") + lines.append("- **CEF** (Chrome runtime) and **WebKitGTK**: native dialog and download handling, plus a test injection answering without a dialog.") + for name, (folder, data) in manifests.items(): + lines += ["", f"## {name} ({data['engine']})", ""] + for image in data["images"]: + shutil.copyfile(folder / image["file"], images / f"{name}-{image['file']}") + lines += [f"**{image['name']}** ({'spec capture' if image['kind'] == 'spec' else 'native scenario'})", "", + f"![{name} {image['name']}](images/{name}-{image['file']})", ""] + if not data["images"]: + lines.append("No capture was produced.") + failed = [t for t, s in data["tests"].items() if s == "failed"] + if failed: + lines += ["", "Failed: " + ", ".join(f"`{t}`" for t in failed)] + out.write_text("\n".join(lines) + "\n") + print(f"wrote {out} ({len(manifests)} platforms)") + return 0 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = parser.add_subparsers(dest="command", required=True) + c = sub.add_parser("collect") + c.add_argument("--build", required=True) + c.add_argument("--evidence") + c.add_argument("--platform", required=True) + c.add_argument("--output", required=True) + r = sub.add_parser("report") + r.add_argument("--input", required=True) + r.add_argument("--output", required=True) + args = parser.parse_args() + return collect(args) if args.command == "collect" else report(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test/unit/ContentPolicyTests.cpp b/test/unit/ContentPolicyTests.cpp index 06f0d6d3..b82e890f 100644 --- a/test/unit/ContentPolicyTests.cpp +++ b/test/unit/ContentPolicyTests.cpp @@ -70,6 +70,14 @@ SCENARIO("Content policy compares complete HTTP origins") { REQUIRE(policy.allowsBridge(std::nullopt)); REQUIRE(policy.allowsNavigation("http://127.0.0.1:9002/next?x=1#fragment")); } + THEN("a Blob of the application's origin (a generated download) is allowed, one of another origin is not") { + REQUIRE(policy.allowsNavigation("blob:http://127.0.0.1:9002/0b1f2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d")); + REQUIRE(policy.allowsNavigation("BLOB:http://127.0.0.1:9002/id")); + for (const auto* url : {"blob:https://example.com/id", "blob:null/id", "blob:", "blob:http://127.0.0.1:9002@evil/id", "blob:blob:http://127.0.0.1:9002/id"}) { + INFO(url); + REQUIRE_FALSE(policy.allowsNavigation(url)); + } + } THEN("other origins and ambiguous syntax fail closed") { for (const auto* origin : invalidBridgeOrigins) { INFO(origin); diff --git a/test/web/CEFFileServices.cpp b/test/web/CEFFileServices.cpp new file mode 100644 index 00000000..57f5dd0d --- /dev/null +++ b/test/web/CEFFileServices.cpp @@ -0,0 +1,169 @@ +// Qualification of and downloads in the CEF frontend (issue #451): the chooser is answered by the +// client's injection point and opened by a real mouse click sent to the engine; the download goes to a private folder. +#include "QualificationEvidence.hpp" +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace { +void require(bool value, const char* message) { + if (!value) + throw std::runtime_error(message); +} + +struct Scenario { + std::string mode; // download | choose | cancel + std::filesystem::path folder; + std::filesystem::path fixture; + std::string title; + std::string downloaded; + bool asked = false; +}; +Scenario scenario; +webfront::testing::QualificationEvidence evidence; + +class Client : public webfront::cef::SimpleCEFClient { +public: + Client() : SimpleCEFClient(webfront::detail::BoundContentPolicy{}) { + chooseFiles = [] { + scenario.asked = true; + return scenario.mode == "choose" ? std::vector{scenario.fixture.string()} : std::vector{}; + }; + downloadDirectory = scenario.folder; + downloadFinished = [this](const std::string& path) { + scenario.downloaded = path; + finish(); + }; + } + void OnTitleChange(CefRefPtr browser, const CefString& title) override { + scenario.title = title.ToString(); + window = browser; + if (scenario.title == "ready" && scenario.mode != "download") + CefPostDelayedTask(TID_UI, new Click(this, 40), 500); + else if (scenario.title.starts_with("picked:") || scenario.title == "cancelled") + finish(); + } + void OnAfterCreated(CefRefPtr browser) override { + SimpleCEFClient::OnAfterCreated(browser); + window = browser; + CefPostDelayedTask(TID_UI, new Deadline(this), 20'000); + } + void close() { + if (window) + window->GetHost()->CloseBrowser(true); + } + /// Captures the final state with WebFront's own capture, then closes the window on the UI thread. + void finish() { + if (finishing) + return; + finishing = true; + evidence.capture("CEF", + scenario.mode == "choose" ? "choose-file" + : scenario.mode == "cancel" ? "cancel-choose" + : "download", + [this] { + CefPostTask(TID_UI, new Close(this)); + }); + } + +private: + CefRefPtr window; + bool finishing = false; + struct Close : CefTask { + explicit Close(Client* owner) : client(owner) {} + void Execute() override { + client->close(); + } + CefRefPtr client; + IMPLEMENT_REFCOUNTING(Close); + }; + +public: + void clickChooser() { + // Runtime.evaluate with userGesture: the page's own click, counted as a user gesture by the engine. + auto params = CefDictionaryValue::Create(); + params->SetString("expression", "document.getElementById('picker').click()"); + params->SetBool("userGesture", true); + window->GetHost()->ExecuteDevToolsMethod(0, "Runtime.evaluate", params); + } + // The window may not take input right away: click again until the chooser was requested. + struct Click : CefTask { + Click(Client* owner, int left) : client(owner), remaining(left) {} + void Execute() override { + if (scenario.asked || remaining == 0) + return; + client->clickChooser(); + CefPostDelayedTask(TID_UI, new Click(client.get(), remaining - 1), 250); + } + CefRefPtr client; + int remaining; + IMPLEMENT_REFCOUNTING(Click); + }; + struct Deadline : CefTask { + explicit Deadline(Client* owner) : client(owner) {} + void Execute() override { + client->close(); + } + CefRefPtr client; + IMPLEMENT_REFCOUNTING(Deadline); + }; + IMPLEMENT_REFCOUNTING(Client); +}; + +struct Frontend { + static constexpr auto action = webfront::frontend::Action::closeServerAfterOpen; + static void initialize() { + webfront::frontend::CEFFrontend::initialize(); + } + static void open(std::string_view port, std::string_view page) { + open("127.0.0.1", port, page, {}); + } + static void open(std::string_view address, std::string_view port, std::string_view page, const webfront::ContentPolicy& policy) { + webfront::cef::detail::openWindow(webfront::frontend::detail::applicationUrl(address, port, page), + webfront::detail::BoundContentPolicy{webfront::detail::applicationOrigin(address, port), policy}, + new Client); + } +}; +} // namespace + +int main(int argc, char** argv) { + try { + webfront::detail::ensureFrontendInitialized(); // CEF subprocesses run this program too and end here. + require(argc == 2, "usage: cef_file_services download|choose|cancel"); + scenario.mode = argv[1]; + scenario.folder = std::filesystem::temp_directory_path() / ("webfront-cef-" + scenario.mode + "-" + std::to_string(getpid())); + std::filesystem::remove_all(scenario.folder); + std::filesystem::create_directories(scenario.folder); + scenario.fixture = scenario.folder / "fixture.txt"; + std::ofstream(scenario.fixture) << "chosen by the test"; + using FS = webfront::fs::Multi; + webfront::BasicWFWithFrontend app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?" + (scenario.mode == "download" ? std::string("download") : std::string("choose"))); + if (scenario.mode == "download") { + require(!scenario.downloaded.empty(), "The download did not finish"); + // The engine neutralizes the page's "../webfront-download.txt" itself (Chrome writes "_webfront-download.txt"). + require(std::filesystem::path(scenario.downloaded).parent_path() == scenario.folder, + ("The download left its folder: " + scenario.downloaded).c_str()); + require(std::filesystem::path(scenario.downloaded).filename().string().ends_with("webfront-download.txt"), "The download lost its name"); + std::ifstream stream(scenario.downloaded, std::ios::binary); + require(std::string(std::istreambuf_iterator(stream), {}) == "downloaded by WebFront", "The downloaded file has the wrong content"); + } else { + require(scenario.asked, ("The file chooser was not requested; title=" + scenario.title).c_str()); + require(scenario.title == (scenario.mode == "choose" ? "picked:chosen by the test" : "cancelled"), + ("Unexpected page state: " + scenario.title).c_str()); + } + evidence = {}; + std::filesystem::remove_all(scenario.folder); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index b5f981b9..1b2e1e71 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -182,6 +182,11 @@ if(_browser_tests_available) FRONTEND "${WEBFRONT_WEBTEST_FRONTEND}" TIMEOUT 30 SPECS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer/capture.spec.js" ARGS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer") + # File services of the engine (issue #451), with captures as evidence for the qualification report. + webfront_add_jasmine_test(NAME ConsumerJasmine-file-services TARGET jasmine_consumer + FRONTEND "${WEBFRONT_WEBTEST_FRONTEND}" TIMEOUT 30 + SPECS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer/file-services.spec.js" + ARGS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer") add_test(NAME ConsumerJasmineCaptures COMMAND "${CMAKE_COMMAND}" "-DDIRECTORY=${CMAKE_CURRENT_BINARY_DIR}/webfront-jasmine/ConsumerJasmine-capture/captures" -P "${PROJECT_SOURCE_DIR}/test/cmake/CheckConsumerCaptures.cmake") @@ -233,6 +238,17 @@ if(WEBFRONT_EMBED_CEF AND CMAKE_SYSTEM_NAME STREQUAL "Linux") add_test(NAME CEFContentPolicy COMMAND "${_policy_xvfb}" -a $) webfront_set_browser_test_properties(CEFContentPolicy "${CMAKE_CURRENT_SOURCE_DIR}" 45) endif() + # File chooser and downloads (issue #451). + add_executable(cef_file_services CEFFileServices.cpp) + target_link_libraries(cef_file_services PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) + webfront_setup_frontends_for_target(cef_file_services) + add_dependencies(webtest cef_file_services) + if(_policy_xvfb) + foreach(mode download choose cancel) + add_test(NAME CEFFileServices-${mode} COMMAND "${_policy_xvfb}" -a $ ${mode}) + webfront_set_browser_test_properties(CEFFileServices-${mode} "${CMAKE_CURRENT_SOURCE_DIR}" 60) + endforeach() + endif() endif() if(_browser_tests_available) diff --git a/test/web/QualificationEvidence.hpp b/test/web/QualificationEvidence.hpp new file mode 100644 index 00000000..d696b4b7 --- /dev/null +++ b/test/web/QualificationEvidence.hpp @@ -0,0 +1,46 @@ +#pragma once + +// Evidence of a qualification scenario (issue #451): when WEBFRONT_QUALIFICATION_DIR is set, the scenario's final state is +// captured with WebFront's own window capture and recorded next to a JSON result. test/tools/Qualification.py gathers them. +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::testing { + +class QualificationEvidence { +public: + /// Captures the window (from a worker thread: the event loop keeps running), then calls `then` from that thread. + void capture(const std::string& engine, const std::string& scenario, std::function then) { + const char* directory = std::getenv("WEBFRONT_QUALIFICATION_DIR"); + if (!directory || !*directory) { + then(); + return; + } + worker = std::jthread([=, this] { + const std::filesystem::path folder{directory}; + std::filesystem::create_directories(folder); + const auto result = frontend::capturePng(std::chrono::seconds{10}); + std::string image; + if (result) { + image = scenario + ".png"; + std::ofstream(folder / image, std::ios::binary) + .write(reinterpret_cast(result->data()), static_cast(result->size())); + } + std::ofstream(folder / (scenario + ".json")) << "{\"engine\":\"" << engine << "\",\"scenario\":\"" << scenario << "\",\"image\":\"" << image + << "\",\"capture\":\"" << (result ? "ok" : "failed") << "\"}\n"; + then(); + }); + } + +private: + std::jthread worker; +}; + +} // namespace webfront::testing diff --git a/test/web/WebKitGTKLifecycle.cpp b/test/web/WebKitGTKLifecycle.cpp index 869847f7..0ee6ec55 100644 --- a/test/web/WebKitGTKLifecycle.cpp +++ b/test/web/WebKitGTKLifecycle.cpp @@ -1,8 +1,13 @@ +#include "QualificationEvidence.hpp" + #include #include #include +#include #include +#include +#include #include #include #include @@ -127,6 +132,155 @@ void nativeClose() { app.show("no-bridge.html"); } +/// Runs a page of the test folder in a session configured by the scenario, for at most `seconds`. +struct ScenarioFrontend : Frontend { + static inline std::function configure; + static inline std::function finished; // Polled; true captures the evidence, then closes the window. + static inline std::string name; // The scenario, for the qualification evidence. + static void open(std::string_view port, std::string_view page) { + open("127.0.0.1", port, page, {}); + } + static void open(std::string_view address, std::string_view port, std::string_view page, const webfront::ContentPolicy& policy) { + gtk::Session session(webfront::detail::BoundContentPolicy{webfront::frontend::detail::applicationUrl(address, port, ""), policy}); + session.create(); + configure(session); + struct Poll { + gtk::Session& session; + int remaining = 150; // 15 s + unsigned timer = 0; + bool finishing = false; + webfront::testing::QualificationEvidence evidence; + } poll{session, 150, 0, false, {}}; + poll.timer = session.a.timeoutAdd( + 100, + [](void* data) -> int { + auto& probe = *static_cast(data); + if (probe.session.closed) + return 0; + if (probe.finishing) + return 1; + if (finished(probe.session)) { + probe.finishing = true; + probe.evidence.capture("WebKitGTK", name, [&probe] { + probe.session.close(); + }); + return 1; + } + if (--probe.remaining == 0) { + probe.timer = 0; + probe.session.close(); + return 0; + } + return 1; + }, + &poll); + session.run(webfront::frontend::detail::applicationUrl(address, port, page)); + poll.evidence = {}; // Joins the capture thread before the session goes away. + if (poll.timer) + session.a.sourceRemove(poll.timer); + } +}; + +using ScenarioApp = webfront::BasicWFWithFrontend; + +std::string readFile(const std::filesystem::path& path) { + std::ifstream stream(path, std::ios::binary); + return {std::istreambuf_iterator(stream), {}}; +} + +void download() { + const auto folder = std::filesystem::temp_directory_path() / ("webfront-download-" + std::to_string(getpid())); + std::filesystem::remove_all(folder); + std::filesystem::create_directories(folder); + std::string destination; + bool done = false; + ScenarioFrontend::name = "download"; + ScenarioFrontend::configure = [&](gtk::Session& session) { + session.downloadDirectory = folder; + session.downloadFinished = [&](const std::string& path) { + destination = path; + done = true; + }; + }; + ScenarioFrontend::finished = [&](gtk::Session&) { + return done; + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?download"); + if (!done) + throw std::runtime_error("The download did not finish"); + // The suggested name "../webfront-download.txt" must never leave the download folder. + if (std::filesystem::path(destination) != folder / "webfront-download.txt") + throw std::runtime_error("Unexpected download destination: " + destination); + if (readFile(destination) != "downloaded by WebFront") + throw std::runtime_error("The downloaded file has the wrong content"); + std::filesystem::remove_all(folder); +} + +/// A real pointer click through the X server's XTest extension: web content only opens a file chooser for a user gesture. +struct FakeClick { + void* x11 = dlopen("libX11.so.6", RTLD_NOW); + void* xtest = dlopen("libXtst.so.6", RTLD_NOW); + using Open = void* (*)(const char*); + using Flush = int (*)(void*); + using Move = int (*)(void*, int, int, int, unsigned long); + using Press = int (*)(void*, unsigned, int, unsigned long); + Open open = x11 ? reinterpret_cast(dlsym(x11, "XOpenDisplay")) : nullptr; + Flush flush = x11 ? reinterpret_cast(dlsym(x11, "XFlush")) : nullptr; + Move move = xtest ? reinterpret_cast(dlsym(xtest, "XTestFakeMotionEvent")) : nullptr; + Press press = xtest ? reinterpret_cast(dlsym(xtest, "XTestFakeButtonEvent")) : nullptr; + void* display = open ? open(nullptr) : nullptr; + + bool available() const { + return display && move && press && flush; + } + void click(int x, int y) const { + move(display, 0, x, y, 0); + press(display, 1, 1, 0); + press(display, 1, 0, 0); + flush(display); + } +}; + +void chooseFile(bool cancel) { + const auto fixture = std::filesystem::temp_directory_path() / ("webfront-chooser-" + std::to_string(getpid()) + ".txt"); + std::ofstream(fixture) << "chosen by the test"; + bool asked = false; + ScenarioFrontend::name = cancel ? "cancel-choose" : "choose-file"; + ScenarioFrontend::configure = [&](gtk::Session& session) { + session.chooseFiles = [&]() -> std::vector { + asked = true; + return cancel ? std::vector{} : std::vector{fixture.string()}; + }; + }; + std::string title; + const FakeClick pointer; + if (!pointer.available()) + throw std::runtime_error("XTest is unavailable: run the scenario under Xvfb with libXtst"); + int ticks = 0; + ScenarioFrontend::finished = [&](gtk::Session& session) { + const char* current = session.a.viewTitle(session.view); + title = current ? current : ""; + if (title == "ready" && !asked && ++ticks % 5 == 1) + pointer.click(40, 20); // The "Choose File" button, at the page's top-left corner. + return title.starts_with("picked:") || title == "cancelled"; + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?choose"); + std::filesystem::remove(fixture); + if (!asked) + throw std::runtime_error("The file chooser was not requested"); + const std::string expected = cancel ? "cancelled" : "picked:chosen by the test"; + if (title != expected) + throw std::runtime_error("Unexpected page state after the chooser: " + title); +} +void chooseOne() { + chooseFile(false); +} +void chooseCancel() { + chooseFile(true); +} + void windowTitle() { gtk::initialize(); const auto titleOf = [](webfront::WindowOptions window) { @@ -177,7 +331,10 @@ void run(std::string_view mode) { { "native-close", nativeClose}, { "pre-run-failure", preRunFailure}, {"profile-permissions", profilePermissions}, - { "window-title", windowTitle} + { "window-title", windowTitle}, + { "download", download}, + { "choose-file", chooseOne}, + { "cancel-choose", chooseCancel} }; const auto selected = cases.find(mode); if (selected == cases.end()) diff --git a/test/web/file-services.html b/test/web/file-services.html new file mode 100644 index 00000000..f2ae1c50 --- /dev/null +++ b/test/web/file-services.html @@ -0,0 +1,30 @@ + + +File chooser and downloads + + +

WebFront file services

+

waiting

+ diff --git a/test/web/jasmine-consumer/file-services.spec.js b/test/web/jasmine-consumer/file-services.spec.js new file mode 100644 index 00000000..534b76f0 --- /dev/null +++ b/test/web/jasmine-consumer/file-services.spec.js @@ -0,0 +1,55 @@ +// Qualification of the file services every engine must give a page without any native API (issue #451): files reach the +// page as File objects, a generated Blob can be offered for download, and the page keeps working afterwards. +describe('File services in the embedded engine', () => { + let host; + beforeEach(() => { + host = document.createElement('section'); + document.body.append(host); + }); + afterEach(() => host.remove()); + + it('reads the content of files given to an and to a drop', async () => { + const input = document.createElement('input'); + input.type = 'file'; + input.multiple = true; + host.append(input); + const transfer = new DataTransfer(); + transfer.items.add(new File(['first file'], 'first.txt', {type: 'text/plain'})); + transfer.items.add(new File([new Uint8Array([1, 2, 3, 255])], 'second.bin')); + const changed = new Promise(resolve => input.addEventListener('change', resolve, {once: true})); + input.files = transfer.files; + input.dispatchEvent(new Event('change', {bubbles: true})); + await changed; + expect(input.files.length).toBe(2); + expect(await input.files[0].text()).toBe('first file'); + expect(Array.from(new Uint8Array(await input.files[1].arrayBuffer()))).toEqual([1, 2, 3, 255]); + const summary = document.createElement('p'); + summary.textContent = Array.from(input.files, file => `${file.name} (${file.size} bytes)`).join(', '); + host.append(summary); + expect(await webFrontCapture.screenshot('file-input')).toBeGreaterThan(100); + }); + + it('accepts the directory flag and the accept filter on the input', () => { + const input = document.createElement('input'); + input.type = 'file'; + input.accept = '.txt,image/*'; + input.webkitdirectory = true; + host.append(input); + expect(input.accept).toBe('.txt,image/*'); + expect(input.webkitdirectory).toBe(true); + }); + + it('offers a generated Blob for download without breaking the page or the bridge', async () => { + const link = document.createElement('a'); + link.href = URL.createObjectURL(new Blob(['generated by the page'], {type: 'text/plain'})); + link.download = 'generated.txt'; + link.textContent = 'generated.txt'; + host.append(link); + link.click(); + await new Promise(resolve => setTimeout(resolve, 500)); + expect(location.protocol).toMatch(/^https?:$/); // The window stayed on the application. + expect(await webFront.cppFunction('consumer.answer')()).toBe(42); + expect(await webFrontCapture.screenshot('download-link')).toBeGreaterThan(100); + URL.revokeObjectURL(link.href); + }); +}); From aaf8a363f3b69a99bb6dee3101605e4dced8ab08 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:54:36 +0100 Subject: [PATCH 02/18] Fix the CI failures and address the review of #451 The WebKitGTK policy test still expected every blob: navigation to be cancelled; a blob of an admitted origin is now allowed. Rename a local that shadowed Session::url in WKWebView. Download to a temporary file when the save panel replaces an existing one, clear the stale GLib timer id, report a lost capture in the qualification table, keep images out of the step summary and describe the spec's assertions exactly. Unit tests for the download names. --- .github/workflows/BuildAndTest.yml | 3 +- docs/FRONTENDS.md | 4 +-- include/webfront/frontend/WKWebView.hpp | 37 +++++++++++++++++++------ test/tools/Qualification.py | 7 ++++- test/unit/CMakeLists.txt | 2 +- test/unit/DownloadsTests.cpp | 33 ++++++++++++++++++++++ test/unit/WebKitGTKPolicyTests.cpp | 3 +- test/web/WebKitGTKLifecycle.cpp | 4 ++- 8 files changed, 78 insertions(+), 15 deletions(-) create mode 100644 test/unit/DownloadsTests.cpp diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index a9276b3b..b742203d 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -566,7 +566,8 @@ jobs: [ -d "$directory" ] && mv "$directory" "qualification-input/${directory#qualification-input/qualification-}" done python3 test/tools/Qualification.py report --input qualification-input --output qualification-report/QUALIFICATION.md - cat qualification-report/QUALIFICATION.md >> "$GITHUB_STEP_SUMMARY" + # The summary cannot serve the artifact's images: show the tables only and point to the artifact. + { grep -v '^!\[' qualification-report/QUALIFICATION.md; echo; echo "The captures are in the \`qualification-report\` artifact of this run."; } >> "$GITHUB_STEP_SUMMARY" - uses: actions/upload-artifact@v4 with: name: qualification-report diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 77a3e550..8b389b99 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -64,8 +64,8 @@ Xvfb for WebKitGTK) or a `Runtime.evaluate` with `userGesture` (CEF). ### Qualification report -`ConsumerJasmine-file-services` (all engines) checks that files reach the page as `File` objects, that `accept` and -`webkitdirectory` are honoured, and that offering a generated Blob leaves the page and the bridge working. +`ConsumerJasmine-file-services` (all engines) checks that files reach the page as `File` objects, that the `accept` and +`webkitdirectory` properties keep their values (filtering and directory selection themselves are not exercised), and that offering a generated Blob leaves the page and the bridge working. `WebKitGTKAdapter-download|choose-file|cancel-choose` and `CEFFileServices-download|choose|cancel` drive the dialog and the download through the injection points. Every scenario captures its final state with WebFront's own window capture (`QualificationEvidence.hpp`, `ConsumerJasmine` captures). In CI each platform job retains a `qualification-` diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index cb489f4d..5c2f5ba7 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -289,7 +289,11 @@ struct Session { WKWebViewOptions options; webfront::detail::BoundContentPolicy contentPolicy; std::function navigationCancelled; - std::map downloadDestinations; // WKDownload -> destination, until it finishes. + struct PendingDownload { + std::string temporary; // Where WKDownload writes: it needs a file that does not exist yet. + std::string target; // Where the user wants it; differs from `temporary` when "Replace" was chosen. + }; + std::map downloadDestinations; // WKDownload -> its paths, until it ends. id app = nullptr, window = nullptr, view = nullptr, delegate = nullptr, timer = nullptr; id previousDelegate = nullptr, previousMenu = nullptr; long previousActivationPolicy = 0; @@ -564,7 +568,7 @@ struct Session { guard([&] { if (!options.downloadDirectory.empty()) { const auto destination = frontend::detail::uniqueDownloadPath(options.downloadDirectory, suggested); - downloadDestinations[download] = destination.string(); + downloadDestinations[download] = {destination.string(), destination.string()}; Object path(text(destination.string())); result = send(type("NSURL"), "fileURLWithPath:", path.get()); return; @@ -574,10 +578,20 @@ struct Session { send(panel, "setNameFieldStringValue:", name.get()); auto handler = Block_copy(completion); void (^finished)(long) = ^(long response) { - id url = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK - if (url) - downloadDestinations[download] = utf8(send(url, "path")); - handler(url); + id chosen = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK + if (chosen) { + // "Replace" returns an existing file, which WKDownload refuses: download beside it, replace when done. + const std::filesystem::path target = utf8(send(chosen, "path")); + std::error_code code; + auto temporary = target; + if (std::filesystem::exists(target, code)) { + temporary = frontend::detail::uniqueDownloadPath(target.parent_path(), target.filename().string() + ".part"); + Object path(text(temporary.string())); + chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); + } + downloadDestinations[download] = {temporary.string(), target.string()}; + } + handler(chosen); Block_release(handler); }; deferred = true; @@ -591,11 +605,18 @@ struct Session { const auto found = downloadDestinations.find(download); if (found == downloadDestinations.end()) return; - const auto destination = std::move(found->second); + const auto pending = std::move(found->second); downloadDestinations.erase(found); + std::error_code code; + if (pending.temporary != pending.target) { + if (completed) + std::filesystem::rename(pending.temporary, pending.target, code); // The old file survives any failure before this. + if (!completed || code) + std::filesystem::remove(pending.temporary, code); + } if (completed && options.downloadFinished) guard([&] { - options.downloadFinished(destination); + options.downloadFinished(pending.target); }); } diff --git a/test/tools/Qualification.py b/test/tools/Qualification.py index b8470356..5f40e0d4 100644 --- a/test/tools/Qualification.py +++ b/test/tools/Qualification.py @@ -114,7 +114,12 @@ def report(args: argparse.Namespace) -> int: row = [name, engine, mark(data["tests"].get(GENERIC[0]))] for scenario in NATIVE: test = native_test(engine, scenario) - row.append(mark(data["tests"].get(test)) if test else "⚪ not injected") + cell = mark(data["tests"].get(test)) if test else "⚪ not injected" + # A scenario can pass while its capture failed: say that the visual evidence is missing. + lost = [n for n in data.get("native", []) if n.get("scenario") == scenario and n.get("capture") != "ok"] + if lost and test and data["tests"].get(test) == "passed": + cell += " (no capture)" + row.append(cell) lines.append("| " + " | ".join(row) + " |") missing = [e for e in ENGINES if not any(d["engine"] == e for _, d in manifests.values())] if missing: diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 6fe85792..f20e0e9c 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -26,7 +26,7 @@ endif() set(TESTS_LIST) list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServerTests.cpp HTTPEncodingTests.cpp GzipExecutorTests.cpp AcceptEncodingTests.cpp GzipTests.cpp ModuleHTTPServerTests.cpp EncodingsTests.cpp WebSocketTests.cpp LoggerTests.cpp MimeTypeTests.cpp) 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) +list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST BroadcastTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationStdioTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp) diff --git a/test/unit/DownloadsTests.cpp b/test/unit/DownloadsTests.cpp new file mode 100644 index 00000000..927732f3 --- /dev/null +++ b/test/unit/DownloadsTests.cpp @@ -0,0 +1,33 @@ +#include +#include + +#include +#include + +using webfront::frontend::detail::uniqueDownloadPath; + +SCENARIO("A download name suggested by a page stays inside the download folder") { + const auto folder = std::filesystem::temp_directory_path() / "webfront-downloads-unit"; + std::filesystem::remove_all(folder); + std::filesystem::create_directories(folder); + GIVEN("names that try to leave the folder or name nothing") { + THEN("only the last component is kept, and an empty name becomes \"download\"") { + REQUIRE(uniqueDownloadPath(folder, "report.txt") == folder / "report.txt"); + REQUIRE(uniqueDownloadPath(folder, "../../etc/passwd") == folder / "passwd"); + REQUIRE(uniqueDownloadPath(folder, "a/b/c.bin") == folder / "c.bin"); + for (const auto* name : {"", ".", "..", "dir/.."}) { + INFO(name); + REQUIRE(uniqueDownloadPath(folder, name) == folder / "download"); + } + } + } + GIVEN("files that already exist") { + std::ofstream(folder / "report.txt") << "1"; + THEN("the name is numbered rather than overwritten") { + REQUIRE(uniqueDownloadPath(folder, "report.txt") == folder / "report (1).txt"); + std::ofstream(folder / "report (1).txt") << "2"; + REQUIRE(uniqueDownloadPath(folder, "report.txt") == folder / "report (2).txt"); + } + } + std::filesystem::remove_all(folder); +} diff --git a/test/unit/WebKitGTKPolicyTests.cpp b/test/unit/WebKitGTKPolicyTests.cpp index aa4267c7..5ddaac76 100644 --- a/test/unit/WebKitGTKPolicyTests.cpp +++ b/test/unit/WebKitGTKPolicyTests.cpp @@ -25,7 +25,8 @@ SCENARIO("WebKitGTK applies navigation policy without toolkit objects") { { PolicyEvent::navigation, "about:blank", false, 0, false, PolicyDecision::allow}, { PolicyEvent::navigation, "about:srcdoc", false, 0, false, PolicyDecision::allow}, { PolicyEvent::navigation, "data:text/html,hello", false, 0, false, PolicyDecision::cancel}, - { PolicyEvent::navigation, "blob:http://127.0.0.1:9002/id", false, 0, false, PolicyDecision::cancel}, + { PolicyEvent::navigation, "blob:http://127.0.0.1:9002/id", false, 0, false, PolicyDecision::allow}, + { PolicyEvent::navigation, "blob:null/id", false, 0, false, PolicyDecision::cancel}, { PolicyEvent::navigation, "file:///etc/passwd", false, 0, false, PolicyDecision::cancel}, { PolicyEvent::navigation, nullptr, false, 0, false, PolicyDecision::cancel}, { PolicyEvent::response, "https://other.example/page", false, 403, true, PolicyDecision::allow}, diff --git a/test/web/WebKitGTKLifecycle.cpp b/test/web/WebKitGTKLifecycle.cpp index 0ee6ec55..a9d24a34 100644 --- a/test/web/WebKitGTKLifecycle.cpp +++ b/test/web/WebKitGTKLifecycle.cpp @@ -155,8 +155,10 @@ struct ScenarioFrontend : Frontend { 100, [](void* data) -> int { auto& probe = *static_cast(data); - if (probe.session.closed) + if (probe.session.closed) { + probe.timer = 0; // Returning 0 removes the source: it must not be removed again. return 0; + } if (probe.finishing) return 1; if (finished(probe.session)) { From 51b268db67dd4adc28695d802ca633f012352661 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:18:33 +0100 Subject: [PATCH 03/18] Remove the qualification report job and fix two WKWebView download cases (#451) Drop the qualification-report job, the evidence collection steps, their artifacts, Qualification.py and QualificationEvidence.hpp; the file-service tests stay. WKWebView creates a configured download folder, and no longer reports a finished download when replacing the target failed. --- .github/workflows/BuildAndTest.yml | 55 -------- docs/CHANGELOG.md | 3 +- docs/FRONTENDS.md | 14 +- docs/adr/ADR-020-services-systeme.md | 3 +- include/webfront/frontend/WKWebView.hpp | 3 + test/tools/Qualification.py | 163 ------------------------ test/web/CEFFileServices.cpp | 22 +--- test/web/CMakeLists.txt | 2 +- test/web/QualificationEvidence.hpp | 46 ------- test/web/WebKitGTKLifecycle.cpp | 23 +--- 10 files changed, 16 insertions(+), 318 deletions(-) delete mode 100644 test/tools/Qualification.py delete mode 100644 test/web/QualificationEvidence.hpp diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index b742203d..73981f0b 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -181,10 +181,6 @@ jobs: Write-Host "WebView2 runtime $version at $($executable.FullName)" } # The fast tier (docs/TEST_TIERS.md): unit tests only, so a plain regression is reported before the browser suite starts. - # The file-service scenarios write their captures here (#451); see test/tools/Qualification.py. - - name: Choose the qualification evidence folder - shell: bash - run: echo "WEBFRONT_QUALIFICATION_DIR=$GITHUB_WORKSPACE/qualification-evidence" >> "$GITHUB_ENV" - name: Fast tests shell: bash run: ctest --test-dir build -C ${{ matrix.build_type }} -L fast --parallel 4 --output-on-failure --no-tests=error @@ -200,17 +196,6 @@ jobs: -DREPEAT=${{ (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master') || (github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests)) && '3' || '1' }} -DLABEL_EXCLUDE=${{ (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master') || (github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests)) && 'none' || 'portability' }} -P test/cmake/RunTestSuite.cmake - - name: Collect the qualification evidence - if: always() - shell: bash - run: python3 test/tools/Qualification.py collect --build build --evidence qualification-evidence --platform ${{ matrix.platform }} --output qualification/${{ matrix.platform }} - - name: Retain the qualification evidence - if: always() - uses: actions/upload-artifact@v4 - with: - name: qualification-${{ matrix.platform }} - path: qualification/${{ matrix.platform }}/ - if-no-files-found: ignore - name: Analyze CTest timings if: always() shell: bash @@ -511,8 +496,6 @@ jobs: sudo ip6tables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT sudo ip6tables -A OUTPUT ! -o lo -j REJECT - name: Run Jasmine bridge test - env: - WEBFRONT_QUALIFICATION_DIR: ${{ github.workspace }}/qualification-evidence run: >- ctest --test-dir ${{github.workspace}}/build-cef -L web-integration --output-on-failure --no-tests=error --parallel 4 --output-junit "${{ github.workspace }}/build-cef/test-results.xml" @@ -521,16 +504,6 @@ jobs: run: | sudo iptables -F OUTPUT sudo ip6tables -F OUTPUT - - name: Collect the qualification evidence - if: always() - run: python3 test/tools/Qualification.py collect --build build-cef --evidence qualification-evidence --platform linux-cef-${{ matrix.compiler }} --output qualification/linux-cef-${{ matrix.compiler }} - - name: Retain the qualification evidence - if: always() - uses: actions/upload-artifact@v4 - with: - name: qualification-linux-cef-${{ matrix.compiler }} - path: qualification/linux-cef-${{ matrix.compiler }}/ - if-no-files-found: ignore - name: Compiler cache statistics if: always() shell: bash @@ -544,31 +517,3 @@ jobs: build-cef/test-results.xml build-cef/Testing/Temporary/LastTest.log if-no-files-found: ignore - - # One document for every platform, built from the captures the jobs above retained (#451). It runs even when a job failed: - # a failing or missing platform is then written into the report instead of being left out. - qualification-report: - needs: [desktop, desktop-native, web-integration] - if: ${{ !cancelled() }} - runs-on: ubuntu-24.04 - timeout-minutes: 10 - steps: - - uses: actions/checkout@v7 - - uses: actions/download-artifact@v4 - with: - pattern: qualification-* - path: qualification-input - - name: Assemble the qualification document - shell: bash - run: | - # Each artifact holds one platform's folder; give it that platform's name. - for directory in qualification-input/qualification-*; do - [ -d "$directory" ] && mv "$directory" "qualification-input/${directory#qualification-input/qualification-}" - done - python3 test/tools/Qualification.py report --input qualification-input --output qualification-report/QUALIFICATION.md - # The summary cannot serve the artifact's images: show the tables only and point to the artifact. - { grep -v '^!\[' qualification-report/QUALIFICATION.md; echo; echo "The captures are in the \`qualification-report\` artifact of this run."; } >> "$GITHUB_STEP_SUMMARY" - - uses: actions/upload-artifact@v4 - with: - name: qualification-report - path: qualification-report/ diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 13641d83..2218d555 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6,8 +6,7 @@ download folder (name reduced to its last component, never overwritten); WKWebView gets `runOpenPanelWithParameters` and `WKDownload` (not yet run on a Mac); CEF and WebView2 use the engine's own handling. A `blob:` URL of an admitted origin now passes the navigation policy, so a generated Blob can be downloaded. Test injection points answer the chooser and the - download without a dialog; CI builds a per-platform qualification report with window captures - (`test/tools/Qualification.py`, `docs/FRONTENDS.md`). + download without a dialog (`docs/FRONTENDS.md`). - Developer environment: the distribution is served from `https://dist.webfront.fr/` (#478, ADR-021). The sources advance to 0.6.5, the first version published under that address; `site.mjs` writes the `CNAME` file of the Pages branch and `wf run pin` diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 8b389b99..24a2dae7 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -58,20 +58,16 @@ admitted origin passes the navigation policy (`webfront::detail::blobOriginUrl`) | WKWebView | `runOpenPanelWithParameters` shows an `NSOpenPanel` sheet of the window; only frames admitted by the policy | `WKDownload` (macOS 11.3+): a save panel proposes the name | `WKWebViewOptions::chooseFiles`, `downloadDirectory`, `downloadFinished` | | WebView2 | the engine's native chooser | the engine's native download UI | none yet | -WKWebView is written but has not been run on a Mac by its author: the qualification report below is the first check. The +WKWebView is covered by the shared spec below and by its CI job, but its chooser and download have no native scenario yet. The engines require a user gesture to open a chooser, so the native scenarios click with a real pointer event (XTest under Xvfb for WebKitGTK) or a `Runtime.evaluate` with `userGesture` (CEF). -### Qualification report +### Tests `ConsumerJasmine-file-services` (all engines) checks that files reach the page as `File` objects, that the `accept` and -`webkitdirectory` properties keep their values (filtering and directory selection themselves are not exercised), and that offering a generated Blob leaves the page and the bridge working. -`WebKitGTKAdapter-download|choose-file|cancel-choose` and `CEFFileServices-download|choose|cancel` drive the dialog and -the download through the injection points. Every scenario captures its final state with WebFront's own window capture -(`QualificationEvidence.hpp`, `ConsumerJasmine` captures). In CI each platform job retains a `qualification-` -artifact (`test/tools/Qualification.py collect`) and the `qualification-report` job assembles them into -`QUALIFICATION.md` with the images, for Linux (WebKitGTK; CEF on pull requests into `master` and on the weekly run), -Windows (WebView2) and macOS (WKWebView). A platform that did not report is written as missing. +`webkitdirectory` properties keep their values (filtering and directory selection themselves are not exercised), and +that offering a generated Blob leaves the page and the bridge working. `WebKitGTKAdapter-download|choose-file|cancel-choose` +and `CEFFileServices-download|choose|cancel` drive the dialog and the download through the injection points. ## Adding a frontend diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 125a6d5d..585b995a 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -353,8 +353,7 @@ Le code vérifié le 2026-10-31 ne permet pas encore d'implémenter ces règles. | 5 | [#450](https://github.com/ambroise-leclerc/WebFront/issues/450) Intégration native des frontends | [#462](https://github.com/ambroise-leclerc/WebFront/issues/462) exécuteur du thread d'interface, y compris le navigateur système ; [#463](https://github.com/ambroise-leclerc/WebFront/issues/463) fenêtre native et correspondance avec les connexions | backend natif seulement | État de l'étape 1 (#451) : sélecteur et téléchargements qualifiés sous WebKitGTK et CEF (Linux), implémentés sous -WKWebView, laissés au comportement natif sous WebView2 ; le rapport de qualification de la CI (`docs/FRONTENDS.md`) documente -chaque moteur. #452 reste à faire. +WKWebView, laissés au comportement natif sous WebView2 ; `docs/FRONTENDS.md` documente chaque moteur. #452 reste à faire. Après l'étape 4, le premier service (sélecteur HTML, poignées, import et export côté client) fera l'objet de sa propre épique ; les dialogues natifs suivront l'étape 5. `PUT`/`POST` ne sont pas des préalables : les écritures passent par diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 5c2f5ba7..e4b9026c 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -567,6 +567,7 @@ struct Session { bool deferred = false; guard([&] { if (!options.downloadDirectory.empty()) { + std::filesystem::create_directories(options.downloadDirectory); // WebKit needs the folder to exist. const auto destination = frontend::detail::uniqueDownloadPath(options.downloadDirectory, suggested); downloadDestinations[download] = {destination.string(), destination.string()}; Object path(text(destination.string())); @@ -613,6 +614,8 @@ struct Session { std::filesystem::rename(pending.temporary, pending.target, code); // The old file survives any failure before this. if (!completed || code) std::filesystem::remove(pending.temporary, code); + if (code) + completed = false; // The target still holds the old file: this is not a finished download. } if (completed && options.downloadFinished) guard([&] { diff --git a/test/tools/Qualification.py b/test/tools/Qualification.py deleted file mode 100644 index 5f40e0d4..00000000 --- a/test/tools/Qualification.py +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env python3 -"""Qualification report of the file services of the embedded frontends (issue #451). - -Two steps, both pure standard library: - - Qualification.py collect --build DIR --evidence DIR --platform NAME --output DIR - Gathers, on one CI platform, the CTest results of the file-service tests, the captures the specs wrote and the - evidence of the native scenarios (WEBFRONT_QUALIFICATION_DIR) into one folder with a manifest. - - Qualification.py report --input DIR --output FILE - Assembles the manifests of every platform (one sub-folder each) into a Markdown document that embeds the captures. - A platform that did not report, or a scenario nobody ran, is written as such rather than left out. -""" -import argparse -import datetime -import json -import pathlib -import shutil -import sys -import xml.etree.ElementTree as ET - -# Scenario -> (title, what it proves). The CTest names carry the platform-independent part. -GENERIC = ("ConsumerJasmine-file-services", "Files and Blob download offered to the page (File API, ``, `
`)") -NATIVE = { - "choose-file": "``: the chooser answers with a fixture file, the page reads it", - "cancel-choose": "``: cancelling the chooser emits `cancel`, no error", - "download": "`` of a generated Blob lands in the download folder, inside it", -} -NATIVE_TESTS = { # engine -> CTest name pattern of a native scenario - "WebKitGTK": "WebKitGTKAdapter-{}", - "CEF": {"choose-file": "CEFFileServices-choose", "cancel-choose": "CEFFileServices-cancel", "download": "CEFFileServices-download"}, -} -ENGINES = ["WebKitGTK", "CEF", "WKWebView", "WebView2"] -NOT_INJECTED = { - "WKWebView": "chooser and download are implemented (`runOpenPanelWithParameters`, `WKDownloadDelegate`) with a test injection, but no native scenario drives them yet", - "WebView2": "the engine's own chooser and download UI are used; no injection point exists yet", -} - - -def engine_of(platform: str) -> str: - lowered = platform.lower() - for engine in ENGINES: - if engine.lower() in lowered: - return engine - return platform - - -def junit_results(build: pathlib.Path) -> dict[str, str]: - results: dict[str, str] = {} - for path in sorted(build.glob("test-results-*.xml")) + sorted(build.glob("test-results.xml")): - for case in ET.parse(path).getroot().iter("testcase"): - name = case.get("name", "") - if "file-services" not in name and "FileServices" not in name and not name.startswith("WebKitGTKAdapter-"): - continue - if case.find("failure") is not None or case.find("error") is not None: - status = "failed" - elif case.find("skipped") is not None: - status = "skipped" - else: - status = "passed" - # Several passes (repeated runs): any failure wins. - if results.get(name) != "failed": - results[name] = status - return results - - -def collect(args: argparse.Namespace) -> int: - build, out = pathlib.Path(args.build), pathlib.Path(args.output) - out.mkdir(parents=True, exist_ok=True) - manifest = {"platform": args.platform, "engine": engine_of(args.platform), "tests": junit_results(build), "images": []} - sources = [(p, "spec") for p in build.glob("test/web/webfront-jasmine/ConsumerJasmine-file-services/captures/*.png")] - evidence = pathlib.Path(args.evidence) if args.evidence else None - if evidence and evidence.is_dir(): - sources += [(p, "native") for p in evidence.glob("*.png")] - for source, kind in sources: - target = f"{kind}-{source.name}" - shutil.copyfile(source, out / target) - manifest["images"].append({"file": target, "kind": kind, "name": source.stem}) - if evidence and evidence.is_dir(): - manifest["native"] = [json.loads(p.read_text()) for p in sorted(evidence.glob("*.json"))] - (out / "manifest.json").write_text(json.dumps(manifest, indent=2)) - print(f"{args.platform}: {len(manifest['tests'])} results, {len(manifest['images'])} captures") - return 0 - - -def native_test(engine: str, scenario: str): - entry = NATIVE_TESTS.get(engine) - if isinstance(entry, str): - return entry.format(scenario) - return entry.get(scenario) if entry else None - - -def mark(status): - return {"passed": "✅ passed", "failed": "❌ failed", "skipped": "⏭ skipped"}.get(status, "⚪ not run") - - -def report(args: argparse.Namespace) -> int: - root, out = pathlib.Path(args.input), pathlib.Path(args.output) - manifests = {} - for path in sorted(root.glob("*/manifest.json")): - data = json.loads(path.read_text()) - manifests[path.parent.name] = (path.parent, data) - out.parent.mkdir(parents=True, exist_ok=True) - images = out.parent / "images" - images.mkdir(exist_ok=True) - lines = ["# Qualification of the file services of the embedded frontends", "", - f"Generated by CI on {datetime.date.today().isoformat()} from the run's platform artifacts (issue #451). " - "Captures are taken by WebFront's own window capture (`webfront::frontend::capturePng`): web content only, " - "native dialogs are not part of them.", "", - "## Summary", "", "| Platform | Engine | Spec: files and Blob download | " + " | ".join(NATIVE.values()) + " |", - "| --- | --- | --- | " + " | ".join("---" for _ in NATIVE) + " |"] - for name, (_, data) in manifests.items(): - engine = data["engine"] - row = [name, engine, mark(data["tests"].get(GENERIC[0]))] - for scenario in NATIVE: - test = native_test(engine, scenario) - cell = mark(data["tests"].get(test)) if test else "⚪ not injected" - # A scenario can pass while its capture failed: say that the visual evidence is missing. - lost = [n for n in data.get("native", []) if n.get("scenario") == scenario and n.get("capture") != "ok"] - if lost and test and data["tests"].get(test) == "passed": - cell += " (no capture)" - row.append(cell) - lines.append("| " + " | ".join(row) + " |") - missing = [e for e in ENGINES if not any(d["engine"] == e for _, d in manifests.values())] - if missing: - lines += ["", "No report from: " + ", ".join(missing) + " (the job did not run in this workflow, or failed before reporting)."] - lines += ["", "## Limits by engine", ""] - for engine, reason in NOT_INJECTED.items(): - lines.append(f"- **{engine}**: {reason}.") - lines.append("- **CEF** (Chrome runtime) and **WebKitGTK**: native dialog and download handling, plus a test injection answering without a dialog.") - for name, (folder, data) in manifests.items(): - lines += ["", f"## {name} ({data['engine']})", ""] - for image in data["images"]: - shutil.copyfile(folder / image["file"], images / f"{name}-{image['file']}") - lines += [f"**{image['name']}** ({'spec capture' if image['kind'] == 'spec' else 'native scenario'})", "", - f"![{name} {image['name']}](images/{name}-{image['file']})", ""] - if not data["images"]: - lines.append("No capture was produced.") - failed = [t for t, s in data["tests"].items() if s == "failed"] - if failed: - lines += ["", "Failed: " + ", ".join(f"`{t}`" for t in failed)] - out.write_text("\n".join(lines) + "\n") - print(f"wrote {out} ({len(manifests)} platforms)") - return 0 - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - sub = parser.add_subparsers(dest="command", required=True) - c = sub.add_parser("collect") - c.add_argument("--build", required=True) - c.add_argument("--evidence") - c.add_argument("--platform", required=True) - c.add_argument("--output", required=True) - r = sub.add_parser("report") - r.add_argument("--input", required=True) - r.add_argument("--output", required=True) - args = parser.parse_args() - return collect(args) if args.command == "collect" else report(args) - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/test/web/CEFFileServices.cpp b/test/web/CEFFileServices.cpp index 57f5dd0d..eb2aebf8 100644 --- a/test/web/CEFFileServices.cpp +++ b/test/web/CEFFileServices.cpp @@ -1,6 +1,5 @@ // Qualification of and downloads in the CEF frontend (issue #451): the chooser is answered by the // client's injection point and opened by a real mouse click sent to the engine; the download goes to a private folder. -#include "QualificationEvidence.hpp" #include #include #include @@ -26,8 +25,7 @@ struct Scenario { std::string downloaded; bool asked = false; }; -Scenario scenario; -webfront::testing::QualificationEvidence evidence; +Scenario scenario; class Client : public webfront::cef::SimpleCEFClient { public: @@ -59,31 +57,16 @@ class Client : public webfront::cef::SimpleCEFClient { if (window) window->GetHost()->CloseBrowser(true); } - /// Captures the final state with WebFront's own capture, then closes the window on the UI thread. void finish() { if (finishing) return; finishing = true; - evidence.capture("CEF", - scenario.mode == "choose" ? "choose-file" - : scenario.mode == "cancel" ? "cancel-choose" - : "download", - [this] { - CefPostTask(TID_UI, new Close(this)); - }); + close(); } private: CefRefPtr window; bool finishing = false; - struct Close : CefTask { - explicit Close(Client* owner) : client(owner) {} - void Execute() override { - client->close(); - } - CefRefPtr client; - IMPLEMENT_REFCOUNTING(Close); - }; public: void clickChooser() { @@ -159,7 +142,6 @@ int main(int argc, char** argv) { require(scenario.title == (scenario.mode == "choose" ? "picked:chosen by the test" : "cancelled"), ("Unexpected page state: " + scenario.title).c_str()); } - evidence = {}; std::filesystem::remove_all(scenario.folder); return 0; } catch (const std::exception& error) { diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 1b2e1e71..2aa56e02 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -182,7 +182,7 @@ if(_browser_tests_available) FRONTEND "${WEBFRONT_WEBTEST_FRONTEND}" TIMEOUT 30 SPECS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer/capture.spec.js" ARGS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer") - # File services of the engine (issue #451), with captures as evidence for the qualification report. + # File services of the engine (issue #451), shared by every embedded frontend. webfront_add_jasmine_test(NAME ConsumerJasmine-file-services TARGET jasmine_consumer FRONTEND "${WEBFRONT_WEBTEST_FRONTEND}" TIMEOUT 30 SPECS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer/file-services.spec.js" diff --git a/test/web/QualificationEvidence.hpp b/test/web/QualificationEvidence.hpp deleted file mode 100644 index d696b4b7..00000000 --- a/test/web/QualificationEvidence.hpp +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -// Evidence of a qualification scenario (issue #451): when WEBFRONT_QUALIFICATION_DIR is set, the scenario's final state is -// captured with WebFront's own window capture and recorded next to a JSON result. test/tools/Qualification.py gathers them. -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace webfront::testing { - -class QualificationEvidence { -public: - /// Captures the window (from a worker thread: the event loop keeps running), then calls `then` from that thread. - void capture(const std::string& engine, const std::string& scenario, std::function then) { - const char* directory = std::getenv("WEBFRONT_QUALIFICATION_DIR"); - if (!directory || !*directory) { - then(); - return; - } - worker = std::jthread([=, this] { - const std::filesystem::path folder{directory}; - std::filesystem::create_directories(folder); - const auto result = frontend::capturePng(std::chrono::seconds{10}); - std::string image; - if (result) { - image = scenario + ".png"; - std::ofstream(folder / image, std::ios::binary) - .write(reinterpret_cast(result->data()), static_cast(result->size())); - } - std::ofstream(folder / (scenario + ".json")) << "{\"engine\":\"" << engine << "\",\"scenario\":\"" << scenario << "\",\"image\":\"" << image - << "\",\"capture\":\"" << (result ? "ok" : "failed") << "\"}\n"; - then(); - }); - } - -private: - std::jthread worker; -}; - -} // namespace webfront::testing diff --git a/test/web/WebKitGTKLifecycle.cpp b/test/web/WebKitGTKLifecycle.cpp index a9d24a34..b8e3c918 100644 --- a/test/web/WebKitGTKLifecycle.cpp +++ b/test/web/WebKitGTKLifecycle.cpp @@ -1,5 +1,3 @@ -#include "QualificationEvidence.hpp" - #include #include @@ -135,8 +133,7 @@ void nativeClose() { /// Runs a page of the test folder in a session configured by the scenario, for at most `seconds`. struct ScenarioFrontend : Frontend { static inline std::function configure; - static inline std::function finished; // Polled; true captures the evidence, then closes the window. - static inline std::string name; // The scenario, for the qualification evidence. + static inline std::function finished; // Polled; true closes the window. static void open(std::string_view port, std::string_view page) { open("127.0.0.1", port, page, {}); } @@ -148,9 +145,7 @@ struct ScenarioFrontend : Frontend { gtk::Session& session; int remaining = 150; // 15 s unsigned timer = 0; - bool finishing = false; - webfront::testing::QualificationEvidence evidence; - } poll{session, 150, 0, false, {}}; + } poll{session, 150, 0}; poll.timer = session.a.timeoutAdd( 100, [](void* data) -> int { @@ -159,16 +154,7 @@ struct ScenarioFrontend : Frontend { probe.timer = 0; // Returning 0 removes the source: it must not be removed again. return 0; } - if (probe.finishing) - return 1; - if (finished(probe.session)) { - probe.finishing = true; - probe.evidence.capture("WebKitGTK", name, [&probe] { - probe.session.close(); - }); - return 1; - } - if (--probe.remaining == 0) { + if (finished(probe.session) || --probe.remaining == 0) { probe.timer = 0; probe.session.close(); return 0; @@ -177,7 +163,6 @@ struct ScenarioFrontend : Frontend { }, &poll); session.run(webfront::frontend::detail::applicationUrl(address, port, page)); - poll.evidence = {}; // Joins the capture thread before the session goes away. if (poll.timer) session.a.sourceRemove(poll.timer); } @@ -196,7 +181,6 @@ void download() { std::filesystem::create_directories(folder); std::string destination; bool done = false; - ScenarioFrontend::name = "download"; ScenarioFrontend::configure = [&](gtk::Session& session) { session.downloadDirectory = folder; session.downloadFinished = [&](const std::string& path) { @@ -248,7 +232,6 @@ void chooseFile(bool cancel) { const auto fixture = std::filesystem::temp_directory_path() / ("webfront-chooser-" + std::to_string(getpid()) + ".txt"); std::ofstream(fixture) << "chosen by the test"; bool asked = false; - ScenarioFrontend::name = cancel ? "cancel-choose" : "choose-file"; ScenarioFrontend::configure = [&](gtk::Session& session) { session.chooseFiles = [&]() -> std::vector { asked = true; From 839b8fb73efabe54b07cb3993f60ff9713eda4fb Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:20:55 +0100 Subject: [PATCH 04/18] Keep a replaced download's outcome, resolve the download folder with GLib, pick folders only for webkitdirectory (#451) --- include/webfront/frontend/WKWebView.hpp | 18 +++++++++++------- include/webfront/frontend/WebKitGTK.hpp | 6 ++++-- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index e4b9026c..0312d47d 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -547,8 +547,10 @@ struct Session { } const auto panel = send(type("NSOpenPanel"), "openPanel"); send(panel, "setAllowsMultipleSelection:", send(parameters, "allowsMultipleSelection")); - send(panel, "setCanChooseDirectories:", send(parameters, "allowsDirectories")); - send(panel, "setCanChooseFiles:", static_cast(true)); + // chooses a folder, and only a folder. + const auto directories = send(parameters, "allowsDirectories"); + send(panel, "setCanChooseDirectories:", directories); + send(panel, "setCanChooseFiles:", static_cast(!directories)); auto handler = Block_copy(completion); void (^finished)(long) = ^(long response) { handler(response == 1 ? send(panel, "URLs") : nullptr); // NSModalResponseOK @@ -608,14 +610,16 @@ struct Session { return; const auto pending = std::move(found->second); downloadDestinations.erase(found); - std::error_code code; if (pending.temporary != pending.target) { + std::error_code replaced; if (completed) - std::filesystem::rename(pending.temporary, pending.target, code); // The old file survives any failure before this. - if (!completed || code) - std::filesystem::remove(pending.temporary, code); - if (code) + std::filesystem::rename(pending.temporary, pending.target, replaced); // The old file survives any failure before this. + if (replaced) completed = false; // The target still holds the old file: this is not a finished download. + if (!completed) { + std::error_code cleanup; // Its own code: cleaning up must not hide the outcome of the replacement. + std::filesystem::remove(pending.temporary, cleanup); + } } if (completed && options.downloadFinished) guard([&] { diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 5ce2f730..15fd8124 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -115,6 +115,8 @@ class Api { const void* (*bytesData)(Object, std::size_t*) = symbol("g_bytes_get_data"); void (*bytesUnref)(Object) = symbol("g_bytes_unref"); void (*errorFree)(Error*) = symbol("g_error_free"); + // GLib resolves the folder from user-dirs.dirs (a user may have moved it), not only from the environment. + const char* (*userDirectory)(int) = symbol("g_get_user_special_dir"); // G_USER_DIRECTORY_DOWNLOAD = 2 void (*downloadDestination)(Object, const char*) = symbol("webkit_download_set_destination"); void (*downloadCancel)(Object) = symbol("webkit_download_cancel"); const char* (*downloadGetDestination)(Object) = symbol("webkit_download_get_destination"); @@ -419,8 +421,8 @@ struct Session : FailureState { std::filesystem::path destinationFolder() const { if (!downloadDirectory.empty()) return downloadDirectory; - if (const auto* xdg = std::getenv("XDG_DOWNLOAD_DIR"); xdg && *xdg) - return xdg; + if (const auto* folder = a.userDirectory(2); folder && *folder) + return folder; if (const auto* home = std::getenv("HOME"); home && *home) { std::error_code error; const auto folder = std::filesystem::path(home) / "Downloads"; From 7194ca61e5686ad92e26a75dda2309749262e364 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 2 Nov 2026 18:14:50 +0100 Subject: [PATCH 05/18] Qualify WebView2 file services on Windows --- cmake/WebView2Support.cmake | 3 +- docs/CHANGELOG.md | 3 +- docs/FRONTENDS.md | 9 +- include/webfront/testing/Process.hpp | 2 + test/web/WebView2Lifecycle.cpp | 166 ++++++++++++++++++++++++++- test/web/host/HostProbe.cpp | 4 +- 6 files changed, 179 insertions(+), 8 deletions(-) diff --git a/cmake/WebView2Support.cmake b/cmake/WebView2Support.cmake index b969378f..7725049b 100644 --- a/cmake/WebView2Support.cmake +++ b/cmake/WebView2Support.cmake @@ -65,7 +65,8 @@ function(webfront_add_webview2_tests) "${webtest_source_dir}/WebView2HeaderConsumer.cpp") target_link_libraries(webview2_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) foreach(mode repeated-show native-early-close navigation-diagnostic mta missing-runtime - closed-startup-timeout failed-startup-timeout late-navigation-failure runtime-ready) + closed-startup-timeout failed-startup-timeout late-navigation-failure runtime-ready + file-choose file-cancel file-download) add_test(NAME WebView2Lifecycle-${mode} COMMAND webview2_lifecycle ${mode}) webfront_set_browser_test_properties("WebView2Lifecycle-${mode}" "${webtest_source_dir}" 45) endforeach() diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 2218d555..3df85696 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6,7 +6,8 @@ download folder (name reduced to its last component, never overwritten); WKWebView gets `runOpenPanelWithParameters` and `WKDownload` (not yet run on a Mac); CEF and WebView2 use the engine's own handling. A `blob:` URL of an admitted origin now passes the navigation policy, so a generated Blob can be downloaded. Test injection points answer the chooser and the - download without a dialog (`docs/FRONTENDS.md`). + download without a dialog (`docs/FRONTENDS.md`). On Windows, WebView2 tests exercise chooser selection and cancellation + through DevTools and verify completed downloads on disk; the native dialog UI itself remains unqualified. - Developer environment: the distribution is served from `https://dist.webfront.fr/` (#478, ADR-021). The sources advance to 0.6.5, the first version published under that address; `site.mjs` writes the `CNAME` file of the Pages branch and `wf run pin` diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 24a2dae7..c82d8b34 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -47,8 +47,8 @@ initialization, frontend selection and unavailable-engine diagnostics. These tes ## File chooser and downloads -`` (single, multiple, `accept`, `webkitdirectory`) and downloads (``, generated `blob:` URLs) -work in every embedded frontend with the engine's own dialog, without a WebFront API (ADR-020, rule 6). A `blob:` URL of an +The embedded frontends use their engine's file chooser and download handling without a WebFront API (ADR-020, rule 6). +Coverage varies by engine and does not yet qualify all native dialogs, `accept` filters or directory selection. A `blob:` URL of an admitted origin passes the navigation policy (`webfront::detail::blobOriginUrl`); a `blob:` URL of any other origin does not. | Frontend | Chooser | Download | Test injection | @@ -56,7 +56,7 @@ admitted origin passes the navigation policy (`webfront::detail::blobOriginUrl`) | WebKitGTK | default `run-file-chooser` dialog (portal under Flatpak) | `download-started` / `decide-destination`: the user's XDG download folder, the page's name reduced to its last component, never overwriting (`name (1).ext`) | `Session::chooseFiles`, `downloadDirectory`, `downloadFinished` | | CEF (Chrome runtime) | the runtime's dialog | the runtime's download handling | `SimpleCEFClient::chooseFiles` (`CefDialogHandler::OnFileDialog`), `downloadDirectory`, `downloadFinished`. The runtime itself turns a suggested name `../x` into `_x` | | WKWebView | `runOpenPanelWithParameters` shows an `NSOpenPanel` sheet of the window; only frames admitted by the policy | `WKDownload` (macOS 11.3+): a save panel proposes the name | `WKWebViewOptions::chooseFiles`, `downloadDirectory`, `downloadFinished` | -| WebView2 | the engine's native chooser | the engine's native download UI | none yet | +| WebView2 | the engine's native chooser | the engine's native download UI | DevTools intercepts the chooser in tests; `DownloadStarting` redirects the download to a private path | WKWebView is covered by the shared spec below and by its CI job, but its chooser and download have no native scenario yet. The engines require a user gesture to open a chooser, so the native scenarios click with a real pointer event (XTest under @@ -68,6 +68,9 @@ Xvfb for WebKitGTK) or a `Runtime.evaluate` with `userGesture` (CEF). `webkitdirectory` properties keep their values (filtering and directory selection themselves are not exercised), and that offering a generated Blob leaves the page and the bridge working. `WebKitGTKAdapter-download|choose-file|cancel-choose` and `CEFFileServices-download|choose|cancel` drive the dialog and the download through the injection points. +`WebView2Lifecycle-file-choose|file-cancel|file-download` verifies the engine's chooser request, selection and cancellation +events, and the bytes written by a completed Blob download. It intercepts the chooser with DevTools and suppresses the download UI, +so it does not qualify the native dialogs themselves or closing the window while one is open. ## Adding a frontend diff --git a/include/webfront/testing/Process.hpp b/include/webfront/testing/Process.hpp index 87ea73a1..56edd0df 100644 --- a/include/webfront/testing/Process.hpp +++ b/include/webfront/testing/Process.hpp @@ -245,6 +245,8 @@ inline ProcessResult runProcessWindows(const ProcessSpec& spec, const std::atomi HANDLE inherited[3] = {input.handle, outWrite.handle, errWrite.handle}; SIZE_T attributeSize = 0; ::InitializeProcThreadAttributeList(nullptr, 1, 0, &attributeSize); + if (attributeSize == 0) + throw std::runtime_error("Cannot determine the process attribute size"); std::vector attributeStorage(attributeSize); auto* attributes = reinterpret_cast(attributeStorage.data()); if (!::InitializeProcThreadAttributeList(attributes, 1, 0, &attributeSize)) diff --git a/test/web/WebView2Lifecycle.cpp b/test/web/WebView2Lifecycle.cpp index 0cec7fa2..095d56a8 100644 --- a/test/web/WebView2Lifecycle.cpp +++ b/test/web/WebView2Lifecycle.cpp @@ -1,12 +1,15 @@ #include "../driver/TestFrontend.hpp" #include +#include #include #include #include #include +#include #include #include +#include #include #include #include @@ -200,6 +203,155 @@ int lateNavigationFailure() { return observed ? 0 : 1; } +// Exercise the engine's chooser and download paths. DevTools supplies the chooser answer because +// WebView2 exposes no file-dialog callback; DownloadStarting supplies a private destination. +int fileServices(std::string_view mode) { + using namespace webfront::frontend::detail::webview2; + const auto folder = std::filesystem::temp_directory_path() + / ("webfront-webview2-files-" + std::to_string(GetCurrentProcessId()) + "-" + + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + require(std::filesystem::create_directory(folder), "Cannot create private test directory"); + struct Cleanup { + std::filesystem::path path; + ~Cleanup() { + std::error_code error; + std::filesystem::remove_all(path, error); + } + } cleanup{folder}; + const auto fixture = folder / "fixture.txt"; + std::ofstream(fixture) << "chosen by the test"; + const auto destination = folder / "result.txt"; + + webfront::http::Server server("127.0.0.1", "9002", std::filesystem::current_path()); + std::jthread worker([&](std::stop_token stop) { + std::stop_callback cleanupServer(stop, [&] { + server.stop(); + }); + server.run(); + }); + Apartment apartment; + auto session = std::make_shared(); + session->url = mode == "download" ? L"http://127.0.0.1:9002/file-services.html?download" : L"http://127.0.0.1:9002/file-services.html?choose"; + session->contentPolicy = webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002", {}}; + session->createWindow(webfront::testdriver::diagnosticWindows()); + Actions actions; + actions.onFailure = [&] { + session->fail(); + }; + bool ready = false, interceptRequested = false, clicked = false, asked = false, finished = false; + Microsoft::WRL::ComPtr download; + Microsoft::WRL::ComPtr chooser; + session->viewReady = [&] { + EventRegistrationToken token{}; + if (mode == "download") { + Microsoft::WRL::ComPtr view4; + check(session->view.As(&view4), "querying download support"); + check(view4->add_DownloadStarting( + Microsoft::WRL::Callback([&](ICoreWebView2*, + ICoreWebView2DownloadStartingEventArgs* args) -> HRESULT { + try { + check(args->get_DownloadOperation(&download), "getting download operation"); + check(args->put_ResultFilePath(destination.c_str()), "setting download destination"); + check(args->put_Handled(TRUE), "suppressing download UI"); + } catch (...) { + session->fail(); + } + return S_OK; + }).Get(), + &token), + "registering download handler"); + ready = true; + return; + } + check(session->view->GetDevToolsProtocolEventReceiver(L"Page.fileChooserOpened", &chooser), "getting chooser event"); + check(chooser->add_DevToolsProtocolEventReceived( + Microsoft::WRL::Callback( + [&](ICoreWebView2*, ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT { + try { + LPWSTR raw = nullptr; + check(args->get_ParameterObjectAsJson(&raw), "reading chooser event"); + const std::unique_ptr json(raw, CoTaskMemFree); + std::wcmatch match; + require(std::regex_search(json.get(), match, std::wregex(L"\\\"backendNodeId\\\"\\s*:\\s*(\\d+)")), + "Chooser event has no input node"); + asked = true; + if (mode == "cancel") + return S_OK; // The interception was configured to cancel and emit the page's cancel event. + const auto files = webfront::json::quote(utf8(fixture.c_str())); + const auto parameters = utf16("{\"backendNodeId\":" + utf8(match[1].str()) + ",\"files\":[" + files + "]}"); + check(session->view->CallDevToolsProtocolMethod(L"DOM.setFileInputFiles", parameters.c_str(), nullptr), "answering chooser"); + } catch (...) { + session->fail(); + } + return S_OK; + }) + .Get(), + &token), + "registering chooser handler"); + }; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{30}; + actions.dispatch = [&](UINT) { + if (std::chrono::steady_clock::now() >= deadline) + throw std::runtime_error("File service scenario timed out: ready=" + std::to_string(ready) + " clicked=" + std::to_string(clicked) + + " asked=" + std::to_string(asked) + " loading=" + std::to_string(session->loadingInitialPage())); + if (!session->view || session->loadingInitialPage()) + return; + if (mode != "download" && !interceptRequested) { + interceptRequested = true; + check(session->view->CallDevToolsProtocolMethod(L"Page.enable", L"{}", nullptr), "enabling page events"); + const auto parameters = mode == "cancel" ? L"{\"enabled\":true,\"cancel\":true}" : L"{\"enabled\":true}"; + check(session->view->CallDevToolsProtocolMethod( + L"Page.setInterceptFileChooserDialog", + parameters, + Microsoft::WRL::Callback([&](HRESULT result, LPCWSTR) -> HRESULT { + try { + check(result, "enabling chooser interception"); + ready = true; + } catch (...) { + session->fail(); + } + return S_OK; + }).Get()), + "enabling chooser interception"); + } + if (!ready) + return; + if (mode == "download") { + if (!download) + return; + COREWEBVIEW2_DOWNLOAD_STATE state{}; + check(download->get_State(&state), "reading download state"); + require(state != COREWEBVIEW2_DOWNLOAD_STATE_INTERRUPTED, "Download was interrupted"); + finished = state == COREWEBVIEW2_DOWNLOAD_STATE_COMPLETED; + } else { + if (!clicked) { + clicked = true; + check(session->view->CallDevToolsProtocolMethod(L"Runtime.evaluate", + L"{\"expression\":\"document.getElementById('picker').click()\",\"userGesture\":true}", + nullptr), + "opening chooser"); + } + LPWSTR raw = nullptr; + check(session->view->get_DocumentTitle(&raw), "reading page result"); + const std::unique_ptr title(raw, CoTaskMemFree); + finished = asked && std::wstring_view(title.get()) == (mode == "choose" ? L"picked:chosen by the test" : L"cancelled"); + } + if (finished) + PostMessageW(session->window, WM_CLOSE, 0, 0); + }; + require(SetTimer(actions.window, 1, 20, nullptr) != 0, "Cannot start file service watchdog"); + session->start(userDataFolder()); + session->run(); + if (actions.failure) + std::rethrow_exception(actions.failure); + require(finished, "File service did not finish"); + if (mode == "download") { + std::ifstream stream(destination, std::ios::binary); + require(std::string(std::istreambuf_iterator(stream), {}) == "downloaded by WebFront", "Wrong downloaded content"); + } + return 0; +} + int rejectMta() { if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return 1; @@ -354,7 +506,19 @@ int run(std::string_view mode) { if (!webView2ClosesServer()) return 1; const std::map> cases{ - { "runtime-ready",runtimeReadyBeforePageLoad }, + { "file-choose", + [] { + return fileServices("choose"); + } }, + { "file-cancel", + [] { + return fileServices("cancel"); + } }, + { "file-download", + [] { + return fileServices("download"); + } }, + { "runtime-ready", runtimeReadyBeforePageLoad}, { "closed-startup-timeout", [] { return startupCompletion(false); diff --git a/test/web/host/HostProbe.cpp b/test/web/host/HostProbe.cpp index 70617d91..93234505 100644 --- a/test/web/host/HostProbe.cpp +++ b/test/web/host/HostProbe.cpp @@ -93,8 +93,8 @@ void startAgain(const char* self, const char* mode, const char* argument) { int main(int argc, char** argv) { #ifdef _WIN32 // Text mode would turn each '\n' into "\r\n": the tests compare bytes. - _setmode(_fileno(stdout), _O_BINARY); - _setmode(_fileno(stderr), _O_BINARY); + if (_setmode(_fileno(stdout), _O_BINARY) == -1 || _setmode(_fileno(stderr), _O_BINARY) == -1) + return 1; std::vector utf8Arguments; std::vector utf8Pointers; { From 6436a53b9b35c8eaf00c18b7e2117029040e7d06 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 2 Nov 2026 18:19:50 +0100 Subject: [PATCH 06/18] Avoid GCC warning in CEF download verification --- test/web/CEFFileServices.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/test/web/CEFFileServices.cpp b/test/web/CEFFileServices.cpp index eb2aebf8..531b22d7 100644 --- a/test/web/CEFFileServices.cpp +++ b/test/web/CEFFileServices.cpp @@ -6,8 +6,8 @@ #include #include -#include #include +#include #include @@ -136,7 +136,12 @@ int main(int argc, char** argv) { ("The download left its folder: " + scenario.downloaded).c_str()); require(std::filesystem::path(scenario.downloaded).filename().string().ends_with("webfront-download.txt"), "The download lost its name"); std::ifstream stream(scenario.downloaded, std::ios::binary); - require(std::string(std::istreambuf_iterator(stream), {}) == "downloaded by WebFront", "The downloaded file has the wrong content"); + require(stream.is_open(), "The downloaded file could not be opened"); + constexpr std::string_view expected = "downloaded by WebFront"; + std::string contents(expected.size() + 1, '\0'); + stream.read(contents.data(), static_cast(contents.size())); + contents.resize(static_cast(stream.gcount())); + require(contents == expected, "The downloaded file has the wrong content"); } else { require(scenario.asked, ("The file chooser was not requested; title=" + scenario.title).c_str()); require(scenario.title == (scenario.mode == "choose" ? "picked:chosen by the test" : "cancelled"), From 11e8bcc156039fb147b879c71243f6cafe291bd6 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 2 Nov 2026 21:15:25 +0100 Subject: [PATCH 07/18] Qualify WKWebView file services on macOS Native scenarios for the download of a generated Blob, the file chooser (selection and cancellation) and the replace-on-success logic of a download, using the WKWebViewOptions test injections. --- cmake/WKWebViewSupport.cmake | 2 +- docs/FRONTENDS.md | 9 +- test/web/WKWebViewLifecycle.cpp | 149 +++++++++++++++++++++++++++++++- 3 files changed, 155 insertions(+), 5 deletions(-) diff --git a/cmake/WKWebViewSupport.cmake b/cmake/WKWebViewSupport.cmake index a95d70ad..66899603 100644 --- a/cmake/WKWebViewSupport.cmake +++ b/cmake/WKWebViewSupport.cmake @@ -18,7 +18,7 @@ function(webfront_add_wkwebview_tests) add_executable(wkwebview_lifecycle "${webtest_source_dir}/WKWebViewLifecycle.cpp" "${webtest_source_dir}/WKWebViewHeaderConsumer.cpp") target_link_libraries(wkwebview_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) - foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings redirect-policy missing-response committed-navigation agent-application) + foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download) add_test(NAME WKWebViewLifecycle-${mode} COMMAND wkwebview_lifecycle ${mode}) webfront_set_browser_test_properties("WKWebViewLifecycle-${mode}" "${webtest_source_dir}" 90) endforeach() diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index c82d8b34..5f5be6e0 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -58,9 +58,12 @@ admitted origin passes the navigation policy (`webfront::detail::blobOriginUrl`) | WKWebView | `runOpenPanelWithParameters` shows an `NSOpenPanel` sheet of the window; only frames admitted by the policy | `WKDownload` (macOS 11.3+): a save panel proposes the name | `WKWebViewOptions::chooseFiles`, `downloadDirectory`, `downloadFinished` | | WebView2 | the engine's native chooser | the engine's native download UI | DevTools intercepts the chooser in tests; `DownloadStarting` redirects the download to a private path | -WKWebView is covered by the shared spec below and by its CI job, but its chooser and download have no native scenario yet. The -engines require a user gesture to open a chooser, so the native scenarios click with a real pointer event (XTest under -Xvfb for WebKitGTK) or a `Runtime.evaluate` with `userGesture` (CEF). +The engines require a user gesture to open a chooser, so the native scenarios click with a real pointer event (XTest under +Xvfb for WebKitGTK), a `Runtime.evaluate` with `userGesture` (CEF) or `evaluateJavaScript`, which WebKit treats as a user +gesture (WKWebView). The WKWebView scenarios (`WKWebViewLifecycle-download`, `-choose-file`, `-cancel-choose`, +`-replaced-download`) use the test injections of `WKWebViewOptions`: they qualify the delegate wiring, the blob download +policy, the destination handling and the replace-on-success logic, not the system `NSOpenPanel`/`NSSavePanel` themselves. +WebKit reduces a suggested name such as `../x.txt` to `_x.txt` before the frontend sees it. ### Tests diff --git a/test/web/WKWebViewLifecycle.cpp b/test/web/WKWebViewLifecycle.cpp index 96dd00fd..4245b0a9 100644 --- a/test/web/WKWebViewLifecycle.cpp +++ b/test/web/WKWebViewLifecycle.cpp @@ -1,10 +1,15 @@ #include "../driver/TestFrontend.hpp" #include +#include +#include +#include #include #include +#include #include #include +#include #include #include @@ -268,6 +273,144 @@ void agentApplication() { require(send(app, "activationPolicy") == previousPolicy, "Session did not restore the host activation policy"); } +std::string readFile(const std::filesystem::path& path) { + std::ifstream stream(path, std::ios::binary); + return {std::istreambuf_iterator(stream), {}}; +} + +/// Opens a page with the file-service test injections of WKWebViewOptions, which a scenario fills in before show(). +struct ScenarioFrontend : Frontend { + static inline std::function configure; + static inline std::function started; + + static void open(std::string_view port, std::string_view page) { + initialize(); + Object pool(send(type("NSAutoreleasePool"), "new")); + webfront::frontend::WKWebViewOptions options{.visible = webfront::testdriver::diagnosticWindows()}; + if (configure) + configure(options); + Session session(webfront::frontend::detail::applicationUrl("127.0.0.1", port, page), options); + session.create(); + session.start(); + if (started) + started(session); + session.run(); + } +}; +using ScenarioApp = webfront::WebFrontWithFrontend; + +/// Ends the AppKit loop from a native callback, as the Quit menu item does. +void quitApplication() { + send(send(type("NSApplication"), "sharedApplication"), "terminate:", static_cast(nullptr)); +} + +void resetScenario() { + ScenarioFrontend::configure = nullptr; + ScenarioFrontend::started = nullptr; +} + +void download() { + const auto folder = std::filesystem::temp_directory_path() / ("webfront-wk-download-" + std::to_string(getpid())); + std::filesystem::remove_all(folder); + std::string destination; + bool done = false; + ScenarioFrontend::configure = [&](webfront::frontend::WKWebViewOptions& options) { + options.downloadDirectory = folder; // Created by the frontend when the download starts. + options.downloadFinished = [&](const std::string& path) { + destination = path; + done = true; + quitApplication(); + }; + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?download"); + resetScenario(); + require(done, "The download did not finish"); + // The suggested name "../webfront-download.txt" must never leave the download folder. WebKit already neutralizes the + // separators before the frontend sees the name (it arrives as "_webfront-download.txt"), so the folder is what is checked. + const std::filesystem::path saved(destination); + require(saved.parent_path() == folder && saved.filename().string().ends_with("webfront-download.txt"), ("Unexpected download destination: " + destination).c_str()); + require(readFile(destination) == "downloaded by WebFront", "The downloaded file has the wrong content"); + std::filesystem::remove_all(folder); +} + +void chooseFile(bool cancel) { + const auto fixture = std::filesystem::temp_directory_path() / ("webfront-wk-chooser-" + std::to_string(getpid()) + ".txt"); + std::ofstream(fixture) << "chosen by the test"; + bool asked = false; + static std::string finalTitle; + finalTitle.clear(); + ScenarioFrontend::configure = [&](webfront::frontend::WKWebViewOptions& options) { + options.chooseFiles = [&]() -> std::vector { + asked = true; + return cancel ? std::vector{} : std::vector{fixture.string()}; + }; + }; + ScenarioFrontend::started = [](Session& session) { + // A chooser needs a user gesture, and evaluateJavaScript counts as one. The page reports through its title. + Session* live = &session; + auto tick = ^(id timer) { + const auto title = utf8(send(live->view, "title")); + if (title.starts_with("picked:") || title == "cancelled") { + finalTitle = title; + send(timer, "invalidate"); + quitApplication(); + return; + } + Object script(text("document.title === 'ready' && !window.clicked && (window.clicked = true, document.getElementById('picker').click())")); + send(live->view, "evaluateJavaScript:completionHandler:", script.get(), static_cast(nullptr)); + }; + send(type("NSTimer"), "scheduledTimerWithTimeInterval:repeats:block:", 0.1, static_cast(true), tick); + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?choose"); + resetScenario(); + std::filesystem::remove(fixture); + require(asked, "The file chooser was not requested"); + const std::string expected = cancel ? "cancelled" : "picked:chosen by the test"; + require(finalTitle == expected, ("Unexpected page state after the chooser: " + finalTitle).c_str()); +} +void chooseOne() { + chooseFile(false); +} +void chooseCancel() { + chooseFile(true); +} + +/// The save panel's "Replace" choice: the page's bytes land beside the old file and replace it only on success. +void replacedDownload() { + Object pool(send(type("NSAutoreleasePool"), "new")); + const auto folder = std::filesystem::temp_directory_path() / ("webfront-wk-replace-" + std::to_string(getpid())); + std::filesystem::remove_all(folder); + std::filesystem::create_directories(folder); + const auto target = folder / "report.txt"; + const auto temporary = folder / "report.txt.part"; + std::vector finished; + Session session("http://127.0.0.1:0/", {.visible = false, .downloadFinished = [&](const std::string& path) { + finished.push_back(path); + }}); + const auto start = [&](std::uintptr_t key, std::string_view oldContent, std::string_view downloaded) { + std::ofstream(target) << oldContent; + if (!downloaded.empty()) + std::ofstream(temporary) << downloaded; + session.downloadDestinations[reinterpret_cast(key)] = {temporary.string(), target.string()}; + }; + start(1, "old", "new"); + session.downloadEnded(reinterpret_cast(std::uintptr_t{1}), true); + require(readFile(target) == "new" && !std::filesystem::exists(temporary), "A completed download did not replace the old file"); + require(finished == std::vector{target.string()}, "The finished download was not reported at the chosen path"); + + start(2, "old", "partial"); + session.downloadEnded(reinterpret_cast(std::uintptr_t{2}), false); + require(readFile(target) == "old" && !std::filesystem::exists(temporary), "A failed download damaged the old file or left its part behind"); + + start(3, "old", ""); // The engine reported success but the part is gone: the replacement fails, the old file stays. + session.downloadEnded(reinterpret_cast(std::uintptr_t{3}), true); + require(readFile(target) == "old" && finished.size() == 1, "A failed replacement was reported as a finished download"); + require(session.downloadDestinations.empty(), "A download outlived its end"); + std::filesystem::remove_all(folder); +} + void nativeEarlyClose() { nativeClose(false); } @@ -297,7 +440,11 @@ int main(int argc, char** argv) { {"navigation-diagnostic", navigationDiagnostic}, { "missing-response", missingResponse}, { "committed-navigation", committedNavigation}, - { "agent-application", agentApplication} + { "agent-application", agentApplication}, + { "download", download}, + { "choose-file", chooseOne}, + { "cancel-choose", chooseCancel}, + { "replaced-download", replacedDownload} }; cases.at(argc == 2 ? argv[1] : "")(); return 0; From a3da18fc6006137e802f35aded6abaa1274f44ad Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 2 Nov 2026 21:48:48 +0100 Subject: [PATCH 08/18] Test the GLib download folder and closing WebKitGTK's window over its file dialog (#451) --- cmake/WebKitGTKSupport.cmake | 2 +- docs/FRONTENDS.md | 4 ++ include/webfront/frontend/WebKitGTK.hpp | 7 ++- test/web/WebKitGTKLifecycle.cpp | 64 +++++++++++++++++++++++++ 4 files changed, 75 insertions(+), 2 deletions(-) diff --git a/cmake/WebKitGTKSupport.cmake b/cmake/WebKitGTKSupport.cmake index c73c604c..b901fd30 100644 --- a/cmake/WebKitGTKSupport.cmake +++ b/cmake/WebKitGTKSupport.cmake @@ -25,7 +25,7 @@ function(webfront_add_webkitgtk_tests) target_link_libraries(webkitgtk_lifecycle PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) add_dependencies(webtest webkitgtk_lifecycle) webfront_find_xvfb(display_runner) - foreach(mode no-display worker-thread native-close repeated-show http-error pre-run-failure profile-permissions window-title download choose-file cancel-choose) + foreach(mode no-display worker-thread native-close repeated-show http-error pre-run-failure profile-permissions window-title download download-user-dir choose-file cancel-choose close-with-dialog) if(mode MATCHES "^(no-display|worker-thread|pre-run-failure|profile-permissions)$") add_test(NAME WebKitGTKAdapter-${mode} COMMAND webkitgtk_lifecycle ${mode}) elseif(display_runner) diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 5f5be6e0..eb5a783f 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -71,6 +71,10 @@ WebKit reduces a suggested name such as `../x.txt` to `_x.txt` before the fronte `webkitdirectory` properties keep their values (filtering and directory selection themselves are not exercised), and that offering a generated Blob leaves the page and the bridge working. `WebKitGTKAdapter-download|choose-file|cancel-choose` and `CEFFileServices-download|choose|cancel` drive the dialog and the download through the injection points. +`WebKitGTKAdapter-download-user-dir` checks that, without a configured folder, the download lands in GLib's user download +directory (read from `user-dirs.dirs`, not from an environment variable). `WebKitGTKAdapter-close-with-dialog` opens the +real system dialog with a pointer click, closes the window under it and requires a clean exit; the other engines do not +test that case. `WebView2Lifecycle-file-choose|file-cancel|file-download` verifies the engine's chooser request, selection and cancellation events, and the bytes written by a completed Blob download. It intercepts the chooser with DevTools and suppresses the download UI, so it does not qualify the native dialogs themselves or closing the window while one is open. diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 15fd8124..49eeb359 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -287,6 +287,8 @@ struct Session : FailureState { std::filesystem::path downloadDirectory; /// Test injection: answers without a dialog (an empty list cancels). Unset shows the system dialog. std::function()> chooseFiles; + /// Test hook: called when the system file dialog is about to open. + std::function chooserOpened; /// Test injection: called with the destination of each finished download. std::function downloadFinished; struct Download { @@ -578,8 +580,11 @@ struct Session : FailureState { }); } static int onRunFileChooser(Api::Object, Api::Object request, Session* self) noexcept { - if (!self->chooseFiles) + if (!self->chooseFiles) { + if (self->chooserOpened) + self->chooserOpened(); return 0; // The system dialog, attached to the window by WebKitGTK. + } try { const auto files = self->chooseFiles(); std::vector pointers; diff --git a/test/web/WebKitGTKLifecycle.cpp b/test/web/WebKitGTKLifecycle.cpp index b8e3c918..8f98102f 100644 --- a/test/web/WebKitGTKLifecycle.cpp +++ b/test/web/WebKitGTKLifecycle.cpp @@ -203,6 +203,41 @@ void download() { std::filesystem::remove_all(folder); } +/// Without a configured folder, the download lands in GLib's user download directory (user-dirs.dirs), not in an +/// XDG_DOWNLOAD_DIR environment variable, which nothing defines in a normal session. +void downloadUserDirectory() { + const auto base = std::filesystem::temp_directory_path() / ("webfront-userdir-" + std::to_string(getpid())); + std::filesystem::remove_all(base); + const auto config = base / "config"; + const auto folder = base / "Telechargements"; + const auto decoy = base / "decoy"; + std::filesystem::create_directories(config); + std::filesystem::create_directories(folder); + std::filesystem::create_directories(decoy); + std::ofstream(config / "user-dirs.dirs") << "XDG_DOWNLOAD_DIR=\"" << folder.string() << "\"\n"; + // GLib reads the configuration once, at the first query: set it before any session exists. + setenv("XDG_CONFIG_HOME", config.c_str(), 1); + setenv("XDG_DOWNLOAD_DIR", decoy.c_str(), 1); + std::string destination; + bool done = false; + ScenarioFrontend::configure = [&](gtk::Session& session) { + session.downloadFinished = [&](const std::string& path) { + destination = path; + done = true; + }; + }; + ScenarioFrontend::finished = [&](gtk::Session&) { + return done; + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?download"); + if (!done) + throw std::runtime_error("The download did not finish"); + if (std::filesystem::path(destination) != folder / "webfront-download.txt") + throw std::runtime_error("The download ignored GLib's user download directory: " + destination); + std::filesystem::remove_all(base); +} + /// A real pointer click through the X server's XTest extension: web content only opens a file chooser for a user gesture. struct FakeClick { void* x11 = dlopen("libX11.so.6", RTLD_NOW); @@ -266,6 +301,33 @@ void chooseCancel() { chooseFile(true); } +/// Closing the window while the system file dialog is open must end cleanly, without waiting for an answer. +void closeWithDialog() { + bool opened = false; + int open = 0; // Poll ticks since the dialog opened. + ScenarioFrontend::configure = [&](gtk::Session& session) { + session.chooserOpened = [&] { + opened = true; + }; + }; + std::string title; + const FakeClick pointer; + if (!pointer.available()) + throw std::runtime_error("XTest is unavailable: run the scenario under Xvfb with libXtst"); + int ticks = 0; + ScenarioFrontend::finished = [&](gtk::Session& session) { + const char* current = session.a.viewTitle(session.view); + title = current ? current : ""; + if (title == "ready" && !opened && ++ticks % 5 == 1) + pointer.click(40, 20); + return opened && ++open > 10; // Let the dialog map, then close the window under it. + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?choose"); + if (!opened) + throw std::runtime_error("The file dialog was not opened"); +} + void windowTitle() { gtk::initialize(); const auto titleOf = [](webfront::WindowOptions window) { @@ -318,6 +380,8 @@ void run(std::string_view mode) { {"profile-permissions", profilePermissions}, { "window-title", windowTitle}, { "download", download}, + {"download-user-dir", downloadUserDirectory}, + { "close-with-dialog", closeWithDialog}, { "choose-file", chooseOne}, { "cancel-choose", chooseCancel} }; From 2e6e12cf9b25a2e97da0865febac5be8e92e65d6 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:30:41 +0100 Subject: [PATCH 09/18] Keep WKWebView's panel answers independent of the session and judge about:blank frames by their origin (#451) --- cmake/WKWebViewSupport.cmake | 2 +- docs/FRONTENDS.md | 4 +- include/webfront/frontend/WKWebView.hpp | 44 ++++++++++++++-- test/web/WKWebViewLifecycle.cpp | 67 +++++++++++++++++++++++-- test/web/file-services.html | 19 +++++++ 5 files changed, 126 insertions(+), 10 deletions(-) diff --git a/cmake/WKWebViewSupport.cmake b/cmake/WKWebViewSupport.cmake index 66899603..8a49393b 100644 --- a/cmake/WKWebViewSupport.cmake +++ b/cmake/WKWebViewSupport.cmake @@ -18,7 +18,7 @@ function(webfront_add_wkwebview_tests) add_executable(wkwebview_lifecycle "${webtest_source_dir}/WKWebViewLifecycle.cpp" "${webtest_source_dir}/WKWebViewHeaderConsumer.cpp") target_link_libraries(wkwebview_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) - foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download) + foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download choose-in-blank choose-in-srcdoc close-with-open-panel close-with-save-panel) add_test(NAME WKWebViewLifecycle-${mode} COMMAND wkwebview_lifecycle ${mode}) webfront_set_browser_test_properties("WKWebViewLifecycle-${mode}" "${webtest_source_dir}" 90) endforeach() diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index eb5a783f..db0b925a 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -74,7 +74,9 @@ and `CEFFileServices-download|choose|cancel` drive the dialog and the download t `WebKitGTKAdapter-download-user-dir` checks that, without a configured folder, the download lands in GLib's user download directory (read from `user-dirs.dirs`, not from an environment variable). `WebKitGTKAdapter-close-with-dialog` opens the real system dialog with a pointer click, closes the window under it and requires a clean exit; the other engines do not -test that case. +test that case on a real dialog. `WKWebViewLifecycle-close-with-open-panel|close-with-save-panel` close the window under an +`NSOpenPanel` / `NSSavePanel` sheet, and `choose-in-blank|choose-in-srcdoc` open a chooser from `about:blank` and `srcdoc` +frames, which WKWebView judges by their inherited origin. `WebView2Lifecycle-file-choose|file-cancel|file-download` verifies the engine's chooser request, selection and cancellation events, and the bytes written by a completed Blob download. It intercepts the chooser with DevTools and suppresses the download UI, so it does not qualify the native dialogs themselves or closing the window while one is open. diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 0312d47d..f1a464c1 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -294,6 +294,8 @@ struct Session { std::string target; // Where the user wants it; differs from `temporary` when "Replace" was chosen. }; std::map downloadDestinations; // WKDownload -> its paths, until it ends. + /// What the answers of a system panel hold instead of `this`: AppKit may deliver one after the session is gone. + std::shared_ptr alive = std::make_shared(this); id app = nullptr, window = nullptr, view = nullptr, delegate = nullptr, timer = nullptr; id previousDelegate = nullptr, previousMenu = nullptr; long previousActivationPolicy = 0; @@ -304,6 +306,8 @@ struct Session { CaptureRegistration captureRegistration; ~Session() { + *alive = nullptr; + endSheets(); // Each open panel answers "cancel" now, while the view still exists to receive it. captureRegistration = {}; abandonCaptures(*captureTarget); if (timer) { @@ -342,6 +346,16 @@ struct Session { } } + /// Dismisses the panels attached to the window: their completion handlers run, so WebKit gets its answers. + void endSheets() noexcept { + if (!window) + return; + const auto sheets = send(window, "sheets"); + const auto count = send(sheets, "count"); + for (auto index = count; index > 0; --index) + send(window, "endSheet:", send(sheets, "objectAtIndex:", index - 1)); + } + void close() noexcept { closed = true; if (!running) @@ -525,13 +539,28 @@ struct Session { decision(policy); // Exactly once, including after a C++ exception. } + /// The address a frame is judged by. A frame the page creates without a document of its own (no `src`, or `srcdoc`) + /// is `about:blank` / `about:srcdoc` and inherits its creator's origin, which is what the policy has to see. + static std::string effectiveFrameUrl(id frame) { + auto address = utf8(send(send(send(frame, "request"), "URL"), "absoluteString")); + if (!address.empty() && !address.starts_with("about:")) + return address; + const auto origin = send(frame, "securityOrigin"); + const auto protocol = utf8(send(origin, "protocol")); + const auto host = utf8(send(origin, "host")); + if (protocol.empty() || host.empty()) + return address; // An opaque origin (sandboxed frame): not the application's. + const auto port = send(origin, "port"); + return protocol + "://" + host + (port > 0 ? ":" + std::to_string(port) : "") + "/"; + } + /// : the system panel as a sheet of the window, or the test injection. The handler runs exactly once. void chooseFilesForPage(id parameters, id frame, void (^completion)(id)) noexcept { id result = nullptr; // NSArray*; nil cancels. bool deferred = false; guard([&] { // Only the frames the policy admits may open a chooser. - if (!contentPolicy.allowsNavigation(utf8(send(send(send(frame, "request"), "URL"), "absoluteString")))) + if (!contentPolicy.allowsNavigation(effectiveFrameUrl(frame))) return; if (options.chooseFiles) { const auto files = options.chooseFiles(); @@ -551,9 +580,11 @@ struct Session { const auto directories = send(parameters, "allowsDirectories"); send(panel, "setCanChooseDirectories:", directories); send(panel, "setCanChooseFiles:", static_cast(!directories)); - auto handler = Block_copy(completion); + auto handler = Block_copy(completion); + send(panel, "retain"); void (^finished)(long) = ^(long response) { handler(response == 1 ? send(panel, "URLs") : nullptr); // NSModalResponseOK + send(panel, "release"); Block_release(handler); }; deferred = true; @@ -579,9 +610,13 @@ struct Session { const auto panel = send(type("NSSavePanel"), "savePanel"); Object name(text(std::filesystem::path(suggested).filename().string())); send(panel, "setNameFieldStringValue:", name.get()); - auto handler = Block_copy(completion); + auto handler = Block_copy(completion); + auto token = alive; // Not `this`: the window may close, and the session end, while the panel is open. + send(panel, "retain"); void (^finished)(long) = ^(long response) { id chosen = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK + if (chosen && !*token) + chosen = nullptr; // The session is gone: nobody could move the file afterwards. if (chosen) { // "Replace" returns an existing file, which WKDownload refuses: download beside it, replace when done. const std::filesystem::path target = utf8(send(chosen, "path")); @@ -592,9 +627,10 @@ struct Session { Object path(text(temporary.string())); chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); } - downloadDestinations[download] = {temporary.string(), target.string()}; + (*token)->downloadDestinations[download] = {temporary.string(), target.string()}; } handler(chosen); + send(panel, "release"); Block_release(handler); }; deferred = true; diff --git a/test/web/WKWebViewLifecycle.cpp b/test/web/WKWebViewLifecycle.cpp index 4245b0a9..03635ea0 100644 --- a/test/web/WKWebViewLifecycle.cpp +++ b/test/web/WKWebViewLifecycle.cpp @@ -334,7 +334,7 @@ void download() { std::filesystem::remove_all(folder); } -void chooseFile(bool cancel) { +void chooseFile(bool cancel, const char* page = "file-services.html?choose", const char* click = "document.getElementById('picker').click()") { const auto fixture = std::filesystem::temp_directory_path() / ("webfront-wk-chooser-" + std::to_string(getpid()) + ".txt"); std::ofstream(fixture) << "chosen by the test"; bool asked = false; @@ -346,6 +346,8 @@ void chooseFile(bool cancel) { return cancel ? std::vector{} : std::vector{fixture.string()}; }; }; + static std::string clickScript; + clickScript = std::string("document.title === 'ready' && !window.clicked && (window.clicked = true, ") + click + ")"; ScenarioFrontend::started = [](Session& session) { // A chooser needs a user gesture, and evaluateJavaScript counts as one. The page reports through its title. Session* live = &session; @@ -357,13 +359,13 @@ void chooseFile(bool cancel) { quitApplication(); return; } - Object script(text("document.title === 'ready' && !window.clicked && (window.clicked = true, document.getElementById('picker').click())")); + Object script(text(clickScript)); send(live->view, "evaluateJavaScript:completionHandler:", script.get(), static_cast(nullptr)); }; send(type("NSTimer"), "scheduledTimerWithTimeInterval:repeats:block:", 0.1, static_cast(true), tick); }; ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); - app.show("file-services.html?choose"); + app.show(page); resetScenario(); std::filesystem::remove(fixture); require(asked, "The file chooser was not requested"); @@ -376,6 +378,59 @@ void chooseOne() { void chooseCancel() { chooseFile(true); } +/// A frame created by the page without an address inherits its origin: its chooser is the application's own. +void chooseInBlankFrame() { + chooseFile(false, "file-services.html?blank", "document.querySelector('iframe').contentDocument.getElementById('picker').click()"); +} +void chooseInSrcdocFrame() { + chooseFile(false, "file-services.html?srcdoc", "document.querySelector('iframe').contentDocument.getElementById('picker').click()"); +} + +/// Closing the window while a system panel is open: the panel answers "cancel" and its late answer touches nothing. +void closeWithPanel(const char* page, const char* click) { + Object pool(send(type("NSAutoreleasePool"), "new")); + static bool sawPanel; + static std::string script; + sawPanel = false; + script = click; + ScenarioFrontend::configure = [](webfront::frontend::WKWebViewOptions& options) { + options.visible = true; // No injection: the real NSSavePanel / NSOpenPanel opens as a sheet of a visible window. + }; + ScenarioFrontend::started = [](Session& session) { + Session* live = &session; + auto ticks = std::make_shared(0); + auto tick = ^(id timer) { + const auto sheets = send(live->window, "sheets"); + if (send(sheets, "count") > 0) { + sawPanel = true; + if (++*ticks > 3) { // Let the sheet settle, then close the window under it. + send(timer, "invalidate"); + quitApplication(); + } + return; + } + if (!script.empty()) { + Object code(text("document.title === 'ready' && !window.clicked && (window.clicked = true, " + script + ")")); + send(live->view, "evaluateJavaScript:completionHandler:", code.get(), static_cast(nullptr)); + } + }; + send(type("NSTimer"), "scheduledTimerWithTimeInterval:repeats:block:", 0.1, static_cast(true), tick); + }; + { + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show(page); + } + resetScenario(); + // A late answer from AppKit after the session ended must find nothing to touch. + send(send(type("NSRunLoop"), "currentRunLoop"), "runUntilDate:", send(type("NSDate"), "dateWithTimeIntervalSinceNow:", 0.5)); + require(sawPanel, "The system panel did not open"); +} +void closeWithOpenPanel() { + closeWithPanel("file-services.html?choose", "document.getElementById('picker').click()"); +} +void closeWithSavePanel() { + closeWithPanel("file-services.html?download", ""); +} /// The save panel's "Replace" choice: the page's bytes land beside the old file and replace it only on success. void replacedDownload() { @@ -444,7 +499,11 @@ int main(int argc, char** argv) { { "download", download}, { "choose-file", chooseOne}, { "cancel-choose", chooseCancel}, - { "replaced-download", replacedDownload} + { "replaced-download", replacedDownload}, + { "choose-in-blank", chooseInBlankFrame}, + { "choose-in-srcdoc", chooseInSrcdocFrame}, + { "close-with-open-panel", closeWithOpenPanel}, + { "close-with-save-panel", closeWithSavePanel} }; cases.at(argc == 2 ? argv[1] : "")(); return 0; diff --git a/test/web/file-services.html b/test/web/file-services.html index f2ae1c50..b8077065 100644 --- a/test/web/file-services.html +++ b/test/web/file-services.html @@ -18,6 +18,25 @@

WebFront file services

document.body.append(link); result.textContent = "download requested"; link.click(); + } else if (mode === "?blank" || mode === "?srcdoc") { + // The chooser of a frame the page creates without an address of its own: about:blank / about:srcdoc, same origin. + const markup = ''; + const frame = document.createElement("iframe"); + const wire = () => { + const picker = frame.contentDocument.getElementById("picker"); + if (!picker || picker.wired) return; + picker.wired = true; + picker.addEventListener("change", async () => { + const text = await picker.files[0].text(); + report("picked:" + text, picker.files[0].name + ": " + text); + }); + picker.addEventListener("cancel", () => report("cancelled", "cancelled")); + document.title = "ready"; + }; + frame.addEventListener("load", wire); + if (mode === "?srcdoc") frame.srcdoc = markup; + document.body.append(frame); + if (mode === "?blank") { frame.contentDocument.body.innerHTML = markup; wire(); } } else if (mode === "?choose") { const picker = document.getElementById("picker"); picker.addEventListener("change", async () => { From bb60002b8ca77b28fc181427d3765882bc9a029a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:30:50 +0100 Subject: [PATCH 10/18] Correct the list of engines that test closing over a dialog (#451) --- docs/FRONTENDS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index db0b925a..e5646c03 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -73,8 +73,8 @@ that offering a generated Blob leaves the page and the bridge working. `WebKitGT and `CEFFileServices-download|choose|cancel` drive the dialog and the download through the injection points. `WebKitGTKAdapter-download-user-dir` checks that, without a configured folder, the download lands in GLib's user download directory (read from `user-dirs.dirs`, not from an environment variable). `WebKitGTKAdapter-close-with-dialog` opens the -real system dialog with a pointer click, closes the window under it and requires a clean exit; the other engines do not -test that case on a real dialog. `WKWebViewLifecycle-close-with-open-panel|close-with-save-panel` close the window under an +real system dialog with a pointer click, closes the window under it and requires a clean exit; CEF and WebView2 do not +test that case. `WKWebViewLifecycle-close-with-open-panel|close-with-save-panel` close the window under an `NSOpenPanel` / `NSSavePanel` sheet, and `choose-in-blank|choose-in-srcdoc` open a chooser from `about:blank` and `srcdoc` frames, which WKWebView judges by their inherited origin. `WebView2Lifecycle-file-choose|file-cancel|file-download` verifies the engine's chooser request, selection and cancellation From 46515830b21b0ea60da9e733064a05e4bc0dae50 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:37:15 +0100 Subject: [PATCH 11/18] Create the WebKitGTK download folder, cancel WKDownloads on close, record the delivery in ADR-020, steady the XTest click (#451) --- docs/adr/ADR-020-services-systeme.md | 9 +++++---- include/webfront/frontend/WKWebView.hpp | 13 +++++++++++++ include/webfront/frontend/WebKitGTK.hpp | 7 ++++++- test/web/WebKitGTKLifecycle.cpp | 14 +++++++++----- 4 files changed, 33 insertions(+), 10 deletions(-) diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 585b995a..5bbbb530 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -5,11 +5,12 @@ | Version | Date | État | Auteur | Évolution | Révision Git | | --- | --- | --- | --- | --- | --- | | 1.0 | 2026-10-31 | Proposée | Ambroise Leclerc | Décision initiale : distinction hôte/client, préalables regroupés en épiques (#446 à #450), confinement des racines pendant la résolution et hypothèse de confiance face au déplacement d'un répertoire ouvert ou de la racine, autorisation attachée à l'emplacement déclaré, propriétaires admissibles des répertoires et des ancêtres, transport du navigateur système déclaré (`loopbackAttested`) plutôt que prouvé par un secret de lancement, jetons de lecture réutilisables liés à la connexion par un cookie, exposition des jetons et transport des lectures distantes, exception de confiance explicite, liaison HTTP par profil de navigateur avec cookies nommés par client, contenu actif neutralisé, transport déclaré et association de lancement du navigateur système, racines déclarées accessibles à tout script admis, services en composants facultatifs, sélection par l'utilisateur valant autorisation (poignées plutôt que chemins), backends natif, HTML et navigateur choisis par connexion, contenu des fichiers par HTTP à jeton ; état de l'art et inventaire des autres services. | À renseigner après intégration. | +| 1.1 | 2026-11-02 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de l'étape 1 pour #451 (sélecteur de fichiers et téléchargements sous WebKitGTK, CEF, WKWebView et WebView2) ; #452 reste à faire. Validations exécutées : tests unitaires de la politique de contenu, des chemins de téléchargement et de WebKitGTK ; scénarios de cycle de vie WebKitGTK, CEF, WKWebView et WebView2 de la CI ; `docs/FRONTENDS.md` précise ce que chaque moteur ne couvre pas. | Branche `451-file-chooser-downloads` (PR #484) | ## État et chronologie -**Proposée** le **2026-10-31**. Aucun code n'est livré avec cette version : elle fixe le cadre des services -système et leurs préalables (épiques #446 à #450) avant l'implémentation du premier d'entre eux (sélection de fichiers). Elle passera à « Acceptée » quand les +**Proposée** le **2026-10-31**. La version 1.0 ne livrait aucun code : elle fixe le cadre des services +système et leurs préalables (épiques #446 à #450) avant l'implémentation du premier d'entre eux (sélection de fichiers). La version 1.1 livre une partie de l'étape 1 (#451) ; la décision reste proposée. Elle passera à « Acceptée » quand les critères de la section dédiée seront démontrés. ## Contexte @@ -352,8 +353,8 @@ Le code vérifié le 2026-10-31 ne permet pas encore d'implémenter ces règles. | 4 | [#449](https://github.com/ambroise-leclerc/WebFront/issues/449) Stockage modifiable et livraison des services | [#460](https://github.com/ambroise-leclerc/WebFront/issues/460) stockage sous racines déclarées, confiné pendant la résolution (révision de l'ADR-002) ; [#461](https://github.com/ambroise-leclerc/WebFront/issues/461) paquet `@webfront/services` | sélecteur HTML et écritures (règles 2 à 4) | | 5 | [#450](https://github.com/ambroise-leclerc/WebFront/issues/450) Intégration native des frontends | [#462](https://github.com/ambroise-leclerc/WebFront/issues/462) exécuteur du thread d'interface, y compris le navigateur système ; [#463](https://github.com/ambroise-leclerc/WebFront/issues/463) fenêtre native et correspondance avec les connexions | backend natif seulement | -État de l'étape 1 (#451) : sélecteur et téléchargements qualifiés sous WebKitGTK et CEF (Linux), implémentés sous -WKWebView, laissés au comportement natif sous WebView2 ; `docs/FRONTENDS.md` documente chaque moteur. #452 reste à faire. +État de l'étape 1 (#451) : sélecteur et téléchargements implémentés et exercés par la CI sous WebKitGTK, CEF, +WKWebView et WebView2 ; `docs/FRONTENDS.md` documente chaque moteur et ses limites. #452 reste à faire. Après l'étape 4, le premier service (sélecteur HTML, poignées, import et export côté client) fera l'objet de sa propre épique ; les dialogues natifs suivront l'étape 5. `PUT`/`POST` ne sont pas des préalables : les écritures passent par diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index f1a464c1..447a38aa 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -308,6 +308,7 @@ struct Session { ~Session() { *alive = nullptr; endSheets(); // Each open panel answers "cancel" now, while the view still exists to receive it. + abandonDownloads(); captureRegistration = {}; abandonCaptures(*captureTarget); if (timer) { @@ -356,6 +357,18 @@ struct Session { send(window, "endSheet:", send(sheets, "objectAtIndex:", index - 1)); } + /// Cancels the downloads still running and removes the `.part` files that a "Replace" choice made them write. + void abandonDownloads() noexcept { + auto pending = std::exchange(downloadDestinations, {}); // Their failure callbacks must find nothing to settle. + for (const auto& [download, paths] : pending) { + send(download, "cancel:", static_cast(nullptr)); + if (paths.temporary != paths.target) { + std::error_code ignored; + std::filesystem::remove(paths.temporary, ignored); + } + } + } + void close() noexcept { closed = true; if (!running) diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 49eeb359..cc90e5b4 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -435,7 +435,12 @@ struct Session : FailureState { return std::filesystem::temp_directory_path(); } std::filesystem::path uniqueDestination(std::string_view suggested) const { - return uniqueDownloadPath(destinationFolder(), suggested); + const auto folder = destinationFolder(); + std::error_code error; + std::filesystem::create_directories(folder, error); // WebKitGTK writes into an existing folder only. + if (error) + throw std::filesystem::filesystem_error("WebKitGTK: cannot create the download folder", folder, error); + return uniqueDownloadPath(folder, suggested); } void trackDownload(Api::Object download) { Download entry{download, {}}; diff --git a/test/web/WebKitGTKLifecycle.cpp b/test/web/WebKitGTKLifecycle.cpp index 8f98102f..01777032 100644 --- a/test/web/WebKitGTKLifecycle.cpp +++ b/test/web/WebKitGTKLifecycle.cpp @@ -176,9 +176,9 @@ std::string readFile(const std::filesystem::path& path) { } void download() { - const auto folder = std::filesystem::temp_directory_path() / ("webfront-download-" + std::to_string(getpid())); - std::filesystem::remove_all(folder); - std::filesystem::create_directories(folder); + const auto parent = std::filesystem::temp_directory_path() / ("webfront-download-" + std::to_string(getpid())); + const auto folder = parent / "not" / "yet"; // The frontend creates the folder: WebKitGTK writes into an existing one only. + std::filesystem::remove_all(parent); std::string destination; bool done = false; ScenarioFrontend::configure = [&](gtk::Session& session) { @@ -200,7 +200,7 @@ void download() { throw std::runtime_error("Unexpected download destination: " + destination); if (readFile(destination) != "downloaded by WebFront") throw std::runtime_error("The downloaded file has the wrong content"); - std::filesystem::remove_all(folder); + std::filesystem::remove_all(parent); } /// Without a configured folder, the download lands in GLib's user download directory (user-dirs.dirs), not in an @@ -256,6 +256,10 @@ struct FakeClick { return display && move && press && flush; } void click(int x, int y) const { + // Without a window manager the pointer may already rest at the target: a press with no motion before it can be + // delivered before the page knows the pointer is over it. Arrive from a neighbouring point. + move(display, 0, x + 6, y + 6, 0); + flush(display); move(display, 0, x, y, 0); press(display, 1, 1, 0); press(display, 1, 0, 0); @@ -289,7 +293,7 @@ void chooseFile(bool cancel) { app.show("file-services.html?choose"); std::filesystem::remove(fixture); if (!asked) - throw std::runtime_error("The file chooser was not requested"); + throw std::runtime_error("The file chooser was not requested (page title \"" + title + "\", " + std::to_string(ticks) + " clicks)"); const std::string expected = cancel ? "cancelled" : "picked:chosen by the test"; if (title != expected) throw std::runtime_error("Unexpected page state after the chooser: " + title); From 3db2c49947a475d6281db8db8736ceb31b25ace5 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 3 Nov 2026 09:11:33 +0100 Subject: [PATCH 12/18] Reserve download destinations so concurrent downloads never share a path (#451) --- docs/FRONTENDS.md | 2 +- include/webfront/frontend/CEF.hpp | 26 ++++++++++- include/webfront/frontend/Downloads.hpp | 47 +++++++++++++++++++- include/webfront/frontend/WKWebView.hpp | 16 +++++-- include/webfront/frontend/WebKitGTK.hpp | 16 +++++-- test/unit/DownloadsTests.cpp | 59 +++++++++++++++++++++++++ test/web/WKWebViewLifecycle.cpp | 2 +- 7 files changed, 154 insertions(+), 14 deletions(-) diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index e5646c03..3dcafed7 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -53,7 +53,7 @@ admitted origin passes the navigation policy (`webfront::detail::blobOriginUrl`) | Frontend | Chooser | Download | Test injection | | --- | --- | --- | --- | -| WebKitGTK | default `run-file-chooser` dialog (portal under Flatpak) | `download-started` / `decide-destination`: the user's XDG download folder, the page's name reduced to its last component, never overwriting (`name (1).ext`) | `Session::chooseFiles`, `downloadDirectory`, `downloadFinished` | +| WebKitGTK | default `run-file-chooser` dialog (portal under Flatpak) | `download-started` / `decide-destination`: the user's XDG download folder, the page's name reduced to its last component, never overwriting (`name (1).ext`), also between downloads that run at the same time (`DownloadReservations`) | `Session::chooseFiles`, `downloadDirectory`, `downloadFinished` | | CEF (Chrome runtime) | the runtime's dialog | the runtime's download handling | `SimpleCEFClient::chooseFiles` (`CefDialogHandler::OnFileDialog`), `downloadDirectory`, `downloadFinished`. The runtime itself turns a suggested name `../x` into `_x` | | WKWebView | `runOpenPanelWithParameters` shows an `NSOpenPanel` sheet of the window; only frames admitted by the policy | `WKDownload` (macOS 11.3+): a save panel proposes the name | `WKWebViewOptions::chooseFiles`, `downloadDirectory`, `downloadFinished` | | WebView2 | the engine's native chooser | the engine's native download UI | DevTools intercepts the chooser in tests; `DownloadStarting` redirects the download to a private path | diff --git a/include/webfront/frontend/CEF.hpp b/include/webfront/frontend/CEF.hpp index 817843e7..901587c4 100644 --- a/include/webfront/frontend/CEF.hpp +++ b/include/webfront/frontend/CEF.hpp @@ -17,6 +17,8 @@ #include #include #include +#include +#include #include #include #include @@ -521,6 +523,9 @@ class SimpleCEFClient : public CefClient, std::function()> chooseFiles; /// Test injection: a non-empty folder receives downloads without a "save as" dialog. std::filesystem::path downloadDirectory; + frontend::detail::DownloadReservations downloadReservations; + std::mutex reservedMutex; + std::map reservedByDownload; // CefDownloadItem id -> destination /// Test injection: called with the full path of each completed download. std::function downloadFinished; @@ -553,16 +558,33 @@ class SimpleCEFClient : public CefClient, callback->Continue(files); return true; } - bool OnBeforeDownload(CefRefPtr, CefRefPtr, const CefString& suggested, CefRefPtr callback) override { + bool OnBeforeDownload(CefRefPtr, CefRefPtr item, const CefString& suggested, CefRefPtr callback) override { if (downloadDirectory.empty()) return false; - const auto result = frontend::detail::uniqueDownloadPath(downloadDirectory, suggested.ToString()); + const auto result = downloadReservations.reserve(downloadDirectory, suggested.ToString()); + { + std::scoped_lock lock{reservedMutex}; + reservedByDownload[item->GetId()] = result; + } callback->Continue(result.string(), false); return true; } void OnDownloadUpdated(CefRefPtr, CefRefPtr item, CefRefPtr) override { if (item->IsComplete() && downloadFinished) downloadFinished(item->GetFullPath().ToString()); + if (item->IsInProgress()) + return; + // Complete, cancelled or interrupted: the name can be given to another download again. + std::filesystem::path reserved; + { + std::scoped_lock lock{reservedMutex}; + if (const auto found = reservedByDownload.find(item->GetId()); found != reservedByDownload.end()) { + reserved = std::move(found->second); + reservedByDownload.erase(found); + } + } + if (!reserved.empty()) + downloadReservations.release(reserved); } bool OnBeforeBrowse(CefRefPtr, CefRefPtr frame, CefRefPtr request, bool, bool) override { diff --git a/include/webfront/frontend/Downloads.hpp b/include/webfront/frontend/Downloads.hpp index 156c6bf1..7c2f817d 100644 --- a/include/webfront/frontend/Downloads.hpp +++ b/include/webfront/frontend/Downloads.hpp @@ -1,6 +1,10 @@ #pragma once #include +#include +#include +#include +#include #include #include @@ -11,16 +15,55 @@ namespace webfront::frontend::detail { * * Only the final component of the suggested name is kept (a page can neither choose a folder nor climb out of it), an * empty name becomes "download", and an existing file is kept: "name", then "name (1).ext", "name (2).ext", and so on. + * `taken` additionally rejects the names that another download has reserved but not created yet. */ -inline std::filesystem::path uniqueDownloadPath(const std::filesystem::path& folder, std::string_view suggested) { +inline std::filesystem::path uniqueDownloadPath(const std::filesystem::path& folder, + std::string_view suggested, + const std::function& taken = {}) { auto name = std::filesystem::path(std::string(suggested)).filename(); if (name.empty() || name == "." || name == "..") name = "download"; auto result = folder / name; std::error_code error; - for (int index = 1; std::filesystem::exists(result, error) && index < 10'000; ++index) + const auto unavailable = [&](const std::filesystem::path& path) { + return std::filesystem::exists(path, error) || (taken && taken(path)); + }; + for (int index = 1; unavailable(result) && index < 10'000; ++index) result = folder / (name.stem().string() + " (" + std::to_string(index) + ")" + name.extension().string()); return result; } +/** + * @brief The destinations handed to downloads that have not created their file yet. + * + * A name is free only if no file has it and no running download was given it: two downloads that ask for the same name + * before either file exists get "name" and "name (1)", never the same path. Choosing and reserving happen under one lock; + * release a path when its download ends (finished, failed or cancelled) so that the name can be used again. + */ +class DownloadReservations { +public: + [[nodiscard]] std::filesystem::path reserve(const std::filesystem::path& folder, std::string_view suggested) { + std::scoped_lock lock{mutex}; + auto result = uniqueDownloadPath(folder, suggested, [&](const std::filesystem::path& path) { + return reserved.contains(path); + }); + reserved.insert(result); + return result; + } + + void release(const std::filesystem::path& path) { + std::scoped_lock lock{mutex}; + reserved.erase(path); + } + + [[nodiscard]] bool empty() const { + std::scoped_lock lock{mutex}; + return reserved.empty(); + } + +private: + mutable std::mutex mutex; + std::set reserved; +}; + } // namespace webfront::frontend::detail diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 447a38aa..5540a203 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -292,7 +292,9 @@ struct Session { struct PendingDownload { std::string temporary; // Where WKDownload writes: it needs a file that does not exist yet. std::string target; // Where the user wants it; differs from `temporary` when "Replace" was chosen. + bool reserved; // `temporary` was handed out by `reservations`: give it back when the download ends. }; + frontend::detail::DownloadReservations reservations; std::map downloadDestinations; // WKDownload -> its paths, until it ends. /// What the answers of a system panel hold instead of `this`: AppKit may deliver one after the session is gone. std::shared_ptr alive = std::make_shared(this); @@ -366,6 +368,8 @@ struct Session { std::error_code ignored; std::filesystem::remove(paths.temporary, ignored); } + if (paths.reserved) + reservations.release(paths.temporary); } } @@ -614,8 +618,8 @@ struct Session { guard([&] { if (!options.downloadDirectory.empty()) { std::filesystem::create_directories(options.downloadDirectory); // WebKit needs the folder to exist. - const auto destination = frontend::detail::uniqueDownloadPath(options.downloadDirectory, suggested); - downloadDestinations[download] = {destination.string(), destination.string()}; + const auto destination = reservations.reserve(options.downloadDirectory, suggested); + downloadDestinations[download] = {destination.string(), destination.string(), true}; Object path(text(destination.string())); result = send(type("NSURL"), "fileURLWithPath:", path.get()); return; @@ -635,12 +639,14 @@ struct Session { const std::filesystem::path target = utf8(send(chosen, "path")); std::error_code code; auto temporary = target; + bool reserved = false; if (std::filesystem::exists(target, code)) { - temporary = frontend::detail::uniqueDownloadPath(target.parent_path(), target.filename().string() + ".part"); + temporary = (*token)->reservations.reserve(target.parent_path(), target.filename().string() + ".part"); + reserved = true; Object path(text(temporary.string())); chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); } - (*token)->downloadDestinations[download] = {temporary.string(), target.string()}; + (*token)->downloadDestinations[download] = {temporary.string(), target.string(), reserved}; } handler(chosen); send(panel, "release"); @@ -670,6 +676,8 @@ struct Session { std::filesystem::remove(pending.temporary, cleanup); } } + if (pending.reserved) + reservations.release(pending.temporary); if (completed && options.downloadFinished) guard([&] { options.downloadFinished(pending.target); diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index cc90e5b4..bf0c80e4 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -294,7 +294,9 @@ struct Session : FailureState { struct Download { Api::Object object; std::vector handlers; + std::filesystem::path reserved; // The destination given to this download, until it ends. }; + DownloadReservations reservations; std::vector downloads; unsigned long downloadStartedHandler = 0; bool closed = false; @@ -434,16 +436,16 @@ struct Session : FailureState { } return std::filesystem::temp_directory_path(); } - std::filesystem::path uniqueDestination(std::string_view suggested) const { + std::filesystem::path reserveDestination(std::string_view suggested) { const auto folder = destinationFolder(); std::error_code error; std::filesystem::create_directories(folder, error); // WebKitGTK writes into an existing folder only. if (error) throw std::filesystem::filesystem_error("WebKitGTK: cannot create the download folder", folder, error); - return uniqueDownloadPath(folder, suggested); + return reservations.reserve(folder, suggested); } void trackDownload(Api::Object download) { - Download entry{download, {}}; + Download entry{download, {}, {}}; a.refSink(download); entry.handlers.push_back(a.connect(download, "decide-destination", reinterpret_cast(onDecideDestination), this, nullptr, 0)); entry.handlers.push_back(a.connect(download, "finished", reinterpret_cast(onDownloadFinished), this, nullptr, 0)); @@ -456,6 +458,8 @@ struct Session : FailureState { return; for (auto handler : found->handlers) a.disconnect(download, handler); + if (!found->reserved.empty()) + reservations.release(found->reserved); a.unref(found->object); downloads.erase(found); } @@ -562,7 +566,11 @@ struct Session : FailureState { } static int onDecideDestination(Api::Object download, const char* suggested, Session* self) noexcept { try { - const auto destination = self->uniqueDestination(suggested ? suggested : ""); + const auto destination = self->reserveDestination(suggested ? suggested : ""); + if (const auto entry = std::ranges::find(self->downloads, download, &Download::object); entry != self->downloads.end()) + entry->reserved = destination; + else + self->reservations.release(destination); api().downloadDestination(download, destination.c_str()); } catch (...) { api().downloadCancel(download); diff --git a/test/unit/DownloadsTests.cpp b/test/unit/DownloadsTests.cpp index 927732f3..0e7a2cae 100644 --- a/test/unit/DownloadsTests.cpp +++ b/test/unit/DownloadsTests.cpp @@ -2,8 +2,13 @@ #include #include +#include #include +#include +#include +#include +using webfront::frontend::detail::DownloadReservations; using webfront::frontend::detail::uniqueDownloadPath; SCENARIO("A download name suggested by a page stays inside the download folder") { @@ -31,3 +36,57 @@ SCENARIO("A download name suggested by a page stays inside the download folder") } std::filesystem::remove_all(folder); } + +SCENARIO("Downloads that ask for the same name before their files exist get different destinations") { + const auto folder = std::filesystem::temp_directory_path() / "webfront-downloads-reserved"; + std::filesystem::remove_all(folder); + std::filesystem::create_directories(folder); + DownloadReservations reservations; + GIVEN("two downloads suggesting report.txt, neither file created yet") { + const auto first = reservations.reserve(folder, "report.txt"); + const auto second = reservations.reserve(folder, "report.txt"); + THEN("the second one is numbered") { + REQUIRE(first == folder / "report.txt"); + REQUIRE(second == folder / "report (1).txt"); + REQUIRE(reservations.reserve(folder, "report.txt") == folder / "report (2).txt"); + } + AND_WHEN("the first download ends without creating a file") { + reservations.release(first); + THEN("its name is available again") { + REQUIRE(reservations.reserve(folder, "report.txt") == first); + } + } + AND_WHEN("a file appears under a released name") { + reservations.release(first); + std::ofstream(first) << "done"; + THEN("it is the existing file that keeps the name taken") { + REQUIRE(reservations.reserve(folder, "report.txt") == folder / "report (2).txt"); + } + } + } + GIVEN("many threads asking for the same name at once") { + constexpr std::size_t threads = 16; + std::vector granted(threads); + std::vector workers; + for (std::size_t index = 0; index < threads; ++index) + workers.emplace_back([&, index] { + granted[index] = reservations.reserve(folder, "same.bin"); + }); + for (auto& worker : workers) + worker.join(); + THEN("every destination is distinct") { + REQUIRE(std::set(granted.begin(), granted.end()).size() == threads); + } + } + GIVEN("released reservations") { + const auto path = reservations.reserve(folder, "once.txt"); + reservations.release(path); + THEN("nothing stays reserved") { + DownloadReservations other; + const auto again = other.reserve(folder, "x"); + other.release(again); + REQUIRE(other.empty()); + } + } + std::filesystem::remove_all(folder); +} diff --git a/test/web/WKWebViewLifecycle.cpp b/test/web/WKWebViewLifecycle.cpp index 03635ea0..4d28569a 100644 --- a/test/web/WKWebViewLifecycle.cpp +++ b/test/web/WKWebViewLifecycle.cpp @@ -448,7 +448,7 @@ void replacedDownload() { std::ofstream(target) << oldContent; if (!downloaded.empty()) std::ofstream(temporary) << downloaded; - session.downloadDestinations[reinterpret_cast(key)] = {temporary.string(), target.string()}; + session.downloadDestinations[reinterpret_cast(key)] = {temporary.string(), target.string(), false}; }; start(1, "old", "new"); session.downloadEnded(reinterpret_cast(std::uintptr_t{1}), true); From bc3f3f351530a68366d436dc49800d506daca0d5 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 3 Nov 2026 09:57:35 +0100 Subject: [PATCH 13/18] Key a WKWebView download by its own pointer when the save panel answers, and close the window under the panels (#451) The block that answers NSSavePanel captured the download through the enclosing lambda's reference, so by the time AppKit called it the pointer read as null: the destination was recorded under a null key, downloadEnded never found it, a "Replace" choice left its .part file beside the old file and downloadFinished was never reported. Copy the pointer by value before creating the block. Found by driving the real panels. close-with-save-panel ended the application with terminate:, which never reaches the delegate while the save sheet is attached, so the test hung until its timeout. It now closes the window, as a user does. --- include/webfront/frontend/WKWebView.hpp | 3 ++- test/web/WKWebViewLifecycle.cpp | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 5540a203..7f357e8c 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -629,6 +629,7 @@ struct Session { send(panel, "setNameFieldStringValue:", name.get()); auto handler = Block_copy(completion); auto token = alive; // Not `this`: the window may close, and the session end, while the panel is open. + const id key = download; // By value: the panel answers after this lambda and its references are gone. send(panel, "retain"); void (^finished)(long) = ^(long response) { id chosen = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK @@ -646,7 +647,7 @@ struct Session { Object path(text(temporary.string())); chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); } - (*token)->downloadDestinations[download] = {temporary.string(), target.string(), reserved}; + (*token)->downloadDestinations[key] = {temporary.string(), target.string(), reserved}; } handler(chosen); send(panel, "release"); diff --git a/test/web/WKWebViewLifecycle.cpp b/test/web/WKWebViewLifecycle.cpp index 4d28569a..b1181104 100644 --- a/test/web/WKWebViewLifecycle.cpp +++ b/test/web/WKWebViewLifecycle.cpp @@ -91,7 +91,7 @@ void nativeClose(bool quit) { if (quit) send(app, "terminate:", static_cast(nullptr)); else - send(session.window, "performClose:", static_cast(nullptr)); + send(session.window, "close"); require(session.closed, "Native close/Quit did not close the session"); session.run(); } @@ -405,7 +405,7 @@ void closeWithPanel(const char* page, const char* click) { sawPanel = true; if (++*ticks > 3) { // Let the sheet settle, then close the window under it. send(timer, "invalidate"); - quitApplication(); + send(live->window, "close"); } return; } From effe73cbbc73bbda83a2598298b1a188a6af2078 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 3 Nov 2026 09:57:52 +0100 Subject: [PATCH 14/18] Record the manual qualification of the macOS save panel (#451) --- docs/FRONTENDS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 3dcafed7..a76240cb 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -63,6 +63,8 @@ Xvfb for WebKitGTK), a `Runtime.evaluate` with `userGesture` (CEF) or `evaluateJ gesture (WKWebView). The WKWebView scenarios (`WKWebViewLifecycle-download`, `-choose-file`, `-cancel-choose`, `-replaced-download`) use the test injections of `WKWebViewOptions`: they qualify the delegate wiring, the blob download policy, the destination handling and the replace-on-success logic, not the system `NSOpenPanel`/`NSSavePanel` themselves. +The real `NSSavePanel` was driven by hand (accessibility actions) on macOS: saving, and the "Replace" choice over an existing +file, report the finished download and leave no `.part` file. No automated test opens it. WebKit reduces a suggested name such as `../x.txt` to `_x.txt` before the frontend sees it. ### Tests From 109db0f6c95c43fc3363fc2462933958a36d8884 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 3 Nov 2026 10:05:18 +0100 Subject: [PATCH 15/18] Remove the incomplete files of the downloads a closing session cancels (#451) Closing the window cancelled the running WKDownloads but kept the fragments they had written at their destination, where a truncated file looks like a finished download. Only the "Replace" .part files were removed. The engine refuses an existing destination, so every incomplete file is one it created: remove them all. Verified with a slow local server, two simultaneous downloads of one name, and a response the engine cannot display. --- docs/FRONTENDS.md | 7 +++++-- include/webfront/frontend/WKWebView.hpp | 8 +++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index a76240cb..e0cbcfd8 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -63,8 +63,11 @@ Xvfb for WebKitGTK), a `Runtime.evaluate` with `userGesture` (CEF) or `evaluateJ gesture (WKWebView). The WKWebView scenarios (`WKWebViewLifecycle-download`, `-choose-file`, `-cancel-choose`, `-replaced-download`) use the test injections of `WKWebViewOptions`: they qualify the delegate wiring, the blob download policy, the destination handling and the replace-on-success logic, not the system `NSOpenPanel`/`NSSavePanel` themselves. -The real `NSSavePanel` was driven by hand (accessibility actions) on macOS: saving, and the "Replace" choice over an existing -file, report the finished download and leave no `.part` file. No automated test opens it. +The real panels were driven by hand on macOS (accessibility actions, a local slow server, no automated test): saving and the +"Replace" choice report the finished download and leave no `.part` file; cancelling the save sheet creates nothing; an +`` panel offers folders only; two simultaneous downloads of one name get `same.bin` and +`same (1).bin`; closing the window cancels the downloads in progress and removes their incomplete files; a response the +engine cannot display (`application/octet-stream`) is saved as a download. WebKit reduces a suggested name such as `../x.txt` to `_x.txt` before the frontend sees it. ### Tests diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 7f357e8c..d9df8119 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -359,15 +359,13 @@ struct Session { send(window, "endSheet:", send(sheets, "objectAtIndex:", index - 1)); } - /// Cancels the downloads still running and removes the `.part` files that a "Replace" choice made them write. + /// Cancels the downloads still running and removes the incomplete files they were writing. void abandonDownloads() noexcept { auto pending = std::exchange(downloadDestinations, {}); // Their failure callbacks must find nothing to settle. for (const auto& [download, paths] : pending) { send(download, "cancel:", static_cast(nullptr)); - if (paths.temporary != paths.target) { - std::error_code ignored; - std::filesystem::remove(paths.temporary, ignored); - } + std::error_code ignored; // The engine created this file (it refuses an existing destination): it is only a fragment. + std::filesystem::remove(paths.temporary, ignored); if (paths.reserved) reservations.release(paths.temporary); } From 158ceb5088959e64ecf07bec6f7644ad149ca7bc Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 3 Nov 2026 10:49:06 +0100 Subject: [PATCH 16/18] Fix failed download cleanup and file-service CI regressions (#451) --- docs/CHANGELOG.md | 4 +- docs/FRONTENDS.md | 2 + include/webfront/frontend/CEF.hpp | 19 ++++-- include/webfront/frontend/Downloads.hpp | 11 ++-- include/webfront/frontend/WKWebView.hpp | 58 ++++++++++-------- test/cmake/CheckFrontendConsumer.cmake | 31 ++++++++-- test/unit/CMakeLists.txt | 4 ++ test/unit/DownloadsTests.cpp | 23 +++++++ test/web/WKWebViewLifecycle.cpp | 16 +++++ test/web/WebKitGTKLifecycle.cpp | 79 +++++++++++++++++-------- 10 files changed, 181 insertions(+), 66 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3df85696..5acacfdd 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,10 +4,12 @@ - Embedded frontends: `` and downloads (#451, ADR-020 rule 6). WebKitGTK saves downloads to the user's download folder (name reduced to its last component, never overwritten); WKWebView gets `runOpenPanelWithParameters` and - `WKDownload` (not yet run on a Mac); CEF and WebView2 use the engine's own handling. A `blob:` URL of an admitted origin + `WKDownload`; CEF and WebView2 use the engine's own handling. A `blob:` URL of an admitted origin now passes the navigation policy, so a generated Blob can be downloaded. Test injection points answer the chooser and the download without a dialog (`docs/FRONTENDS.md`). On Windows, WebView2 tests exercise chooser selection and cancellation through DevTools and verify completed downloads on disk; the native dialog UI itself remains unqualified. + Failed WKWebView downloads remove their incomplete files; automatic destination selection cancels instead of reusing + an occupied path when all 10,000 candidate names are taken. - Developer environment: the distribution is served from `https://dist.webfront.fr/` (#478, ADR-021). The sources advance to 0.6.5, the first version published under that address; `site.mjs` writes the `CNAME` file of the Pages branch and `wf run pin` diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index e0cbcfd8..eaeda06a 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -69,6 +69,8 @@ The real panels were driven by hand on macOS (accessibility actions, a local slo `same (1).bin`; closing the window cancels the downloads in progress and removes their incomplete files; a response the engine cannot display (`application/octet-stream`) is saved as a download. WebKit reduces a suggested name such as `../x.txt` to `_x.txt` before the frontend sees it. +If all 10,000 candidate names are occupied, automatic destination selection fails and cancels the download. +WKWebView also removes incomplete files when a download fails, including ordinary saves without an existing target. ### Tests diff --git a/include/webfront/frontend/CEF.hpp b/include/webfront/frontend/CEF.hpp index 901587c4..7fe95c26 100644 --- a/include/webfront/frontend/CEF.hpp +++ b/include/webfront/frontend/CEF.hpp @@ -558,15 +558,22 @@ class SimpleCEFClient : public CefClient, callback->Continue(files); return true; } - bool OnBeforeDownload(CefRefPtr, CefRefPtr item, const CefString& suggested, CefRefPtr callback) override { + bool OnBeforeDownload(CefRefPtr, + CefRefPtr item, + const CefString& suggested, + CefRefPtr callback) override { if (downloadDirectory.empty()) return false; - const auto result = downloadReservations.reserve(downloadDirectory, suggested.ToString()); - { - std::scoped_lock lock{reservedMutex}; - reservedByDownload[item->GetId()] = result; + try { + const auto result = downloadReservations.reserve(downloadDirectory, suggested.ToString()); + { + std::scoped_lock lock{reservedMutex}; + reservedByDownload[item->GetId()] = result; + } + callback->Continue(result.string(), false); + } catch (const std::filesystem::filesystem_error&) { + // Returning true without continuing cancels the download, including when all candidate names are occupied. } - callback->Continue(result.string(), false); return true; } void OnDownloadUpdated(CefRefPtr, CefRefPtr item, CefRefPtr) override { diff --git a/include/webfront/frontend/Downloads.hpp b/include/webfront/frontend/Downloads.hpp index 7c2f817d..5f58d3d4 100644 --- a/include/webfront/frontend/Downloads.hpp +++ b/include/webfront/frontend/Downloads.hpp @@ -16,10 +16,10 @@ namespace webfront::frontend::detail { * Only the final component of the suggested name is kept (a page can neither choose a folder nor climb out of it), an * empty name becomes "download", and an existing file is kept: "name", then "name (1).ext", "name (2).ext", and so on. * `taken` additionally rejects the names that another download has reserved but not created yet. + * Throws `std::filesystem::filesystem_error` if all 10,000 candidates are occupied. */ -inline std::filesystem::path uniqueDownloadPath(const std::filesystem::path& folder, - std::string_view suggested, - const std::function& taken = {}) { +inline std::filesystem::path +uniqueDownloadPath(const std::filesystem::path& folder, std::string_view suggested, const std::function& taken = {}) { auto name = std::filesystem::path(std::string(suggested)).filename(); if (name.empty() || name == "." || name == "..") name = "download"; @@ -28,8 +28,11 @@ inline std::filesystem::path uniqueDownloadPath(const std::filesystem::path& const auto unavailable = [&](const std::filesystem::path& path) { return std::filesystem::exists(path, error) || (taken && taken(path)); }; - for (int index = 1; unavailable(result) && index < 10'000; ++index) + for (int index = 1; unavailable(result); ++index) { + if (index == 10'000) + throw std::filesystem::filesystem_error("No free download destination", folder / name, std::make_error_code(std::errc::file_exists)); result = folder / (name.stem().string() + " (" + std::to_string(index) + ")" + name.extension().string()); + } return result; } diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index d9df8119..9436ea6c 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -616,7 +616,12 @@ struct Session { guard([&] { if (!options.downloadDirectory.empty()) { std::filesystem::create_directories(options.downloadDirectory); // WebKit needs the folder to exist. - const auto destination = reservations.reserve(options.downloadDirectory, suggested); + std::filesystem::path destination; + try { + destination = reservations.reserve(options.downloadDirectory, suggested); + } catch (const std::filesystem::filesystem_error&) { + return; // No candidate is free: nil cancels this download without stopping the session. + } downloadDestinations[download] = {destination.string(), destination.string(), true}; Object path(text(destination.string())); result = send(type("NSURL"), "fileURLWithPath:", path.get()); @@ -625,27 +630,31 @@ struct Session { const auto panel = send(type("NSSavePanel"), "savePanel"); Object name(text(std::filesystem::path(suggested).filename().string())); send(panel, "setNameFieldStringValue:", name.get()); - auto handler = Block_copy(completion); - auto token = alive; // Not `this`: the window may close, and the session end, while the panel is open. - const id key = download; // By value: the panel answers after this lambda and its references are gone. + auto handler = Block_copy(completion); + auto token = alive; // Not `this`: the window may close, and the session end, while the panel is open. + const id key = download; // By value: the panel answers after this lambda and its references are gone. send(panel, "retain"); void (^finished)(long) = ^(long response) { id chosen = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK if (chosen && !*token) - chosen = nullptr; // The session is gone: nobody could move the file afterwards. - if (chosen) { - // "Replace" returns an existing file, which WKDownload refuses: download beside it, replace when done. - const std::filesystem::path target = utf8(send(chosen, "path")); - std::error_code code; - auto temporary = target; - bool reserved = false; - if (std::filesystem::exists(target, code)) { - temporary = (*token)->reservations.reserve(target.parent_path(), target.filename().string() + ".part"); - reserved = true; - Object path(text(temporary.string())); - chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); + chosen = nullptr; // The session is gone: nobody could move the file afterwards. + try { + if (chosen) { + // "Replace" returns an existing file, which WKDownload refuses: download beside it, replace when done. + const std::filesystem::path target = utf8(send(chosen, "path")); + std::error_code code; + auto temporary = target; + bool reserved = false; + if (std::filesystem::exists(target, code)) { + temporary = (*token)->reservations.reserve(target.parent_path(), target.filename().string() + ".part"); + reserved = true; + Object path(text(temporary.string())); + chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); + } + (*token)->downloadDestinations[key] = {temporary.string(), target.string(), reserved}; } - (*token)->downloadDestinations[key] = {temporary.string(), target.string(), reserved}; + } catch (const std::filesystem::filesystem_error&) { + chosen = nullptr; // No temporary name is free: answer WebKit once, without crossing the AppKit block. } handler(chosen); send(panel, "release"); @@ -664,16 +673,15 @@ struct Session { return; const auto pending = std::move(found->second); downloadDestinations.erase(found); - if (pending.temporary != pending.target) { + if (completed && pending.temporary != pending.target) { std::error_code replaced; - if (completed) - std::filesystem::rename(pending.temporary, pending.target, replaced); // The old file survives any failure before this. + std::filesystem::rename(pending.temporary, pending.target, replaced); // The old file survives any failure before this. if (replaced) - completed = false; // The target still holds the old file: this is not a finished download. - if (!completed) { - std::error_code cleanup; // Its own code: cleaning up must not hide the outcome of the replacement. - std::filesystem::remove(pending.temporary, cleanup); - } + completed = false; // The target still holds the old file: this is not a finished download. + } + if (!completed) { + std::error_code cleanup; + std::filesystem::remove(pending.temporary, cleanup); } if (pending.reserved) reservations.release(pending.temporary); diff --git a/test/cmake/CheckFrontendConsumer.cmake b/test/cmake/CheckFrontendConsumer.cmake index 4ba64241..259f2342 100644 --- a/test/cmake/CheckFrontendConsumer.cmake +++ b/test/cmake/CheckFrontendConsumer.cmake @@ -2,9 +2,23 @@ cmake_minimum_required(VERSION 3.31) if(NOT ROOT OR NOT WORK_DIR) message(FATAL_ERROR "ROOT and WORK_DIR are required") endif() +set(configure_args) +if(TEST_GENERATOR) + list(APPEND configure_args -G "${TEST_GENERATOR}") +endif() +if(TEST_CXX_COMPILER) + list(APPEND configure_args "-DCMAKE_CXX_COMPILER=${TEST_CXX_COMPILER}") +endif() +if(TEST_GENERATOR_PLATFORM) + list(APPEND configure_args -A "${TEST_GENERATOR_PLATFORM}") +endif() +if(TEST_GENERATOR_TOOLSET) + list(APPEND configure_args -T "${TEST_GENERATOR_TOOLSET}") +endif() foreach(probe ON OFF) foreach(full_project OFF ON) - execute_process(COMMAND "${CMAKE_COMMAND}" --fresh + message(STATUS "Consumer configure: probe=${probe}, full_project=${full_project}") + execute_process(COMMAND "${CMAKE_COMMAND}" --fresh ${configure_args} -S "${ROOT}/test/cmake/frontend-consumer" -B "${WORK_DIR}/${probe}-${full_project}" "-DROOT=${ROOT}" "-DPROBE=${probe}" "-DFULL_PROJECT=${full_project}" "-DCPM_MODULE=${CPM_MODULE}" ${DEPENDENCY_ARGS} @@ -12,6 +26,12 @@ foreach(probe ON OFF) if(NOT result EQUAL 0) message(FATAL_ERROR "Consumer native probe ${probe}: ${output}${error}") endif() + if(TEST_GENERATOR) + file(STRINGS "${WORK_DIR}/${probe}-${full_project}/CMakeCache.txt" generator REGEX "^CMAKE_GENERATOR:INTERNAL=") + if(NOT generator STREQUAL "CMAKE_GENERATOR:INTERNAL=${TEST_GENERATOR}") + message(FATAL_ERROR "Consumer lost the parent generator: ${generator}") + endif() + endif() if(NOT probe AND NOT "${output}${error}" MATCHES "parent_app_native will open the default browser instead") message(FATAL_ERROR "Consumer fallback must explain the default browser: ${output}${error}") endif() @@ -27,7 +47,8 @@ foreach(probe ON OFF) endforeach() # Explicit OFF is distinct from a probe that cannot find the dependency. -execute_process(COMMAND "${CMAKE_COMMAND}" --fresh +message(STATUS "Consumer configure: explicit OFF") +execute_process(COMMAND "${CMAKE_COMMAND}" --fresh ${configure_args} -S "${ROOT}/test/cmake/frontend-consumer" -B "${WORK_DIR}/explicit-off" "-DROOT=${ROOT}" -DPROBE=OFF -DFULL_PROJECT=ON "-DCPM_MODULE=${CPM_MODULE}" -DWEBFRONT_EMBED_CONSUMER=OFF ${DEPENDENCY_ARGS} @@ -37,7 +58,8 @@ if(NOT result EQUAL 0 OR NOT "${output}${error}" MATCHES "explicitly disabled") endif() # A support module's final option is what other directories observe. -execute_process(COMMAND "${CMAKE_COMMAND}" --fresh +message(STATUS "Consumer configure: support option change") +execute_process(COMMAND "${CMAKE_COMMAND}" --fresh ${configure_args} -S "${ROOT}/test/cmake/frontend-consumer" -B "${WORK_DIR}/support-change" "-DROOT=${ROOT}" -DPROBE=ON -DMUTATE_OTHER=ON RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) @@ -46,7 +68,8 @@ if(NOT result EQUAL 0) endif() # A consumer opts in to one of WebFront's test options only by its prefixed name (#412). -execute_process(COMMAND "${CMAKE_COMMAND}" --fresh +message(STATUS "Consumer configure: prefixed coverage option") +execute_process(COMMAND "${CMAKE_COMMAND}" --fresh ${configure_args} -S "${ROOT}/test/cmake/frontend-consumer" -B "${WORK_DIR}/consumer-coverage" "-DROOT=${ROOT}" -DPROBE=ON -DFULL_PROJECT=ON "-DCPM_MODULE=${CPM_MODULE}" -DWEBFRONT_ENABLE_COVERAGE=ON ${DEPENDENCY_ARGS} diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index f20e0e9c..b9c3373d 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -296,6 +296,10 @@ add_test(NAME FrontendConsumerConfiguration -DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/frontend-consumer -DCPM_MODULE=${CPM_DOWNLOAD_LOCATION} "-DDEPENDENCY_ARGS=${_consumer_dependency_args}" + "-DTEST_GENERATOR=${CMAKE_GENERATOR}" + "-DTEST_CXX_COMPILER=${CMAKE_CXX_COMPILER}" + "-DTEST_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}" + "-DTEST_GENERATOR_TOOLSET=${CMAKE_GENERATOR_TOOLSET}" -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckFrontendConsumer.cmake) set_tests_properties(FrontendConsumerConfiguration PROPERTIES TIMEOUT 120) # Read the actual target's launcher at generation time, including an explicitly diff --git a/test/unit/DownloadsTests.cpp b/test/unit/DownloadsTests.cpp index 0e7a2cae..3b09378b 100644 --- a/test/unit/DownloadsTests.cpp +++ b/test/unit/DownloadsTests.cpp @@ -34,6 +34,29 @@ SCENARIO("A download name suggested by a page stays inside the download folder") REQUIRE(uniqueDownloadPath(folder, "report.txt") == folder / "report (2).txt"); } } + GIVEN("every candidate is reserved by another download") { + THEN("exhaustion is reported instead of returning an occupied path") { + std::size_t probes = 0; + REQUIRE_THROWS_AS(uniqueDownloadPath(folder, + "report.txt", + [&](const auto&) { + ++probes; + return true; + }), + std::filesystem::filesystem_error); + REQUIRE(probes == 10'000); + } + } + GIVEN("only the last candidate is available") { + THEN("that candidate can still be used") { + REQUIRE(uniqueDownloadPath(folder, + "report.txt", + [&](const auto& path) { + return path.filename() != "report (9999).txt"; + }) + == folder / "report (9999).txt"); + } + } std::filesystem::remove_all(folder); } diff --git a/test/web/WKWebViewLifecycle.cpp b/test/web/WKWebViewLifecycle.cpp index b1181104..66cdac61 100644 --- a/test/web/WKWebViewLifecycle.cpp +++ b/test/web/WKWebViewLifecycle.cpp @@ -462,6 +462,22 @@ void replacedDownload() { start(3, "old", ""); // The engine reported success but the part is gone: the replacement fails, the old file stays. session.downloadEnded(reinterpret_cast(std::uintptr_t{3}), true); require(readFile(target) == "old" && finished.size() == 1, "A failed replacement was reported as a finished download"); + + // Ordinary downloads write directly to the chosen path. A network failure must remove that fragment too. + const auto ordinary = session.reservations.reserve(folder, "ordinary.txt"); + std::ofstream(ordinary) << "partial"; + const auto key = reinterpret_cast(std::uintptr_t{4}); + session.downloadDestinations[key] = {ordinary.string(), ordinary.string(), true}; + session.downloadEnded(key, false); + require(!std::filesystem::exists(ordinary), "A failed ordinary download left an incomplete file"); + require(session.reservations.empty() && finished.size() == 1, "A failed download kept its reservation or reported success"); + + // Successful ordinary downloads must keep their bytes and report the destination exactly once. + std::ofstream(ordinary) << "complete"; + session.downloadDestinations[key] = {ordinary.string(), ordinary.string(), false}; + session.downloadEnded(key, true); + require(readFile(ordinary) == "complete", "A completed ordinary download was removed"); + require(finished == std::vector{target.string(), ordinary.string()}, "An ordinary download was not reported"); require(session.downloadDestinations.empty(), "A download outlived its end"); std::filesystem::remove_all(folder); } diff --git a/test/web/WebKitGTKLifecycle.cpp b/test/web/WebKitGTKLifecycle.cpp index 01777032..d22fffa4 100644 --- a/test/web/WebKitGTKLifecycle.cpp +++ b/test/web/WebKitGTKLifecycle.cpp @@ -240,29 +240,56 @@ void downloadUserDirectory() { /// A real pointer click through the X server's XTest extension: web content only opens a file chooser for a user gesture. struct FakeClick { - void* x11 = dlopen("libX11.so.6", RTLD_NOW); - void* xtest = dlopen("libXtst.so.6", RTLD_NOW); - using Open = void* (*)(const char*); - using Flush = int (*)(void*); - using Move = int (*)(void*, int, int, int, unsigned long); - using Press = int (*)(void*, unsigned, int, unsigned long); - Open open = x11 ? reinterpret_cast(dlsym(x11, "XOpenDisplay")) : nullptr; - Flush flush = x11 ? reinterpret_cast(dlsym(x11, "XFlush")) : nullptr; - Move move = xtest ? reinterpret_cast(dlsym(xtest, "XTestFakeMotionEvent")) : nullptr; - Press press = xtest ? reinterpret_cast(dlsym(xtest, "XTestFakeButtonEvent")) : nullptr; - void* display = open ? open(nullptr) : nullptr; + void* x11 = dlopen("libX11.so.6", RTLD_NOW); + void* xtest = dlopen("libXtst.so.6", RTLD_NOW); + void* gtkModule = dlopen("libgtk-4.so.1", RTLD_NOW | RTLD_LOCAL); + using Open = void* (*)(const char*); + using Flush = int (*)(void*); + using Move = int (*)(void*, int, int, int, unsigned long); + using Press = int (*)(void*, unsigned, int, unsigned long); + using Translate = int (*)(void*, unsigned long, unsigned long, int, int, int*, int*, unsigned long*); + using Root = unsigned long (*)(void*); + using Surface = void* (*)(void*); + using Xid = unsigned long (*)(void*); + Open open = x11 ? reinterpret_cast(dlsym(x11, "XOpenDisplay")) : nullptr; + Flush flush = x11 ? reinterpret_cast(dlsym(x11, "XFlush")) : nullptr; + Move move = xtest ? reinterpret_cast(dlsym(xtest, "XTestFakeMotionEvent")) : nullptr; + Press press = xtest ? reinterpret_cast(dlsym(xtest, "XTestFakeButtonEvent")) : nullptr; + Translate translate = x11 ? reinterpret_cast(dlsym(x11, "XTranslateCoordinates")) : nullptr; + Root root = x11 ? reinterpret_cast(dlsym(x11, "XDefaultRootWindow")) : nullptr; + // GTK's client surface need not start at the root window's origin, even under Xvfb. + Surface surface = gtkModule ? reinterpret_cast(dlsym(gtkModule, "gtk_native_get_surface")) : nullptr; + Xid xid = gtkModule ? reinterpret_cast(dlsym(gtkModule, "gdk_x11_surface_get_xid")) : nullptr; + void* display = open ? open(nullptr) : nullptr; bool available() const { - return display && move && press && flush; + return display && move && press && flush && translate && root && surface && xid; } - void click(int x, int y) const { - // Without a window manager the pointer may already rest at the target: a press with no motion before it can be - // delivered before the page knows the pointer is over it. Arrive from a neighbouring point. - move(display, 0, x + 6, y + 6, 0); - flush(display); - move(display, 0, x, y, 0); - press(display, 1, 1, 0); - press(display, 1, 0, 0); + void click(void* window, int x, int y, int phase) const { + const auto native = surface(window); + if (!native) + return; + int rootX = 0, rootY = 0; + unsigned long child = 0; + if (!translate(display, xid(native), root(display), x, y, &rootX, &rootY, &child)) + throw std::runtime_error("Cannot locate the GTK file chooser in the X root window"); + // One step per poll: GTK and the web process must see the pointer enter before they receive the button events. + switch (phase) { + case 0: + move(display, 0, rootX + 120, rootY + 60, 0); + break; + case 1: + move(display, 0, rootX, rootY, 0); + break; + case 2: + press(display, 1, 1, 0); + break; + case 3: + press(display, 1, 0, 0); + break; + default: + break; + } flush(display); } }; @@ -270,7 +297,7 @@ struct FakeClick { void chooseFile(bool cancel) { const auto fixture = std::filesystem::temp_directory_path() / ("webfront-chooser-" + std::to_string(getpid()) + ".txt"); std::ofstream(fixture) << "chosen by the test"; - bool asked = false; + bool asked = false; ScenarioFrontend::configure = [&](gtk::Session& session) { session.chooseFiles = [&]() -> std::vector { asked = true; @@ -285,15 +312,15 @@ void chooseFile(bool cancel) { ScenarioFrontend::finished = [&](gtk::Session& session) { const char* current = session.a.viewTitle(session.view); title = current ? current : ""; - if (title == "ready" && !asked && ++ticks % 5 == 1) - pointer.click(40, 20); // The "Choose File" button, at the page's top-left corner. + if (title == "ready" && !asked) + pointer.click(session.window, 40, 20, ticks++ % 5); // The button's position within the GTK client surface. return title.starts_with("picked:") || title == "cancelled"; }; ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); app.show("file-services.html?choose"); std::filesystem::remove(fixture); if (!asked) - throw std::runtime_error("The file chooser was not requested (page title \"" + title + "\", " + std::to_string(ticks) + " clicks)"); + throw std::runtime_error("The file chooser was not requested (page title \"" + title + "\", " + std::to_string(ticks) + " pointer steps)"); const std::string expected = cancel ? "cancelled" : "picked:chosen by the test"; if (title != expected) throw std::runtime_error("Unexpected page state after the chooser: " + title); @@ -322,8 +349,8 @@ void closeWithDialog() { ScenarioFrontend::finished = [&](gtk::Session& session) { const char* current = session.a.viewTitle(session.view); title = current ? current : ""; - if (title == "ready" && !opened && ++ticks % 5 == 1) - pointer.click(40, 20); + if (title == "ready" && !opened) + pointer.click(session.window, 40, 20, ticks++ % 5); return opened && ++open > 10; // Let the dialog map, then close the window under it. }; ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); From 52d8c6820db895a5a97c65052a6bbcf35fe3a484 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:35:45 +0100 Subject: [PATCH 17/18] Preserve unrelated files during WKWebView downloads --- docs/CHANGELOG.md | 3 +- docs/FRONTENDS.md | 4 +- include/webfront/frontend/Downloads.hpp | 58 +++++++++++++++++++++++++ include/webfront/frontend/WKWebView.hpp | 57 ++++++++++++------------ test/unit/DownloadsTests.cpp | 31 +++++++++++++ test/web/WKWebViewLifecycle.cpp | 25 ++++++++--- 6 files changed, 139 insertions(+), 39 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 5acacfdd..ffaa02fc 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,7 +8,8 @@ now passes the navigation policy, so a generated Blob can be downloaded. Test injection points answer the chooser and the download without a dialog (`docs/FRONTENDS.md`). On Windows, WebView2 tests exercise chooser selection and cancellation through DevTools and verify completed downloads on disk; the native dialog UI itself remains unqualified. - Failed WKWebView downloads remove their incomplete files; automatic destination selection cancels instead of reusing + WKWebView stages downloads privately and preserves a destination created during transfer; failed downloads remove their + incomplete files. Automatic destination selection cancels instead of reusing an occupied path when all 10,000 candidate names are taken. - Developer environment: the distribution is served from `https://dist.webfront.fr/` (#478, ADR-021). The sources advance to 0.6.5, the diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index eaeda06a..4b445616 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -70,7 +70,9 @@ The real panels were driven by hand on macOS (accessibility actions, a local slo engine cannot display (`application/octet-stream`) is saved as a download. WebKit reduces a suggested name such as `../x.txt` to `_x.txt` before the frontend sees it. If all 10,000 candidate names are occupied, automatic destination selection fails and cancels the download. -WKWebView also removes incomplete files when a download fails, including ordinary saves without an existing target. +WKWebView writes each download in a private staging directory beside the destination. On success it installs the file; +if a destination that was free appears during the download, it preserves that file and discards the download. Failed and +cancelled downloads remove their staging directory. Installing a new destination requires hard-link support on its filesystem. ### Tests diff --git a/include/webfront/frontend/Downloads.hpp b/include/webfront/frontend/Downloads.hpp index 5f58d3d4..8df2f28b 100644 --- a/include/webfront/frontend/Downloads.hpp +++ b/include/webfront/frontend/Downloads.hpp @@ -1,15 +1,73 @@ #pragma once #include +#include #include #include +#include #include #include #include #include +#include +#include + +#ifdef __APPLE__ + #include +#endif namespace webfront::frontend::detail { +/** A private staging directory beside a download target. */ +class DownloadStaging { +public: + explicit DownloadStaging(const std::filesystem::path& parent) { +#ifdef __APPLE__ + auto pattern = (parent / ".webfront-download-XXXXXX").string(); + std::vector buffer(pattern.begin(), pattern.end()); + buffer.push_back('\0'); + if (!::mkdtemp(buffer.data())) + throw std::filesystem::filesystem_error("Cannot create download staging", parent, std::error_code(errno, std::generic_category())); + directory = buffer.data(); +#else + std::random_device random; + for (int attempt = 0; attempt < 100; ++attempt) { + auto candidate = parent / (".webfront-download-" + std::to_string(random()) + "-" + std::to_string(random())); + std::error_code error; + if (std::filesystem::create_directory(candidate, error)) { + directory = std::move(candidate); + std::filesystem::permissions(directory, std::filesystem::perms::owner_all, std::filesystem::perm_options::replace, error); + if (error) { + std::filesystem::remove(directory); + throw std::filesystem::filesystem_error("Cannot secure download staging", directory, error); + } + return; + } + if (error && error != std::errc::file_exists) + throw std::filesystem::filesystem_error("Cannot create download staging", candidate, error); + } + throw std::filesystem::filesystem_error("Cannot allocate download staging", parent, std::make_error_code(std::errc::file_exists)); +#endif + } + DownloadStaging(const DownloadStaging&) = delete; + DownloadStaging& operator=(const DownloadStaging&) = delete; + ~DownloadStaging() { + std::error_code ignored; + std::filesystem::remove_all(directory, ignored); + } + [[nodiscard]] std::filesystem::path path() const { return directory / "download"; } + bool finish(const std::filesystem::path& target, bool replace) const { + std::error_code error; + if (replace) + std::filesystem::rename(path(), target, error); + else + std::filesystem::create_hard_link(path(), target, error); + return !error; + } +private: + std::filesystem::path directory; +}; + /** * @brief A path in `folder` that does not exist yet, for a download whose name the page suggested. * diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 9436ea6c..ada3d979 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -290,9 +290,10 @@ struct Session { webfront::detail::BoundContentPolicy contentPolicy; std::function navigationCancelled; struct PendingDownload { - std::string temporary; // Where WKDownload writes: it needs a file that does not exist yet. - std::string target; // Where the user wants it; differs from `temporary` when "Replace" was chosen. - bool reserved; // `temporary` was handed out by `reservations`: give it back when the download ends. + std::unique_ptr staging; + std::filesystem::path target; + bool reserved; + bool replace; }; frontend::detail::DownloadReservations reservations; std::map downloadDestinations; // WKDownload -> its paths, until it ends. @@ -364,10 +365,8 @@ struct Session { auto pending = std::exchange(downloadDestinations, {}); // Their failure callbacks must find nothing to settle. for (const auto& [download, paths] : pending) { send(download, "cancel:", static_cast(nullptr)); - std::error_code ignored; // The engine created this file (it refuses an existing destination): it is only a fragment. - std::filesystem::remove(paths.temporary, ignored); if (paths.reserved) - reservations.release(paths.temporary); + reservations.release(paths.target); } } @@ -622,8 +621,16 @@ struct Session { } catch (const std::filesystem::filesystem_error&) { return; // No candidate is free: nil cancels this download without stopping the session. } - downloadDestinations[download] = {destination.string(), destination.string(), true}; - Object path(text(destination.string())); + std::unique_ptr staging; + try { + staging = std::make_unique(destination.parent_path()); + } catch (...) { + reservations.release(destination); + throw; + } + const auto temporary = staging->path(); + downloadDestinations[download] = {std::move(staging), destination, true, false}; + Object path(text(temporary.string())); result = send(type("NSURL"), "fileURLWithPath:", path.get()); return; } @@ -640,18 +647,16 @@ struct Session { chosen = nullptr; // The session is gone: nobody could move the file afterwards. try { if (chosen) { - // "Replace" returns an existing file, which WKDownload refuses: download beside it, replace when done. const std::filesystem::path target = utf8(send(chosen, "path")); std::error_code code; - auto temporary = target; - bool reserved = false; - if (std::filesystem::exists(target, code)) { - temporary = (*token)->reservations.reserve(target.parent_path(), target.filename().string() + ".part"); - reserved = true; - Object path(text(temporary.string())); - chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); - } - (*token)->downloadDestinations[key] = {temporary.string(), target.string(), reserved}; + const bool replace = std::filesystem::exists(target, code); + if (code) + throw std::filesystem::filesystem_error("Cannot inspect download target", target, code); + auto staging = std::make_unique(target.parent_path()); + const auto temporary = staging->path(); + Object path(text(temporary.string())); + chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); + (*token)->downloadDestinations[key] = {std::move(staging), target, false, replace}; } } catch (const std::filesystem::filesystem_error&) { chosen = nullptr; // No temporary name is free: answer WebKit once, without crossing the AppKit block. @@ -673,21 +678,13 @@ struct Session { return; const auto pending = std::move(found->second); downloadDestinations.erase(found); - if (completed && pending.temporary != pending.target) { - std::error_code replaced; - std::filesystem::rename(pending.temporary, pending.target, replaced); // The old file survives any failure before this. - if (replaced) - completed = false; // The target still holds the old file: this is not a finished download. - } - if (!completed) { - std::error_code cleanup; - std::filesystem::remove(pending.temporary, cleanup); - } + if (completed) + completed = pending.staging->finish(pending.target, pending.replace); if (pending.reserved) - reservations.release(pending.temporary); + reservations.release(pending.target); if (completed && options.downloadFinished) guard([&] { - options.downloadFinished(pending.target); + options.downloadFinished(pending.target.string()); }); } diff --git a/test/unit/DownloadsTests.cpp b/test/unit/DownloadsTests.cpp index 3b09378b..9b863f9b 100644 --- a/test/unit/DownloadsTests.cpp +++ b/test/unit/DownloadsTests.cpp @@ -11,6 +11,37 @@ using webfront::frontend::detail::DownloadReservations; using webfront::frontend::detail::uniqueDownloadPath; +SCENARIO("Download staging preserves a destination created while a download runs") { + std::random_device random; + const auto folder = std::filesystem::temp_directory_path() / ("webfront-download-staging-unit-" + std::to_string(random())); + REQUIRE(std::filesystem::create_directory(folder)); + const auto target = folder / "target.txt"; + std::filesystem::remove(target); + std::filesystem::path stagingPath; + { + webfront::frontend::detail::DownloadStaging staging(folder); + stagingPath = staging.path(); + std::ofstream(stagingPath) << "download"; + std::ofstream(target) << "other file"; + REQUIRE_FALSE(staging.finish(target, false)); + } + std::ifstream stream(target); + REQUIRE(std::string(std::istreambuf_iterator(stream), {}) == "other file"); + REQUIRE_FALSE(std::filesystem::exists(stagingPath)); + stream.close(); + std::filesystem::remove(target); + { + webfront::frontend::detail::DownloadStaging staging(folder); + std::ofstream(staging.path()) << "completed"; + REQUIRE(staging.finish(target, false)); + } + std::ifstream completed(target); + REQUIRE(std::string(std::istreambuf_iterator(completed), {}) == "completed"); + completed.close(); + std::filesystem::remove(target); + std::filesystem::remove(folder); +} + SCENARIO("A download name suggested by a page stays inside the download folder") { const auto folder = std::filesystem::temp_directory_path() / "webfront-downloads-unit"; std::filesystem::remove_all(folder); diff --git a/test/web/WKWebViewLifecycle.cpp b/test/web/WKWebViewLifecycle.cpp index 66cdac61..3ac1547c 100644 --- a/test/web/WKWebViewLifecycle.cpp +++ b/test/web/WKWebViewLifecycle.cpp @@ -439,16 +439,18 @@ void replacedDownload() { std::filesystem::remove_all(folder); std::filesystem::create_directories(folder); const auto target = folder / "report.txt"; - const auto temporary = folder / "report.txt.part"; + std::filesystem::path temporary; std::vector finished; Session session("http://127.0.0.1:0/", {.visible = false, .downloadFinished = [&](const std::string& path) { finished.push_back(path); }}); const auto start = [&](std::uintptr_t key, std::string_view oldContent, std::string_view downloaded) { std::ofstream(target) << oldContent; + auto staging = std::make_unique(folder); + temporary = staging->path(); if (!downloaded.empty()) std::ofstream(temporary) << downloaded; - session.downloadDestinations[reinterpret_cast(key)] = {temporary.string(), target.string(), false}; + session.downloadDestinations[reinterpret_cast(key)] = {std::move(staging), target, false, true}; }; start(1, "old", "new"); session.downloadEnded(reinterpret_cast(std::uintptr_t{1}), true); @@ -463,18 +465,27 @@ void replacedDownload() { session.downloadEnded(reinterpret_cast(std::uintptr_t{3}), true); require(readFile(target) == "old" && finished.size() == 1, "A failed replacement was reported as a finished download"); - // Ordinary downloads write directly to the chosen path. A network failure must remove that fragment too. + // A failed ordinary download removes its private fragment and releases its destination. const auto ordinary = session.reservations.reserve(folder, "ordinary.txt"); - std::ofstream(ordinary) << "partial"; + auto staging = std::make_unique(folder); + std::ofstream(staging->path()) << "partial"; const auto key = reinterpret_cast(std::uintptr_t{4}); - session.downloadDestinations[key] = {ordinary.string(), ordinary.string(), true}; + session.downloadDestinations[key] = {std::move(staging), ordinary, true, false}; session.downloadEnded(key, false); require(!std::filesystem::exists(ordinary), "A failed ordinary download left an incomplete file"); require(session.reservations.empty() && finished.size() == 1, "A failed download kept its reservation or reported success"); + staging = std::make_unique(folder); + session.downloadDestinations[key] = {std::move(staging), ordinary, false, false}; + std::ofstream(ordinary) << "created by another process"; + session.downloadEnded(key, false); + require(readFile(ordinary) == "created by another process", "A failed download removed an unrelated file"); + std::filesystem::remove(ordinary); + // Successful ordinary downloads must keep their bytes and report the destination exactly once. - std::ofstream(ordinary) << "complete"; - session.downloadDestinations[key] = {ordinary.string(), ordinary.string(), false}; + staging = std::make_unique(folder); + std::ofstream(staging->path()) << "complete"; + session.downloadDestinations[key] = {std::move(staging), ordinary, false, false}; session.downloadEnded(key, true); require(readFile(ordinary) == "complete", "A completed ordinary download was removed"); require(finished == std::vector{target.string(), ordinary.string()}, "An ordinary download was not reported"); From ac3b738bbbc89363690b832cf5ff866087355d8a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:38:19 +0100 Subject: [PATCH 18/18] Fix macOS staging declaration and clarify validation evidence (#451) --- docs/FRONTENDS.md | 5 ++- docs/adr/ADR-020-services-systeme.md | 20 +++++++-- include/webfront/frontend/Downloads.hpp | 2 +- test/unit/DownloadsTests.cpp | 57 ++++++++++++++++--------- 4 files changed, 58 insertions(+), 26 deletions(-) diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 4b445616..ab8a0859 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -63,11 +63,14 @@ Xvfb for WebKitGTK), a `Runtime.evaluate` with `userGesture` (CEF) or `evaluateJ gesture (WKWebView). The WKWebView scenarios (`WKWebViewLifecycle-download`, `-choose-file`, `-cancel-choose`, `-replaced-download`) use the test injections of `WKWebViewOptions`: they qualify the delegate wiring, the blob download policy, the destination handling and the replace-on-success logic, not the system `NSOpenPanel`/`NSSavePanel` themselves. -The real panels were driven by hand on macOS (accessibility actions, a local slow server, no automated test): saving and the +The real panels were driven by hand on macOS before the private staging change in `52d8c68` (accessibility actions, a +local slow server, no automated test): saving and the "Replace" choice report the finished download and leave no `.part` file; cancelling the save sheet creates nothing; an `` panel offers folders only; two simultaneous downloads of one name get `same.bin` and `same (1).bin`; closing the window cancels the downloads in progress and removes their incomplete files; a response the engine cannot display (`application/octet-stream`) is saved as a download. +These earlier manual results do not qualify the private staging implementation; the PR records subsequent validation +separately. Native dialog qualification remains incomplete. WebKit reduces a suggested name such as `../x.txt` to `_x.txt` before the frontend sees it. If all 10,000 candidate names are occupied, automatic destination selection fails and cancels the download. WKWebView writes each download in a private staging directory beside the destination. On success it installs the file; diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 5bbbb530..11295d76 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -5,7 +5,7 @@ | Version | Date | État | Auteur | Évolution | Révision Git | | --- | --- | --- | --- | --- | --- | | 1.0 | 2026-10-31 | Proposée | Ambroise Leclerc | Décision initiale : distinction hôte/client, préalables regroupés en épiques (#446 à #450), confinement des racines pendant la résolution et hypothèse de confiance face au déplacement d'un répertoire ouvert ou de la racine, autorisation attachée à l'emplacement déclaré, propriétaires admissibles des répertoires et des ancêtres, transport du navigateur système déclaré (`loopbackAttested`) plutôt que prouvé par un secret de lancement, jetons de lecture réutilisables liés à la connexion par un cookie, exposition des jetons et transport des lectures distantes, exception de confiance explicite, liaison HTTP par profil de navigateur avec cookies nommés par client, contenu actif neutralisé, transport déclaré et association de lancement du navigateur système, racines déclarées accessibles à tout script admis, services en composants facultatifs, sélection par l'utilisateur valant autorisation (poignées plutôt que chemins), backends natif, HTML et navigateur choisis par connexion, contenu des fichiers par HTTP à jeton ; état de l'art et inventaire des autres services. | À renseigner après intégration. | -| 1.1 | 2026-11-02 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de l'étape 1 pour #451 (sélecteur de fichiers et téléchargements sous WebKitGTK, CEF, WKWebView et WebView2) ; #452 reste à faire. Validations exécutées : tests unitaires de la politique de contenu, des chemins de téléchargement et de WebKitGTK ; scénarios de cycle de vie WebKitGTK, CEF, WKWebView et WebView2 de la CI ; `docs/FRONTENDS.md` précise ce que chaque moteur ne couvre pas. | Branche `451-file-chooser-downloads` (PR #484) | +| 1.1 | 2026-11-02 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison partielle de l'étape 1 pour #451 (sélecteur de fichiers et téléchargements sous WebKitGTK, CEF, WKWebView et WebView2) ; #452 reste à faire. La section « État de l'étape 1 » distingue les preuves de validation par moteur et par révision ; `docs/FRONTENDS.md` précise les limites de couverture. | Branche `451-file-chooser-downloads` (PR #484), implémentation initiale `91049ab`, stockage privé WKWebView `52d8c68` | ## État et chronologie @@ -353,8 +353,22 @@ Le code vérifié le 2026-10-31 ne permet pas encore d'implémenter ces règles. | 4 | [#449](https://github.com/ambroise-leclerc/WebFront/issues/449) Stockage modifiable et livraison des services | [#460](https://github.com/ambroise-leclerc/WebFront/issues/460) stockage sous racines déclarées, confiné pendant la résolution (révision de l'ADR-002) ; [#461](https://github.com/ambroise-leclerc/WebFront/issues/461) paquet `@webfront/services` | sélecteur HTML et écritures (règles 2 à 4) | | 5 | [#450](https://github.com/ambroise-leclerc/WebFront/issues/450) Intégration native des frontends | [#462](https://github.com/ambroise-leclerc/WebFront/issues/462) exécuteur du thread d'interface, y compris le navigateur système ; [#463](https://github.com/ambroise-leclerc/WebFront/issues/463) fenêtre native et correspondance avec les connexions | backend natif seulement | -État de l'étape 1 (#451) : sélecteur et téléchargements implémentés et exercés par la CI sous WebKitGTK, CEF, -WKWebView et WebView2 ; `docs/FRONTENDS.md` documente chaque moteur et ses limites. #452 reste à faire. +État de l'étape 1 (#451), preuves disponibles au 2026-11-03 : sélecteur et téléchargements implémentés dans les quatre +moteurs, avec des validations de provenance et de révision distinctes. Les résultats suivants ne valent que pour les +révisions indiquées ; ils ne qualifient pas automatiquement les changements ultérieurs. + +| Moteur | Source de validation | Révision et portée | +| --- | --- | --- | +| WebKitGTK | [CI Linux](https://github.com/ambroise-leclerc/WebFront/actions/runs/41628819255/job/125892906278) | `52d8c68` : suite CTest, dont sélection, annulation et téléchargements. | +| WebView2 | [CI Windows](https://github.com/ambroise-leclerc/WebFront/actions/runs/41628819255/job/125892850205) | `52d8c68` : suite CTest ; sélection interceptée par DevTools et téléchargements redirigés, sans qualification des dialogues natifs. Les 538 tests MSVC Release locaux rapportés dans la [PR #484](https://github.com/ambroise-leclerc/WebFront/pull/484) constituent une preuve locale distincte. | +| CEF | [CI étendue GCC et Clang](https://github.com/ambroise-leclerc/WebFront/actions/runs/41614144327) | `158ceb5`, antérieure au stockage privé WKWebView : scénarios CEF de fichiers et suite Jasmine. Les essais Linux locaux rapportés dans la PR sont distincts de cette exécution CI. | +| WKWebView | [CI macOS](https://github.com/ambroise-leclerc/WebFront/actions/runs/41614129707/job/125843186922) | `158ceb5`, antérieure au stockage privé ajouté dans `52d8c68` : scénarios automatisés de sélection, téléchargement, remplacement et fermeture sous un panneau. | +| WKWebView, panneaux réels | Essais manuels locaux rapportés dans la [PR #484](https://github.com/ambroise-leclerc/WebFront/pull/484) et `docs/FRONTENDS.md` | Réalisés avant `52d8c68` ; la révision exacte de chaque essai n'est pas consignée. Ces résultats ne qualifient pas le nouveau stockage privé. | + +À la révision `52d8c68`, le nouveau stockage privé WKWebView n'avait pas été exécuté sur macOS : la compilation CI avait +échoué avant les tests. Le correctif et les validations ultérieures sont consignés dans la PR #484. La qualification +des dialogues natifs reste partielle ; les injections de test ne la remplacent pas. `docs/FRONTENDS.md` détaille les +limites par moteur. #452 reste à faire et l'ADR reste proposée. Après l'étape 4, le premier service (sélecteur HTML, poignées, import et export côté client) fera l'objet de sa propre épique ; les dialogues natifs suivront l'étape 5. `PUT`/`POST` ne sont pas des préalables : les écritures passent par diff --git a/include/webfront/frontend/Downloads.hpp b/include/webfront/frontend/Downloads.hpp index 8df2f28b..5686f236 100644 --- a/include/webfront/frontend/Downloads.hpp +++ b/include/webfront/frontend/Downloads.hpp @@ -13,7 +13,7 @@ #include #ifdef __APPLE__ - #include + #include #endif namespace webfront::frontend::detail { diff --git a/test/unit/DownloadsTests.cpp b/test/unit/DownloadsTests.cpp index 9b863f9b..ffefe481 100644 --- a/test/unit/DownloadsTests.cpp +++ b/test/unit/DownloadsTests.cpp @@ -13,31 +13,46 @@ using webfront::frontend::detail::uniqueDownloadPath; SCENARIO("Download staging preserves a destination created while a download runs") { std::random_device random; - const auto folder = std::filesystem::temp_directory_path() / ("webfront-download-staging-unit-" + std::to_string(random())); + const auto folder = std::filesystem::temp_directory_path() / ("webfront-download-staging-unit-" + std::to_string(random())); REQUIRE(std::filesystem::create_directory(folder)); const auto target = folder / "target.txt"; - std::filesystem::remove(target); - std::filesystem::path stagingPath; - { - webfront::frontend::detail::DownloadStaging staging(folder); - stagingPath = staging.path(); - std::ofstream(stagingPath) << "download"; - std::ofstream(target) << "other file"; - REQUIRE_FALSE(staging.finish(target, false)); + GIVEN("another process creates the destination during the download") { + WHEN("the completed download is installed without permission to replace") { + std::filesystem::path stagingPath; + bool installed = false; + { + webfront::frontend::detail::DownloadStaging staging(folder); + stagingPath = staging.path(); + std::ofstream(stagingPath) << "download"; + std::ofstream(target) << "other file"; + installed = staging.finish(target, false); + } + THEN("the other file survives and the private staging directory is removed") { + REQUIRE_FALSE(installed); + std::ifstream stream(target); + REQUIRE(std::string(std::istreambuf_iterator(stream), {}) == "other file"); + REQUIRE_FALSE(std::filesystem::exists(stagingPath.parent_path())); + } + } } - std::ifstream stream(target); - REQUIRE(std::string(std::istreambuf_iterator(stream), {}) == "other file"); - REQUIRE_FALSE(std::filesystem::exists(stagingPath)); - stream.close(); - std::filesystem::remove(target); - { - webfront::frontend::detail::DownloadStaging staging(folder); - std::ofstream(staging.path()) << "completed"; - REQUIRE(staging.finish(target, false)); + GIVEN("the destination is free") { + WHEN("the completed download is installed") { + std::filesystem::path stagingPath; + bool installed = false; + { + webfront::frontend::detail::DownloadStaging staging(folder); + stagingPath = staging.path(); + std::ofstream(stagingPath) << "completed"; + installed = staging.finish(target, false); + } + THEN("the destination holds the completed bytes and staging is removed") { + REQUIRE(installed); + std::ifstream completed(target); + REQUIRE(std::string(std::istreambuf_iterator(completed), {}) == "completed"); + REQUIRE_FALSE(std::filesystem::exists(stagingPath.parent_path())); + } + } } - std::ifstream completed(target); - REQUIRE(std::string(std::istreambuf_iterator(completed), {}) == "completed"); - completed.close(); std::filesystem::remove(target); std::filesystem::remove(folder); }