Skip to content

AsyncContext proposal integration - #13063

Open
nicolo-ribaudo wants to merge 20 commits into
whatwg:mainfrom
nicolo-ribaudo:async-context/html-pr
Open

nicolo-ribaudo wants to merge 20 commits into
whatwg:mainfrom
nicolo-ribaudo:async-context/html-pr

Conversation

@nicolo-ribaudo

@nicolo-ribaudo nicolo-ribaudo commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

Ref #10432

This PR integrates the AsyncContext proposal into HTML APIs. This PR includes:

  • basic refs to the proposal
  • propagation through APIs that take a callback to signal completion
  • propagation through top-level script execution
  • propagation through APIs that fire events (this is what most of the PR is for). A lot of those APIs actually needed no change, because either they are sync or the event is meant to run in the empty context.
  • propagation to custom element reactions

It follows the design decisions discussed at past WHATNOT meetings, and written down in https://github.com/tc39/proposal-async-context/blob/master/WEB-INTEGRATION.md / https://github.com/tc39/proposal-async-context/blob/master/web-integration/html__events.md

For custom element reactions it follows what's currently described in detail at https://github.com/tc39/proposal-async-context/blob/main/web-integration/html__custom-elements.md. That's a new document, but it's the behavior we get by applying the two bullet points we had in WEB-INTEGRATION.md about custom elements.

I am maintaining a gh stack parallel to this PR with the same changes at https://github.com/nicolo-ribaudo/html/pulls?q=sort%3Acreated-desc%20is%3Apr%20label%3A%22async%20context%22: it was originally there to help myself with tracking the status of what I was doing, but I believe it can also be useful for reviewers to see more detailed context behind why some changes are the way they are (each of those PRs has a semi-detailed list of decisions and things to test in WPT).

There currently are some open questions:

Corresponding PRs in other specs that need to land at the same time (they cyclically depend on each other) are whatwg/webidl#1568 and whatwg/dom#1451.

I also have a pending WebIDL PR to open to capture the context for rejection in WebIDL-managed promises, so that the Expose Async Context Mappings on promise rejection events commit works for them as well as it does for JS-created ones. UPDATE: we might make the change in the ECMAScript proposal instead.


  • At least two implementers are interested (and none opposed):
    • …
    • …
  • Tests are written and can be reviewed and commented upon at:
    • …
  • Implementation bugs are filed:
    • Chromium: …
    • Gecko: …
    • WebKit: …
    • Deno (only for timers, structured clone, base64 utils, channel messaging, module resolution, web workers, and web storage): …
    • Node.js (only for timers, structured clone, base64 utils, channel messaging, and module resolution): …
  • Corresponding HTML AAM & ARIA in HTML issues & PRs:
  • MDN issue is filed: …
  • The top of this comment includes a clear commit message to use.

(See WHATWG Working Mode: Changes for more details.)


/browsing-the-web.html ( diff )
/canvas.html ( diff )
/custom-elements.html ( diff )
/dnd.html ( diff )
/document-lifecycle.html ( diff )
/dom.html ( diff )
/iframe-embed-object.html ( diff )
/imagebitmap-and-animations.html ( diff )
/images.html ( diff )
/index.html ( diff )
/infrastructure.html ( diff )
/input.html ( diff )
/interaction.html ( diff )
/interactive-elements.html ( diff )
/links.html ( diff )
/media.html ( diff )
/obsolete.html ( diff )
/popover.html ( diff )
/references.html ( diff )
/scripting.html ( diff )
/semantics.html ( diff )
/server-sent-events.html ( diff )
/timers-and-user-prompts.html ( diff )
/webappapis.html ( diff )
/workers.html ( diff )

andreubotella and others added 19 commits October 12, 2026 14:54
This PR updates HTML to integrate with the TC39 AsyncContext proposal,
which allows storing state associated with an async flow of execution
in JavaScript, and preserving it across different kinds of async
continuations in both JS and the web platform.

This PR does not yet handle events, since the exact behavior of those
with AsyncContext is still pending to be fully decided. But it covers
microtasks, timers, deferred script execution, focus/blur and others.

