From 912c5f8ad4346f9a5a3a410b904d81081f504482 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 29 Oct 2026 09:57:18 +0800 Subject: [PATCH] fix(browser): serve remote HTML sites at their public root --- src/apps/desktop/AGENTS.md | 5 +- src/apps/desktop/src/api/html_preview_api.rs | 99 ++++- .../desktop/src/api/html_preview_api/tests.rs | 348 +++++++++++++++++- .../remote_connect_api/relay_routes_tests.rs | 13 +- src/web-ui/src/app/scenes/browser/README.md | 21 +- tests/e2e/AGENTS.md | 6 +- tests/e2e/scripts/run-html-preview.mjs | 45 +++ 7 files changed, 525 insertions(+), 12 deletions(-) diff --git a/src/apps/desktop/AGENTS.md b/src/apps/desktop/AGENTS.md index d1c058b95b..9f5a8909aa 100644 --- a/src/apps/desktop/AGENTS.md +++ b/src/apps/desktop/AGENTS.md @@ -349,8 +349,9 @@ and rechecks its authorization binding before publishing the result. Model-scope requests require the separately advertised `subscription_model_quota_v1` capability; legacy requests retain the exact account-slot path. These tests do not contact billing. -For workspace HTML gateway authentication, chunking, cancellation and peer -capability negotiation and encrypted loopback Relay transfer, run: +For workspace HTML gateway authentication, chunking, cancellation, site-root +entry URLs, document-route fallback, owner-error preservation, peer capability +negotiation and encrypted loopback Relay transfer, run: ```bash cargo test --locked -p openbitfun-desktop --lib html_preview diff --git a/src/apps/desktop/src/api/html_preview_api.rs b/src/apps/desktop/src/api/html_preview_api.rs index 3e1c174931..1b23159796 100644 --- a/src/apps/desktop/src/api/html_preview_api.rs +++ b/src/apps/desktop/src/api/html_preview_api.rs @@ -336,7 +336,11 @@ async fn preview_handler( .status(StatusCode::FOUND) .header( header::LOCATION, - format!("/{}", encode_url_path(&state.entry_path)), + if index_entry_filename(&state.entry_path).is_some() { + "/".to_string() + } else { + format!("/{}", encode_url_path(&state.entry_path)) + }, ) .header( header::SET_COOKIE, @@ -359,20 +363,55 @@ async fn preview_handler( Ok(relative) => relative.into_owned(), Err(_) => return response(StatusCode::BAD_REQUEST, "Invalid preview path"), }; + let index_entry = index_entry_filename(&state.entry_path); + if index_entry.is_some_and(|filename| relative == filename || relative == state.entry_path) { + // The site router must see its public root, including when a link uses + // the entry filename or an older workspace-prefixed preview URL. + return Response::builder() + .status(StatusCode::FOUND) + .header(header::LOCATION, site_root_url(&uri)) + .header(header::CACHE_CONTROL, "no-store") + .header(header::REFERRER_POLICY, "no-referrer") + .body(Body::empty()) + .unwrap_or_else(|_| response(StatusCode::BAD_REQUEST, "Invalid preview path")); + } let mut request = state.request.clone(); - request.resource_path = Some(relative); + request.resource_path = if index_entry.is_some() && relative.is_empty() { + None + } else { + Some(relative.clone()) + }; request.metadata_only = method == Method::HEAD; let bypass_cache = force_resource_reload(&headers); let resource = match state .transfer .open( - request, + request.clone(), bypass_cache, uri.path_and_query().map(|path| path.as_str().to_string()), ) .await { Ok(resource) => resource, + Err(error) + if error.code == Code::NotFound + && index_entry.is_some() + && is_document_route(&relative, &headers) => + { + // Existing files always win. Only document navigation can use the + // selected index as a history-router fallback; assets, authorization + // failures and offline owners retain their original error. None is + // the existing v1 entry request, so older peer hosts work unchanged. + request.resource_path = None; + match state + .transfer + .open(request, bypass_cache, Some(site_root_url(&uri))) + .await + { + Ok(resource) => resource, + Err(error) => return preview_error_response(error), + } + } Err(error) => return preview_error_response(error), }; let size = resource.metadata.size; @@ -399,6 +438,60 @@ async fn preview_handler( }) } +fn index_entry_filename(entry_path: &str) -> Option<&str> { + entry_path.rsplit('/').next().filter(|filename| { + filename.eq_ignore_ascii_case("index.html") || filename.eq_ignore_ascii_case("index.htm") + }) +} + +fn site_root_url(uri: &Uri) -> String { + match uri.query() { + Some(query) => format!("/?{query}"), + None => "/".to_string(), + } +} + +fn is_document_route(path: &str, headers: &HeaderMap) -> bool { + // Explicit filenames (including missing .html pages) remain ordinary file + // requests. Browser fetches that accept */* are not page navigations. + if path + .trim_end_matches('/') + .rsplit('/') + .next() + .is_some_and(|part| part.contains('.')) + { + return false; + } + if headers + .get("sec-fetch-dest") + .is_some_and(|value| value != "document" && value != "iframe" && value != "frame") + { + return false; + } + headers + .get_all(header::ACCEPT) + .iter() + .filter_map(|value| value.to_str().ok()) + .any(|value| { + value.split(',').any(|range| { + let mut parts = range.trim().split(';'); + parts + .next() + .is_some_and(|mime| mime.trim().eq_ignore_ascii_case("text/html")) + && parts.all(|parameter| { + let Some((name, value)) = parameter.trim().split_once('=') else { + return true; + }; + !name.trim().eq_ignore_ascii_case("q") + || value + .trim() + .parse::() + .is_ok_and(|quality| quality > 0.0 && quality <= 1.0) + }) + }) + }) +} + fn force_resource_reload(headers: &HeaderMap) -> bool { [header::CACHE_CONTROL, header::PRAGMA].iter().any(|name| { headers diff --git a/src/apps/desktop/src/api/html_preview_api/tests.rs b/src/apps/desktop/src/api/html_preview_api/tests.rs index 3a549663b9..a5ea732091 100644 --- a/src/apps/desktop/src/api/html_preview_api/tests.rs +++ b/src/apps/desktop/src/api/html_preview_api/tests.rs @@ -118,6 +118,287 @@ async fn release(preview: HtmlPreviewCreateResponse) { .unwrap(); } +async fn site_fixture( + filename: &str, +) -> ( + tempfile::TempDir, + HtmlPreviewCreateResponse, + reqwest::Client, +) { + use openbitfun_services_integrations::remote_connect::{ + file_projection::SessionFileTarget, html_preview::HtmlPreviewSource, + }; + crate::ensure_rustls_crypto_provider(); + let directory = tempfile::tempdir().unwrap(); + let site = directory.path().join("website/dist"); + std::fs::create_dir_all(site.join("assets")).unwrap(); + std::fs::create_dir_all(site.join("guide")).unwrap(); + std::fs::write(site.join(filename), b"
site entry
").unwrap(); + std::fs::write(site.join("assets/image.png"), [137, 80, 78, 71]).unwrap(); + std::fs::write(site.join("assets/app.js"), b"window.siteLoaded=true").unwrap(); + std::fs::write(site.join("guide/index.html"), b"
static guide
").unwrap(); + let mut request = resource_request(); + request.file_path = site.join(filename).to_string_lossy().into_owned(); + let reader = HtmlPreviewSource::new( + SessionFileTarget { + fs: Arc::new(openbitfun_services_core::workspace::LocalWorkspaceFs), + root: directory.path().to_string_lossy().into_owned(), + path: request.file_path.clone(), + remote: false, + }, + "site-workspace", + ) + .await + .unwrap(); + let preview = start_preview(Arc::new(reader), request).await.unwrap(); + let client = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + (directory, preview, client) +} + +#[tokio::test] +async fn site_index_opens_at_root_and_document_routes_reuse_the_entry() { + for filename in ["index.html", "index.htm"] { + let (_directory, preview, client) = site_fixture(filename).await; + let reply = client.get(&preview.url).send().await.unwrap(); + assert_eq!(reply.headers()[header::LOCATION], "/"); + let cookie = reply.headers()[header::SET_COOKIE] + .to_str() + .unwrap() + .split(';') + .next() + .unwrap(); + let origin = reqwest::Url::parse(&preview.url) + .unwrap() + .join("/") + .unwrap(); + for route in [ + "/", + "/evaluation?tab=results", + "/zh/evaluation/snapshots/example", + "/docs/", + ] { + let reply = client + .get(origin.join(route).unwrap()) + .header(header::COOKIE, cookie) + .header(header::ACCEPT, "text/html,application/xhtml+xml,*/*;q=0.8") + .header("sec-fetch-dest", "document") + .send() + .await + .unwrap(); + assert_eq!(reply.status(), StatusCode::OK, "{filename}: {route}"); + assert_eq!(reply.text().await.unwrap(), "
site entry
"); + } + let reply = client + .head(origin.join("/evaluation").unwrap()) + .header(header::COOKIE, cookie) + .header(header::ACCEPT, "text/html") + .send() + .await + .unwrap(); + assert_eq!(reply.status(), StatusCode::OK); + assert_eq!(reply.headers()[header::CONTENT_LENGTH], "23"); + assert!(reply.bytes().await.unwrap().is_empty()); + let reply = client + .get(origin.join("/guide/").unwrap()) + .header(header::COOKIE, cookie) + .header(header::ACCEPT, "text/html") + .send() + .await + .unwrap(); + assert_eq!(reply.text().await.unwrap(), "
static guide
"); + for alias in [format!("/{filename}"), format!("/website/dist/{filename}")] { + let reply = client + .get(origin.join(&format!("{alias}?lang=en")).unwrap()) + .header(header::COOKIE, cookie) + .send() + .await + .unwrap(); + assert_eq!(reply.status(), StatusCode::FOUND); + assert_eq!(reply.headers()[header::LOCATION], "/?lang=en"); + } + release(preview).await; + } +} + +#[tokio::test] +async fn site_routes_never_replace_missing_assets_or_bypass_path_authorization() { + let (_directory, preview, client) = site_fixture("index.html").await; + let reply = client.get(&preview.url).send().await.unwrap(); + let cookie = reply.headers()[header::SET_COOKIE] + .to_str() + .unwrap() + .split(';') + .next() + .unwrap(); + let origin = reqwest::Url::parse(&preview.url) + .unwrap() + .join("/") + .unwrap(); + for (path, accept, destination) in [ + ("/assets/missing.png", "text/html", "document"), + ("/assets/missing.js", "text/html", "document"), + ("/missing.html", "text/html", "document"), + ("/missing", "application/json", "empty"), + ("/missing", "*/*", "empty"), + ("/missing", "text/html;q=0,*/*", "document"), + ("/missing", "text/html", "image"), + ("/missing", "text/html", "script"), + ] { + let reply = client + .get(origin.join(path).unwrap()) + .header(header::COOKIE, cookie) + .header(header::ACCEPT, accept) + .header("sec-fetch-dest", destination) + .send() + .await + .unwrap(); + assert_eq!( + reply.status(), + StatusCode::NOT_FOUND, + "{path}: {accept}, {destination}" + ); + } + let reply = client + .get(origin.join("/evaluation").unwrap()) + .header(header::ACCEPT, "text/html") + .send() + .await + .unwrap(); + assert_eq!(reply.status(), StatusCode::NOT_FOUND); + let reply = client + .get(origin.join("/%2e%2e%2Fprivate").unwrap()) + .header(header::COOKIE, cookie) + .header(header::ACCEPT, "text/html") + .send() + .await + .unwrap(); + assert_eq!(reply.status(), StatusCode::BAD_REQUEST); + let reply = client + .get(origin.join("/assets/image.png").unwrap()) + .header(header::COOKIE, cookie) + .header(header::ACCEPT, "image/*") + .send() + .await + .unwrap(); + assert_eq!(reply.headers()[header::CONTENT_TYPE], "image/png"); + assert_eq!(reply.bytes().await.unwrap().as_ref(), &[137, 80, 78, 71]); + release(preview).await; +} + +#[tokio::test] +async fn standalone_html_keeps_its_directory_and_does_not_gain_site_route_fallback() { + let (_directory, preview, client) = site_fixture("report #1.html").await; + let reply = client.get(&preview.url).send().await.unwrap(); + assert_eq!( + reply.headers()[header::LOCATION], + "/website/dist/report%20%231.html" + ); + let cookie = reply.headers()[header::SET_COOKIE] + .to_str() + .unwrap() + .split(';') + .next() + .unwrap(); + let reply = client + .get( + reqwest::Url::parse(&preview.url) + .unwrap() + .join("/evaluation") + .unwrap(), + ) + .header(header::COOKIE, cookie) + .header(header::ACCEPT, "text/html") + .send() + .await + .unwrap(); + assert_eq!(reply.status(), StatusCode::NOT_FOUND); + release(preview).await; +} + +#[tokio::test] +async fn site_document_routes_preserve_owner_errors_instead_of_reading_the_entry() { + struct FailingSiteReader { + error: Code, + entry_reads: std::sync::atomic::AtomicUsize, + } + #[async_trait::async_trait] + impl PreviewReader for FailingSiteReader { + async fn read( + &self, + request: &HtmlPreviewResourceRequest, + ) -> Result { + if request.resource_path.is_some() { + return Err(HtmlPreviewError::new( + self.error, + "Owner rejected the resource", + )); + } + self.entry_reads.fetch_add(1, Ordering::SeqCst); + Ok(HtmlPreviewResource { + entry_path: "website/dist/index.html".into(), + resource_path: "website/dist/index.html".into(), + source: "owner".into(), + revision: "revision".into(), + mime_type: "text/html; charset=utf-8".into(), + size: 0, + offset: 0, + content_base64: String::new(), + }) + } + } + crate::ensure_rustls_crypto_provider(); + let client = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + for (error, status) in [ + (Code::Forbidden, StatusCode::FORBIDDEN), + (Code::Unavailable, StatusCode::BAD_GATEWAY), + (Code::Changed, StatusCode::CONFLICT), + (Code::InvalidPath, StatusCode::BAD_REQUEST), + (Code::TooLarge, StatusCode::PAYLOAD_TOO_LARGE), + ] { + let reader = Arc::new(FailingSiteReader { + error, + entry_reads: Default::default(), + }); + let preview = start_preview(reader.clone(), resource_request()) + .await + .unwrap(); + let reply = client.get(&preview.url).send().await.unwrap(); + let cookie = reply.headers()[header::SET_COOKIE] + .to_str() + .unwrap() + .split(';') + .next() + .unwrap(); + let reply = client + .get( + reqwest::Url::parse(&preview.url) + .unwrap() + .join("/evaluation") + .unwrap(), + ) + .header(header::COOKIE, cookie) + .header(header::ACCEPT, "text/html") + .send() + .await + .unwrap(); + assert_eq!(reply.status(), status); + assert_eq!( + reader.entry_reads.load(Ordering::SeqCst), + 1, + "Only bootstrap may read the entry" + ); + release(preview).await; + } +} + #[tokio::test] async fn http_bootstrap_streams_bounded_chunks_and_preserves_head() { let bytes = vec![71; PREVIEW_CHUNK_BYTES * 2 + 11]; @@ -395,6 +676,69 @@ pub(crate) async fn verify_encrypted_peer_gateway( release(preview).await; } +// Uses the existing v1 peer reader, including a target without any routing changes. +pub(crate) async fn verify_encrypted_peer_site_routes( + device_id: &str, + request: HtmlPreviewResourceRequest, + expected_html: &[u8], + expected_image: &[u8], +) { + let reader = Arc::new(PeerPreviewReader { + device_id: device_id.into(), + account_generation: account_context_generation(), + }); + reader.ensure_supported().await.unwrap(); + let preview = start_preview(reader, request).await.unwrap(); + let client = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + let reply = client.get(&preview.url).send().await.unwrap(); + assert_eq!(reply.headers()[header::LOCATION], "/"); + let cookie = reply.headers()[header::SET_COOKIE] + .to_str() + .unwrap() + .split(';') + .next() + .unwrap(); + let origin = reqwest::Url::parse(&preview.url) + .unwrap() + .join("/") + .unwrap(); + for route in ["/", "/evaluation", "/docs/detail?lang=en", "/evaluation"] { + let reply = client + .get(origin.join(route).unwrap()) + .header(header::COOKIE, cookie) + .header(header::ACCEPT, "text/html") + .header(header::CACHE_CONTROL, "no-cache") + .send() + .await + .unwrap(); + assert_eq!(reply.status(), StatusCode::OK, "{route}"); + assert_eq!(reply.bytes().await.unwrap().as_ref(), expected_html); + } + let reply = client + .get(origin.join("/assets/image.png").unwrap()) + .header(header::COOKIE, cookie) + .header(header::ACCEPT, "image/png") + .send() + .await + .unwrap(); + assert_eq!(reply.status(), StatusCode::OK); + assert_eq!(reply.headers()[header::CONTENT_TYPE], "image/png"); + assert_eq!(reply.bytes().await.unwrap().as_ref(), expected_image); + let reply = client + .get(origin.join("/assets/missing.png").unwrap()) + .header(header::COOKIE, cookie) + .header(header::ACCEPT, "image/png") + .send() + .await + .unwrap(); + assert_eq!(reply.status(), StatusCode::NOT_FOUND); + release(preview).await; +} + pub(crate) async fn benchmark_encrypted_peer_gateway( device_id: &str, mut input: HtmlPreviewResourceRequest, @@ -458,7 +802,9 @@ pub(crate) async fn benchmark_encrypted_peer_gateway( stream::iter(group.iter()) .map(|(path, expected)| { let client = client.clone(); - let url = origin.join(&format!("/{path}")).unwrap(); + let url = origin + .join(if path == &files[0].0 { "/" } else { path }) + .unwrap(); async move { let response = client .get(url) diff --git a/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs b/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs index b93d0c69f3..37b72f3110 100644 --- a/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs +++ b/src/apps/desktop/src/api/remote_connect_api/relay_routes_tests.rs @@ -655,7 +655,7 @@ async fn peer_preview_fixture(benchmark: bool) { std::time::Duration::from_secs(20), crate::api::html_preview_api::tests::verify_encrypted_peer_gateway( "preview-peer", - request, + request.clone(), &bytes, ), ) @@ -666,6 +666,17 @@ async fn peer_preview_fixture(benchmark: bool) { 4, "entry metadata and three encrypted chunks" ); + tokio::time::timeout( + std::time::Duration::from_secs(20), + crate::api::html_preview_api::tests::verify_encrypted_peer_site_routes( + "preview-peer", + request, + &files[0].1, + &files[3].1, + ), + ) + .await + .unwrap(); } client.disconnect().await; serving.abort(); diff --git a/src/web-ui/src/app/scenes/browser/README.md b/src/web-ui/src/app/scenes/browser/README.md index 20beba29c6..819f7a29b3 100644 --- a/src/web-ui/src/app/scenes/browser/README.md +++ b/src/web-ui/src/app/scenes/browser/README.md @@ -122,16 +122,29 @@ must advertise `workspace_html_preview_v1`; older hosts receive an explicit upgrade message. The browser remains on the controller, and a peer read never falls back to controller-local files. -The document URL retains its workspace-relative path so `./` and `../` references -keep working. Root-relative assets such as `/assets/app.js` first resolve beside -the selected HTML, then under the workspace root. This supports a nested `dist` -without breaking workspace-prefixed links. Resources stay inside the workspace; +Opening `index.html` or `index.htm` treats its directory as the site's public +root and starts the browser at `/`. Entry-filename and workspace-prefixed entry +links redirect to that root while preserving their query. Browser document +navigation to a missing extensionless path serves the selected index, so history +routes such as `/evaluation` and deep-link reloads reach the site's router. +Existing files and directory indexes take precedence. Missing assets, explicit +filenames, non-document fetches, forbidden paths and offline owners retain their +resource errors; they never receive the index as a substitute. + +Other HTML filenames retain their workspace-relative URL so standalone documents +can keep `./` and `../` references. Index previews use normal site-root URL +resolution, including the browser's root boundary for parent-relative links. +Root-relative assets such as `/assets/app.js` first resolve beside the selected +HTML, then under the workspace root. Workspace-prefixed resource links remain +available. Resources stay inside the workspace; remote symlinks are rejected. The service streams files up to 64 MiB in 256 KiB chunks and checks workspace identity and file revision throughout a transfer. The controller prefetches up to four chunks per resource, preserves byte order, and limits each preview to eight active resources and eight remote reads. Dropped responses cancel their pending prefetches. SSH and peer resources use the same transfer service without changing the `workspace_html_preview_v1` wire contract. +Site routing is controller-side and uses the existing v1 entry request, so an +already capable older Desktop/CLI peer does not need a new routing capability. Each preview retains at most 64 complete resources / 16 MiB in memory, with a 4 MiB per-resource limit. Cache hits first revalidate the selected owner's diff --git a/tests/e2e/AGENTS.md b/tests/e2e/AGENTS.md index 9431548335..fcf764ac48 100644 --- a/tests/e2e/AGENTS.md +++ b/tests/e2e/AGENTS.md @@ -166,5 +166,9 @@ The native browser fixture uses isolated product storage and completed binary / frontend snapshots. It verifies nested build output with root-relative CSS, relative JavaScript modules and dynamic imports, parent-relative styles, images, encoded filenames, and reloading one preview after opening another. Inspect its -`result.json`; this is native local browser coverage. The services-integrations +`result.json`. It also opens a nested site index at `/`, follows a real page link, +reloads a history route, loads a deep link with a query, and verifies images/modules +plus a true 404 for a missing image. Views are shown and an image entrance +animation must finish, so decoding in a hidden view cannot satisfy the check. +This is native local browser coverage. The services-integrations OpenSSH fixture separately covers the SSH/SFTP resource provider. diff --git a/tests/e2e/scripts/run-html-preview.mjs b/tests/e2e/scripts/run-html-preview.mjs index 3e1b935235..697db05654 100644 --- a/tests/e2e/scripts/run-html-preview.mjs +++ b/tests/e2e/scripts/run-html-preview.mjs @@ -93,8 +93,16 @@ for (const [directory, color, marker] of [['site/dist', 'rgb(23, 81, 139)', 'fir await writeFile(path.join(site, 'assets/chunk.mjs'), 'export const marker = ' + JSON.stringify(marker) + ';'); await writeFile(path.join(site, 'assets/pixel.png'), Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=', 'base64')); } +const spa = path.join(workspace, 'website #1/dist'); +await mkdir(path.join(spa, 'assets'), { recursive: true }); +await writeFile(path.join(spa, 'index.html'), '
loading
Evaluation'); +await writeFile(path.join(spa, 'assets/app.css'), '#route { color: rgb(23, 81, 139); } @keyframes reveal { from { opacity: 0; } to { opacity: 1; } } #image { animation: reveal 120ms both; }'); +await writeFile(path.join(spa, 'assets/app.mjs'), 'const { routes } = await import("./routes.mjs"); document.querySelector("#route").textContent = routes.includes(location.pathname) ? location.pathname : "PAGE NOT FOUND";'); +await writeFile(path.join(spa, 'assets/routes.mjs'), 'export const routes = ["/", "/evaluation", "/docs/detail"];'); +await cp(path.join(workspace, 'site/dist/assets/pixel.png'), path.join(spa, 'assets/pixel.png')); const previews = []; async function checkPage(label, marker, color) { + await invoke('plugin:webview|webview_show', { label }); await request('/session/' + session + '/window', { handle: label }); try { await until(() => execute((marker, color) => { @@ -111,13 +119,27 @@ async function checkPage(label, marker, color) { report.checks.push(details); } finally { await request('/session/' + session + '/window', { handle: 'main' }); + await invoke('plugin:webview|webview_hide', { label }); } } +async function checkRoute(route) { + await until(() => execute(route => { + const result = document.querySelector('#route'); + const image = document.querySelector('#image'); + return document.visibilityState === 'visible' && location.pathname === route && result?.textContent === route + && getComputedStyle(result).color === 'rgb(23, 81, 139)' + && image?.complete && image.naturalWidth === 1 && getComputedStyle(image).opacity === '1'; + }, route), 'site route and resources for ' + route); + report.checks.push(await execute(() => ({ url: location.href, + route: document.querySelector('#route').textContent, imageWidth: document.querySelector('#image').naturalWidth, + resources: performance.getEntriesByType('resource').map(entry => entry.name) }))); +} try { await until(async () => (await request('/status')).ready, 'embedded driver'); session = (await request('/session', {})).sessionId; await request('/session/' + session + '/timeouts', { script: 10000 }); await until(() => execute(() => !!window.__TAURI_INTERNALS__), 'main frontend'); + await invoke('show_main_window'); const opened = await invoke('open_workspace', { request: { path: workspace, createLocal: true } }); for (const [directory, marker, color] of [['site/dist', 'first', 'rgb(23, 81, 139)'], ['other/build', 'second', 'rgb(163, 45, 18)']]) { const preview = await invoke('html_preview_create', { request: { workspaceId: opened.id, @@ -132,6 +154,29 @@ try { await request('/session/' + session + '/refresh', {}); await request('/session/' + session + '/window', { handle: 'main' }); await checkPage('embedded-browser-panel-view-html-first', 'first', 'rgb(23, 81, 139)'); + const sitePreview = await invoke('html_preview_create', { request: { workspaceId: opened.id, + filePath: path.join(spa, 'index.html') } }); + previews.push(sitePreview); + const siteLabel = 'embedded-browser-panel-view-html-site'; + await invoke('browser_webview_create', { request: { label: siteLabel, url: sitePreview.url, x: 350, y: 80, width: 480, height: 320 } }); + await invoke('plugin:webview|webview_show', { label: siteLabel }); + await request('/session/' + session + '/window', { handle: siteLabel }); + await checkRoute('/'); + await execute(() => document.querySelector('#navigate').click()); + await checkRoute('/evaluation'); + await request('/session/' + session + '/refresh', {}); + await checkRoute('/evaluation'); + const siteOrigin = new URL(sitePreview.url).origin; + await request('/session/' + session + '/url', { url: siteOrigin + '/docs/detail?lang=en' }); + await checkRoute('/docs/detail'); + assert.equal(await execute(() => location.search), '?lang=en'); + const missing = await execute(async () => { + const reply = await fetch('/assets/missing.png', { headers: { accept: 'image/png' } }); + return { status: reply.status, body: await reply.text() }; + }); + assert.equal(missing.status, 404); + assert.equal(missing.body, 'Preview resource not found'); + await request('/session/' + session + '/window', { handle: 'main' }); for (const preview of previews) await invoke('html_preview_release', { request: { sessionId: preview.sessionId } }); report.passed = true; } catch (error) {