diff --git a/docs/validation/beforeunload-pagehide-persistence-20260921.md b/docs/validation/beforeunload-pagehide-persistence-20260921.md new file mode 100644 index 00000000..c8464888 --- /dev/null +++ b/docs/validation/beforeunload-pagehide-persistence-20260921.md @@ -0,0 +1,54 @@ +# Beforeunload persistence before pagehide teardown + +Date: 2026-09-21 +Issue: [#880](https://github.com/SceneTech/WebScene/issues/880) + +## Product evidence + +An exact AppScene `cd0a02e` / WebScene `a39280e4` Release reproduced an +immediate VS Code OSS reload after accepting a real MCP password input. The +replacement workbench reported one `beforeunload`, one `pagehide`, and one +reload, but `IMcpRegistry.getSavedInputs(StorageScope.WORKSPACE)` returned no +keys. A copy of the transient native database also contained no `mcpInputs` +record. + +VS Code's `beforeunload` handler asks its storage service to flush immediately. +The flush starts through a zero-delay timer. Its synchronous `pagehide` handler +then disposes the workbench and cancels that timer. The terminal persistence +lineage from #878 therefore never reached IndexedDB. + +## Runtime change + +Top-level terminal lifecycle now keeps `beforeunload` synchronous so veto and +error behavior stays unchanged. When that event creates bounded terminal +persistence work, WebScene delays `pagehide` until the existing #878 lineage +drains. It then dispatches `pagehide` once as its own browser task and waits for +any bounded zero-delay/IndexedDB descendants before exposing the host request. + +Intervals, positive-delay timers, animation frames, unrelated work, and tasks +beyond the 1,024-task terminal budget remain excluded. Pending phase state is +cleared on cancellation, failure, successful handoff, navigation reset, and +realm teardown. + +## Focused gate + +The native fixture models the unchanged VS Code sequence: `beforeunload` +schedules a zero-delay durable write, while `pagehide` clears that timer. It +requires this exact order before the reload request becomes visible: + +```text +beforeunload,flush-timer,commit,continuation,pagehide +``` + +The restarted engine must read the durable value. The retained self-refilling +timer case also consumes the bounded budget and cannot starve navigation. + +```text +ctest --test-dir /private/tmp/webscene-878-build \ + -R '^webscene_native_terminal_indexeddb_navigation$' --output-on-failure + +1/1 passed +Total real time: 1.21 seconds +``` + +The exact unchanged-product Release retest is the downstream acceptance gate. diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp index 3d7c78aa..b9870b5e 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp @@ -7027,6 +7027,7 @@ struct v8_dom_runtime::implementation final { const auto count = pending_terminal_host_requests.size(); pending_terminal_host_requests.clear(); terminal_handoff_task_budget = 0U; + terminal_pagehide_pending = false; reserved_host_request_count = count > reserved_host_request_count ? 0U : reserved_host_request_count - count; } @@ -7073,7 +7074,6 @@ struct v8_dom_runtime::implementation final { bool has_terminal_handoff_persistence_work() const noexcept { - if (pending_terminal_host_requests.empty()) return false; if (std::any_of(timers.begin(), timers.end(), [](const auto& timer) { return timer.terminal_handoff_critical; })) return true; @@ -7092,6 +7092,7 @@ struct v8_dom_runtime::implementation final { std::lock_guard lock(host_request_mutex); if (pending_terminal_host_requests.empty()) { terminal_handoff_task_budget = 0U; + terminal_pagehide_pending = false; return true; } while (!pending_terminal_host_requests.empty()) { @@ -7109,6 +7110,7 @@ struct v8_dom_runtime::implementation final { notify = true; } terminal_handoff_task_budget = 0U; + terminal_pagehide_pending = false; } if (notify && host_request_available) host_request_available(); return true; diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_browser_apis.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_browser_apis.inc index 4438b3cd..e4f03374 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_browser_apis.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_browser_apis.inc @@ -1454,55 +1454,87 @@ info.GetReturnValue().Set(result); } - uint32_t request_window_close_in_current_realm( - v8::Local local_context) + bool dispatch_window_lifecycle_event( + v8::Local local_context, + const char* type, + bool cancelable, + bool include_persisted, + v8::Local& result) { - if (local_context.IsEmpty()) { - last_error = "Native window close has no active top-level realm"; - return WEBSCENE_WINDOW_CLOSE_ERROR_V1; - } - if (terminal_pagehide_dispatched) { - return WEBSCENE_WINDOW_CLOSE_ALLOW_V1; - } - auto target = local_context->Global(); v8::Local dispatcher; if (!target->Get(local_context, js_string(isolate, "dispatchEvent")) .ToLocal(&dispatcher) || !dispatcher->IsFunction()) { last_error = "Native window close dispatcher is unavailable"; - return WEBSCENE_WINDOW_CLOSE_ERROR_V1; + return false; } - - const auto dispatch = [&](const char* type, bool cancelable, - bool include_persisted, - v8::Local& result) { - v8::TryCatch try_catch(isolate); - auto event = create_event_instance(local_context); - event->Set(local_context, js_string(isolate, "type"), - js_string(isolate, type)).Check(); - event->Set(local_context, js_string(isolate, "bubbles"), + v8::TryCatch try_catch(isolate); + auto event = create_event_instance(local_context); + event->Set(local_context, js_string(isolate, "type"), + js_string(isolate, type)).Check(); + event->Set(local_context, js_string(isolate, "bubbles"), + v8::False(isolate)).Check(); + event->Set(local_context, js_string(isolate, "cancelable"), + v8::Boolean::New(isolate, cancelable)).Check(); + if (include_persisted) { + event->Set(local_context, js_string(isolate, "persisted"), v8::False(isolate)).Check(); - event->Set(local_context, js_string(isolate, "cancelable"), - v8::Boolean::New(isolate, cancelable)).Check(); - if (include_persisted) { - event->Set(local_context, js_string(isolate, "persisted"), - v8::False(isolate)).Check(); - } - v8::Local arguments[] = {event}; - if (dispatcher.As()->Call( - local_context, target, 1, arguments).ToLocal(&result)) { - return true; - } + } + v8::Local arguments[] = {event}; + if (!dispatcher.As()->Call( + local_context, target, 1, arguments).ToLocal(&result)) { last_error = std::string("Native window ") + type + " dispatch failed: " + describe_reported_exception(try_catch, local_context); ++frame_script_error_count; return false; - }; + } + return true; + } + + bool dispatch_pending_terminal_pagehide_task() + { + if (!terminal_pagehide_pending) return true; + auto local_context = context.Get(isolate); + if (local_context.IsEmpty()) { + last_error = "Deferred native pagehide has no active top-level realm"; + return false; + } + v8::Context::Scope context_scope(local_context); + struct lifecycle_dispatch_guard final { + bool& dispatching; + bool previous; + explicit lifecycle_dispatch_guard(bool& value) + : dispatching(value), previous(value) { dispatching = true; } + ~lifecycle_dispatch_guard() { dispatching = previous; } + } dispatch_guard(window_close_lifecycle_dispatching); + v8::Local pagehide_result; + if (!dispatch_window_lifecycle_event( + local_context, "pagehide", false, true, pagehide_result)) { + return false; + } + perform_microtask_checkpoint(); + terminal_pagehide_pending = false; + terminal_pagehide_dispatched = true; + return true; + } + + uint32_t request_window_close_in_current_realm( + v8::Local local_context) + { + if (local_context.IsEmpty()) { + last_error = "Native window close has no active top-level realm"; + return WEBSCENE_WINDOW_CLOSE_ERROR_V1; + } + if (terminal_pagehide_dispatched || terminal_pagehide_pending) { + return WEBSCENE_WINDOW_CLOSE_ALLOW_V1; + } v8::Local beforeunload_result; - if (!dispatch("beforeunload", true, false, beforeunload_result)) { + if (!dispatch_window_lifecycle_event( + local_context, "beforeunload", true, false, + beforeunload_result)) { return WEBSCENE_WINDOW_CLOSE_ERROR_V1; } perform_microtask_checkpoint(); @@ -1510,8 +1542,17 @@ return WEBSCENE_WINDOW_CLOSE_VETO_V1; } + // A browser workbench can schedule its durable shutdown flush from + // beforeunload and dispose that scheduler from pagehide. Give only the + // bounded terminal-critical lineage a task boundary before teardown. + if (has_terminal_handoff_persistence_work()) { + terminal_pagehide_pending = true; + return WEBSCENE_WINDOW_CLOSE_ALLOW_V1; + } + v8::Local pagehide_result; - if (!dispatch("pagehide", false, true, pagehide_result)) { + if (!dispatch_window_lifecycle_event( + local_context, "pagehide", false, true, pagehide_result)) { return WEBSCENE_WINDOW_CLOSE_ERROR_V1; } perform_microtask_checkpoint(); diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_lifecycle.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_lifecycle.inc index 25b3da63..6b8ae58b 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_lifecycle.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_lifecycle.inc @@ -370,6 +370,7 @@ frame_dom_content_loaded_listeners.clear(); frame_beforeunload_dispatches.clear(); frame_pagehide_dispatched.clear(); + terminal_pagehide_pending = false; frame_unload_dispatches.clear(); frame_unload_dispatched.clear(); hidden_frame_document_roots.clear(); diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_navigation.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_navigation.inc index d3e56394..5644d029 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_navigation.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_navigation.inc @@ -138,6 +138,7 @@ abort_signal_compositions.clear(); retire_file_system_handles_for_contexts(retired_contexts); terminal_pagehide_dispatched = false; + terminal_pagehide_pending = false; file_targets.clear(); { std::lock_guard lock(file_requests_mutex); file_requests.clear(); } cancel_native_host_promises( diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state.inc index dca4bcfc..ad05bc63 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state.inc @@ -780,6 +780,7 @@ bool document_visible{true}; bool document_focused{true}; bool terminal_pagehide_dispatched{false}; + bool terminal_pagehide_pending{false}; bool window_close_lifecycle_dispatching{false}; bool desktop_environment_initialized{false}; webscene_desktop_environment_v1 desktop_environment{}; diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_tasks.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_tasks.inc index 31fe36c0..23768380 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_tasks.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_tasks.inc @@ -835,6 +835,13 @@ // IndexedDB persistence work, then expose every terminal request. if (!pending_terminal_host_requests.empty() && !has_terminal_handoff_persistence_work()) { + if (terminal_pagehide_pending) { + if (!dispatch_pending_terminal_pagehide_task()) { + cancel_pending_terminal_host_requests(); + return false; + } + return true; + } return drain_terminal_host_request_task(); } const auto timer_due = has_due_timer(); diff --git a/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_indexeddb_tests.inc b/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_indexeddb_tests.inc index 19459190..ea24a90b 100644 --- a/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_indexeddb_tests.inc +++ b/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_indexeddb_tests.inc @@ -639,7 +639,8 @@ void test_terminal_navigation_waits_for_indexeddb_commit() "terminal IndexedDB navigation engine creation failed"); execute_and_wait(engine, R"JS( globalThis.terminalIndexedDb = { - ready: false, committed: false, continuation: false, error: null + ready: false, committed: false, continuation: false, error: null, + order: [] }; (async () => { const database = await new Promise((resolve, reject) => { @@ -648,12 +649,15 @@ void test_terminal_navigation_waits_for_indexeddb_commit() request.onerror = () => reject(request.error); request.onsuccess = () => resolve(request.result); }); + let pendingFlushTimer = 0; addEventListener('beforeunload', () => { + terminalIndexedDb.order.push('beforeunload'); // An unrelated interval and future timer must not hold navigation. setInterval(() => {}, 60000); setTimeout(() => {}, 60000); // Browser storage commonly enters IndexedDB from a lifecycle task. - setTimeout(() => { + pendingFlushTimer = setTimeout(() => { + terminalIndexedDb.order.push('flush-timer'); const transaction = database.transaction('state', 'readwrite'); transaction.objectStore('state').put('durable', 'mcpInputs'); transaction.onerror = transaction.onabort = () => { @@ -661,14 +665,21 @@ void test_terminal_navigation_waits_for_indexeddb_commit() }; transaction.oncomplete = () => { terminalIndexedDb.committed = true; + terminalIndexedDb.order.push('commit'); // Promise/timer work descended from the native completion also // remains ahead of the terminal host handoff. Promise.resolve().then(() => setTimeout(() => { terminalIndexedDb.continuation = true; + terminalIndexedDb.order.push('continuation'); }, 0)); }; }, 0); }); + addEventListener('pagehide', () => { + terminalIndexedDb.order.push('pagehide'); + // Model VS Code disposing its delayed storage flush during pagehide. + clearTimeout(pendingFlushTimer); + }); terminalIndexedDb.ready = true; })().catch(error => { terminalIndexedDb.error = `${error?.name}:${error?.message}`; @@ -697,6 +708,8 @@ void test_terminal_navigation_waits_for_indexeddb_commit() "terminalIndexedDb.ready===true" "&&terminalIndexedDb.committed===true" "&&terminalIndexedDb.continuation===true" + "&&terminalIndexedDb.order.join(',')===" + "'beforeunload,flush-timer,commit,continuation,pagehide'" "&&terminalIndexedDb.error===null", "terminal-indexeddb-before-handoff-result.js") == "true", "terminal reload preceded IndexedDB completion: " + terminal_state);