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(local-system): guard readFile against binary blobs and oversized output (#14602)

Arvin Xu96165e453a39
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts
new file mode 100644
index 00000000000..5339f3a2794
--- /dev/null
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts
@@ -0,0 +1,176 @@
+import fs from 'node:fs';
+import { mkdir, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type App } from '@/core/App';
+
+import LocalFileCtr from '../LocalFileCtr';
+
+// Real fs + real @lobechat/file-loaders end-to-end. We only mock the
+// boundaries we genuinely cannot run in a test process: electron IPC,
+// execa shell-outs, logger, net fetch.
+vi.mock('electron', () => ({
+ dialog: { showOpenDialog: vi.fn(), showSaveDialog: vi.fn() },
+ ipcMain: { handle: vi.fn() },
+ shell: { openPath: vi.fn() },
+}));
+
+vi.mock('execa', () => ({ execa: vi.fn() }));
+
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ }),
+}));
+
+vi.mock('@/utils/net-fetch', () => ({ netFetch: vi.fn() }));
+
+vi.mock('@/utils/file-system', () => ({ makeSureDirExist: vi.fn() }));
+
+const mockApp = {
+ appStoragePath: '/mock/app/storage',
+ getService: vi.fn(),
+ toolDetectorManager: { getBestTool: vi.fn(() => null) },
+} as unknown as App;
+
+describe('LocalFileCtr β€” readFile / readFiles (real fs)', () => {
+ const tmpDir = path.join(os.tmpdir(), 'localfilectr-readfile-test-' + process.pid);
+ let localFileCtr: LocalFileCtr;
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ await mkdir(tmpDir, { recursive: true });
+ localFileCtr = new LocalFileCtr(mockApp);
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpDir, { force: true, recursive: true });
+ });
+
+ describe('readFile', () => {
+ it('should read file successfully with default location', async () => {
+ const filePath = path.join(tmpDir, 'test.txt');
+ const content = 'line1\nline2\nline3\nline4\nline5';
+ await writeFile(filePath, content);
+
+ const result = await localFileCtr.readFile({ path: filePath });
+
+ expect(result).toEqual({
+ charCount: 29,
+ content,
+ createdTime: expect.any(Date),
+ fileType: 'txt',
+ filename: 'test.txt',
+ lineCount: 5,
+ loc: [0, 200],
+ modifiedTime: expect.any(Date),
+ totalCharCount: 29,
+ totalLineCount: 5,
+ });
+ });
+
+ it('should read file with custom location range', async () => {
+ const filePath = path.join(tmpDir, 'range.txt');
+ await writeFile(filePath, 'line1\nline2\nline3\nline4\nline5');
+
+ const result = await localFileCtr.readFile({ loc: [1, 3], path: filePath });
+
+ expect(result).toEqual({
+ charCount: 11,
+ content: 'line2\nline3',
+ createdTime: expect.any(Date),
+ fileType: 'txt',
+ filename: 'range.txt',
+ lineCount: 2,
+ loc: [1, 3],
+ modifiedTime: expect.any(Date),
+ totalCharCount: 29,
+ totalLineCount: 5,
+ });
+ });
+
+ it('should read full file content when fullContent is true', async () => {
+ const filePath = path.join(tmpDir, 'full.txt');
+ const content = 'line1\nline2\nline3\nline4\nline5';
+ await writeFile(filePath, content);
+
+ const result = await localFileCtr.readFile({ fullContent: true, path: filePath });
+
+ expect(result).toEqual({
+ charCount: 29,
+ content,
+ createdTime: expect.any(Date),
+ fileType: 'txt',
+ filename: 'full.txt',
+ lineCount: 5,
+ loc: [0, 5],
+ modifiedTime: expect.any(Date),
+ totalCharCount: 29,
+ totalLineCount: 5,
+ });
+ });
+
+ it('should handle file read error', async () => {
+ const result = await localFileCtr.readFile({
+ path: path.join(tmpDir, 'does-not-exist.txt'),
+ });
+
+ expect(result).toEqual({
+ charCount: 0,
+ content: expect.stringContaining('Error accessing or processing file'),
+ createdTime: expect.any(Date),
+ fileType: 'txt',
+ filename: 'does-not-exist.txt',
+ lineCount: 0,
+ loc: [0, 0],
+ modifiedTime: expect.any(Date),
+ totalCharCount: 0,
+ totalLineCount: 0,
+ });
+ });
+ });
+
+ describe('readFiles', () => {
+ it('should read multiple files successfully', async () => {
+ const file1 = path.join(tmpDir, 'a.txt');
+ const file2 = path.join(tmpDir, 'b.txt');
+ await writeFile(file1, 'content a');
+ await writeFile(file2, 'content b');
+
+ const result = await localFileCtr.readFiles({ paths: [file1, file2] });
+
+ expect(result).toEqual([
+ {
+ charCount: 9,
+ content: 'content a',
+ createdTime: expect.any(Date),
+ fileType: 'txt',
+ filename: 'a.txt',
+ lineCount: 1,
+ loc: [0, 200],
+ modifiedTime: expect.any(Date),
+ totalCharCount: 9,
+ totalLineCount: 1,
+ },
+ {
+ charCount: 9,
+ content: 'content b',
+ createdTime: expect.any(Date),
+ fileType: 'txt',
+ filename: 'b.txt',
+ lineCount: 1,
+ loc: [0, 200],
+ modifiedTime: expect.any(Date),
+ totalCharCount: 9,
+ totalLineCount: 1,
+ },
+ ]);
+ });
+ });
+});
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index 1204692ab26..5076da17f0c 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -106,7 +106,6 @@ const mockApp = {
describe('LocalFileCtr', () => {
let localFileCtr: LocalFileCtr;
let mockShell: any;
- let mockLoadFile: any;
let mockFsPromises: any;
beforeEach(async () => {
@@ -114,7 +113,6 @@ describe('LocalFileCtr', () => {
// Import mocks
mockShell = (await import('electron')).shell;
- mockLoadFile = (await import('@lobechat/file-loaders')).loadFile;
mockFsPromises = await import('node:fs/promises');
localFileCtr = new LocalFileCtr(mockApp);
@@ -178,91 +176,9 @@ describe('LocalFileCtr', () => {
});
});
- describe('readFile', () => {
- it('should read file successfully with default location', async () => {
- const mockFileContent = 'line1\nline2\nline3\nline4\nline5';
- vi.mocked(mockLoadFile).mockResolvedValue({
- content: mockFileContent,
- filename: 'test.txt',
- fileType: 'txt',
- createdTime: new Date('2024-01-01'),
- modifiedTime: new Date('2024-01-02'),
- });
-
- const result = await localFileCtr.readFile({ path: '/test/file.txt' });
-
- expect(result.filename).toBe('test.txt');
- expect(result.fileType).toBe('txt');
- expect(result.totalLineCount).toBe(5);
- expect(result.content).toBe(mockFileContent);
- });
-
- it('should read file with custom location range', async () => {
- const mockFileContent = 'line1\nline2\nline3\nline4\nline5';
- vi.mocked(mockLoadFile).mockResolvedValue({
- content: mockFileContent,
- filename: 'test.txt',
- fileType: 'txt',
- createdTime: new Date('2024-01-01'),
- modifiedTime: new Date('2024-01-02'),
- });
-
- const result = await localFileCtr.readFile({ path: '/test/file.txt', loc: [1, 3] });
-
- expect(result.content).toBe('line2\nline3');
- expect(result.lineCount).toBe(2);
- expect(result.totalLineCount).toBe(5);
- });
-
- it('should read full file content when fullContent is true', async () => {
- const mockFileContent = 'line1\nline2\nline3\nline4\nline5';
- vi.mocked(mockLoadFile).mockResolvedValue({
- content: mockFileContent,
- filename: 'test.txt',
- fileType: 'txt',
- createdTime: new Date('2024-01-01'),
- modifiedTime: new Date('2024-01-02'),
- });
-
- const result = await localFileCtr.readFile({ path: '/test/file.txt', fullContent: true });
-
- expect(result.content).toBe(mockFileContent);
- expect(result.lineCount).toBe(5);
- expect(result.charCount).toBe(mockFileContent.length);
- expect(result.totalLineCount).toBe(5);
- expect(result.totalCharCount).toBe(mockFileContent.length);
- expect(result.loc).toEqual([0, 5]);
- });
-
- it('should handle file read error', async () => {
- vi.mocked(mockLoadFile).mockRejectedValue(new Error('File not found'));
-
- const result = await localFileCtr.readFile({ path: '/test/missing.txt' });
-
- expect(result.content).toContain('Error accessing or processing file');
- expect(result.lineCount).toBe(0);
- expect(result.charCount).toBe(0);
- });
- });
-
- describe('readFiles', () => {
- it('should read multiple files successfully', async () => {
- vi.mocked(mockLoadFile).mockResolvedValue({
- content: 'file content',
- filename: 'test.txt',
- fileType: 'txt',
- createdTime: new Date('2024-01-01'),
- modifiedTime: new Date('2024-01-02'),
- });
-
- const result = await localFileCtr.readFiles({
- paths: ['/test/file1.txt', '/test/file2.txt'],
- });
-
- expect(result).toHaveLength(2);
- expect(mockLoadFile).toHaveBeenCalledTimes(2);
- });
- });
+ // readFile / readFiles e2e tests live in LocalFileCtr.readFile.test.ts so
+ // they exercise real fs + file-loaders without fighting the heavy mocks
+ // this suite needs for execa-driven tools, electron, and the like.
describe('handleWriteFile', () => {
it('should write file successfully', async () => {
diff --git a/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx b/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx
index 67e63fc0a2a..b07212b5563 100644
--- a/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx
@@ -1,6 +1,6 @@
import type { WriteLocalFileParams } from '@lobechat/electron-client-ipc';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, Highlighter, Icon, Markdown, Skeleton } from '@lobehub/ui';
+import { Flexbox, Icon, Markdown, PatchDiff, Skeleton } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { ChevronRight } from 'lucide-react';
import path from 'path-browserify-esm';
@@ -21,35 +21,40 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
+const buildNewFilePatch = (filePath: string, content: string) => {
+ const hasTrailingNewline = content.endsWith('\n');
+ const lines = content.split('\n');
+ const bodyLines = hasTrailingNewline ? lines.slice(0, -1) : lines;
+ const lineCount = bodyLines.length;
+ const header = `--- /dev/null\n+++ b/${filePath}\n@@ -0,0 +1,${lineCount} @@\n`;
+ const body = bodyLines.map((line) => `+${line}`).join('\n');
+ return hasTrailingNewline
+ ? `${header}${body}\n`
+ : `${header}${body}\n\\ No newline at end of file\n`;
+};
+
const WriteFile = memo<BuiltinRenderProps<WriteLocalFileParams>>(({ args }) => {
if (!args) return <Skeleton active />;
const { base, dir } = path.parse(args.path);
const ext = path.extname(args.path).slice(1).toLowerCase();
+ const isMarkdown = ext === 'md' || ext === 'mdx';
- const renderContent = () => {
- if (!args.content) return null;
-
- if (ext === 'md' || ext === 'mdx') {
- return (
- <Markdown style={{ maxHeight: 240, overflow: 'auto', padding: '0 8px' }} variant={'chat'}>
- {args.content}
- </Markdown>
- );
- }
-
+ // Code-type files render as a "new file" unified diff so the visual is
+ // consistent with EditLocalFile's PatchDiff. Markdown keeps its rendered
+ // preview because a rendered doc reads better than an all-green diff.
+ if (!isMarkdown && args.content) {
return (
- <Highlighter
- wrap
- language={ext || 'text'}
- showLanguage={false}
- style={{ maxHeight: 240, overflow: 'auto' }}
+ <PatchDiff
+ fileName={base}
+ language={ext || undefined}
+ patch={buildNewFilePatch(args.path, args.content)}
+ showHeader={false}
variant={'borderless'}
- >
- {args.content}
- </Highlighter>
+ viewMode={'unified'}
+ />
);
- };
+ }
return (
<Flexbox className={styles.container} gap={12}>
@@ -59,7 +64,13 @@ const WriteFile = memo<BuiltinRenderProps<WriteLocalFileParams>>(({ args }) => {
<LocalFile name={base} path={args.path} />
</Flexbox>
- {args.content && <Flexbox className={styles.previewBox}>{renderContent()}</Flexbox>}
+ {args.content && (
+ <Flexbox className={styles.previewBox}>
+ <Markdown style={{ maxHeight: 240, overflow: 'auto', padding: '0 8px' }} variant={'chat'}>
+ {args.content}
+ </Markdown>
+ </Flexbox>
+ )}
</Flexbox>
);
});
diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.ts
index df6fff5063c..cddc93cbe92 100644
--- a/packages/builtin-tool-local-system/src/manifest.ts
+++ b/packages/builtin-tool-local-system/src/manifest.ts
@@ -47,7 +47,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {
},
{
description:
- 'Read the content of a specific file. Input should be the file path. Output is the file content as a string.',
+ 'Read the content of a text or document file (txt/md/json/source code/pdf/docx/etc.). Binary files (.bin/.exe/.zip/.b64/encoded blobs) are rejected with a structured error β€” use runCommand with file/hexdump/strings to inspect those instead. Output is capped at 500K chars total and 8K chars per line; for larger files, use a narrower line range or grepContent.',
humanIntervention: {
dynamic: {
default: 'never',
diff --git a/packages/file-loaders/src/index.ts b/packages/file-loaders/src/index.ts
index 5c64ce2bd3c..aa0fc390fd6 100644
--- a/packages/file-loaders/src/index.ts
+++ b/packages/file-loaders/src/index.ts
@@ -1,3 +1,5 @@
export * from './blackList';
export * from './loadFile';
export * from './types';
+export * from './utils/isBinaryContent';
+export * from './utils/isTextReadableFile';
diff --git a/packages/file-loaders/src/loaders/text/index.ts b/packages/file-loaders/src/loaders/text/index.ts
index 4cd6212d94b..9c04ec8a2f9 100644
--- a/packages/file-loaders/src/loaders/text/index.ts
+++ b/packages/file-loaders/src/loaders/text/index.ts
@@ -3,43 +3,10 @@ import { readFile } from 'node:fs/promises';
import debug from 'debug';
import type { DocumentPage, FileLoaderInterface } from '../../types';
+import { detectUtf16NoBom } from '../../utils/detectUtf16';
const log = debug('file-loaders:text');
-const HEURISTIC_SAMPLE_BYTES = 512;
-const HEURISTIC_THRESHOLD = 0.3;
-
-type Utf16Variant = 'utf-16le' | 'utf-16be';
-
-/**
- * Detect UTF-16 without BOM by sampling and counting ASCII-shaped code-unit
- * pairs. ASCII chars in UTF-16 produce a 0x00 byte at the high half: at
- * odd index for LE, at even index for BE.
- */
-const detectUtf16NoBom = (buffer: Buffer): Utf16Variant | null => {
- const sample = buffer.subarray(0, Math.min(HEURISTIC_SAMPLE_BYTES, buffer.length));
- if (sample.length < 4 || sample.length % 2 !== 0) return null;
-
- let leAsciiPairs = 0;
- let beAsciiPairs = 0;
- const totalPairs = sample.length / 2;
-
- for (let i = 0; i < sample.length; i += 2) {
- const lo = sample[i];
- const hi = sample[i + 1];
- if (hi === 0x00 && lo !== 0x00) leAsciiPairs++;
- else if (lo === 0x00 && hi !== 0x00) beAsciiPairs++;
- }
-
- if (leAsciiPairs > beAsciiPairs && leAsciiPairs / totalPairs >= HEURISTIC_THRESHOLD) {
- return 'utf-16le';
- }
- if (beAsciiPairs > leAsciiPairs && beAsciiPairs / totalPairs >= HEURISTIC_THRESHOLD) {
- return 'utf-16be';
- }
- return null;
-};
-
/**
* Read a text file with automatic encoding detection.
* Detects UTF-8, UTF-16LE, and UTF-16BE via BOM, with a heuristic fallback
diff --git a/packages/file-loaders/src/utils/detectUtf16.ts b/packages/file-loaders/src/utils/detectUtf16.ts
new file mode 100644
index 00000000000..96da44901dd
--- /dev/null
+++ b/packages/file-loaders/src/utils/detectUtf16.ts
@@ -0,0 +1,37 @@
+const HEURISTIC_SAMPLE_BYTES = 512;
+const HEURISTIC_THRESHOLD = 0.3;
+
+export type Utf16Variant = 'utf-16le' | 'utf-16be';
+
+/**
+ * Detect UTF-16 without BOM by sampling and counting ASCII-shaped code-unit
+ * pairs. ASCII chars in UTF-16 produce a 0x00 byte at the high half: at
+ * odd index for LE, at even index for BE.
+ *
+ * Used both by `TextLoader` (to pick the right decoder) and by the binary
+ * sniffer (so a UTF-16 text file without BOM isn't mistaken for binary
+ * because of its alternating null bytes).
+ */
+export const detectUtf16NoBom = (buffer: Buffer): Utf16Variant | null => {
+ const sample = buffer.subarray(0, Math.min(HEURISTIC_SAMPLE_BYTES, buffer.length));
+ if (sample.length < 4 || sample.length % 2 !== 0) return null;
+
+ let leAsciiPairs = 0;
+ let beAsciiPairs = 0;
+ const totalPairs = sample.length / 2;
+
+ for (let i = 0; i < sample.length; i += 2) {
+ const lo = sample[i];
+ const hi = sample[i + 1];
+ if (hi === 0x00 && lo !== 0x00) leAsciiPairs++;
+ else if (lo === 0x00 && hi !== 0x00) beAsciiPairs++;
+ }
+
+ if (leAsciiPairs > beAsciiPairs && leAsciiPairs / totalPairs >= HEURISTIC_THRESHOLD) {
+ return 'utf-16le';
+ }
+ if (beAsciiPairs > leAsciiPairs && beAsciiPairs / totalPairs >= HEURISTIC_THRESHOLD) {
+ return 'utf-16be';
+ }
+ return null;
+};
diff --git a/packages/file-loaders/src/utils/isBinaryContent.test.ts b/packages/file-loaders/src/utils/isBinaryContent.test.ts
new file mode 100644
index 00000000000..3409bed3ebb
--- /dev/null
+++ b/packages/file-loaders/src/utils/isBinaryContent.test.ts
@@ -0,0 +1,102 @@
+import fs from 'node:fs';
+import { mkdir, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { sniffBinaryBuffer, sniffBinaryFile } from './isBinaryContent';
+
+describe('sniffBinaryBuffer', () => {
+ it('treats empty buffer as text', () => {
+ expect(sniffBinaryBuffer(Buffer.alloc(0))).toEqual({ isBinary: false });
+ });
+
+ it('treats plain ASCII text as text', () => {
+ const buf = Buffer.from('hello world\nthis is text\n', 'utf8');
+ expect(sniffBinaryBuffer(buf).isBinary).toBe(false);
+ });
+
+ it('treats UTF-8 with CJK as text', () => {
+ const buf = Buffer.from('δ½ ε₯½,δΈ–η•Œγ€‚θΏ™ζ˜―δΈ­ζ–‡γ€‚\nθΏ™δΉŸζ˜―δΈ­ζ–‡γ€‚', 'utf8');
+ expect(sniffBinaryBuffer(buf).isBinary).toBe(false);
+ });
+
+ it('treats base64 text as text (no null bytes, all printable)', () => {
+ const longBase64 = Buffer.from('A'.repeat(2000) + 'B'.repeat(2000) + '+/=', 'utf8');
+ expect(sniffBinaryBuffer(longBase64).isBinary).toBe(false);
+ });
+
+ it('flags buffers containing a null byte as binary', () => {
+ const buf = Buffer.concat([Buffer.from('hello'), Buffer.from([0x00]), Buffer.from('world')]);
+ const result = sniffBinaryBuffer(buf);
+ expect(result.isBinary).toBe(true);
+ expect(result.reason).toContain('null byte');
+ });
+
+ it('respects UTF-8 BOM and treats as text', () => {
+ const buf = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from('hello')]);
+ expect(sniffBinaryBuffer(buf).isBinary).toBe(false);
+ });
+
+ it('respects UTF-16LE BOM and treats as text even with embedded zero bytes', () => {
+ const buf = Buffer.concat([
+ Buffer.from([0xff, 0xfe]),
+ Buffer.from([0x68, 0x00, 0x69, 0x00]), // "hi" in UTF-16LE
+ ]);
+ expect(sniffBinaryBuffer(buf).isBinary).toBe(false);
+ });
+
+ it('treats UTF-16LE without BOM as text (Windows-style exports)', () => {
+ const buf = Buffer.from('hello world\nthis is a longer ASCII sample\n', 'utf16le');
+ expect(sniffBinaryBuffer(buf).isBinary).toBe(false);
+ });
+
+ it('treats UTF-16BE without BOM as text', () => {
+ const ascii = 'hello world\nthis is a longer ASCII sample\n';
+ const bytes = Buffer.alloc(ascii.length * 2);
+ for (let i = 0; i < ascii.length; i++) {
+ bytes[i * 2] = 0x00;
+ bytes[i * 2 + 1] = ascii.charCodeAt(i);
+ }
+ expect(sniffBinaryBuffer(bytes).isBinary).toBe(false);
+ });
+
+ it('flags buffers with high non-printable ratio', () => {
+ const bytes: number[] = [];
+ for (let i = 0; i < 100; i++) bytes.push(i % 0x20 === 0 ? 0x41 : 0x01);
+ const buf = Buffer.from(bytes);
+ const result = sniffBinaryBuffer(buf);
+ expect(result.isBinary).toBe(true);
+ });
+});
+
+describe('sniffBinaryFile', () => {
+ const tmpDir = path.join(os.tmpdir(), 'sniff-binary-test-' + process.pid);
+
+ beforeEach(async () => {
+ await mkdir(tmpDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpDir, { force: true, recursive: true });
+ });
+
+ it('reads only the first 8KB and reports text for plain ASCII', async () => {
+ const filePath = path.join(tmpDir, 'plain.txt');
+ await writeFile(filePath, 'a'.repeat(20_000));
+ const result = await sniffBinaryFile(filePath);
+ expect(result.isBinary).toBe(false);
+ });
+
+ it('flags a file whose first bytes contain null', async () => {
+ const filePath = path.join(tmpDir, 'binary.bin');
+ // PNG magic + IHDR length: contains nulls but doesn't pattern-match UTF-16.
+ await writeFile(
+ filePath,
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d]),
+ );
+ const result = await sniffBinaryFile(filePath);
+ expect(result.isBinary).toBe(true);
+ });
+});
diff --git a/packages/file-loaders/src/utils/isBinaryContent.ts b/packages/file-loaders/src/utils/isBinaryContent.ts
new file mode 100644
index 00000000000..11d1c7e5385
--- /dev/null
+++ b/packages/file-loaders/src/utils/isBinaryContent.ts
@@ -0,0 +1,91 @@
+import { open } from 'node:fs/promises';
+
+import { detectUtf16NoBom } from './detectUtf16';
+
+const SNIFF_BYTES = 8192;
+const NON_PRINTABLE_THRESHOLD = 0.3;
+
+export interface BinarySniffResult {
+ isBinary: boolean;
+ reason?: string;
+}
+
+const hasUtf8Bom = (buf: Buffer): boolean =>
+ buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf;
+
+const hasUtf16Bom = (buf: Buffer): boolean =>
+ buf.length >= 2 && ((buf[0] === 0xff && buf[1] === 0xfe) || (buf[0] === 0xfe && buf[1] === 0xff));
+
+/**
+ * Heuristically determine if a buffer looks like binary data.
+ *
+ * - UTF-8 / UTF-16 BOM β†’ text
+ * - UTF-16 detected without BOM (Windows-style exports) β†’ text, decoded for
+ * the printable-ratio check
+ * - Any null byte (and not UTF-16) β†’ binary
+ * - More than 30% of decoded chars are control or U+FFFD replacement β†’ binary
+ *
+ * Note: this only catches truly binary content. Text-encoded blobs (e.g., a
+ * single 27KB line of base64) will pass this check β€” the extension whitelist
+ * and the post-load char cap are what stop those.
+ */
+export const sniffBinaryBuffer = (buffer: Buffer): BinarySniffResult => {
+ if (buffer.length === 0) return { isBinary: false };
+
+ if (hasUtf8Bom(buffer) || hasUtf16Bom(buffer)) return { isBinary: false };
+
+ const utf16Variant = detectUtf16NoBom(buffer);
+ if (utf16Variant) {
+ const text = new TextDecoder(utf16Variant, { fatal: false }).decode(buffer);
+ return checkPrintableRatio(text, buffer.length);
+ }
+
+ if (buffer.includes(0)) {
+ return { isBinary: true, reason: 'contains null byte' };
+ }
+
+ const text = new TextDecoder('utf-8', { fatal: false }).decode(buffer);
+ return checkPrintableRatio(text, buffer.length);
+};
+
+const REPLACEMENT_CHAR = 'οΏ½';
+
+const checkPrintableRatio = (text: string, sampledBytes: number): BinarySniffResult => {
+ if (text.length === 0) return { isBinary: false };
+
+ let suspect = 0;
+ for (const ch of text) {
+ if (ch === REPLACEMENT_CHAR) {
+ suspect++;
+ continue;
+ }
+ const code = ch.codePointAt(0)!;
+ if (code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) {
+ suspect++;
+ }
+ }
+
+ const ratio = suspect / text.length;
+ if (ratio > NON_PRINTABLE_THRESHOLD) {
+ return {
+ isBinary: true,
+ reason: `${(ratio * 100).toFixed(1)}% non-printable chars in first ${sampledBytes} bytes`,
+ };
+ }
+
+ return { isBinary: false };
+};
+
+/**
+ * Read up to the leading 8KB of a file and run the binary heuristic on it.
+ */
+export const sniffBinaryFile = async (filePath: string): Promise<BinarySniffResult> => {
+ const fd = await open(filePath, 'r');
+ try {
+ const buffer = Buffer.alloc(SNIFF_BYTES);
+ const { bytesRead } = await fd.read(buffer, 0, SNIFF_BYTES, 0);
+ return sniffBinaryBuffer(buffer.subarray(0, bytesRead));
+ } finally {
+ await fd.close();
+ }
+};
diff --git a/packages/file-loaders/src/utils/isTextReadableFile.ts b/packages/file-loaders/src/utils/isTextReadableFile.ts
index 384ef29f17f..269e375f633 100644
--- a/packages/file-loaders/src/utils/isTextReadableFile.ts
+++ b/packages/file-loaders/src/utils/isTextReadableFile.ts
@@ -7,6 +7,8 @@ export const TEXT_READABLE_FILE_TYPES = [
// Configuration & Data
'json',
+ 'jsonc',
+ 'json5',
'xml',
'yaml',
'yml',
@@ -15,6 +17,8 @@ export const TEXT_READABLE_FILE_TYPES = [
'cfg',
'conf',
'csv',
+ 'env',
+ 'properties',
// Web Development
'html',
@@ -27,6 +31,9 @@ export const TEXT_READABLE_FILE_TYPES = [
'ts',
'tsx',
'mjs',
+ 'cjs',
+ 'mts',
+ 'cts',
'vue',
'svelte',
'svg',
@@ -49,6 +56,11 @@ export const TEXT_READABLE_FILE_TYPES = [
'bash',
'bat',
'ps1',
+ 'lua',
+ 'dart',
+ 'scala',
+ 'groovy',
+ 'gradle',
// Other
'log',
@@ -58,6 +70,12 @@ export const TEXT_READABLE_FILE_TYPES = [
'db', // Often text-based, like SQLite journals
];
+/**
+ * Extensions that have dedicated parsers in `loadFile`. These are not text but
+ * are explicitly supported file types that we know how to extract text from.
+ */
+export const SPECIAL_PARSED_FILE_TYPES = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'pptx'];
+
/**
* Determine if a file can be read as text based on its extension.
* @param fileType File extension (without the leading dot)
@@ -66,3 +84,15 @@ export const TEXT_READABLE_FILE_TYPES = [
export function isTextReadableFile(fileType: string): boolean {
return TEXT_READABLE_FILE_TYPES.includes(fileType.toLowerCase());
}
+
+/**
+ * Whether the agent's `readFile` should be willing to attempt reading this
+ * extension at all. True for known text formats and for the special parsed
+ * binary formats (pdf/doc/etc.) that have dedicated loaders. Anything else β€”
+ * `.bin`, `.zip`, `.b64`, `.exe`, … β€” should be hard-rejected before the file
+ * is opened, to avoid feeding a binary blob to the LLM.
+ */
+export function isReadableFileType(fileType: string): boolean {
+ const ext = fileType.toLowerCase();
+ return TEXT_READABLE_FILE_TYPES.includes(ext) || SPECIAL_PARSED_FILE_TYPES.includes(ext);
+}
diff --git a/packages/local-file-shell/src/file/__tests__/file.test.ts b/packages/local-file-shell/src/file/__tests__/file.test.ts
index b982820116b..6154cf4c025 100644
--- a/packages/local-file-shell/src/file/__tests__/file.test.ts
+++ b/packages/local-file-shell/src/file/__tests__/file.test.ts
@@ -100,6 +100,82 @@ describe('file operations', () => {
expect(result.createdTime).toBeInstanceOf(Date);
expect(result.modifiedTime).toBeInstanceOf(Date);
});
+
+ it('should reject unsupported binary file extensions', async () => {
+ const filePath = path.join(tmpDir, 'cm.bundle.b64');
+ await writeFile(filePath, 'A'.repeat(20_000));
+
+ const result = await readLocalFile({ path: filePath });
+
+ expect(result.content).toContain('Unsupported binary file type');
+ expect(result.content).toContain('.b64');
+ expect(result.charCount).toBe(0);
+ expect(result.lineCount).toBe(0);
+ });
+
+ it('should reject .bin / .exe / .zip extensions', async () => {
+ for (const ext of ['bin', 'exe', 'zip']) {
+ const filePath = path.join(tmpDir, `payload.${ext}`);
+ await writeFile(filePath, 'data');
+ const result = await readLocalFile({ path: filePath });
+ expect(result.content).toContain('Unsupported binary file type');
+ expect(result.content).toContain(`.${ext}`);
+ }
+ });
+
+ it('should reject files whose content sniffs as binary even with text extension', async () => {
+ const filePath = path.join(tmpDir, 'sneaky.txt');
+ const buf = Buffer.concat([Buffer.from('header\n'), Buffer.from([0x00, 0x01, 0x02, 0x03])]);
+ await writeFile(filePath, buf);
+
+ const result = await readLocalFile({ path: filePath });
+ expect(result.content).toContain('binary');
+ });
+
+ it('should truncate single very long lines to per-line cap', async () => {
+ const filePath = path.join(tmpDir, 'long-line.txt');
+ // 27KB single line of base64-like text β€” the LOBE-8703 scenario.
+ await writeFile(filePath, 'A'.repeat(27_000));
+
+ const result = await readLocalFile({ path: filePath });
+
+ expect(result.linesTruncated).toBeGreaterThan(0);
+ // The returned content for a single line must be bounded.
+ expect(result.content.length).toBeLessThan(10_000);
+ expect(result.content).toContain('line truncated');
+ });
+
+ it('should cap total content length and set truncated flag', async () => {
+ const filePath = path.join(tmpDir, 'huge.txt');
+ // Many short lines, totalling > 500K chars.
+ const lines = Array.from({ length: 8000 }, (_, i) => `line ${i} ${'x'.repeat(80)}`);
+ await writeFile(filePath, lines.join('\n'));
+
+ const result = await readLocalFile({ fullContent: true, path: filePath });
+
+ expect(result.truncated).toBe(true);
+ expect(result.content).toContain('content truncated');
+ });
+
+ it('should reject files larger than the hard size cap', async () => {
+ const filePath = path.join(tmpDir, 'big.txt');
+ // Slightly over 10MB.
+ await writeFile(filePath, 'a'.repeat(10 * 1024 * 1024 + 1));
+
+ const result = await readLocalFile({ path: filePath });
+
+ expect(result.content).toContain('too large');
+ expect(result.charCount).toBe(0);
+ });
+
+ it('should still read normal source files of allowed extensions', async () => {
+ const filePath = path.join(tmpDir, 'app.cjs');
+ await writeFile(filePath, "module.exports = { hello: 'world' };\n");
+
+ const result = await readLocalFile({ path: filePath });
+ expect(result.content).toContain("hello: 'world'");
+ expect(result.charCount).toBeGreaterThan(0);
+ });
});
// ─── writeLocalFile ───
diff --git a/packages/local-file-shell/src/file/read.ts b/packages/local-file-shell/src/file/read.ts
index 2b1e3a526ba..be16e6217fb 100644
--- a/packages/local-file-shell/src/file/read.ts
+++ b/packages/local-file-shell/src/file/read.ts
@@ -1,11 +1,47 @@
import { stat } from 'node:fs/promises';
import path from 'node:path';
-import { loadFile } from '@lobechat/file-loaders';
+import {
+ isReadableFileType,
+ loadFile,
+ sniffBinaryFile,
+ SPECIAL_PARSED_FILE_TYPES,
+} from '@lobechat/file-loaders';
import type { ReadFileParams, ReadFileResult } from '../types';
import { expandTilde } from './expandTilde';
+/** Hard cap on file size we will read into memory at all (10MB). */
+const MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024;
+/** Cap on the total chars returned to the agent. */
+const MAX_OUTPUT_CHARS = 500_000;
+/** Cap on chars per line. Keeps a single 27KB base64 line from blowing up the response. */
+const MAX_LINE_CHARS = 8_000;
+
+const inferFileType = (filePath: string): string =>
+ path.extname(filePath).toLowerCase().replace('.', '') || 'unknown';
+
+const buildErrorResult = (filePath: string, message: string): ReadFileResult => ({
+ charCount: 0,
+ content: message,
+ createdTime: new Date(),
+ fileType: inferFileType(filePath),
+ filename: path.basename(filePath),
+ lineCount: 0,
+ loc: [0, 0],
+ modifiedTime: new Date(),
+ totalCharCount: 0,
+ totalLineCount: 0,
+});
+
+const truncateLine = (line: string): { line: string; truncated: boolean } => {
+ if (line.length <= MAX_LINE_CHARS) return { line, truncated: false };
+ return {
+ line: `${line.slice(0, MAX_LINE_CHARS)}… [line truncated: was ${line.length} chars, kept first ${MAX_LINE_CHARS}]`,
+ truncated: true,
+ };
+};
+
export async function readLocalFile({
path: rawPath,
loc,
@@ -14,10 +50,53 @@ export async function readLocalFile({
const filePath = expandTilde(rawPath) ?? rawPath;
const effectiveLoc = fullContent ? undefined : (loc ?? [0, 200]);
+ let stats;
+ try {
+ stats = await stat(filePath);
+ } catch (error) {
+ return buildErrorResult(
+ filePath,
+ `Error accessing or processing file: ${(error as Error).message}`,
+ );
+ }
+
+ if (stats.isDirectory()) {
+ return buildErrorResult(filePath, 'This is a directory and cannot be read as plain text.');
+ }
+
+ if (stats.size > MAX_FILE_SIZE_BYTES) {
+ return buildErrorResult(
+ filePath,
+ `Error: File is too large to read (${stats.size} bytes, limit ${MAX_FILE_SIZE_BYTES}). Use grep / shell tools to inspect specific parts.`,
+ );
+ }
+
+ const extension = path.extname(filePath).toLowerCase().replace('.', '');
+ if (extension && !isReadableFileType(extension)) {
+ return buildErrorResult(
+ filePath,
+ `Error: Unsupported binary file type: .${extension}. Use a different tool (e.g., 'runCommand' with file/hexdump/strings) to inspect binary files.`,
+ );
+ }
+
+ const isSpecialParsed = SPECIAL_PARSED_FILE_TYPES.includes(extension);
+ if (!isSpecialParsed) {
+ try {
+ const sniff = await sniffBinaryFile(filePath);
+ if (sniff.isBinary) {
+ return buildErrorResult(
+ filePath,
+ `Error: File appears to be binary (${sniff.reason}). Refusing to read as text.`,
+ );
+ }
+ } catch {
+ // Sniffing failures are not fatal; loadFile will surface the real error.
+ }
+ }
+
try {
const fileDocument = await loadFile(filePath);
- // loadFile returns error in metadata instead of throwing
if (fileDocument.metadata?.error) {
return {
charCount: 0,
@@ -37,67 +116,51 @@ export async function readLocalFile({
const totalLineCount = lines.length;
const totalCharCount = fileDocument.content.length;
- let content: string;
- let charCount: number;
- let lineCount: number;
+ let workingLines: string[];
let actualLoc: [number, number];
-
if (effectiveLoc === undefined) {
- content = fileDocument.content;
- charCount = totalCharCount;
- lineCount = totalLineCount;
+ workingLines = lines;
actualLoc = [0, totalLineCount];
} else {
const [startLine, endLine] = effectiveLoc;
- const selectedLines = lines.slice(startLine, endLine);
- content = selectedLines.join('\n');
- charCount = content.length;
- lineCount = selectedLines.length;
+ workingLines = lines.slice(startLine, endLine);
actualLoc = effectiveLoc;
}
- const fileType = fileDocument.fileType || 'unknown';
+ let linesTruncated = 0;
+ const cappedLines = workingLines.map((line) => {
+ const r = truncateLine(line);
+ if (r.truncated) linesTruncated++;
+ return r.line;
+ });
+
+ let content = cappedLines.join('\n');
+ let truncated = false;
+ if (content.length > MAX_OUTPUT_CHARS) {
+ const originalLength = content.length;
+ content = `${content.slice(0, MAX_OUTPUT_CHARS)}\n[content truncated: response was ${originalLength} chars, kept first ${MAX_OUTPUT_CHARS}. Use a smaller line range or grep to narrow down.]`;
+ truncated = true;
+ }
const result: ReadFileResult = {
- charCount,
+ charCount: content.length,
content,
createdTime: fileDocument.createdTime,
- fileType,
+ fileType: fileDocument.fileType || 'unknown',
filename: fileDocument.filename,
- lineCount,
+ lineCount: workingLines.length,
loc: actualLoc,
modifiedTime: fileDocument.modifiedTime,
totalCharCount,
totalLineCount,
};
-
- try {
- const stats = await stat(filePath);
- if (stats.isDirectory()) {
- result.content = 'This is a directory and cannot be read as plain text.';
- result.charCount = 0;
- result.lineCount = 0;
- result.totalCharCount = 0;
- result.totalLineCount = 0;
- }
- } catch {
- // Ignore stat errors
- }
-
+ if (truncated) result.truncated = true;
+ if (linesTruncated > 0) result.linesTruncated = linesTruncated;
return result;
} catch (error) {
- const errorMessage = (error as Error).message;
- return {
- charCount: 0,
- content: `Error accessing or processing file: ${errorMessage}`,
- createdTime: new Date(),
- fileType: path.extname(filePath).toLowerCase().replace('.', '') || 'unknown',
- filename: path.basename(filePath),
- lineCount: 0,
- loc: [0, 0],
- modifiedTime: new Date(),
- totalCharCount: 0,
- totalLineCount: 0,
- };
+ return buildErrorResult(
+ filePath,
+ `Error accessing or processing file: ${(error as Error).message}`,
+ );
}
}
diff --git a/packages/local-file-shell/src/types.ts b/packages/local-file-shell/src/types.ts
index 0d22587202e..dba34ba3233 100644
--- a/packages/local-file-shell/src/types.ts
+++ b/packages/local-file-shell/src/types.ts
@@ -57,10 +57,14 @@ export interface ReadFileResult {
filename: string;
fileType: string;
lineCount: number;
+ /** Number of returned lines truncated because they exceeded the per-line character cap. */
+ linesTruncated?: number;
loc: [number, number];
modifiedTime: Date;
totalCharCount: number;
totalLineCount: number;
+ /** True when the returned content was truncated because it exceeded the total character cap. */
+ truncated?: boolean;
}
export interface WriteFileParams {