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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions docs/validation/beforeunload-pagehide-persistence-20260921.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand All @@ -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()) {
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1454,64 +1454,105 @@
info.GetReturnValue().Set(result);
}

uint32_t request_window_close_in_current_realm(
v8::Local<v8::Context> local_context)
bool dispatch_window_lifecycle_event(
v8::Local<v8::Context> local_context,
const char* type,
bool cancelable,
bool include_persisted,
v8::Local<v8::Value>& 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<v8::Value> 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<v8::Value>& 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<v8::Value> arguments[] = {event};
if (dispatcher.As<v8::Function>()->Call(
local_context, target, 1, arguments).ToLocal(&result)) {
return true;
}
}
v8::Local<v8::Value> arguments[] = {event};
if (!dispatcher.As<v8::Function>()->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<v8::Value> 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<v8::Context> 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<v8::Value> 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();
if (beforeunload_result->IsFalse()) {
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<v8::Value> 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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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{};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand All @@ -648,27 +649,37 @@ 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 = () => {
terminalIndexedDb.error = String(transaction.error);
};
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}`;
Expand Down Expand Up @@ -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);
Expand Down
Loading