This patch does not include any changes to the `error` and
`unhandledrejection` event handling, as well as to
`HostEnqueueFinalizationRegistryCleanupJob`. This relies on the
assumption that the changes in tc39/proposal-async-context#148 and
tc39/proposal-async-context#150 will be accepted. Otherwise, error
contexts will need to be handled in HTML.

This patch relies on PR [TODO] to define the
`[PropagatesAsyncContext]` extended attribute in WebIDL.
Co-Authored-By: Nicolò Ribaudo <nribaudo@igalia.com>
Co-Authored-By: Nicolò Ribaudo <nribaudo@igalia.com>
Co-Authored-By: Nicolò Ribaudo <nribaudo@igalia.com>
The mapping captured when the container navigates is threaded through
navigate and attempt to populate the history entry's document, stored on
the created Document, and consumed by completely finish loading a
document to fire the load event on the container.

Navigations initiated inside the frame reach navigate without the
argument, so their load events do not inherit the embedder's context.
The frame element is covered transitively, since navigate an iframe or
frame is shared.

Co-Authored-By: Nicolò Ribaudo <nribaudo@igalia.com>
Co-Authored-By: Nicolò Ribaudo <nribaudo@igalia.com>
Co-Authored-By: Nicolò Ribaudo <nribaudo@igalia.com>
Co-Authored-By: Nicolò Ribaudo <nribaudo@igalia.com>
Co-Authored-By: Nicolò Ribaudo <nribaudo@igalia.com>
The details, dialog and popover elements all queue their toggle event
through a toggle task tracker. The various algorithms to queue firing
those events (which are always run synchronously with the mutation)
capture the context and use it to actually fire the event.

Closing a dialog captures once and uses the same mapping for both the
toggle event and the close event.

beforetoggle and cancel are fired synchronously and so are already
transparent to AsyncContext.
@nicolo-ribaudo

nicolo-ribaudo commented Oct 20, 2026 •

Copy link
Copy Markdown
Member Author

I updated the PR (and PR description) to also cover custom element reactions. That was the last big piece missing.

@nicolo-ribaudo

nicolo-ribaudo commented Oct 29, 2026 •

Copy link
Copy Markdown
Member Author

I run the html-spec-review skill on this PR and it found some problems (I still need to study / address it, but posting it here in case anybody is curious):

Details

