Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(web-browsing): keep saving a crawled page from blocking the event loop (#22907)

Mochaea6a6a9dbace
diff --git a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
index 96abdd0b093..d2d8efe2de9 100644
--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
@@ -193,6 +193,44 @@ describe('WebBrowsingExecutionRuntime', () => {
expect(result.content).toMatch(/Lines \d+-5000 were left out\./);
});
+ it('returns an oversized crawl result without saving it as a document', async () => {
+ // A 13 MB JS bundle served from a CDN was snapshotted into a document on the
+ // main thread and kept the event loop busy until the liveness probe killed the pod.
+ const hugeBody = 'const a = 1;\n'.repeat(100_000);
+ const createDocument = vi.fn().mockResolvedValue({ id: 'docs-1' });
+ const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const runtime = new WebBrowsingExecutionRuntime({
+ canReadSavedDocuments: true,
+ documentService: {
+ associateDocument: vi.fn().mockResolvedValue({ id: 'agent-doc-1' }),
+ createDocument,
+ },
+ searchService: {
+ crawlPages: vi.fn().mockResolvedValue({
+ results: [
+ {
+ data: { content: hugeBody, title: 'Bundle', url: 'https://example.com/index.js' },
+ originalUrl: 'https://example.com/index.js',
+ },
+ ],
+ }),
+ webSearch: vi.fn(),
+ } as any,
+ });
+
+ try {
+ const result = await runtime.crawlMultiPages({ urls: ['https://example.com/index.js'] });
+
+ expect(createDocument).not.toHaveBeenCalled();
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('const a = 1;');
+ expect(result.content).toMatch(/Lines \d+-\d+ were left out\./);
+ expect(result.content).not.toContain('readDocument');
+ } finally {
+ consoleWarn.mockRestore();
+ }
+ });
+
it('logs a save failure by its driver cause instead of the query parameters', async () => {
// Drizzle's "Failed query" wrapper embeds every bound parameter, here the whole
// page and its editor JSON; logging it whole wrote about 30 MB to stderr per failure.
diff --git a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
index d56d52b56d9..d624ce106d0 100644
--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
@@ -10,7 +10,11 @@ import type {
} from '@lobechat/types';
import type { CrawlSuccessResult } from '@lobechat/web-crawler';
-import { CRAWL_CONTENT_LIMITED_COUNT, SEARCH_ITEM_LIMITED_COUNT } from '../const';
+import {
+ CRAWL_CONTENT_LIMITED_COUNT,
+ CRAWL_SAVE_MAX_CHARS,
+ SEARCH_ITEM_LIMITED_COUNT,
+} from '../const';
const MAX_LOGGED_ERROR_LENGTH = 500;
@@ -138,6 +142,13 @@ export class WebBrowsingExecutionRuntime {
const pageData = item.data as CrawlSuccessResult;
if (!pageData.content) return;
+ if (pageData.content.length > CRAWL_SAVE_MAX_CHARS) {
+ console.warn(
+ `[WebBrowsing] Skipped saving crawl result as a document, ${pageData.content.length} characters exceeds the ${CRAWL_SAVE_MAX_CHARS} limit (${pageData.url})`,
+ );
+ return;
+ }
+
try {
const doc = await this.documentService!.createDocument({
content: pageData.content,
diff --git a/packages/builtin-tool-web-browsing/src/const.ts b/packages/builtin-tool-web-browsing/src/const.ts
index 2aca20a0cc2..dd0ab9f1086 100644
--- a/packages/builtin-tool-web-browsing/src/const.ts
+++ b/packages/builtin-tool-web-browsing/src/const.ts
@@ -46,4 +46,11 @@ export const ENGINE_ICON_MAP: Record<string, string> = {
/** Characters of a crawled page returned to the model; longer pages end with the shared window notice. */
export const CRAWL_CONTENT_LIMITED_COUNT = 25_000;
+/**
+ * Largest crawled page saved as a document. Saving parses the page into an editor
+ * snapshot synchronously, so a multi-megabyte body (a JS bundle, a data dump) blocks
+ * the event loop; such a page is still returned to the model, just not saved.
+ */
+export const CRAWL_SAVE_MAX_CHARS = 1_000_000;
+
export const SEARCH_ITEM_LIMITED_COUNT = 30;
diff --git a/patches/[email protected] b/patches/[email protected]
index ce19732eff3..a7f7f896250 100644
--- a/patches/[email protected]
+++ b/patches/[email protected]
@@ -6,7 +6,7 @@ diff --git a/dev/lib/syntax.js b/dev/lib/syntax.js
- * @import {Code, ConstructRecord, Event, Extension, Previous, State, TokenizeContext, Tokenizer} from 'micromark-util-types'
+ * @import {Code, ConstructRecord, Event, Extension, Previous, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'
*/
-
+
import {
@@ -16,6 +16,7 @@
const domain = {tokenize: tokenizeDomain, partial: true}
@@ -25,7 +25,7 @@ diff --git a/dev/lib/syntax.js b/dev/lib/syntax.js
+ let strong
let sizeOpen = 0
let sizeClose = 0
-
+
@@ -656,7 +660,13 @@
code === codes.underscore ||
code === codes.tilde
@@ -39,12 +39,12 @@ diff --git a/dev/lib/syntax.js b/dev/lib/syntax.js
+ : pathAtPunctuation
+ )(code)
}
-
+
if (
@@ -671,6 +681,13 @@
return pathInside
}
-
+
+ /** @type {State} */
+ function atStrongEnd(code) {
+ // Only resolve the prefix once a qualifying closing boundary is found.
@@ -57,7 +57,7 @@ diff --git a/dev/lib/syntax.js b/dev/lib/syntax.js
*
@@ -693,6 +710,94 @@
}
-
+
/**
+ * Resolve a detached prefix to distinguish a fresh ** opener from a delimiter
+ * already used as a closer. Use the tokenizer's actual resolver order, including
@@ -150,6 +150,84 @@ diff --git a/dev/lib/syntax.js b/dev/lib/syntax.js
* Trail.
*
* This calls `ok` if this *is* the trail, followed by an end, which means
+@@ -947,20 +1052,66 @@
+ }
+
+ /**
++ * Where a walk back from an event found an unbalanced bracket.
++ * Without it every autolink candidate after an unbalanced bracket walks back
++ * to that bracket again, which is quadratic in the length of the paragraph.
++ *
++ * @typedef Unbalanced
++ * @property {number} from
++ * Index of the event the walk started at.
++ * @property {number} index
++ * Index of the event of the bracket.
++ * @property {Event} event
++ * Event of the bracket.
++ */
++
++/** @type {WeakMap<Event, Unbalanced>} */
++const unbalancedBefore = new WeakMap()
++
++/**
++ * @param {Token} token
++ * @returns {boolean}
++ */
++function unbalancedLabel(token) {
++ return (
++ (token.type === 'labelLink' || token.type === 'labelImage') &&
++ !token._balanced
++ )
++}
++
++/**
+ * @param {Array<Event>} events
+ * @returns {boolean}
+ */
+ function previousUnbalanced(events) {
++ const last = events.length - 1
+ let index = events.length
+ let result = false
+
+ while (index--) {
+ const token = events[index][1]
++ const known = unbalancedBefore.get(events[index])
+
++ // Reuse the bracket an earlier walk from this event found.
++ // Forming a link or image replaces its bracket and moves the events after
++ // it, so the bracket has to still be the same event at the same place.
+ if (
+- (token.type === 'labelLink' || token.type === 'labelImage') &&
+- !token._balanced
++ known &&
++ known.from === index &&
++ events[known.index] === known.event &&
++ unbalancedLabel(known.event[1])
+ ) {
++ unbalancedBefore.set(events[last], {...known, from: last})
++ result = true
++ break
++ }
++
++ if (unbalancedLabel(token)) {
++ unbalancedBefore.set(events[last], {
++ event: events[index],
++ from: last,
++ index
++ })
+ result = true
+ break
+ }
+@@ -976,7 +1127,7 @@
+ if (events.length > 0 && !result) {
+ // Mark the last token as “walked into” w/o finding
+ // anything.
+- events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true
++ events[last][1]._gfmAutolinkLiteralWalkedInto = true
+ }
+
+ return result
diff --git a/lib/syntax.js b/lib/syntax.js
--- a/lib/syntax.js
+++ b/lib/syntax.js
@@ -158,7 +236,7 @@ diff --git a/lib/syntax.js b/lib/syntax.js
- * @import {Code, ConstructRecord, Event, Extension, Previous, State, TokenizeContext, Tokenizer} from 'micromark-util-types'
+ * @import {Code, ConstructRecord, Event, Extension, Previous, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'
*/
-
+
import { asciiAlpha, asciiAlphanumeric, asciiControl, markdownLineEndingOrSpace, unicodePunctuation, unicodeWhitespace } from 'micromark-util-character';
@@ -19,6 +19,10 @@
tokenize: tokenizeTrail,
@@ -193,7 +271,7 @@ diff --git a/lib/syntax.js b/lib/syntax.js
@@ -591,6 +598,13 @@
return pathInside;
}
-
+
+ /** @type {State} */
+ function atStrongEnd(code) {
+ // Only resolve the prefix once a qualifying closing boundary is found.
@@ -204,14 +282,10 @@ diff --git a/lib/syntax.js b/lib/syntax.js
/**
* In path, at potential trailing punctuation, that was not trailing.
*
-@@ -608,6 +622,60 @@
- }
- effects.consume(code);
- return pathInside;
-+ }
-+}
-+
-+/**
+@@ -612,6 +626,60 @@
+ }
+
+ /**
+ * Resolve a detached prefix to distinguish a fresh ** opener from a delimiter
+ * already used as a closer. Use the tokenizer's actual resolver order, including
+ * strikethrough, without mutating the live tokens or their positions.
@@ -262,13 +336,106 @@ diff --git a/lib/syntax.js b/lib/syntax.js
+ function after(code) {
+ const event = self.events[self.events.length - 1];
+ return code !== null && code > 127 && unicodePunctuation(code) && event[0] === 'exit' && event[1].type === 'attentionSequence' && event[1]._close && self.sliceSerialize(event[1]) === '**' ? ok(code) : nok(code);
- }
++ }
++}
++
++/**
+ * Trail.
+ *
+ * This calls `ok` if this *is* the trail, followed by an end, which means
+@@ -825,30 +893,83 @@
}
-
-@@ -851,4 +919,4 @@
- events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true;
+
+ /**
++ * Where a walk back from an event found an unbalanced bracket.
++ * Without it every autolink candidate after an unbalanced bracket walks back
++ * to that bracket again, which is quadratic in the length of the paragraph.
++ *
++ * @typedef Unbalanced
++ * @property {number} from
++ * Index of the event the walk started at.
++ * @property {number} index
++ * Index of the event of the bracket.
++ * @property {Event} event
++ * Event of the bracket.
++ */
++
++/** @type {WeakMap<Event, Unbalanced>} */
++const unbalancedBefore = new WeakMap()
++
++/**
++ * @param {Token} token
++ * @returns {boolean}
++ */
++function unbalancedLabel(token) {
++ return (
++ (token.type === 'labelLink' || token.type === 'labelImage') &&
++ !token._balanced
++ )
++}
++
++/**
+ * @param {Array<Event>} events
+ * @returns {boolean}
+ */
+ function previousUnbalanced(events) {
+- let index = events.length;
+- let result = false;
++ const last = events.length - 1
++ let index = events.length
++ let result = false
++
+ while (index--) {
+- const token = events[index][1];
+- if ((token.type === 'labelLink' || token.type === 'labelImage') && !token._balanced) {
+- result = true;
+- break;
++ const token = events[index][1]
++ const known = unbalancedBefore.get(events[index])
++
++ // Reuse the bracket an earlier walk from this event found.
++ // Forming a link or image replaces its bracket and moves the events after
++ // it, so the bracket has to still be the same event at the same place.
++ if (
++ known &&
++ known.from === index &&
++ events[known.index] === known.event &&
++ unbalancedLabel(known.event[1])
++ ) {
++ unbalancedBefore.set(events[last], {...known, from: last})
++ result = true
++ break
++ }
++
++ if (unbalancedLabel(token)) {
++ unbalancedBefore.set(events[last], {
++ event: events[index],
++ from: last,
++ index
++ })
++ result = true
++ break
+ }
+
+ // If we’ve seen this token, and it was marked as not having any unbalanced
+ // bracket before it, we can exit.
+ if (token._gfmAutolinkLiteralWalkedInto) {
+- result = false;
+- break;
++ result = false
++ break
+ }
}
- return result;
++
+ if (events.length > 0 && !result) {
+ // Mark the last token as “walked into” w/o finding
+ // anything.
+- events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true;
++ events[last][1]._gfmAutolinkLiteralWalkedInto = true
+ }
+- return result;
-}
\ No newline at end of file
++
++ return result
+}
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index c44fcc3a7d4..4dd9efe1cd9 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -81,6 +81,10 @@ overrides:
drizzle-orm: ^0.45.2
fast-xml-parser: 5.4.2
lexical: 0.42.0
+ # 2.2 serializes attention by trial and re-render, which takes minutes on a long
+ # paragraph. The CJK extension is written against the 2.2 attention API and keeps it.
+ mdast-util-to-markdown: 2.1.2
+ 'mdast-util-to-markdown-cjk-friendly>mdast-util-to-markdown': ^2.2.0
# Keep the coupled core/autolink patches applied without a root lockfile.
micromark: 4.0.3
micromark-extension-gfm-autolink-literal: 2.1.0