Skip to content

Fix request tracking, media drag setup, and session-save loop - #962

Merged
AllTerrainDeveloper merged 4 commits into
trunkfrom
codex/media-bridge-lifecycle-fixes
Oct 6, 2026
Merged

AllTerrainDeveloper merged 4 commits into
trunkfrom
codex/media-bridge-lifecycle-fixes

Conversation

@AllTerrainDeveloper

@AllTerrainDeveloper AllTerrainDeveloper commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

OpenStation could retain request callbacks, register duplicate Media drag listeners, retry failed Heartbeats unnecessarily, and enter an endless session-save loop after a synchronous request error. This PR fixes those four defects and adds behavioral regression coverage.

The fixes were identified while investigating Chrome becoming unresponsive during Media uploads and drag-and-drop into Gutenberg. The reported upload-related Wait/Kill freeze remains unconfirmed; this PR does not claim to resolve its root cause.

What changes

1. Release XHR callbacks when their request finishes.

The iframe bridge attached a new loadend listener on every send() but left previous listeners attached. If an uploader or another script reused the same XHR object, later completions ran all earlier callbacks again, multiplying network reports and activity-end messages. Each listener is now removed when its request completes. If send() throws synchronously, cleanup also removes the listener, balances the activity indicator, and rethrows the original error.

2. Recognize Heartbeat requests before starting authentication recovery.

WordPress normally sends action=heartbeat in the POST body. The bridge checked only the URL, so a Heartbeat response with status 401/403 could trigger heartbeat.connectNow() and immediately retry itself. The bridge now checks the URL and supported request-body formats before sending, then uses the result for both activity tracking and authentication recovery. Other requests still trigger normal authentication checks. The completion callbacks retain the classification flag without adding a reference to the upload body.

3. Initialize the Media drag adapter before its first scan.

The adapter called start() before assigning its selectors and delegation guard. Existing grid tiles could miss their initial enhancement, and resetting the guard after startup allowed a later list refresh to install duplicate drag handlers. Initializing these values first makes the initial scan work and keeps list drag handlers installed once.

4. Clear the active session-save promise after it has been assigned.

A synchronous exception during request setup could run the async function's inline finally before the surrounding assignment completed. Cleanup set activeSave to null, but the assignment then replaced it with the already-settled promise. The next flush() repeatedly awaited that same promise, continuously scheduling microtasks and preventing timers and rendering from running.

Cleanup now runs through the returned promise's .finally(), after assignment. A regression test covers the failure and retry without allowing the defective implementation to hang the test worker.

Evidence and validation

These are targeted reproductions, not measurements of typical upload performance:

Scenario Before After
100 completions on a reused XHR 5,050 network reports 100 reports
100 Media list drags across repeated list refreshes 200 drag-start messages 100 messages
One explicit Heartbeat connection receiving HTTP 403; observed for 750 ms 2 POST requests 1 POST request
Second session flush after an injected synchronous request error, in an isolated Chrome worker Flush never completed and its zero-delay timer did not fire before termination at 500 ms Flush completed and the timer fired

The Heartbeat integration check uses the site's real WordPress Heartbeat and jQuery scripts in jsdom against a local HTTP server; neither connectNow() nor jQuery AJAX is mocked. The session-save comparison uses Chrome 154 and isolates the defective code in a worker to protect the editing tab. The session-save report explains the mechanism and reproduction limits.

  • All 6,510 JavaScript tests across 528 files pass, including eight bridge/adapter cases and 18 session-saver cases.
  • Build, TypeScript, and lint pass; lint retains 28 existing file-length warnings with no errors.
  • CI passes, including PHP 8.3/8.4 PHPUnit in single-site and multisite configurations, and Plugin Check.
  • Three PHP assertions that matched JavaScript source strings are replaced by executed JavaScript coverage.

Scope and remaining uncertainty

XHR callback amplification requires reuse of a native XHR object, which has not been established in the reported failing upload. Heartbeat retries were already bounded by the existing five-second cooldown. The session-save loop requires a synchronous request-setup exception; ordinary asynchronous network rejection does not trigger it, and the known in-tree flush caller is reload-after-deploy. The reproduction does not establish retained heap growth or a connection to the upload action.

The separate Media grid disappearance after an attachment-change refresh remains outside this patch. Public APIs and bridge payloads are unchanged.

Open WordPress Playground Preview

@AllTerrainDeveloper AllTerrainDeveloper changed the title Fix accumulating XHR callbacks and duplicate media drag listeners Fix bridge request cleanup, Heartbeat retries, and media drag listeners Oct 5, 2026
@AllTerrainDeveloper AllTerrainDeveloper changed the title Fix bridge request cleanup, Heartbeat retries, and media drag listeners Fix request tracking, media drag setup, and session-save loop Oct 5, 2026
@AllTerrainDeveloper

Copy link
Copy Markdown
Collaborator Author

@claude can you review? Is there any other opportunity related to the 4th point but in other code paths that could leed to the await/kill tab behaviour?

@claude

claude Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Claude finished @AllTerrainDeveloper's task in 2m 26s —— View job


