diff --git a/assets/js/media-library-enhanced.js b/assets/js/media-library-enhanced.js index c20bf4e29..6e83bf352 100644 --- a/assets/js/media-library-enhanced.js +++ b/assets/js/media-library-enhanced.js @@ -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 @@ -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. @@ -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; diff --git a/reports/session-save-loop.md b/reports/session-save-loop.md new file mode 100644 index 000000000..4b9f9aa58 --- /dev/null +++ b/reports/session-save-loop.md @@ -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. diff --git a/src/boot/session-saver.ts b/src/boot/session-saver.ts index 7f6ec6fbd..042639ae6 100644 --- a/src/boot/session-saver.ts +++ b/src/boot/session-saver.ts @@ -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; }; diff --git a/src/chromeless-bridge.js b/src/chromeless-bridge.js index cd8fb9307..6d27c1248 100644 --- a/src/chromeless-bridge.js +++ b/src/chromeless-bridge.js @@ -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' ) { @@ -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 { @@ -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 || '' ); @@ -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 { @@ -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 ) { @@ -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 @@ -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; @@ -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; + } }; } diff --git a/tests/phpunit/tests/openStationChromelessActivity.php b/tests/phpunit/tests/openStationChromelessActivity.php index 4875073d0..d874baa2b 100644 --- a/tests/phpunit/tests/openStationChromelessActivity.php +++ b/tests/phpunit/tests/openStationChromelessActivity.php @@ -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 diff --git a/tests/vitest/media-bridge-lifecycle.test.ts b/tests/vitest/media-bridge-lifecycle.test.ts new file mode 100644 index 000000000..3eb51adf2 --- /dev/null +++ b/tests/vitest/media-bridge-lifecycle.test.ts @@ -0,0 +1,165 @@ +/** Repeated requests and media DOM updates must not multiply bridge callbacks. */ +import { afterEach, describe, expect, test } from 'vitest'; +import { JSDOM } from 'jsdom'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +const ROOT = resolve( __dirname, '../..' ); +const documents: JSDOM[] = []; + +function frame( markup = '' ) { + const dom = new JSDOM( `
${ markup }`, { + url: 'http://localhost/wp-admin/upload.php?openstation_chromeless=1', + runScripts: 'outside-only', + } ); + documents.push( dom ); + const w = dom.window; + const messages: Array< Record< string, unknown > > = []; + Object.defineProperty( w, 'parent', { + value: { postMessage: ( message: Record< string, unknown > ) => messages.push( message ) }, + } ); + const load = ( path: string ) => w.eval( readFileSync( resolve( ROOT, path ), 'utf8' ) ); + return { w, messages, load }; +} + +afterEach( () => { + for ( const dom of documents.splice( 0 ) ) { + dom.window.close(); + } +} ); + +function networkFrame( fetchStatus?: number ) { + const f = frame(); + if ( fetchStatus !== undefined ) { + f.w.fetch = async () => new Response( '', { status: fetchStatus } ); + } + class XHR extends f.w.EventTarget { + status = 200; + failSend = false; + open() {} + setRequestHeader() {} + send() { + if ( this.failSend ) { + throw new Error( 'send failed' ); + } + } + } + f.w.XMLHttpRequest = XHR as unknown as typeof f.w.XMLHttpRequest; + f.load( 'src/chromeless-bridge.js' ); + f.messages.length = 0; + return { ...f, xhr: new f.w.XMLHttpRequest() as unknown as XHR }; +} + +describe( 'media bridge lifecycle', () => { + test.each( [ 'xhr', 'fetch' ] )( '%s Heartbeat failures do not accelerate Heartbeat, while other auth failures still do', async ( transport ) => { + const { w, messages, xhr } = networkFrame( 403 ); + let authChecks = 0; + w.wp = { heartbeat: { connectNow: () => { authChecks++; } } }; + xhr.status = 403; + const form = new w.FormData(); + form.set( 'action', 'heartbeat' ); + const send = async ( url: string, body: string | URLSearchParams | FormData ) => { + if ( transport === 'fetch' ) { + await w.fetch( url, { method: 'POST', body } ); + } else { + const request = xhr as unknown as XMLHttpRequest; + request.open( 'POST', url ); + request.send( body ); + xhr.dispatchEvent( new w.Event( 'loadend' ) ); + } + }; + // Core's jQuery transport sends the action in this serialized POST body. + await send( '/wp-admin/admin-ajax.php', '_nonce=test&action=heartbeat&screen_id=post' ); + await send( '/wp-admin/admin-ajax.php', new w.URLSearchParams( { action: 'heartbeat' } ) ); + await send( '/wp-admin/admin-ajax.php', form ); + await send( '/wp-admin/admin-ajax.php?action=heartbeat', '' ); + expect( authChecks ).toBe( 0 ); + expect( messages.filter( ( m ) => m.type === 'os-iframe-activity' ) ).toHaveLength( 0 ); + // A similar action name must not be mistaken for Heartbeat. Nor may a + // skipped Heartbeat consume the cooldown for a real auth failure. + await send( '/wp-admin/admin-ajax.php', 'action=heartbeat-settings' ); + expect( authChecks ).toBe( 1 ); + expect( messages.filter( ( m ) => m.type === 'os-iframe-activity' ) ).toHaveLength( 2 ); + } ); + + test.each( [ 'xhr', 'fetch' ] )( '%s keeps reads quiet and balances failed writes', async ( transport ) => { + const { w, messages, xhr } = networkFrame( 500 ); + xhr.status = 500; + const send = async ( method: string ) => { + if ( transport === 'fetch' ) { + await w.fetch( '/wp-admin/admin-ajax.php', { method, body: 'action=query-attachments' } ); + } else { + const request = xhr as unknown as XMLHttpRequest; + request.open( method, '/wp-admin/admin-ajax.php' ); + request.send( 'action=query-attachments' ); + xhr.dispatchEvent( new w.Event( 'loadend' ) ); + } + }; + // QUERY carries a body but is still a read. Classification must use + // the method, and a refused start must not emit an unmatched end. + for ( const method of [ 'GET', 'HEAD', 'OPTIONS', 'QUERY' ] ) { + await send( method ); + } + expect( messages.filter( ( m ) => m.type === 'os-iframe-activity' ) ).toEqual( [] ); + await send( 'POST' ); + expect( messages.filter( ( m ) => m.type === 'os-iframe-activity' ) ).toEqual( [ + expect.objectContaining( { phase: 'start' } ), + expect.objectContaining( { phase: 'end', failed: true, status: 500 } ), + ] ); + } ); + + test( 'reusing an XHR reports each completion once, with balanced activity', () => { + const { w, xhr, messages } = networkFrame(); + for ( let i = 0; i < 100; i++ ) { + ( xhr as unknown as XMLHttpRequest ).open( 'POST', `/wp-admin/async-upload.php?chunk=${ i }` ); + xhr.send(); + xhr.dispatchEvent( new w.Event( 'loadend' ) ); + } + const network = messages.filter( ( m ) => m.type === 'os-iframe-network' ); + expect( network ).toHaveLength( 100 ); + expect( new Set( network.map( ( m ) => m.url ) ).size ).toBe( 100 ); + expect( messages.filter( ( m ) => m.type === 'os-iframe-activity' && m.phase === 'start' ) ).toHaveLength( 100 ); + expect( messages.filter( ( m ) => m.type === 'os-iframe-activity' && m.phase === 'end' ) ).toHaveLength( 100 ); + } ); + + test( 'a synchronous send failure settles activity and leaves no callback on retry', () => { + const { w, xhr, messages } = networkFrame(); + ( xhr as unknown as XMLHttpRequest ).open( 'POST', '/wp-admin/async-upload.php' ); + xhr.failSend = true; + expect( () => xhr.send() ).toThrow( 'send failed' ); + expect( messages.filter( ( m ) => m.type === 'os-iframe-activity' && m.phase === 'end' ) ).toEqual( [ + expect.objectContaining( { failed: true, status: 0 } ), + ] ); + xhr.failSend = false; + ( xhr as unknown as XMLHttpRequest ).open( 'POST', '/wp-admin/async-upload.php' ); + xhr.send(); + xhr.dispatchEvent( new w.Event( 'loadend' ) ); + expect( messages.filter( ( m ) => m.type === 'os-iframe-network' ) ).toHaveLength( 2 ); + expect( messages.filter( ( m ) => m.type === 'os-iframe-activity' && m.phase === 'end' ) ).toHaveLength( 2 ); + } ); + + test( 'enhances grid and detail elements already present when the script loads', () => { + const { w, load } = frame( '' ); + load( 'assets/js/media-library-enhanced.js' ); + for ( const el of w.document.querySelectorAll( '.attachment, .attachment-details' ) ) { + expect( el.getAttribute( 'draggable' ) ).toBe( 'true' ); + } + } ); + + test( 'repeated list refreshes still send one start and end per drag', async () => { + const { w, messages, load } = frame( '