From afb6b2111c81bc0aff5d4d8fdce17714cfb6cc6e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 26 Mar 2026 14:59:09 -0700 Subject: [PATCH 1/2] fix: prevent responseListeners memory leak in CoreMessenger (#11901) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Response listeners were only removed when data contained `"done": true`, but most message types (file events, autocomplete, nextEdit, etc.) return responses without a `done` field. This caused every fire-and-forget request to leak its callback lambda permanently in the map. Over a long session with heavy autocomplete and file navigation, this could accumulate hundreds of thousands of entries (40-100+ MB). Fix: invert the removal logic — remove the listener by default, and only keep it when `done == false` (i.e., a streaming response is still in progress). This preserves existing streaming behavior while ensuring all non-streaming responses are cleaned up immediately. --- .../continueintellijextension/continue/CoreMessenger.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index 3821d3466..bd0e12c38 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -65,9 +65,10 @@ class CoreMessenger( responseListeners[messageId]?.let { listener -> listener(data) @Suppress("UNCHECKED_CAST") - val done = (data as? Map)?.get("done") + val done = (data as? Map)?.get("done") as? Boolean - if (done == true) { + // Remove unless explicitly streaming (done == false) + if (done != false) { responseListeners.remove(messageId) } } From afd5e5e18f7f5d3a010d59aacbfaa06d5ce12f10 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 26 Mar 2026 14:59:21 -0700 Subject: [PATCH 2/2] fix: chunk large JCEF messages to prevent JetBrains sidebar freezes (#11899) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: chunk large JCEF messages to prevent JetBrains sidebar freezes When session data exceeds ~1MB (e.g. long conversations with many context items), sendToWebview embeds the entire JSON payload in a single executeJavaScript call. JCEF's JS parser/compiler cannot handle source strings that large and freezes the IDE. This adds a chunked sending path: payloads over 1MB are base64-encoded, split into 512KB chunks sent as individual executeJavaScript calls that each append to a buffer variable, then a final call decodes and dispatches the reassembled message via window.postMessage. Each individual call is trivial for JCEF to parse, and V8 handles the string concatenation and final JSON.parse without issue. Messages under 1MB (the vast majority) take the existing fast path unchanged. * chore: trim verbose comments * fix: clean up partial chunk buffer on failure * fix: use array join instead of string concat for JCEF chunk reassembly Replaces O(n²) string concatenation (+=) with O(n) array push + join for JS-side chunk buffering. Extracts script generation into testable buildChunkScripts() and adds unit tests for chunking logic. * perf: increase chunk size from 512KB to 2MB Reduces IPC round-trips by 4x (e.g. 7 calls instead of 26 for 10MB). Safe because chunks are trivial JS with pure Base64 string literals. * fix: decode chunked messages as UTF-8 to prevent mojibake atob() returns Latin-1, so multi-byte UTF-8 characters (em dashes, accented letters, CJK, emoji) were mangled. Use TextDecoder to properly decode UTF-8 bytes after base64 decoding. --- .../browser/ContinueBrowser.kt | 61 +++++++++++- .../unit/ContinueBrowserChunkTest.kt | 97 +++++++++++++++++++ 2 files changed, 155 insertions(+), 3 deletions(-) create mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueBrowserChunkTest.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt index e4380d311..ec25e4224 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt @@ -13,6 +13,7 @@ import com.intellij.ui.jcef.* import org.cef.CefApp import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter +import java.util.Base64 import javax.swing.JComponent class ContinueBrowser( @@ -90,14 +91,39 @@ class ContinueBrowser( return } val json = gsonService.gson.toJson(BrowserMessage(messageType, messageId, data)) - val jsCode = """window.postMessage($json, "*");""" try { - browser.cefBrowser.executeJavaScript(jsCode, getGuiUrl(), 0) + if (json.length <= CHUNKED_MESSAGE_THRESHOLD) { + browser.cefBrowser.executeJavaScript( + """window.postMessage($json, "*");""", getGuiUrl(), 0 + ) + } else { + sendChunked(json, messageId) + } } catch (error: Exception) { log.warn(error) } } + // Base64-encode and send in 512KB chunks to avoid JCEF freezing on large JS source strings + private fun sendChunked(json: String, bufferId: String) { + val scripts = buildChunkScripts(json, bufferId) + val url = getGuiUrl() + + browser.cefBrowser.executeJavaScript(scripts.init, url, 0) + + try { + for (chunkScript in scripts.chunks) { + browser.cefBrowser.executeJavaScript(chunkScript, url, 0) + } + browser.cefBrowser.executeJavaScript(scripts.finalize, url, 0) + } catch (e: Exception) { + try { + browser.cefBrowser.executeJavaScript(scripts.cleanup, url, 0) + } catch (_: Exception) {} + throw e + } + } + private fun executeJavaScript(myJSQueryOpenInBrowser: JBCefJSQuery) { val script = """ window.postIntellijMessage = function(messageType, data, messageId) { @@ -134,11 +160,40 @@ class ContinueBrowser( } } - private companion object { + internal data class ChunkScripts( + val init: String, + val chunks: List, + val finalize: String, + val cleanup: String, + ) + + internal companion object { + internal const val CHUNKED_MESSAGE_THRESHOLD = 1 * 1024 * 1024 // 1MB + internal const val CHUNK_SIZE = 2 * 1024 * 1024 // 2MB private fun getGuiUrl() = System.getenv("GUI_URL") ?: "http://continue/index.html" + internal fun buildChunkScripts(json: String, bufferId: String, chunkSize: Int = CHUNK_SIZE): ChunkScripts { + val encoded = Base64.getEncoder().encodeToString(json.toByteArray(Charsets.UTF_8)) + val chunks = mutableListOf() + + var offset = 0 + while (offset < encoded.length) { + val end = minOf(offset + chunkSize, encoded.length) + val chunk = encoded.substring(offset, end) + chunks.add("""window.__cc["$bufferId"].push("$chunk");""") + offset = end + } + + return ChunkScripts( + init = """window.__cc=window.__cc||{};window.__cc["$bufferId"]=[];""", + chunks = chunks, + finalize = """try{var b=atob(window.__cc["$bufferId"].join(""));window.postMessage(JSON.parse(new TextDecoder().decode(Uint8Array.from(b,function(c){return c.charCodeAt(0)}))),"*")} +finally{delete window.__cc["$bufferId"]}""", + cleanup = """delete window.__cc["$bufferId"];""", + ) + } } } \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueBrowserChunkTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueBrowserChunkTest.kt new file mode 100644 index 000000000..7ed34c614 --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueBrowserChunkTest.kt @@ -0,0 +1,97 @@ +package com.github.continuedev.continueintellijextension.unit + +import com.github.continuedev.continueintellijextension.browser.ContinueBrowser +import com.github.continuedev.continueintellijextension.browser.ContinueBrowser.Companion.buildChunkScripts +import junit.framework.TestCase +import java.util.Base64 + +class ContinueBrowserChunkTest : TestCase() { + + fun `test small message produces single chunk`() { + val json = """{"messageType":"test","data":"hello"}""" + val scripts = buildChunkScripts(json, "buf1") + + assertEquals(1, scripts.chunks.size) + assertReassemblesTo(json, scripts.chunks, "buf1") + } + + fun `test message splits into expected number of chunks`() { + val json = """{"data":"${"x".repeat(2_000_000)}"}""" + val chunkSize = ContinueBrowser.CHUNK_SIZE + val encoded = Base64.getEncoder().encodeToString(json.toByteArray(Charsets.UTF_8)) + val expectedChunks = (encoded.length + chunkSize - 1) / chunkSize + + val scripts = buildChunkScripts(json, "buf2") + + assertEquals(expectedChunks, scripts.chunks.size) + assertReassemblesTo(json, scripts.chunks, "buf2") + } + + fun `test custom chunk size`() { + val json = """{"data":"${"a".repeat(100)}"}""" + val scripts = buildChunkScripts(json, "buf3", chunkSize = 32) + + assertTrue(scripts.chunks.size > 1) + assertReassemblesTo(json, scripts.chunks, "buf3") + } + + fun `test init script creates array buffer`() { + val scripts = buildChunkScripts("{}", "myId") + assertEquals("""window.__cc=window.__cc||{};window.__cc["myId"]=[];""", scripts.init) + } + + fun `test finalize script joins and decodes`() { + val scripts = buildChunkScripts("{}", "myId") + assertTrue(scripts.finalize.contains("""window.__cc["myId"].join("")""")) + assertTrue(scripts.finalize.contains("atob")) + assertTrue(scripts.finalize.contains("TextDecoder")) + assertTrue(scripts.finalize.contains("JSON.parse")) + assertTrue(scripts.finalize.contains("""delete window.__cc["myId"]""")) + } + + fun `test cleanup script deletes buffer`() { + val scripts = buildChunkScripts("{}", "myId") + assertEquals("""delete window.__cc["myId"];""", scripts.cleanup) + } + + fun `test special characters survive base64 round-trip`() { + val json = """{"data":"héllo wörld 日本語 emoji: 🎉 quotes: \"nested\""}""" + val scripts = buildChunkScripts(json, "buf4", chunkSize = 32) + + assertReassemblesTo(json, scripts.chunks, "buf4") + } + + fun `test exact chunk boundary`() { + // Create a JSON string whose Base64 encoding is exactly 2x chunkSize + val chunkSize = 64 + val target = chunkSize * 2 + // Base64 output is ceil(input/3)*4, so we need input = target * 3 / 4 bytes + val payloadSize = target * 3 / 4 + val json = "x".repeat(payloadSize) + val encoded = Base64.getEncoder().encodeToString(json.toByteArray(Charsets.UTF_8)) + + assertEquals(target, encoded.length) + + val scripts = buildChunkScripts(json, "buf5", chunkSize = chunkSize) + assertEquals(2, scripts.chunks.size) + assertReassemblesTo(json, scripts.chunks, "buf5") + } + + /** + * Simulates the JS-side reassembly: extract push payloads, join, base64-decode, + * and verify the result matches the original JSON. + */ + private fun assertReassemblesTo(expectedJson: String, chunkScripts: List, bufferId: String) { + val pushPrefix = """window.__cc["$bufferId"].push("""" + val pushSuffix = """");""" + + val reassembled = chunkScripts.joinToString("") { script -> + assertTrue("Chunk should use array push", script.startsWith(pushPrefix)) + assertTrue(script.endsWith(pushSuffix)) + script.removePrefix(pushPrefix).removeSuffix(pushSuffix) + } + + val decoded = String(Base64.getDecoder().decode(reassembled), Charsets.UTF_8) + assertEquals(expectedJson, decoded) + } +}