A preview choice is selected once. The dialog closes with "selected". Later, the same connected HTMLDialogElement opens again, the user makes no choice, and the second opening is merely dismissed. If the application reads only dialog.returnValue, the second close can look indistinguishable from another selection because the element can still carry the first cycle’s string.
That is the stale-selection problem this laboratory isolates. The relevant evidence is not one property value. It is the combination of the current case_id, a monotonically increasing cycle_id, the independently authored action expected for that cycle, any current-cycle action handler that actually ran, the native close path, the stored returnValue, and the accepted-selection delta produced by the application.
Nothing here depends on an asynchronous race. The first cycle’s close processing must complete before the same DOM object is reopened. The first selection also remains legitimate: the defect is not that history exists, but that a second selection might be falsely attributed to a later dismissal.
The platform rules establish what must be tested; they are not substitutes for runtime evidence. The fixture and ten-case manifest below are therefore EXPECTED / NOT EXECUTED. No browser laboratory was executed while preparing this article, so no browser build, OS/runtime combination, Playwright version, event trace, timing, or passing result is invented. The overall runtime gate remains HOLD_PENDING_EXECUTION.
Define a result that belongs to the current opening
For a reusable dialog, “the result” needs a cycle boundary. A selection in this fixture means that an explicitly allowed positive action was recorded during the current cycle and later reconciled with a compatible native return string. A dismissal means the cycle ended without that allowed positive action. Pending action is nullable current-cycle application state. cycle_id identifies the opening to which that pending action and subsequent close evidence belong.
That distinction prevents a plausible string from becoming its own proof. The WHATWG HTML dialog rules say the returnValue getter returns the last value to which the property was set, and a newly created dialog starts with the empty string. The close algorithm changes returnValue only when its supplied result is non-null. From those rules, it is reasonable to infer that reopening the same element does not itself create a fresh result value. That retained-value conclusion is an inference to test, not an observation from this unexecuted fixture.
The application therefore keeps two independent sources of expectation. The component records a current-cycle pending_action when an approved handler actually runs. Separately, the test driver owns a literal D01–D10 action manifest. The component cannot establish its own correctness by emitting a receipt that merely looks plausible.
If cycle 1 legitimately selects a preview, its accepted ledger entry remains valid. When cycle 2 dismisses, its expected accepted-selection delta is zero. A cumulative ledger of one is still correct; a cumulative ledger of two is the defect.
This result-state boundary is intentionally narrower than the separate HTML dialog focus lifecycle, which addresses focus ownership, removed invokers, and asynchronous lifecycle concerns rather than sequential returnValue ownership.
The only application effect here is an in-memory acceptedSelections array. It is not authentication evidence, proof of a particular human identity, legal consent, or confirmation that any remote operation succeeded.
Build one reusable native dialog fixture
The fixture uses one connected <dialog>, one outside opener, ordinary programmatic controls, and one method="dialog" form. The dialog has an explicit accessible name. The form contains only two enabled, explicit submit buttons with fixed values: "selected" and "cancelled". There are no editable controls, validation-bearing fields, hidden submitters, custom elements, network requests, or persistence.
The same DOM element is deliberately preserved between sequential cycles inside a seeded case. Between independent cases, the page is reloaded, which resets the fixture without contaminating D01–D10 with preceding history.
The two controlled button paths exist to distinguish application action recording from browser result storage. choose-programmatic records the allowed current-cycle action and closes with "selected". Other controls exercise close(), close(""), and close("cancelled") without manufacturing a selection.
Save the following markup as dialog_returnvalue_fixture.html. Insert the JavaScript listing that follows inside a script element immediately before the closing body tag in that same file.
HTML markup
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Dialog returnValue sequential-cycle fixture</title>
<style>
body { font: 16px/1.5 system-ui, sans-serif; max-width: 50rem; margin: 2rem auto; }
dialog { max-width: 32rem; }
.actions { display: flex; flex-wrap: wrap; gap: .5rem; margin-block: 1rem; }
pre { white-space: pre-wrap; }
</style>
</head>
<body>
<h1>Preview choice fixture</h1>
<button id="open-dialog" type="button">Open preview chooser</button>
<dialog id="preview-dialog" aria-labelledby="dialog-title">
<h2 id="dialog-title">Choose preview result</h2>
<p>This fixture changes only an in-memory evidence ledger.</p>
<div class="actions">
<button id="close-no-arg" type="button">Close without result</button>
<button id="close-empty" type="button">Close with empty result</button>
<button id="close-cancelled" type="button">Close as cancelled</button>
<button id="choose-programmatic" type="button">
Select through programmatic path
</button>
</div>
<form id="dialog-form" method="dialog">
<div class="actions">
<button id="form-selected"
type="submit"
value="selected">
Select preview
</button>
<button id="form-cancelled"
type="submit"
value="cancelled">
Cancel preview
</button>
</div>
</form>
</dialog>
<pre id="status" aria-live="polite"></pre>
</body>
</html>JavaScript for the dialog fixture
(() => {
"use strict";
const dialog = document.querySelector("#preview-dialog");
const opener = document.querySelector("#open-dialog");
const form = document.querySelector("#dialog-form");
const status = document.querySelector("#status");
const state = {
case_id: null,
next_cycle_id: 0,
active_cycle: null,
cycles: [],
acceptedSelections: [],
browserConsole: [],
pageErrors: [],
nextOpenerConfig: null
};
function clone(value) {
return JSON.parse(JSON.stringify(value));
}
function render() {
status.textContent = JSON.stringify({
case_id: state.case_id,
cycles: state.cycles,
acceptedSelections: state.acceptedSelections
}, null, 2);
}
function activeCycleOrThrow() {
if (!state.active_cycle) {
throw new Error("No active dialog cycle");
}
return state.active_cycle;
}
function recordHandler(name, detail = {}) {
const cycle = activeCycleOrThrow();
cycle.action_handler_entries.push({
name,
detail,
cycle_id: cycle.cycle_id
});
}
function declareAction(action, source, submitter_id = null) {
const cycle = activeCycleOrThrow();
if (cycle.pending_action !== null) {
cycle.semantic_errors.push(
pending_action already set to ${cycle.pending_action}
);
return;
}
cycle.pending_action = action;
cycle.pending_action_source = source;
cycle.submitter_identity = submitter_id;
}
function defectiveStringOnlyDecision(returnValue) {
return returnValue === "selected"
? "ACCEPT_CURRENT_SELECTION"
: "DISMISS_WITHOUT_SELECTION";
}
function repairedDecision(cycle) {
if (cycle.close_event_count !== 1) {
return "HOLD_PENDING_EVIDENCE";
}
if (cycle.pending_action === "selected") {
return cycle.return_value_at_close === "selected"
? "ACCEPT_CURRENT_SELECTION"
: "REPAIR_STALE_CLASSIFICATION";
}
if (cycle.pending_action === "cancelled") {
return cycle.return_value_at_close === "cancelled"
? "DISMISS_WITHOUT_SELECTION"
: "REPAIR_STALE_CLASSIFICATION";
}
if (cycle.pending_action === null) {
return cycle.return_value_at_close === "selected"
? "REPAIR_STALE_CLASSIFICATION"
: "DISMISS_WITHOUT_SELECTION";
}
return "HOLD_PENDING_EVIDENCE";
}
function consumeAcceptedSelection(cycle) {
if (cycle.repaired_decision !== "ACCEPT_CURRENT_SELECTION") {
return;
}
if (cycle.selection_consumed) {
cycle.semantic_errors.push("duplicate selection consumption");
return;
}
const duplicate = state.acceptedSelections.some(entry =>
entry.case_id === cycle.case_id &&
entry.cycle_id === cycle.cycle_id
);
if (duplicate) {
cycle.semantic_errors.push("duplicate accepted-selection record");
return;
}
state.acceptedSelections.push({
case_id: cycle.case_id,
cycle_id: cycle.cycle_id,
action: "selected"
});
cycle.selection_consumed = true;
}
function openCycle(config) {
if (dialog.open) {
throw new Error("Cannot open: dialog is already open");
}
if (state.active_cycle !== null) {
throw new Error("Cannot open: previous close processing is incomplete");
}
const repaired = Boolean(config.repaired);
const cycle_id = ++state.next_cycle_id;
if (repaired) {
dialog.returnValue = "";
}
const cycle = {
case_id: state.case_id,
cycle_id,
intended_action: config.intended_action,
repaired_opening: repaired,
dialog_identity_matches_fixture:
dialog === document.querySelector("#preview-dialog"),
return_value_before_opening: dialog.returnValue,
return_value_after_opening: null,
return_value_at_close: null,
open_after_opening: null,
open_at_close_event: null,
pending_action: null,
pending_action_source: null,
submitter_identity: null,
action_handler_entries: [],
cancel_events: [],
close_event_count: 0,
selection_consumed: false,
accepted_count_before: state.acceptedSelections.length,
accepted_count_after: null,
accepted_selection_delta: null,
defective_decision: null,
repaired_decision: null,
semantic_errors: [],
close_processing_complete: false
};
state.active_cycle = cycle;
state.cycles.push(cycle);
dialog.showModal();
cycle.return_value_after_opening = dialog.returnValue;
cycle.open_after_opening = dialog.open;
render();
return cycle_id;
}
opener.addEventListener("click", () => {
if (!state.nextOpenerConfig) {
throw new Error("Opener used without prepared cycle configuration");
}
const config = state.nextOpenerConfig;
state.nextOpenerConfig = null;
openCycle(config);
});
dialog.addEventListener("cancel", event => {
const cycle = activeCycleOrThrow();
cycle.cancel_events.push({
cancelable: event.cancelable,
defaultPrevented: event.defaultPrevented,
open_during_handler: dialog.open,
return_value_during_handler: dialog.returnValue
});
render();
});
dialog.addEventListener("close", () => {
const cycle = activeCycleOrThrow();
cycle.close_event_count += 1;
cycle.open_at_close_event = dialog.open;
cycle.return_value_at_close = dialog.returnValue;
cycle.defective_decision =
defectiveStringOnlyDecision(dialog.returnValue);
cycle.repaired_decision = repairedDecision(cycle);
consumeAcceptedSelection(cycle);
cycle.accepted_count_after = state.acceptedSelections.length;
cycle.accepted_selection_delta =
cycle.accepted_count_after - cycle.accepted_count_before;
cycle.close_processing_complete = true;
state.active_cycle = null;
render();
});
document.querySelector("#close-no-arg")
.addEventListener("click", () => {
recordHandler("close-no-arg");
dialog.close();
});
document.querySelector("#close-empty")
.addEventListener("click", () => {
recordHandler("close-empty");
dialog.close("");
});
document.querySelector("#close-cancelled")
.addEventListener("click", () => {
recordHandler("close-cancelled");
declareAction("cancelled", "programmatic-close");
dialog.close("cancelled");
});
document.querySelector("#choose-programmatic")
.addEventListener("click", () => {
recordHandler("choose-programmatic");
declareAction("selected", "programmatic-selection");
dialog.close("selected");
});
form.addEventListener("submit", event => {
const submitter = event.submitter;
const id = submitter ? submitter.id : null;
const value = submitter ? submitter.value : null;
recordHandler("dialog-form-submit", {
submitter_id: id,
submitter_value: value
});
if (id === "form-selected" && value === "selected") {
declareAction("selected", "method-dialog-submit", id);
} else if (id === "form-cancelled" && value === "cancelled") {
declareAction("cancelled", "method-dialog-submit", id);
}
});
window.dialogLab = {
resetCase(case_id) {
if (dialog.open || state.active_cycle) {
throw new Error("Cannot reset while a cycle is active");
}
state.case_id = case_id;
state.next_cycle_id = 0;
state.cycles = [];
state.acceptedSelections = [];
state.nextOpenerConfig = null;
dialog.returnValue = "";
render();
},
open(config) {
return openCycle(config);
},
prepareOpener(config) {
if (dialog.open || state.active_cycle) {
throw new Error("Cannot prepare opener during an active cycle");
}
state.nextOpenerConfig = clone(config);
},
assignReturnValue(value) {
const cycle = activeCycleOrThrow();
recordHandler("direct-returnValue-assignment", { value });
dialog.returnValue = value;
render();
},
closeNoArg() {
recordHandler("driver-close-no-arg");
dialog.close();
},
closeEmpty() {
recordHandler("driver-close-empty");
dialog.close("");
},
closeCancelled() {
recordHandler("driver-close-cancelled");
declareAction("cancelled", "driver-close");
dialog.close("cancelled");
},
selectAndClose() {
recordHandler("driver-select-and-close");
declareAction("selected", "driver-explicit-selection");
dialog.close("selected");
},
snapshot() {
return clone({
case_id: state.case_id,
next_cycle_id: state.next_cycle_id,
cycles: state.cycles,
acceptedSelections: state.acceptedSelections,
dialog: {
open: dialog.open,
returnValue: dialog.returnValue
}
});
}
};
render();
})();Isolate cases while reusing the element within each case
A page reload between cases provides the clean fixture boundary. Within D02–D07, D09, and D10, the seed cycle and tested cycle use the same #preview-dialog object. The cycle record includes dialog_identity_matches_fixture so an accidental remount or innerHTML replacement cannot silently transform the question into “what does a new element do?”
The driver must also wait until the first close handler has set close_processing_complete=true before opening cycle 2. That barrier matters because the specification queues the close event after the dialog is closed. The experiment is deliberately sequential, not a close/reopen race.
Read the stored property separately from a close outcome
The normative starting point is unusually compact. The WHATWG dialog section says a dialog’s returnValue starts as "", its getter returns the last assigned value, and the closing algorithm writes a replacement only if its result is not null. MDN’s HTMLDialogElement.returnValue documentation likewise describes direct assignment and values supplied during closing, and notes that an Escape dismissal does not itself set a return value.
MDN documents close() as accepting an optional string that replaces the existing returnValue, and distinguishes close() from a cancelable close request. It also says the close event fires after closure. The important test distinction is therefore not “closed versus open” alone; it is whether this particular close supplied a non-null replacement and whether an application action from this cycle owns the resulting value.
showModal() is not described as resetting returnValue. Combined with the “last value” and non-null replacement rules, that supports the retained-value inference for a reused element. The experiment keeps an observed column separate precisely because the specification does not become a browser run merely by being cited.
This is also different browser state from form reset and last-saved defaults, where live form-control values and defaults are the object of study. Here the form has no editable values; the state under qualification is the dialog result property and the application’s per-cycle action ledger.
Lifecycle point | Documented or inferred expectation | Observed |
Element creation | returnValue === "" | NOT EXECUTED |
Direct property assignment | Stored string changes | NOT EXECUTED |
showModal() after old result | No reset rule identified; retention is the inference under test | NOT EXECUTED |
close() without argument | No non-null replacement supplied | NOT EXECUTED |
close("") | Explicit replacement with empty string | NOT EXECUTED |
close("cancelled") | Explicit replacement with "cancelled" | NOT EXECUTED |
Escape dismissal | No new value established merely by Escape | NOT EXECUTED |
method="dialog" selected submitter | Submitter’s optional value used as dialog result | NOT EXECUTED |
The maintenance rule is simple: stored bytes answer “what string is on this object now?” They do not, by themselves, answer “what did the current cycle do?”
Reopen after a selection and dismiss without a new value
D01 provides the clean control. A newly created fixture opens once and is closed with close() without an argument. The expected property remains empty and the accepted-selection delta is zero.
D02 is the decisive stale-history control. Cycle 1 records an allowed "selected" action and closes with "selected". Only after its close ledger is complete does cycle 2 reopen the same dialog without a reset. Cycle 2 then calls close() without an argument. Under the specification-derived inference, cycle 2’s returnValue remains "selected" even though no current-cycle selection handler ran.
A defective classifier makes the mistake explicit:
function defectiveStringOnlyDecision(returnValue) {
return returnValue === "selected"
? "ACCEPT_CURRENT_SELECTION"
: "DISMISS_WITHOUT_SELECTION";
}That function is intentionally non-effectful. It predicts what a bad implementation would do but never adds to the application’s selection ledger.
The authored second-cycle expectation is independent:
{
id: "D02",
current_action: "close()",
expected_return_value: "selected",
expected_selection_delta: 0,
expected_repaired_decision: "REPAIR_STALE_CLASSIFICATION"
}If D02 produces the inferred retained string, the string-only classifier predicts acceptance while the literal manifest expects no second selection. That disagreement is the evidence of the classification defect.
Compare the first cycle's receipt with the second cycle's intent
Do not erase the first cycle’s ledger entry to make D02 “pass.” History is exactly what the test needs. The first receipt should remain something like {case_id:"D02", cycle_id:1, action:"selected"}. The second record should carry cycle_id:2, pending_action:null, and an expected accepted-selection delta of zero.
The property may legitimately contain history. The mistake is treating history as current ownership.
For a seeded case, therefore, compare both the before and after counts:
accepted before cycle 2: 1
expected cycle-2 delta: 0
expected accepted after: 1A cumulative count of one is not evidence that the second cycle selected anything; it is evidence that the earlier selection was preserved.
Compare omitted, empty, and replacement close arguments
D03 and D04 stop three superficially similar calls from collapsing into one category.
close() supplies no string. Under the standard algorithm, the omitted argument becomes the no-result path and the close algorithm changes returnValue only when the result is non-null.
close(""), in contrast, supplies an actual string: the empty string. MDN describes the optional close() argument as replacing the existing result. D03 therefore expects seeded "selected" history to be replaced by "". The cycle still has no selection, so its delta is zero.
close("cancelled") is another explicit replacement. D04 expects the stored result to become "cancelled". In this fixture, "cancelled" is an application dismissal value, not a positive selection, so the current-cycle delta remains zero.
These cases matter because a defensive component may intentionally clear stale state. close("") is a valid way to replace the property during closure; assigning returnValue="" before opening is another. Neither operation is equivalent to proving that a positive choice occurred.
The ten-case manifest is fixed before execution:
ID | Current test action | Authored expected result | Current-cycle policy |
D01 | New element, open, close() | Empty result; closed | No selection |
D02 | Seed selected; reopen; close() | Prior "selected" retained | No second selection; stale classifier exposed |
D03 | Seed selected; close("") | "" replaces history | No selection |
D04 | Seed selected; close("cancelled") | "cancelled" | No selection |
D05 | Seed selected; real Escape | No new selection; prior result expected retained | No second selection |
D06 | Seed selected; selected method="dialog" submitter | "selected" from current submitter | Exactly one new selection |
D07 | Seed selected; cancel submitter | "cancelled" | No new selection |
D08 | Fresh cycle; assign "selected"; close() | String present without allowed selection | Reject string-only selection |
D09 | Seed; repaired opening clears; dismiss | Empty result | No new selection |
D10 | Seed; repaired opening; allowed selection; close("selected") | Current action and result agree | Exactly one new selection |
Every result in this table is EXPECTED / NOT EXECUTED.
Send Escape through the browser input path
D05 must not be implemented with dispatchEvent(new KeyboardEvent(...)) or by manually firing a cancel event. The purpose is to exercise the browser input route. Playwright Python’s Keyboard API accepts "Escape" with keyboard.press(), which generates the keyboard sequence through the automation input API rather than asking application JavaScript to fabricate the semantic event.
The cycle first seeds legitimate "selected" history. After that first close is fully recorded, the driver prepares a second opening and clicks the real outside opener. It then calls:
page.keyboard.press("Escape")The fixture registers cancel and close listeners before any case action. MDN documents cancel as occurring for a dialog close request and specifically identifies Escape as a platform close-request route. Current documentation also qualifies cancelability: platform close requests such as Escape are only cancelable under the conditions described for the triggering path and user activation. The test must therefore record event.cancelable and defaultPrevented; it must not declare that every Escape cancel is cancelable.
There is no prevention listener in this fixture. D05’s success condition is not a particular boolean for cancelable; it is complete current-cycle evidence. If the tested browser does not close, the close ledger never completes, or the trace cannot be associated with the active cycle, the decision is HOLD_PENDING_EVIDENCE.
The stale result expectation is again mechanism, not application intent: MDN says an Escape dismissal does not set a new return value. If runtime evidence shows the seeded "selected" still present, that is not a selection receipt for cycle 2.
For broader event semantics, event cancellation versus listener success is a separate problem boundary. This laboratory does not reuse its synthetic-dispatch methodology because the Escape case specifically requires a browser input path.
Wait for the close record before opening again
The automation wait targets evidence, not elapsed time:
page.wait_for_function(
"""cycleId => {
const s = window.dialogLab.snapshot();
const c = s.cycles.find(x => x.cycle_id === cycleId);
return Boolean(c && c.close_processing_complete);
}""",
cycle_id,
timeout=3000
)A timeout is missing evidence. It must not be “repaired” by manually writing the expected result into the ledger.
This same bounded barrier is used after every seeded first cycle, so cycle 2 cannot begin while cycle 1’s close handler is still pending.
Identify which method-dialog submitter supplied the value
D06 and D07 test the native method="dialog" branch without turning the fixture into a general form-submission laboratory.
The WHATWG form-submission algorithm says that when the effective method is dialog, the containing dialog is found, and for a submit button the result is set from that submitter’s optional value before the dialog is closed. The fixture restricts this to two ordinary enabled type="submit" buttons with fixed values and no validation-bearing inputs.
The form’s submit listener records event.submitter.id and its value before the browser completes the dialog close path:
form.addEventListener("submit", event => {
const submitter = event.submitter;
if (submitter.id === "form-selected") {
declareAction("selected", "method-dialog-submit", submitter.id);
} else if (submitter.id === "form-cancelled") {
declareAction("cancelled", "method-dialog-submit", submitter.id);
}
});For D06, the expected second-cycle evidence is submitter_identity:"form-selected", pending_action:"selected", return_value_at_close:"selected", and accepted-selection delta 1.
For D07, the expected evidence is submitter_identity:"form-cancelled", pending_action:"cancelled", return_value_at_close:"cancelled", and delta 0.
Submitter identity matters because it ties the value to a current-cycle action. The return string and the current action should agree, but the string is not used to invent the action after the fact.
The separate question of which controls contribute to a native payload belongs to native form-entry and submitter validation. This fixture deliberately has no FormData assertion, names, repeated values, disabled fields, or network payload.
Show why assigning a string does not record a choice
D08 is the strongest proof that returnValue === "selected" cannot be a positive-action receipt.
Open a fresh cycle, directly assign:
dialog.returnValue = "selected";Then call close() without an argument.
Direct assignment is explicitly supported by the returnValue API. But in D08 no allowed selection handler runs. The current cycle therefore has pending_action:null.
The string-only classifier predicts ACCEPT_CURRENT_SELECTION. The authored manifest expects zero accepted selections. The repaired classifier returns REPAIR_STALE_CLASSIFICATION.
This is not an assertion that direct assignment is invalid. It is a perfectly legitimate property operation. The point is narrower: mutable state cannot authenticate its own provenance.
Keep application intent independent of returnValue
The component’s pending action is intentionally small:
pending_action = null | "selected" | "cancelled"Only an approved current-cycle route sets it. The close handler consumes "selected" at most once and only when the returned value agrees.
The driver still owns a separate literal manifest. This avoids a circular test in which application code says “I selected” and the test passes merely because it reads that application claim back.
This record has bounded meaning. It establishes that an authored client-side path ran in the named cycle. It does not prove who operated the browser, establish authorization, validate legal consent, or attest to a server-side effect.
Reset result state at the start of the repaired cycle
The repaired opener clears both kinds of per-cycle ambiguity before calling showModal():
dialog.returnValue = "";
pending_action = null;
dialog.showModal();In the supplied fixture, pending_action already belongs to the newly created cycle object, while returnValue is cleared when repaired_opening is true.
D09 first creates legitimate "selected" history. Cycle 2 then uses the repaired opening and dismisses with close() without an argument. Expected evidence is an empty returnValue after opening and at close, no current selection action, and a zero accepted-selection delta.
That repair makes stale bytes less misleading, but clearing alone is not a selection protocol. D08 demonstrates why: any code can put "selected" into the property. The positive path still needs current-cycle ownership.
The historical ledger is not cleared. The accepted cycle-1 selection remains available as evidence:
history:
cycle 1 -> selected, accepted
new repaired cycle:
cycle 2 -> returnValue cleared on open
cycle 2 -> dismissed
cycle 2 -> accepted delta 0The correct repair separates historical truth from current mutable state instead of destroying both.
Accept one explicit selection from the repaired cycle
D10 is the positive repaired control. It seeds one legitimate historical selection, waits for its completed close record, opens cycle 2 with the repaired reset, records an explicit allowed current-cycle "selected" action, and calls close("selected").
Acceptance requires all of these to agree:
case_id D10
cycle_id second cycle
pending_action selected
pending_action_source approved current-cycle handler
return_value_at_close selected
close_event_count 1
selection_consumed false before reconciliation
expected delta +1Only then may the close handler append one in-memory accepted-selection record.
A mismatch is not silently normalized. For example, pending_action:"selected" with returnValue:"cancelled" produces REPAIR_STALE_CLASSIFICATION; an absent or duplicate close record produces HOLD_PENDING_EVIDENCE.
The result is deterministic because the close handler owns one reconciliation point and consumes the pending positive action once.
Check the selection delta rather than a cumulative total
Seeded cases begin cycle 2 with one accepted historical entry. Therefore:
D02 dismissal: before 1, after 1, delta 0
D05 dismissal: before 1, after 1, delta 0
D06 selection: before 1, after 2, delta 1
D07 cancel: before 1, after 1, delta 0
D09 dismissal: before 1, after 1, delta 0
D10 selection: before 1, after 2, delta 1The handler rejects a second accepted record for the same (case_id, cycle_id). That turns duplicate close processing or accidental double consumption into explicit semantic evidence rather than an inflated success count.
Reconcile the complete ten-case evidence set
The automation driver below owns the literal expected manifest, reloads the fixture between cases, preserves within-case element reuse, captures console and page errors separately, executes native Escape only through Playwright keyboard input, and rejects missing or extra records.
No version strings below are prefilled because no laboratory was executed during preparation. When the script is actually run, it records the exact OS description, Python version, installed Playwright package version, browser-reported version, fixture SHA-256 digest, headless mode, and complete case result.
Save the following driver as dialog_returnvalue_test.py in the same directory as the fixture.
from future import annotations
import hashlib
import importlib.metadata
import json
import platform
import sys
from pathlib import Path
from typing import Any
from playwright.sync_api import (
Error as PlaywrightError,
TimeoutError as PlaywrightTimeoutError,
sync_playwright,
)
FIXTURE = Path(__file__).with_name("dialog_returnvalue_fixture.html")
TIMEOUT_MS = 3000
MANIFEST: dict[str, dict[str, Any]] = {
"D01": {
"seed": False,
"repaired": False,
"action": "close_no_arg",
"expected_return": "",
"expected_delta": 0,
"expected_decision": "DISMISS_WITHOUT_SELECTION",
},
"D02": {
"seed": True,
"repaired": False,
"action": "close_no_arg",
"expected_return": "selected",
"expected_delta": 0,
"expected_decision": "REPAIR_STALE_CLASSIFICATION",
},
"D03": {
"seed": True,
"repaired": False,
"action": "close_empty",
"expected_return": "",
"expected_delta": 0,
"expected_decision": "DISMISS_WITHOUT_SELECTION",
},
"D04": {
"seed": True,
"repaired": False,
"action": "close_cancelled",
"expected_return": "cancelled",
"expected_delta": 0,
"expected_decision": "DISMISS_WITHOUT_SELECTION",
},
"D05": {
"seed": True,
"repaired": False,
"action": "escape",
"expected_return": "selected",
"expected_delta": 0,
"expected_decision": "REPAIR_STALE_CLASSIFICATION",
},
"D06": {
"seed": True,
"repaired": False,
"action": "form_selected",
"expected_return": "selected",
"expected_delta": 1,
"expected_decision": "ACCEPT_CURRENT_SELECTION",
},
"D07": {
"seed": True,
"repaired": False,
"action": "form_cancelled",
"expected_return": "cancelled",
"expected_delta": 0,
"expected_decision": "DISMISS_WITHOUT_SELECTION",
},
"D08": {
"seed": False,
"repaired": False,
"action": "assign_selected_then_close",
"expected_return": "selected",
"expected_delta": 0,
"expected_decision": "REPAIR_STALE_CLASSIFICATION",
},
"D09": {
"seed": True,
"repaired": True,
"action": "close_no_arg",
"expected_return": "",
"expected_delta": 0,
"expected_decision": "DISMISS_WITHOUT_SELECTION",
},
"D10": {
"seed": True,
"repaired": True,
"action": "explicit_selected",
"expected_return": "selected",
"expected_delta": 1,
"expected_decision": "ACCEPT_CURRENT_SELECTION",
},
}
def sha256(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
def intended_action(case_id: str) -> str:
return MANIFEST[case_id]["action"]
def wait_cycle_complete(page, cycle_id: int) -> dict[str, Any]:
page.wait_for_function(
"""
cycleId => {
const s = window.dialogLab.snapshot();
const c = s.cycles.find(x => x.cycle_id === cycleId);
return Boolean(c && c.close_processing_complete);
}
""",
cycle_id,
timeout=TIMEOUT_MS,
)
snapshot = page.evaluate("window.dialogLab.snapshot()")
matches = [
c for c in snapshot["cycles"]
if c["cycle_id"] == cycle_id
]
if len(matches) != 1:
raise AssertionError(
f"Expected exactly one record for cycle {cycle_id}, got {len(matches)}"
)
return matches[0]
def open_cycle(
page,
case_id: str,
*,
repaired: bool,
via_opener: bool = False,
) -> int:
config = {
"intended_action": intended_action(case_id),
"repaired": repaired,
}
if via_opener:
page.evaluate(
"(cfg) => window.dialogLab.prepareOpener(cfg)",
config,
)
page.locator("#open-dialog").click()
snapshot = page.evaluate("window.dialogLab.snapshot()")
return snapshot["cycles"][-1]["cycle_id"]
return page.evaluate(
"(cfg) => window.dialogLab.open(cfg)",
config,
)
def seed_selected_cycle(page, case_id: str) -> dict[str, Any]:
seed_config = {
"intended_action": "seed_selected_history",
"repaired": False,
}
cycle_id = page.evaluate(
"(cfg) => window.dialogLab.open(cfg)",
seed_config,
)
page.evaluate("window.dialogLab.selectAndClose()")
cycle = wait_cycle_complete(page, cycle_id)
if cycle["return_value_at_close"] != "selected":
raise AssertionError("Seed cycle did not record selected returnValue")
if cycle["accepted_selection_delta"] != 1:
raise AssertionError("Seed cycle did not add exactly one selection")
if cycle["repaired_decision"] != "ACCEPT_CURRENT_SELECTION":
raise AssertionError("Seed cycle was not accepted")
return cycle
def perform_action(page, case_id: str, cycle_id: int) -> None:
action = MANIFEST[case_id]["action"]
if action == "close_no_arg":
page.evaluate("window.dialogLab.closeNoArg()")
elif action == "close_empty":
page.evaluate("window.dialogLab.closeEmpty()")
elif action == "close_cancelled":
page.evaluate("window.dialogLab.closeCancelled()")
elif action == "escape":
page.keyboard.press("Escape")
elif action == "form_selected":
page.locator("#form-selected").click()
elif action == "form_cancelled":
page.locator("#form-cancelled").click()
elif action == "assign_selected_then_close":
page.evaluate("""() => {
window.dialogLab.assignReturnValue("selected");
window.dialogLab.closeNoArg();
}""")
elif action == "explicit_selected":
page.evaluate("window.dialogLab.selectAndClose()")
else:
raise AssertionError(f"Unknown action: {action}")
def validate_case(
case_id: str,
snapshot: dict[str, Any],
tested_cycle: dict[str, Any],
) -> list[str]:
expected = MANIFEST[case_id]
errors: list[str] = []
if tested_cycle["return_value_at_close"] != expected["expected_return"]:
errors.append(
"returnValue mismatch: "
f"{tested_cycle['return_value_at_close']!r} != "
f"{expected['expected_return']!r}"
)
if tested_cycle["accepted_selection_delta"] != expected["expected_delta"]:
errors.append(
"selection delta mismatch: "
f"{tested_cycle['accepted_selection_delta']} != "
f"{expected['expected_delta']}"
)
if tested_cycle["repaired_decision"] != expected["expected_decision"]:
errors.append(
"decision mismatch: "
f"{tested_cycle['repaired_decision']} != "
f"{expected['expected_decision']}"
)
if tested_cycle["close_event_count"] != 1:
errors.append(
f"expected one close event, got {tested_cycle['close_event_count']}"
)
if not tested_cycle["dialog_identity_matches_fixture"]:
errors.append("dialog identity changed inside the case")
expected_cycles = 2 if expected["seed"] else 1
if len(snapshot["cycles"]) != expected_cycles:
errors.append(
f"expected {expected_cycles} cycle records, "
f"got {len(snapshot['cycles'])}"
)
cycle_ids = [c["cycle_id"] for c in snapshot["cycles"]]
if len(cycle_ids) != len(set(cycle_ids)):
errors.append("duplicate cycle_id detected")
selection_keys = [
(x["case_id"], x["cycle_id"])
for x in snapshot["acceptedSelections"]
]
if len(selection_keys) != len(set(selection_keys)):
errors.append("duplicate accepted-selection record detected")
if case_id == "D05":
if not tested_cycle["cancel_events"]:
errors.append("Escape produced no captured cancel event")
if tested_cycle["open_at_close_event"] is not False:
errors.append("dialog still open at close-event record")
if case_id == "D06":
if tested_cycle["submitter_identity"] != "form-selected":
errors.append("wrong selected submitter identity")
if case_id == "D07":
if tested_cycle["submitter_identity"] != "form-cancelled":
errors.append("wrong cancel submitter identity")
return errors
def run() -> int:
if not FIXTURE.exists():
raise FileNotFoundError(FIXTURE)
evidence: dict[str, Any] = {
"execution_status": "EXECUTED",
"environment": {
"os": platform.platform(),
"python": sys.version,
"playwright_python": importlib.metadata.version("playwright"),
"execution_mode": "chromium headless=True",
"fixture_path": str(FIXTURE.resolve()),
"fixture_sha256": sha256(FIXTURE),
},
"manifest": MANIFEST,
"console": [],
"page_errors": [],
"cases": {},
"overall_decision": "HOLD_PENDING_EVIDENCE",
}
overall_failures: list[str] = []
with sync_playwright() as pw:
browser = pw.chromium.launch(headless=True)
evidence["environment"]["browser"] = {
"engine": "Chromium",
"version": browser.version,
}
page = browser.new_page()
page.on(
"console",
lambda msg: evidence["console"].append({
"type": msg.type,
"text": msg.text,
}),
)
page.on(
"pageerror",
lambda exc: evidence["page_errors"].append(str(exc)),
)
fixture_url = FIXTURE.resolve().as_uri()
for case_id, spec in MANIFEST.items():
record: dict[str, Any] = {
"status": "HOLD_PENDING_EVIDENCE",
"errors": [],
"snapshot": None,
}
try:
page.goto(fixture_url, wait_until="load")
page.evaluate(
"(caseId) => window.dialogLab.resetCase(caseId)",
case_id,
)
if spec["seed"]:
seed_selected_cycle(page, case_id)
cycle_id = open_cycle(
page,
case_id,
repaired=spec["repaired"],
via_opener=(case_id == "D05"),
)
perform_action(page, case_id, cycle_id)
tested_cycle = wait_cycle_complete(page, cycle_id)
snapshot = page.evaluate("window.dialogLab.snapshot()")
record["snapshot"] = snapshot
record["tested_cycle"] = tested_cycle
record["errors"] = validate_case(
case_id,
snapshot,
tested_cycle,
)
if record["errors"]:
record["status"] = "DIVERGENCE"
overall_failures.extend(
f"{case_id}: {e}" for e in record["errors"]
)
else:
record["status"] = "MATCHED_MANIFEST"
except PlaywrightTimeoutError as exc:
record["errors"].append(
f"bounded wait timed out: {exc}"
)
overall_failures.append(
f"{case_id}: missing bounded evidence"
)
except (AssertionError, PlaywrightError, Exception) as exc:
record["errors"].append(
f"{type(exc).__name__}: {exc}"
)
overall_failures.append(
f"{case_id}: {type(exc).__name__}: {exc}"
)
evidence["cases"][case_id] = record
browser.close()
required = set(MANIFEST)
actual = set(evidence["cases"])
if actual != required:
overall_failures.append(
f"case-set mismatch: expected {sorted(required)}, "
f"got {sorted(actual)}"
)
if evidence["page_errors"]:
overall_failures.append("page errors were captured")
all_matched = all(
evidence["cases"][case_id]["status"] == "MATCHED_MANIFEST"
for case_id in MANIFEST
)
evidence["overall_decision"] = (
"QUALIFIED_EXPECTATIONS_MATCHED"
if all_matched and not overall_failures
else "HOLD_PENDING_EVIDENCE"
)
evidence["overall_failures"] = overall_failures
output = Path(__file__).with_name("dialog_returnvalue_evidence.json")
output.write_text(
json.dumps(evidence, indent=2, ensure_ascii=False),
encoding="utf-8",
)
print(json.dumps(evidence["environment"], indent=2))
print(f"Evidence: {output}")
print(f"Overall: {evidence['overall_decision']}")
return 0 if evidence["overall_decision"] == "QUALIFIED_EXPECTATIONS_MATCHED" else 1
if name == "__main__":
raise SystemExit(run())The runner should be installed and its dependency recorded before execution, for example:
python -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install playwright
python -m playwright install chromium
python -m pip freeze > requirements.lock
python dialog_returnvalue_test.pyThese commands are instructions, not a record of a completed laboratory.
The preparation-time environment record is therefore intentionally empty for runtime claims:
Evidence field | Preparation record |
Browser / binary build | NOT EXECUTED (unset) |
Operating system used for browser laboratory | NOT EXECUTED (unset) |
Python used for browser laboratory | NOT EXECUTED (unset) |
Playwright package used for browser laboratory | NOT EXECUTED (unset) |
Execution mode | NOT EXECUTED (unset) |
Fixture digest from actual run | NOT EXECUTED (unset) |
Browser console observations | NOT EXECUTED (unset) |
Page errors | NOT EXECUTED (unset) |
Runtime gate | HOLD_PENDING_EXECUTION |
That is preferable to copying versions from another article or guessing what a future runner will install.
Repair an existing component and retain a safe baseline
For an existing reusable component, the bounded repair has two parts.
First, reset mutable result state when a new opening begins:
dialog.returnValue = "";
pendingAction = null;
dialog.showModal();Second, record an allowed action when that current cycle actually reaches an approved handler, and reconcile it exactly once in close.
A typical component adaptation can keep a cycle token without introducing asynchronous machinery:
let cycleId = 0;
let active = null;
const accepted = [];
function openPreview() {
if (active) {
throw new Error("Previous dialog cycle is unresolved");
}
dialog.returnValue = "";
active = {
cycle_id: ++cycleId,
pending_action: null,
consumed: false
};
dialog.showModal();
}
function choosePreview() {
if (!active || !dialog.open) {
throw new Error("No active preview cycle");
}
active.pending_action = "selected";
dialog.close("selected");
}
dialog.addEventListener("close", () => {
if (!active) {
throw new Error("Close without active cycle");
}
if (
active.pending_action === "selected" &&
dialog.returnValue === "selected" &&
!active.consumed
) {
accepted.push({
cycle_id: active.cycle_id,
result: "selected"
});
active.consumed = true;
}
active = null;
});Retain the previous component revision and the independent manifest while qualifying the repair. Do not rewrite expectations to match the candidate. D02 and D08 must remain negative controls because they are what prove that stale or directly assigned strings cannot gain current-cycle ownership.
The safe baseline is therefore not “the repaired code looks cleaner.” It is the pair of a reversible component change and an unchanged evidence contract.
Reject the candidate when result ownership is unresolved
A candidate remains unqualified if its exact build cannot be identified, a required close record is missing, cycle IDs duplicate, the fixture object was replaced unexpectedly, or the environment record is incomplete.
Reverting a local UI component can restore the earlier interface implementation. It cannot undo an external side effect that already happened elsewhere. This fixture avoids that ambiguity by performing no remote action at all.
Assign the accept, dismiss, repair, and hold decisions
The application-facing decision is derived from ownership evidence, not from string popularity.
Decision | Required evidence | Meaning |
ACCEPT_CURRENT_SELECTION | Current cycle is known; approved positive handler ran; returned result is "selected"; exactly one close record; selection not previously consumed | Add exactly one in-memory current-cycle selection |
DISMISS_WITHOUT_SELECTION | Current cycle is known; no approved positive action owns the result; dismissal/cancel evidence is coherent | Close cycle with delta zero |
REPAIR_STALE_CLASSIFICATION | A plausible positive string exists without an allowed current-cycle positive action, or current action/result disagree | Component classification is unsafe; do not add a selection |
HOLD_PENDING_EVIDENCE | Missing case/cycle record, timeout, duplicate evidence, unresolved event path, environment/build missing, or contradictory observations | Do not qualify the runtime |
The component owner defines which current-cycle handlers are allowed to establish pending_action. QA owns D01–D10 completeness, expected-cycle counts, event traces, exact strings, duplicate rejection, and selection deltas. The reviewer checks that the evidence bundle contains the actual browser version, OS, Python, Playwright package, execution mode, fixture digest, console messages, and page errors from the run being assessed.
For D05, cancelable is evidence, not the acceptance criterion. MDN’s current documentation explicitly makes platform-close cancelability conditional rather than universal. For D06/D07, submitter identity is required because the standard’s dialog-method branch takes the submit button’s optional value.
The exclusions remain deliberate: focus restoration, full keyboard and assistive-technology qualification, removed triggers, asynchronous responses, overlapping openings, form-reset defaults, listener exceptions, authentication, real consent, network requests, and remote persistence are outside this result qualification. requestClose(), closedby, commandfor, manual open-attribute removal, and their compatibility rollout are also excluded.
Interaction-admission questions such as whether inert content can receive focus belong to testing interaction with inert content, not to this return-value ownership gate.
Until a retained execution record exists, all ten rows remain EXPECTED / NOT EXECUTED, and the only defensible overall status is HOLD_PENDING_EXECUTION.
Develop browser-state testing practice with Refonte Learning
The useful handoff from this laboratory is concrete: one reusable component, one literal action manifest that does not derive intent from returnValue, per-cycle native event evidence, an accepted-selection delta, and a bounded decision. That pattern generalizes to frontend state testing without pretending that browser properties prove more than their documented semantics.
Refonte Learning’s FrontEnd Developer Program page, as of November 26, 2026, lists a four-month period and 10–12 hours per week. It describes basic programming concepts as a requirement with HTML/CSS familiarity as a plus, and separately states an admission prerequisite of working toward a bachelor’s or higher-level degree. The published competencies include HTML5/CSS3, JavaScript ES6+, responsive design, React, Redux, APIs/AJAX, Git, accessibility, and performance, with a capstone listed among the featured expertise. The page also identifies an educational mentor and says successful completion can lead to Training and Internship certificates.
For engineers strengthening JavaScript and browser-interface fundamentals, those confirmed foundations provide the relevant connection. The published program information does not confirm this specialised sequential-dialog experiment as a syllabus module or guarantee placement, employment, or a particular mentoring schedule.