Review — async-context/html-pr (whatwg/html#13063) against its fork point on main

Base 86190a4d (merge-base with main) · head 524df481 · 20 commits · source only, 1085+/414−.
Reviewed 2026-10-29.

How this was produced. I read the full diff commit by commit and ran static checks on the base
and the head, keeping only what the branch introduced. For each new parameter I grepped every call
site with a multi-line-aware search. I compared the text against the proposal's web-integration
documents at
ff809754,
and re-checked whatwg/webidl#1568 at its current head
3188eabd.

Proposal documents cited below:

Locations. Each finding names the algorithm, its anchor (#id) in a build of this branch, and a
quoted step fragment. The source:N line given under Fix at is HEAD's line, for applying the
edit.

Verdict. The model is consistent across all 20 commits: capture synchronously, pass a required
parameter or store a slot, fire with the mapping, and use « » for things the user agent decides.
Every new parameter has all of its call sites updated: seek 8/8, navigate an iframe or
frame
3/3, iframe load event steps 3/3, process the linked resource 2 overrides plus 1
caller. Every load/error fired at a link now carries a mapping. What remains:

  • One unfinished placeholder. A "TODO" note in report an exception (§1.1).
  • Three blockers in the IDL integration. Two depend on WebIDL; one is HTML's EventHandler
    callback context (§1.2).
  • A cluster of focus/blur problems (§2.1).
  • A handful of smaller correctness and hygiene issues in the later commits (§2.2–§3).

1. Blockers

1.1 🔴 Placeholder "TODO" note left in report an exception

Where: report an exception (#report-an-exception), the step that sets notHandled by
firing error at global:

TODO: Explain why we're manually fiddling with the context.

Fix at: source:121032 (from f88a6c2a).

This is a <p class="note"> that contains an XXX <span>, so it renders as a note with a TODO
inside. It can't land as is. The same step has two smaller problems:

  • source:121028 (112 columns) and source:121032 (121 columns) are unwrapped.
  • The capture is inline (CreateAsyncContextSnapshotObject(AsyncContextSnapshot())). Everywhere
    else in the branch, the capture is its own step: Let acMapping be AsyncContextSnapshot().

Suggested note. The rationale is already in
EV §8.1
("it must be explicitly overwritten and it would not always happen by default, as it can be
triggered synchronously"):

Report an exception is often reached while the mapping of the code that threw is still
current, e.g. from within a timer callback or while executing a script element. The event is
fired in the empty mapping so that error listeners do not implicitly run in that context; it is
exposed explicitly through uncaughtContext instead.

1.2 🔴 The IDL integration doesn't work yet

  1. All four [PropagatesAsyncContext] annotations are no-ops. This affects toBlob,
    getAsString, queueMicrotask and requestAnimationFrame. At 3188eabd, Add an extended attribute to allow propagating TC39's AsyncContext webidl#1568
    doesn't add the attribute to WebIDL's closed list of extended attributes "applicable to types".
    So in toBlob([PropagatesAsyncContext] BlobCallback _callback, …) it attaches to the argument,
    not to the type, and the PR's capture step ("If the conversion is to an IDL type associated with
    the [PropagatesAsyncContext] extended attribute…") never fires. The fix belongs in WebIDL.
  2. getAsString(FunctionStringCallback? _callback) is nullable, so it would fail
    independently even once (1) is fixed. 'run authentic click activation steps' doesn't deal with the case when activation behavior changes during click event dispatch #1568 has no step that carries an extended attribute from
    T? to T, and nullable conversion converts with the inner type.
  3. HTML's EventHandler callback context is still a bare settings object. 'run authentic click activation steps' doesn't deal with the case when activation behavior changes during click event dispatch #1568 redefines the
    callback context as a pair (settings object, Async Context Mapping-or-null) and destructures it
    in invoke and construct. Fix at: source:125825 (getting the current value of the
    event handler
    ). The context should become (settings object, null).

2. Correctness

2.1 🟠 Focus/blur: one root cause, four symptoms

Where: focus update steps (#focus-update-steps): the blur branch at source:87768, the
focus branch at source:87839, and the change step (#unfocus-causes-change-event,
source:87741).

The intent is
WI "Cross-origin iframes":
.focus() on a cross-origin iframe's window must not carry the caller's context across.

  1. The guard is undefined without script on the stack. It compares against the current
    settings object
    , i.e. the settings object of the current realm. When the focus update steps
    run without JS on the stack, there is no current realm. That happens when the user moves focus,
    in the event loop's focus fixup, in the unfocusing steps' fallback to the viewport, and in flush
    autofocus candidates
    .
  2. change is fired in the same per-entry loop as blur, without the guard. So
    crossOriginFrame.contentWindow.focus() still runs a cross-origin change listener with the
    caller's mapping.
  3. Copy-paste bug. The blur branch's Issue Cross-origin window.focus() vs window.postMessage() #3506 XXX says "If focus event target's
    relevant agent…" (source:87783); it should be blur event target.
  4. Markup.
    • The blur branch's inner <li><p>Fire a focus event … target.</p> has no </li>
      (source:87777-87779), unlike the focus branch.
    • Both branches leave a blank line before the closing </li> (source:87785).
    • The prose "…then run the following steps with « ». Otherwise, run the following steps:"
      hangs one sub-list off two branches. That reads oddly and is part of why change was missed.

One fix for all four: at the top of each per-entry loop body, compute the mapping once, then
fire all events in that body with it. In the old-chain loop that's change and blur; in the
new-chain loop, focus.

Let acMapping be « » if entry's relevant agent is not the surrounding agent, or if there is a
current settings object and entry's relevant settings object's origin is not same origin with
its origin; otherwise, AsyncContextSnapshot().

Then use "fire … with acMapping" (or "run the following step with acMapping") in place of the
two hand-written branches. This removes the duplicated XXX notes (keep one per loop, with the right
variable) and the unbalanced <li>.

2.2 🟠 Three early error paths in prepare the script element don't propagate

Where: prepare the script element (#prepare-the-script-element), inside the
script-processing-src-prepare step. Three paths queue an error event: an external
importmap/speculationrules, an empty src, and an unparsable src (source:69108, :69122,
:69133). All three return before "Set el's execution Async Context Mapping to
AsyncContextSnapshot()" (source:69194).

So s.src = "" inside v.run() fires error in « », while s.src = "404.js" fires it with the
mapping.
EV §4.12.1
asks for "the corresponding load and error events, including those fired while executing the
script element". That wording implies the other error events, which are these three.

Fix: capture into a local before source:69100, and fire those three with it.

2.3 🟠 Clearing the Worker/SharedWorker error entry on success happens off the owner's thread

Where:

  • run a worker (#run-a-worker), the step "Associate worker with worker global scope",
    followed by "Clear AsyncContext for events with « "error" » given worker" (source:137793-137797).
  • The SharedWorker() constructor (#dom-sharedworker), "Associate worker with
    workerGlobalScope" (source:138494-138497).

Run a worker says "Run the rest of these steps in that agent", so the success-path clear runs on
the worker's agent. Meanwhile worker belongs to the outside realm. The SharedWorker
branch runs on the shared worker manager's parallel queue. Both mutate the outside object's
propagation map from another thread. The failure paths in the same commit get this right: they
clear inside the task queued on worker's relevant global.

The notes argue the clear isn't observable, and that's probably true. Even so, mutating state from
off the owning thread is something WHATWG reviewers will flag.

Fix: queue a global task on worker's relevant global object to do the clear. Alternatively,
since it's unobservable, drop the success-path clears and keep the memory argument as a note at the
IDL. Also:

  • Make the clear its own <li>, not a second <p> in the "Associate" step.
  • source:137795-137797 wraps oddly: « ends a line, and "<code sits alone on the next.

2.4 🟠 determine what an object element represents doesn't take the element

Where: #determine-what-an-object-element-represents (source:36863) and its only caller
(source:36850-36852).

The new algorithm is "given an Async Context Mapping acMapping", but its body keeps referring to
"the element", which used to come from the surrounding prose's context. The caller also writes "to
determine what the object element represents with acMapping". That reads like the "run …
with a mapping" idiom, not like passing an argument.

Fix:

  • Preamble: "To determine what an object element represents, given an object element
    element and an Async Context Mapping acMapping:".
  • Caller: "… given element and acMapping".
  • Replacing "the element" with element in the body is optional cleanup in an old-style
    algorithm.

2.5 🟠 The EventSource note contradicts the design it documents

Where: announce the connection (#announce-the-connection), the new note
(source:134859-134864):

So the EventSource constructor's Async Context Mapping reaches the first open or error
event and no later one

Reestablish the connection is not a clearing point, as
EV §9.2
asks ("use that context to fire the open and error events queued by announce the connection,
reestablish the connection, and fail the connection"). Take an initial connection that hits a
network error and is reestablished. It fires one or more error events and then an open, all
with the constructor's mapping. The note's first sentence is accurate ("only once the connection
has either opened or failed permanently"); the second isn't.

Fix: "…reaches every open and error event up to and including the first successful open
or the permanent failure, and no later one."

2.6 🟡 <track>: the abort-path error reads the slot inside the task

Where: start the track processing model (#start-the-track-processing-model), the "If,
while fetching is ongoing…" paragraph (source:43333-43343): "…fires an event named error at the
track element with its track processing Async Context Mapping".

That reads the slot when the task runs, not when the abort happens. A second src change in
the same task overwrites the slot before the queued task runs, and the first abort's error then
carries the second change's mapping. Arguably that's the right owner anyway. But everywhere else the
branch captures before queuing, or (for <track>) explains the late read in a note.

Fix: either "let abortAcMapping be the element's track processing Async Context Mapping, and
… fire … with abortAcMapping", or a sentence at #track-processing-async-context-mapping saying
why a late read is fine.

2.7 🟡 Media: in-task slot reads with no justification at the slot definition

Where: the media data processing steps list (#media-data-processing-steps-list). Six
fires read "with its media loading Async Context Mapping" inside a task: progress/suspend at
source:39990/:39996, error at :40033/:40065, abort at :40090, and emptied at
:40099.

Elsewhere, the same commit captures into loadingAcMapping before queuing. These reads are
race-free because the media element load algorithm removes the element's pending tasks before
the slot is rewritten. Nothing in the text says so, though, and a reader comparing the two styles
will wonder.

Fix: add one sentence to #media-loading-async-context-mapping. Something like: "It may be
read from a task queued by the resource fetch algorithm, because the media element load algorithm
removes those tasks before setting it again."

2.8 🟡 loadingAcMapping declared twice in the resource selection algorithm

Where: #concept-media-load-algorithm. Step 1 has "Let loadingAcMapping be
AsyncContextSnapshot(), and set the element's media loading Async Context Mapping…"
(source:39056). The Failed with attribute step then has "…let loadingAcMapping be the
element's media loading Async Context Mapping…" (source:39183).

Same algorithm and same name, and the second read happens in parallel steps, which can't read
element state.

Fix: drop the second let and pass the step-1 variable.

The other repeated Let loadingAcMapping/playbackAcMapping in the resource fetch algorithm
and ready states sit in separate prose triggers that are mutually exclusive, and they bind the
same value. They're fine.

2.9 🟡 The <script> mapping is never released if the script never executes

Execution Async Context Mapping is cleared in exactly one place, inside execute the script
element
(source:69475). Several paths prepare a script but never run it: a parser aborted while
blocked, a document destroyed with defer/async scripts in flight, or a fetch that never
completes. Each pins the whole mapping for the element's lifetime. That's the same kind of memory
cost
WI "Capture the context when the event listener is registered"
cites against that approach, on a smaller scale.

The capture is also unconditional, so it runs for importmap/speculationrules too, although
EV §4.12.1
scopes it to scripts with src. At minimum add a note; better, clear the slot on the abort paths.


3. Spec hygiene and design nits

  1. Inline captures. The rest of the branch captures in its own step; these don't:

    • fastSeek() (source:41839) also reads "seek to the time given by time given
      AsyncContextSnapshot()", with two "given"s.
    • the currentTime setter (source:40439)
    • enqueue a custom element callback reaction (source:80248)
    • enqueue a custom element upgrade reaction (source:80263)
    • report an exception (§1.1)

    Make each one Let acMapping be AsyncContextSnapshot(). on its own line.

  2. Three phrasings for "with the mapping if it's not null":

    • "with acMapping if that is non-null" (iframe load event steps, source:35931)
    • "with Async Context Mapping containerAsyncContextMapping if that is not null"
      (navigate to a javascript: URL, source:109716)
    • "with Async Context Mapping acMapping if that is not null" (completely finish loading,
      source:115027)

    Pick one. "…at container, with acMapping if it is non-null" matches the "fire … with
    acMapping" used everywhere else.

  3. ErrorEvent.uncaughtContext / PromiseRejectionEvent.rejectedContext descriptions
    (source:121146, :121279): "It is an AsyncContext.Snapshot object…" isn't true for
    author-constructed events, which can be any object or null. It also isn't true for
    UA-fired ErrorEvents outside report an exception, such as the worker error forwarded to
    the outside Worker. Say "When fired by report an exception…" / "For unhandledrejection
    events fired by the user agent…".

  4. Custom elements:
    CE
    says "the context active when the custom element was defined with customElements.define() is
    never used". 524df481 is consistent with that, but nothing in the spec says it. A reader may
    expect the lifecycle callbacks passed to define() to be annotated with
    [PropagatesAsyncContext], like other callbacks. A short note at define() would head that off.

  5. Form-associated custom element restore: the "run … with « »" wrapper only exists to make
    the AsyncContextSnapshot() inside enqueue return « », which is indirect. It's fine as is. If
    enqueue ever grows a mapping parameter, this becomes a plain argument.


4. Editorial (mechanical; all in touched lines)

# Issue Fix at
E1 run (#async-context-mapping-run): the <li> holding the nested <ol> ("Let returnValue be…") has no </li> source:5408-5416
E2 Form-restore autocomplete step starts lowercase: "<li><p><span>enqueue a custom element callback reaction" source:80657
E3 "an user agent decision" → "a user agent decision" source:80650
E4 Bad wraps: "media loading⏎Async⏎Context Mapping" in the resource fetch algorithm; "Async Context⏎Mapping⏎« »" for the autoplay pause source:39948-39950, :40834-40836
E5 Stray extra blank line added after "Assert: handler is a string." (timer initialization steps, from 33f8f03b) source:131518
E6 Default fetch and process the linked resource: the touched "Process the linked resource … and acMapping." step still lacks </p> source:17198
E7 The embed element setup steps preamble: "…element given Async Context Mapping acMapping are" is missing an article and repeats "given". Use "…for an embed element element and an Async Context Mapping acMapping are as follows:" source:36557-36558
E8 Queue a dialog/popover toggle event task: "…and the source attribute initialized to source, and with acMapping" has two "and"s. Use "…initialized to source, with acMapping" source:67597, :93432
E9 Map iteration uses ->; Infra uses → (notify about rejected promises) source:121208
E10 HostPromiseRejectionTracker: "map … <span data-x="map exists">contains</span> promise" — link text doesn't match Infra. Use "…map[promise] exists" source:122850-122851
E11 Redundant data-x="clear AsyncContext for events" where the text already matches (Wattsi matches case-insensitively and collapses whitespace) source:137782, :137795, :138461, :138486, :138496, and the three EventSource sites from 134809 on
E12 [JSASYNCCONTEXT] sits between [JSERRORSTACKACCESSOR] and [JSERRORSTACKS]; [PropagatesAsyncContext] sits between [Global] and [LegacyFactoryFunction] in an alphabetical run source:163277, :2969

5. Commits and tests

  • 33f8f03b's message is stale against this branch. It says the patch "does not include any
    changes to the error and unhandledrejection event handling" (03920812/f88a6c2a now do).
    It also says it "relies on PR [TODO] to define the [PropagatesAsyncContext] extended
    attribute", which should name Add an extended attribute to allow propagating TC39's AsyncContext webidl#1568. If the commits are squashed on merge this
    doesn't matter; otherwise trim the body.
  • No commit misuses Editorial:. All 20 are normative and none is prefixed.
  • WPT: web-platform-tests has no AsyncContext tests yet (checked at
    a91f536d), so there's nothing to
    audit against the diff. The core commits (33f8f03b/ccf42e82/ea34c8a4) will need:
    • setTimeout/setInterval (string and function handlers, and repeat reuse)
    • queueMicrotask, requestAnimationFrame, toBlob, getAsString (all blocked on §1.2)
    • <script src> and type=module load/error
    • the microtask checkpoint's « » reset (a microtask queued from a classic script must not
      inherit the script's mapping)
    • cross-origin focus/blur/change

6. Checked and fine — don't "fix" these

  • Apparent duplicate declarations that aren't. These are all separate algorithms, separate task
    closures, or the same value in exclusive branches:
    • steps in run
    • document/acMapping in completely finish loading (acMapping is used at source:115021
      and :115027)
    • global in notify about rejected promises
    • loadingAcMapping/playbackAcMapping in the resource fetch algorithm and ready states
  • Timers. The snapshot is taken before the task is created. Abort these steps inside the run
    wrapper scopes correctly, and setInterval re-captures inside the wrapper, so repeats keep the
    original mapping. That's what
    WI "Schedulers"
    asks for.
  • Microtask checkpoint. The « » wrapper and its note are needed: clean up after running
    script
    reaches the checkpoint inside execute the script element's mapping. Moving notify about
    rejected promises
    inside the wrapper is harmless, because it only queues a task.
  • Event loop invariant. The Assert plus the note at Perform oldestTask's steps state that
    every task starts in « », which is what the "events run in the empty context unless otherwise
    specified" rule in
    EV §8.1
    relies on.
  • iframe container load Async Context Mapping. It's set for both fetch and javascript:
    documents, read and cleared in completely finish loading, and cleared in abort a document
    load
    . Self-navigations pass null, so they fire in « ».
  • Media abort/emptied in the load algorithm. These deliberately use the new load's
    mapping, and a note says so. The internal pause steps' split (timeupdate with the playback
    mapping, pause with the caller's) is deliberate too.
  • Unchanged on purpose: <source> error, AudioTrackList/VideoTrackList/TextTrackList
    events, and cuechange.
    EV "Events fired on other objects"
    says they run in the empty context, which is what the unchanged text already does.
  • Custom element reactions. A snapshot per reaction, with upgrades running in the enqueuer's
    context, matches
    CE "Propagation model"
    and
    CE "Constructors and upgrades",
    including the .click()-on-summary case that lands on the backup element queue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants