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
9 changes: 6 additions & 3 deletions assets/js/media-library-enhanced.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@
// in), the MutationObserver picks up the freshly-rendered grid
// tiles and runs `enhance()` on them — at which point the
// grid-side `wp.media.attachment()` lookup is safe.
start();

// Flag set during our own attachment drags so the capture-phase
// blocker below can distinguish between "user is dragging a file
// from the OS" (which the WP uploader should handle) and "user is
Expand All @@ -71,6 +69,12 @@
// the `.media` table class so we don't enhance unrelated WP list
// tables (Posts, Pages, …) that share the same row-id convention.
var LIST_SELECTOR = 'table.media tbody tr[id^="post-"]';
var LIST_DELEGATION_INSTALLED = false;

// Initialize selectors and the delegation latch before the first
// scan. Resetting the latch after start() installs a second pair of
// delegated listeners when the observer sees a new list row.
start();

function start() {
// Enhance whatever's already on the page.
Expand Down Expand Up @@ -300,7 +304,6 @@
* Mounted ONCE per page (sentinel-guarded) from `start()`. No
* per-row work, no MutationObserver bookkeeping for list rows.
*/
var LIST_DELEGATION_INSTALLED = false;
function installListDelegation() {
if ( LIST_DELEGATION_INSTALLED ) {
return;
Expand Down
56 changes: 56 additions & 0 deletions reports/session-save-loop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# A confirmed session-save loop, with an unconfirmed connection to uploads

The session saver can starve JavaScript's event loop after request setup throws synchronously. The next `flush()` repeatedly awaits an already-settled promise. Moving cleanup into the promise's `finally()` prevents the stale reference.

This is a confirmed defect, but **it is not yet an explanation for the reported Media/Gutenberg upload freeze**. The reproduction deliberately injects a synchronous request-setup error. Ordinary network failures reject a promise asynchronously and do not take this path. Neither retained heap growth nor Chrome's Wait/Kill dialog was measured in this reproduction.

## The failure sequence

In `src/boot/session-saver.ts`, the original assignment was:

```js
activeSave = (async () => {
try {
await trackedFetch(/* ... */);
} catch (error) {
// Report the failed save.
} finally {
activeSave = null;
}
})();
```

If the request function throws before returning a promise, the async function runs its catch and finally before its caller assigns `activeSave`. The assignment then overwrites `null` with the settled promise. On the next flush:

```js
while (activeSave) {
await activeSave;
}
```

Nothing clears that reference. Each `await` queues another microtask, and the loop prevents timers and rendering from getting their turn. This is microtask starvation; the evidence does not establish recursive call-stack growth or a retained-memory leak.

The fix attaches cleanup with `.finally(...)` to the returned promise. Cleanup therefore runs after the assignment, including when request setup throws synchronously.

## Chrome comparison

Tested in Chrome 154 on macOS. The fixture bundles the actual session-saver source before and after the change, substitutes its external dependencies, and makes the first request throw synchronously. It invokes a second flush after the first failure has been handled.

Each version runs in a dedicated worker so a defective loop cannot freeze the user's editing tab. A timer in the host page terminates each worker after 500 ms. The worker also schedules its own zero-delay timer immediately before the second flush.

| Observation | Original code | Fixed code |
|---|---|---|
| First synchronous error handled | Yes | Yes |
| Second flush completed within the 500 ms window | No | Yes |
| Worker's zero-delay timer fired | No | Yes |
| External termination required to stop the loop | Yes | No loop remained |

The fixed flush reported 0 ms at the available timer resolution. That is below-resolution completion in a synthetic fixture, not a claim of zero execution cost. The 500 ms cutoff is a safety bound, not the duration of a production freeze.

## Regression coverage and limits

`tests/vitest/session-saver-flush.test.ts` checks that a second flush completes after a synchronous request exception. It failed on the original source and passed with the cleanup change. A bounded microtask check and an explicit recovery save allow the old implementation to fail the test without hanging the test runner itself.

Validation: both session-saver suites pass (18 tests); the complete JavaScript suite passes (6,510 tests in 528 files); build, lint and TypeScript checks pass. Lint retains existing file-length warnings.

The known in-tree flush caller is the shell's reload-after-deploy flow. No observed upload action has been shown to reach this loop. The unresolved investigation is still the user's recursive, heap-growing freeze during natural OpenStation use.
27 changes: 15 additions & 12 deletions src/boot/session-saver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,19 +203,22 @@ export function createSessionSaver(
* so a connectivity regression doesn't go silent under
* the session-beacon path. */
doAction( HOOKS.SHELL_ERROR, { scope: 'session-save', error: err } );
} finally {
inFlight = false;
activeSave = null;
if ( dirty ) {
dirty = false;
// Back through `schedule()`, not straight into another
// `doSave()`. Handing over directly would let a slow
// request chain into an immediate second write and
// sidestep both the debounce and the rate limit.
schedule();
}
}
} )();
} )().finally( () => {
// Run cleanup after activeSave has been assigned, even if
// request setup throws synchronously. An inline finally would
// clear it first, then the assignment would retain a settled
// promise and flush() would await it forever without yielding
// to the browser's event loop.
inFlight = false;
activeSave = null;
if ( dirty ) {
dirty = false;
// Back through schedule() so the queued write observes
// both the debounce and the rate limit.
schedule();
}
} );
return activeSave;
};