Review

  • Read trigger comment and gather PR context
  • Review the 4 fixes (XHR cleanup, Heartbeat classification, Media drag adapter init, session-save activeSave fix)
  • Search codebase for other "sync-exception-during-async-setup" patterns that could cause a similar stuck-microtask/freeze behavior
  • Post review + answer

Code review

All four fixes check out; each is a real, narrowly-scoped bug fix with clean regression coverage.

1. XHR loadend listener cleanup (src/chromeless-bridge.js:735-787) — fire now self-removes (xhr.removeEventListener('loadend', fire), line 738) before doing any work, and the synchronous-send()-throw path (lines 779-786) also removes the listener and balances osActivityEnd. Correct and matches the "reused XHR" failure mode described. Good catch that fire unregisters itself before reporting, so a listener added by a later send() on the same object can't be confused with this one.

2. Heartbeat classification before auth retry (src/chromeless-bridge.js:398-418, osIsBackgroundRequest) — checks URL query string, a string body, and a FormData/URLSearchParams-like body via body.get('action'). Used consistently for both activity tracking and osMaybeForceAuthCheck, for both fetch and XHR. The osMaybeForceAuthCheck same-origin + heartbeat-path + wp-login guards (lines 472-489) are unchanged and still sound. The comment-to-code match is accurate: "retain the classification flag without adding a reference to the upload body" — confirmed, only the boolean background is closed over, not the body itself.

3. Media drag adapter init order (assets/js/media-library-enhanced.js:65-77) — selectors and LIST_DELEGATION_INSTALLED = false are now declared before start() is invoked, and nothing resets the latch afterward, so installListDelegation()'s guard (line 308) actually holds across later MutationObserver-triggered calls. One nit: this file is one of the two hand-maintained exceptions to the "assets/js/ is build output" rule per AGENTS.md, so editing it directly here is correct and expected — just flagging it so reviewers don't mistake it for a built-output violation.

4. Session-save loop fix (src/boot/session-saver.ts:173-223) — this is the subtle one and it's correctly diagnosed and fixed. Moving the cleanup from an inline finally inside the async IIFE to a .finally() chained outside the call (line 207) is exactly right: a .finally() reaction always runs as a microtask, so it cannot execute before the synchronous assignment activeSave = (...)().finally(...) on the same line has completed — whereas an inline finally inside the async function body runs synchronously whenever the throw happens before the first await, racing the outer assignment. The regression test in tests/vitest/session-saver-flush.test.ts:146-172 is well-built: it uses a bounded Promise.resolve() loop to detect the hang without actually hanging the worker, and still fails meaningfully (not just timing out) against the old code. Nice touch.

Other code paths with the same shape? (the question asked)

I searched src/ for the specific hazard class — a promise assigned to a variable, where an inline finally/cleanup could race the assignment, and something elsewhere busy-waits on that variable (while (x) { await x; }, the actual mechanism that starves the event loop and makes the tab unresponsive). Findings:

  • src/boot/session-saver.ts's flush() was the only while (promiseVar) { await promiseVar; } loop in src/. Nothing else re-awaits a shared in-flight promise in a loop, so nothing else can spin on a stale settled promise the way this one did.
  • Two other call sites use the same "assign-the-result-of-.finally()-chained-onto-an-IIFE" shape and are already safe, for the same reason fix fix: resolve 3 PHPUnit failures + 1 error on trunk test code #4 relies on:
    • src/wallpapers/lazy.ts:110-167 (hydrate()) — .finally() is chained outside the IIFE, then store.state.inflight.set(id, run) runs after, synchronously. No busy-wait loop reads inflight in a retry loop, only a plain "is one already running" check.
    • src/mio/controller.ts:472-483 (mount()) — same shape: .finally() outside, this.mounting = { generation, promise } assigned after. Also safe.
  • I did not find another } finally { block inside an async function whose cleanup resets a variable that something else loops on. The closest analogs (src/settings/state.ts _saveInFlight, src/boot/menu-refresh.ts *RefreshInFlight, src/app-runtime/paged-list.ts loading) are plain booleans read once per call, not awaited in a loop, so a race there would at worst cause one redundant/skipped request — not an infinite microtask spin.

So: no, I don't see another code path with this exact failure mode currently in the tree. The pattern that caused it (a loop awaiting a shared promise, combined with cleanup living inside the async body instead of chained via .finally()) is otherwise avoided by convention in this codebase already. If a future caller ever adds a second while (p) await p wait-for-in-flight loop, the same rule applies: cleanup must be chained via .finally() on the assigned expression, never written as an inline finally inside the async function body.

Per the PR's own "Scope and remaining uncertainty" section, this doesn't confirm or rule out the originally reported upload Wait/Kill freeze — it's a distinct, independently-reproduced bug class, and the PR is honest about that.

No changes requested; the fixes and tests look correct as written.
· branch

@AllTerrainDeveloper
AllTerrainDeveloper merged commit 5283921 into trunk Oct 6, 2026
7 checks passed
@AllTerrainDeveloper
AllTerrainDeveloper deleted the codex/media-bridge-lifecycle-fixes branch October 6, 2026 07:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant