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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## [Unreleased]

### Fixed
- **Long conversations no longer enter WebKit's virtual-measurement retry loop** — the macOS client now installs a document-start compatibility guard for the upstream transcript-virtualization bug tracked by hermes-webui issue #6654 (fixed upstream by PR #6717, first shipped in `exp-v0.52.374`). When the loaded scheduler still contains the faulty per-window retry reset, virtualization uses WebUI's supported non-virtualized fallback inside WKWebView only. Browser and iOS clients remain unchanged, and virtualization automatically resumes in the Mac client once the server supplies the corrected scheduler.

## [v1.7.3] — 2026-07-18

### Fixed
Expand Down
65 changes: 65 additions & 0 deletions Sources/HermesAgent/BrowserWindowController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,60 @@ private class TitleBarDragView: NSView {

class BrowserWindowController: NSWindowController, NSWindowDelegate, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler {

/// WKWebView-only compatibility guard for the upstream transcript-virtualization
/// retry loop (hermes-webui issue #6654, fixed upstream by PR #6717). The
/// affected WebUI scheduler resets its retry budget whenever WebKit's measured
/// virtual window changes, so alternating measurements can schedule layout
/// work forever on long conversations.
///
/// WebUI already provides `_virtualizeTranscript === false` as its supported
/// non-virtualized path. This document-start accessor remembers the server's
/// requested setting but reports it as disabled while the loaded scheduler still
/// contains the known bad reset. Once the upstream fix is deployed, the reset is
/// absent and the server setting takes effect automatically. Remove this shim once
/// supported WebUI versions universally include that fix.
static let longConversationWebKitCompatibilityScript = """
(function() {
const marker = '__hermesMacLongConversationCompatibilityPatch';
if (window[marker]) return;

const functionToString = Function.prototype.toString;
let requestedValue = window._virtualizeTranscript === true;
// The transcript reads this flag on every scroll event, so classify
// each scheduler function once instead of re-scanning its source.
let classifiedScheduler = null;
let classifiedSchedulerIsFixed = false;

Object.defineProperty(window, marker, {
value: true,
configurable: false,
enumerable: false
});
Object.defineProperty(window, '_virtualizeTranscript', {
configurable: true,
enumerable: true,
get: function() {
if (!requestedValue) return false;
const scheduler = window._scheduleMessageVirtualMeasurementRefresh;
if (typeof scheduler !== 'function') return false;
if (scheduler !== classifiedScheduler) {
const source = functionToString.call(scheduler);
const compactSource = Array.from(source)
.filter(function(character) { return character.charCodeAt(0) > 32; })
.join('');
classifiedSchedulerIsFixed =
!compactSource.includes('_messageVirtualMeasurementRetryCount=0');
classifiedScheduler = scheduler;
}
return classifiedSchedulerIsFixed;
},
set: function(value) {
requestedValue = value === true;
}
});
})();
"""

private var webView: HermesWebView!
private var statusBar: NSView!

Expand Down Expand Up @@ -265,6 +319,17 @@ class BrowserWindowController: NSWindowController, NSWindowDelegate, WKUIDelegat
prefs.setValue(true, forKey: "javaScriptCanAccessClipboard")
prefs.setValue(true, forKey: "DOMPasteAllowed")
config.preferences = prefs

// Install before any page content loads so the WebUI settings bootstrap
// cannot enable the affected virtualizer before this client-side guard.
// Main-frame-only keeps the override out of embedded documents.
let longConversationCompatibilityScript = WKUserScript(
source: Self.longConversationWebKitCompatibilityScript,
injectionTime: .atDocumentStart,
forMainFrameOnly: true
)
config.userContentController.addUserScript(longConversationCompatibilityScript)

let pasteScript = WKUserScript(
source:
"document.addEventListener('paste', function(e) { e.stopImmediatePropagation(); }, true);",
Expand Down
158 changes: 158 additions & 0 deletions Tests/HermesAgentTests/LongConversationCompatibilityTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import JavaScriptCore
import XCTest

/// Regression coverage for the WKWebView-only transcript virtualization guard.
///
/// The production script lives in BrowserWindowController.swift. These tests extract
/// and execute that exact script so changes to the injected JavaScript are exercised,
/// rather than testing a hand-copied Swift model of its behavior.
final class LongConversationCompatibilityTests: XCTestCase {

private func productionScript() throws -> String {
let repositoryRoot = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // HermesAgentTests
.deletingLastPathComponent() // Tests
.deletingLastPathComponent() // repository root
let controllerURL = repositoryRoot
.appendingPathComponent("Sources/HermesAgent/BrowserWindowController.swift")
let source = try String(contentsOf: controllerURL, encoding: .utf8)
let opening = "static let longConversationWebKitCompatibilityScript = \"\"\"\n"
let closing = "\n \"\"\""

guard let openingRange = source.range(of: opening),
let closingRange = source.range(
of: closing,
range: openingRange.upperBound..<source.endIndex
)
else {
throw NSError(
domain: "LongConversationCompatibilityTests",
code: 1,
userInfo: [NSLocalizedDescriptionKey: "Compatibility script not found"]
)
}
return String(source[openingRange.upperBound..<closingRange.lowerBound])
}

private func context(
schedulerBody: String?,
requestedValue: Bool,
installTwice: Bool = false,
prelude: String? = nil
) throws -> JSContext {
let context = try XCTUnwrap(JSContext())
var exception: JSValue?
context.exceptionHandler = { _, value in exception = value }
context.evaluateScript("var window = this;")
if let prelude {
context.evaluateScript(prelude)
}

let script = try productionScript()
context.evaluateScript(script)
if let schedulerBody {
context.evaluateScript(
"window._scheduleMessageVirtualMeasurementRefresh = function() { \(schedulerBody) };"
)
}
context.evaluateScript("window._virtualizeTranscript = \(requestedValue);")
if installTwice {
context.evaluateScript(script)
}

XCTAssertNil(exception?.toString(), "Injected script raised a JavaScript exception")
return context
}

func testKnownBuggySchedulerDisablesVirtualization() throws {
let context = try context(
schedulerBody: "_messageVirtualMeasurementRetryCount = 0;",
requestedValue: true
)

XCTAssertFalse(context.evaluateScript("window._virtualizeTranscript").toBool())
}

func testFixedSchedulerPreservesServerSetting() throws {
let context = try context(
schedulerBody: "_messageVirtualMeasurementCycleKey=cycleKey;",
requestedValue: true
)

XCTAssertTrue(context.evaluateScript("window._virtualizeTranscript").toBool())
}

func testMissingSchedulerFailsClosed() throws {
let context = try context(schedulerBody: nil, requestedValue: true)

XCTAssertFalse(context.evaluateScript("window._virtualizeTranscript").toBool())
}

func testDisabledServerSettingRemainsDisabled() throws {
let context = try context(
schedulerBody: "_messageVirtualMeasurementCycleKey=cycleKey;",
requestedValue: false
)

XCTAssertFalse(context.evaluateScript("window._virtualizeTranscript").toBool())
}

func testRepeatedInstallationIsIdempotent() throws {
let context = try context(
schedulerBody: "_messageVirtualMeasurementCycleKey=cycleKey;",
requestedValue: true,
installTwice: true
)

XCTAssertTrue(context.evaluateScript("window._virtualizeTranscript").toBool())
XCTAssertTrue(
context.evaluateScript("window.__hermesMacLongConversationCompatibilityPatch").toBool()
)
}

/// Counts source reads made through the `Function.prototype.toString` the
/// production script captures at install time.
private let toStringCounterPrelude = """
var __schedulerSourceReads = 0;
var __originalFunctionToString = Function.prototype.toString;
Function.prototype.toString = function() {
__schedulerSourceReads += 1;
return __originalFunctionToString.call(this);
};
"""

func testSchedulerSourceIsClassifiedOnceAcrossRepeatedReads() throws {
let context = try context(
schedulerBody: "_messageVirtualMeasurementCycleKey=cycleKey;",
requestedValue: true,
prelude: toStringCounterPrelude
)

let allTrue = context.evaluateScript("""
(function() {
for (var i = 0; i < 50; i++) {
if (window._virtualizeTranscript !== true) return false;
}
return true;
})()
""")
XCTAssertTrue(allTrue?.toBool() ?? false)
XCTAssertEqual(context.evaluateScript("__schedulerSourceReads").toInt32(), 1)
}

func testReplacedSchedulerIsReclassified() throws {
let context = try context(
schedulerBody: "_messageVirtualMeasurementRetryCount = 0;",
requestedValue: true,
prelude: toStringCounterPrelude
)

XCTAssertFalse(context.evaluateScript("window._virtualizeTranscript").toBool())
XCTAssertFalse(context.evaluateScript("window._virtualizeTranscript").toBool())
context.evaluateScript(
"window._scheduleMessageVirtualMeasurementRefresh = function() { _messageVirtualMeasurementCycleKey=cycleKey; };"
)
XCTAssertTrue(context.evaluateScript("window._virtualizeTranscript").toBool())
XCTAssertEqual(context.evaluateScript("__schedulerSourceReads").toInt32(), 2)
}
}
40 changes: 40 additions & 0 deletions docs/LONG-CONVERSATION-WKWEBVIEW-COMPATIBILITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# WKWebView long-conversation freeze

## Observed freeze

Very long conversations could leave the native macOS app unresponsive while the
same server remained usable in browser and iOS clients.

## Root cause

The WebUI transcript virtualizer uses a scheduler for WebKit measurement work.
When WebKit alternated between measurement windows, the scheduler reset its
retry count and could keep scheduling `requestAnimationFrame` layout work.
The resulting loop made the WKWebView appear frozen.

## Mitigation and scope

`BrowserWindowController` injects a main-frame-only `WKUserScript` at document
start. It preserves the server's virtualization setting but temporarily uses
the supported non-virtualized path while the affected scheduler reset is
present. The script only affects the macOS wrapper because it runs in that
wrapper's WKWebView; browser and iOS clients are unchanged.

## Upstream tracking

- Issue: [nesquena/hermes-webui#6654](https://github.com/nesquena/hermes-webui/issues/6654)
(virtual measurement retry budget resets during window-key oscillation).
- Fix: [nesquena/hermes-webui#6717](https://github.com/nesquena/hermes-webui/pull/6717),
first shipped in the `exp-v0.52.374` experimental release. It deletes the
per-cycle-key reset, which is the exact text this guard looks for, so the guard
turns itself off on servers that include the fix.

The guard matches source text, not behaviour. If a later WebUI release fixes
the bug differently and leaves the literal reset in place (for example, by moving
it behind a once-per-burst check), the guard will keep virtualization disabled.
That is the safe failure direction, but the shim would then never retire itself.

## Removal

Remove the compatibility script and its tests once the upstream scheduler fix
is included in every supported WebUI version, including the stable channel.
Loading