Expand Down
44 changes: 30 additions & 14 deletions src/chromeless-bridge.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/**

Check warning on line 1 in src/chromeless-bridge.js

View workflow job for this annotation

GitHub Actions / Lint · Types · Vitest

This file is 3959 lines — past the 1000-line comfort zone. Be smart, build robust software: modules of ~300–600 lines are easier to read, test, review and reuse. Consider splitting this one along its natural seams — future you will say thanks
* OpenStation — chromeless bridge (iframe side).
*
* Plain ES5-flavoured JavaScript on purpose: this runs inside a real
Expand Down Expand Up @@ -404,10 +404,10 @@
// this reason. The action rides in the POST body, not the
// URL, so both are checked.
try {
if ( String( url || '' ).indexOf( 'action=heartbeat' ) !== -1 ) {
if ( /[?&]action=heartbeat(?:&|$)/.test( String( url || '' ) ) ) {
return true;
}
if ( typeof body === 'string' && body.indexOf( 'action=heartbeat' ) !== -1 ) {
if ( typeof body === 'string' && /(?:^|&)action=heartbeat(?:&|$)/.test( body ) ) {
return true;
}
if ( body && typeof body.get === 'function' && body.get( 'action' ) === 'heartbeat' ) {
Expand All @@ -417,8 +417,8 @@
return false;
};

var osActivityBegin = function ( method, url, body ) {
if ( osIsReadRequest( method ) || osIsBackgroundRequest( url, body ) ) {
var osActivityBegin = function ( method, background ) {
if ( osIsReadRequest( method ) || background ) {
return false;
}
try {
Expand Down Expand Up @@ -457,12 +457,12 @@
// force an immediate tick. `wp.heartbeat.connectNow()` is
// safe to call repeatedly; we still debounce to avoid storms
// when many requests fail at once. Same-origin gate keeps us
// out of third-party 403s. The URL gate avoids looping on
// heartbeat itself (heartbeat shouldn't 403 — but if it does
// the recursive connectNow would not help anyway).
// out of third-party 403s. Recognize Heartbeat before sending:
// Core puts its action in the POST body, not the URL. A failed
// Heartbeat must not accelerate itself or consume the cooldown.
var osAuthCheckCooldownUntil = 0;
var osMaybeForceAuthCheck = function ( status, url ) {
if ( status !== 401 && status !== 403 ) {
var osMaybeForceAuthCheck = function ( status, url, background ) {
if ( background || ( status !== 401 && status !== 403 ) ) {
return;
}
var urlStr = String( url || '' );
Expand Down Expand Up @@ -626,7 +626,10 @@
}
}

var tracked = osActivityBegin( method, url, ( init && init.body ) || ( input && input.body ) );
// Retain only the classification, not an upload body, in
// the completion callbacks shared by activity/auth checks.
var background = osIsBackgroundRequest( url, ( init && init.body ) || ( input && input.body ) );
var tracked = osActivityBegin( method, background );

var promise;
try {
Expand Down Expand Up @@ -656,7 +659,7 @@
// `fetch` resolves for 4xx / 5xx, so the ring
// settles on `res.ok` and not on the promise.
osActivityEnd( tracked, ! res.ok, res.status );
osMaybeForceAuthCheck( res.status, url );
osMaybeForceAuthCheck( res.status, url, background );
return res;
},
function ( err ) {
Expand Down Expand Up @@ -708,7 +711,8 @@
: Date.now();
// The body is where an admin-ajax action name lives,
// and the action name is how Heartbeat is recognised.
var tracked = osActivityBegin( xhr.__wpdMethod, xhr.__wpdUrl, body );
var background = osIsBackgroundRequest( xhr.__wpdUrl, body );
var tracked = osActivityBegin( xhr.__wpdMethod, background );

// Apply contributed headers right before send. Doing it
// here rather than in open() means contributions added
Expand All @@ -729,6 +733,9 @@
}

var fire = function () {
// An uploader may open/send the same XHR again. Keep
// this request's closure out of later completions.
xhr.removeEventListener( 'loadend', fire );
var dur = ( ( typeof performance !== 'undefined' && performance.now )
? performance.now()
: Date.now() ) - start;
Expand Down Expand Up @@ -762,12 +769,21 @@
extra
);
osActivityEnd( tracked, failed, xhr.status );
osMaybeForceAuthCheck( xhr.status, xhr.__wpdUrl );
osMaybeForceAuthCheck( xhr.status, xhr.__wpdUrl, background );
};
try {
xhr.addEventListener( 'loadend', fire );
} catch ( _err ) { /* swallow */ }
return osOrigSend.apply( this, arguments );
try {
return osOrigSend.apply( this, arguments );
} catch ( sync ) {
// A synchronous send failure has no loadend to remove
// the listener or balance the activity-start message.
xhr.removeEventListener( 'loadend', fire );
osReportNetwork( xhr.__wpdMethod, xhr.__wpdUrl, 0, 0, true, null );
osActivityEnd( tracked, true, 0 );
throw sync;
}
};
}

