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): skip binary crawl bodies, strip NUL before saving, log save failures by cause (#22733)

Mocha159d11a7b886
diff --git a/apps/server/src/services/webBrowsing/__tests__/index.test.ts b/apps/server/src/services/webBrowsing/__tests__/index.test.ts
index ac650654d62..aafc341fee8 100644
--- a/apps/server/src/services/webBrowsing/__tests__/index.test.ts
+++ b/apps/server/src/services/webBrowsing/__tests__/index.test.ts
@@ -324,4 +324,38 @@ describe('WebBrowsingDocumentService.upsertCrawledDocument ()', () => {
expect(mocks.documentModel.create).not.toHaveBeenCalled();
expect(mocks.documentService.updateDocument).not.toHaveBeenCalled();
});
+
+ it('strips NUL characters, which PostgreSQL text and jsonb columns reject', async () => {
+ mocks.documentModel.findBySource.mockResolvedValueOnce(undefined);
+ mocks.documentModel.create.mockResolvedValueOnce({ id: 'doc-nul' });
+
+ await service.upsertCrawledDocument({
+ content: 'before\u0000after\u0000',
+ title: 'Page with NUL',
+ url: 'https://example.com/nul',
+ });
+
+ expect(mocks.documentModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'beforeafter',
+ editorData: { root: { fakeNodeFor: 'beforeafter' } },
+ }),
+ );
+ });
+
+ it('compares the NUL-stripped body so an unchanged re-crawl short-circuits', async () => {
+ mocks.documentModel.findBySource.mockResolvedValueOnce({
+ content: 'beforeafter',
+ id: 'doc-nul',
+ } as any);
+
+ const result = await service.upsertCrawledDocument({
+ content: 'before\u0000after',
+ title: 'Page with NUL',
+ url: 'https://example.com/nul',
+ });
+
+ expect(result).toEqual({ id: 'doc-nul', status: 'unchanged' });
+ expect(mocks.documentService.updateDocument).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/server/src/services/webBrowsing/index.ts b/apps/server/src/services/webBrowsing/index.ts
index b9a7e9baf7c..b57b112bc80 100644
--- a/apps/server/src/services/webBrowsing/index.ts
+++ b/apps/server/src/services/webBrowsing/index.ts
@@ -102,9 +102,13 @@ export class WebBrowsingDocumentService {
): Promise<UpsertCrawledDocumentResult> => {
const { content, contentType, description, title, topicId, url } = params;
- // Raw JSON bodies must be fenced before hitting the markdown snapshot
- // guard (see `UpsertCrawledDocumentParams.contentType`).
- const persistedContent = contentType === 'json' ? wrapJsonCrawlContent(content) : content;
+ // PostgreSQL text and jsonb columns reject NUL (`\u0000`), and one stray NUL
+ // in a crawled page would fail the whole insert. Raw JSON bodies must be
+ // fenced before hitting the markdown snapshot guard (see
+ // `UpsertCrawledDocumentParams.contentType`).
+ const safeContent = content.replaceAll('\u0000', '');
+ const persistedContent =
+ contentType === 'json' ? wrapJsonCrawlContent(safeContent) : safeContent;
const existing = await this.documentModel.findBySource(url, 'web');
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 6b730e4051a..96abdd0b093 100644
--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
@@ -192,5 +192,37 @@ describe('WebBrowsingExecutionRuntime', () => {
expect(result.content).toMatch(/Lines \d+-5000 were left out\./);
});
+
+ 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.
+ const queryError = new Error(
+ `Failed query: insert into "documents" ...\nparams: ${'page body '.repeat(10_000)}`,
+ {
+ cause: Object.assign(new Error('unsupported Unicode escape sequence'), { code: '22P05' }),
+ },
+ );
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const runtime = new WebBrowsingExecutionRuntime({
+ documentService: {
+ associateDocument: vi.fn(),
+ createDocument: vi.fn().mockRejectedValue(queryError),
+ },
+ searchService: createSearchService() as any,
+ });
+
+ try {
+ const result = await runtime.crawlMultiPages({ urls: ['https://example.com/long'] });
+
+ expect(result.success).toBe(true);
+ expect(consoleError).toHaveBeenCalledTimes(1);
+ const logged = consoleError.mock.calls[0].map(String).join(' ');
+ expect(logged).toContain('22P05 unsupported Unicode escape sequence');
+ expect(logged).toContain('https://example.com/long');
+ expect(logged).not.toContain('page body');
+ } finally {
+ consoleError.mockRestore();
+ }
+ });
});
});
diff --git a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
index 40a6ade5e7b..d56d52b56d9 100644
--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
@@ -12,6 +12,26 @@ import type { CrawlSuccessResult } from '@lobechat/web-crawler';
import { CRAWL_CONTENT_LIMITED_COUNT, SEARCH_ITEM_LIMITED_COUNT } from '../const';
+const MAX_LOGGED_ERROR_LENGTH = 500;
+
+/**
+ * One-line summary of a document save failure. A Drizzle "Failed query" error
+ * embeds every bound parameter (the whole page and its editor JSON) in its
+ * message, so log the innermost driver cause, truncated.
+ */
+const describeSaveError = (error: unknown): string => {
+ let current = error;
+ while (current instanceof Error && current.cause !== undefined) current = current.cause;
+
+ const code = (current as { code?: unknown } | null)?.code;
+ const message = current instanceof Error ? current.message : String(current);
+ const summary = typeof code === 'string' ? `${code} ${message}` : message;
+
+ return summary.length > MAX_LOGGED_ERROR_LENGTH
+ ? `${summary.slice(0, MAX_LOGGED_ERROR_LENGTH)}…`
+ : summary;
+};
+
export interface WebBrowsingDocumentService {
/** Returns the agent document binding when one was created, so its id can be handed to the model. */
associateDocument: (documentId: string) => Promise<{ id?: string } | void>;
@@ -130,7 +150,9 @@ export class WebBrowsingExecutionRuntime {
const binding = await this.documentService!.associateDocument(doc.id);
if (binding?.id) savedDocumentIds.set(pageData.url, binding.id);
} catch (error) {
- console.error('[WebBrowsing] Failed to save crawl result to agent document:', error);
+ console.error(
+ `[WebBrowsing] Failed to save crawl result to agent document (${pageData.url}): ${describeSaveError(error)}`,
+ );
}
}),
);
diff --git a/packages/web-crawler/src/crawImpl/__tests__/naive.test.ts b/packages/web-crawler/src/crawImpl/__tests__/naive.test.ts
index 0bb9bca2451..6a8b0a21798 100644
--- a/packages/web-crawler/src/crawImpl/__tests__/naive.test.ts
+++ b/packages/web-crawler/src/crawImpl/__tests__/naive.test.ts
@@ -80,6 +80,50 @@ describe('naive crawler', () => {
expect(htmlToMarkdown).not.toHaveBeenCalled();
});
+ it('should skip PDF responses without downloading or parsing them as HTML', async () => {
+ const { withTimeout } = await import('../../utils/withTimeout');
+ const { htmlToMarkdown } = await import('../../utils/htmlToMarkdown');
+ const text = vi.fn().mockResolvedValue('%PDF-1.7\n...');
+
+ vi.mocked(withTimeout).mockResolvedValue({
+ status: 200,
+ ok: true,
+ headers: new Map([['content-type', 'application/pdf; qs=0.001']]),
+ text,
+ } as any);
+
+ const result = await naive('https://example.com/report.pdf', { filterOptions: {} });
+
+ expect(result).toBeUndefined();
+ expect(text).not.toHaveBeenCalled();
+ expect(htmlToMarkdown).not.toHaveBeenCalled();
+ });
+
+ it('should skip binary bodies served under a text or missing content type', async () => {
+ const { withTimeout } = await import('../../utils/withTimeout');
+ const { htmlToMarkdown } = await import('../../utils/htmlToMarkdown');
+
+ const cases: [string | undefined, string][] = [
+ ['text/html', '%PDF-1.4\n%âãÏÓ\n1 0 obj'],
+ [undefined, '<html>\u0000\u0001\u0002 stream bytes'],
+ ];
+
+ for (const [contentType, body] of cases) {
+ vi.mocked(withTimeout).mockResolvedValue({
+ status: 200,
+ ok: true,
+ headers: new Map(contentType ? [['content-type', contentType]] : []),
+ text: vi.fn().mockResolvedValue(body),
+ } as any);
+
+ const result = await naive('https://example.com/download', { filterOptions: {} });
+
+ expect(result).toBeUndefined();
+ }
+
+ expect(htmlToMarkdown).not.toHaveBeenCalled();
+ });
+
it('should throw PageNotFoundError with status for 410 Gone', async () => {
const { withTimeout } = await import('../../utils/withTimeout');
vi.mocked(withTimeout).mockResolvedValue({
diff --git a/packages/web-crawler/src/crawImpl/naive.ts b/packages/web-crawler/src/crawImpl/naive.ts
index 9e1b030c5d5..26196392c12 100755
--- a/packages/web-crawler/src/crawImpl/naive.ts
+++ b/packages/web-crawler/src/crawImpl/naive.ts
@@ -74,6 +74,11 @@ export const naive: CrawlImpl = async (url, { filterOptions }) => {
throw new UnsupportedContentError(`URL points to non-document content (${type})`);
}
+ // A PDF has readable text, but only a PDF-capable crawler can extract it. Skip so
+ // the next crawler gets a turn: fed to the HTML parser, the raw bytes stall the
+ // event loop for tens of seconds and come back as binary noise.
+ if (type?.split(';')[0].trim().toLowerCase() === 'application/pdf') return;
+
if (type?.includes('application/json')) {
let content: string;
@@ -95,6 +100,10 @@ export const naive: CrawlImpl = async (url, { filterOptions }) => {
try {
const html = await res.text();
+ // Binary files are often served as text/html or with no Content-Type. Real pages
+ // never contain NUL characters, so treat such a body like the PDF case above.
+ if (html.startsWith('%PDF-') || html.includes('\u0000')) return;
+
const result = htmlToMarkdown(html, { filterOptions, url });
// if the content is empty or too short, just return