Expand Down
54 changes: 2 additions & 52 deletions tests/phpunit/tests/openStationChromelessActivity.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,58 +105,8 @@ public function test_reads_never_reach_the_ring() {
}
}

/**
* The read check has to gate the `begin`, not sit somewhere
* harmlessly beside it.
*
* @covers ::openstation_chromeless_bridge_script
*/
public function test_the_read_check_gates_the_begin() {
$markup = $this->bridge_markup();

$this->assertStringContainsString(
'if ( osIsReadRequest( method ) || osIsBackgroundRequest( url, body ) ) {',
$markup
);
}

/**
* Heartbeat POSTs to `admin-ajax.php` with the action in the BODY,
* so a URL-only check would miss it and every idle window would
* pulse on a timer.
*
* @covers ::openstation_chromeless_bridge_script
*/
public function test_heartbeat_is_recognised_from_the_body_as_well_as_the_url() {
$markup = $this->bridge_markup();

$this->assertStringContainsString( "String( url || '' ).indexOf( 'action=heartbeat' )", $markup );
$this->assertStringContainsString( "body.indexOf( 'action=heartbeat' )", $markup );
// FormData bodies expose the action through `get()` rather than
// as a string.
$this->assertStringContainsString( "body.get( 'action' ) === 'heartbeat'", $markup );
}

/**
* Both wrappers have to pass the method through, or the read
* exclusion silently applies to nothing.
*
* @covers ::openstation_chromeless_bridge_script
*/
public function test_both_wrappers_report_their_method() {
$markup = $this->bridge_markup();

// fetch
$this->assertStringContainsString(
'osActivityBegin( method, url,',
$markup
);
// XHR — method and URL are recorded on `open()`.
$this->assertStringContainsString(
'osActivityBegin( xhr.__wpdMethod, xhr.__wpdUrl, body )',
$markup
);
}
// Request classification and wrapper behavior are exercised in
// tests/vitest/media-bridge-lifecycle.test.ts by executing the bridge.

/**
* An `end` for a request that was never counted would decrement a
Expand Down
Loading
Loading