🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(cli): restore readFile content and binary sniff in the bundled CLI (#19944)
AmAzing-6f0eba420d7b
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 21ce9ae7cba..73811a668a0 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -73,8 +73,8 @@ jobs:run: pnpm installworking-directory: apps/cli- - name: Test CLI build configuration- run: bunx vitest run --config vitest.config.mts --silent='passed-only' tsdown.config.test.ts+ - name: Test CLI build configuration and bundle+ run: bunx vitest run --config vitest.config.mts --silent='passed-only' tsdown.config.test.ts bundle.test.tsworking-directory: apps/cli- name: Test packages with coveragediff --git a/apps/cli/bundle.test.ts b/apps/cli/bundle.test.tsnew file mode 100644index 00000000000..ad97157c5bf--- /dev/null+++ b/apps/cli/bundle.test.ts@@ -0,0 +1,83 @@+import { execFile } from 'node:child_process';+import { copyFile, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';++import { build } from 'tsdown';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import config from './tsdown.config';++const execFileAsync = promisify(execFile);++/**+ * Runs the real bundle, not the sources. With `codeSplitting: false`, rolldown+ * wraps modules reachable from a dynamic import in lazy initializers, and a+ * binding reached only through such a wrapper stays `undefined` until that+ * dynamic import runs. Vitest executes the unbundled sources and cannot see+ * this class of bug, and the build itself still reports success.+ */+describe('CLI bundle', () => {+ let workDir: string;+ let bundlePath: string;++ beforeAll(async () => {+ workDir = await mkdtemp(path.join(tmpdir(), 'lobehub-cli-bundle-'));+ // The bundle reads `../package.json` at runtime for its version.+ await copyFile(path.join(__dirname, 'package.json'), path.join(workDir, 'package.json'));+ await build({+ ...config,+ clean: true,+ config: false,+ logLevel: 'error',+ outDir: path.join(workDir, 'dist'),+ });+ bundlePath = path.join(workDir, 'dist', 'index.js');+ }, 120_000);++ afterAll(async () => {+ await rm(workDir, { force: true, recursive: true });+ });++ const readFileWithBundle = async (filePath: string) => {+ const argsB64 = Buffer.from(JSON.stringify({ path: filePath })).toString('base64');+ const { stdout } = await execFileAsync(process.execPath, [+ bundlePath,+ 'tool-worker',+ '--api',+ 'readFile',+ '--args-b64',+ argsB64,+ ]);++ return JSON.parse(stdout) as {+ content: string;+ state: { content: string };+ success: boolean;+ };+ };++ it('reads a plain text file', async () => {+ const filePath = path.join(workDir, 'hello.txt');+ await writeFile(filePath, 'hello\nworld\n');++ const result = await readFileWithBundle(filePath);++ expect(result.success).toBe(true);+ expect(result.state.content).toBe('hello\nworld\n');+ });++ it('refuses an extensionless binary file by sniffing its content', async () => {+ const filePath = path.join(workDir, 'elfblob');+ // ELF magic followed by the null bytes every real binary header carries.+ await writeFile(+ filePath,+ Buffer.concat([Buffer.from([0x7f, 0x45, 0x4c, 0x46]), Buffer.alloc(64)]),+ );++ const result = await readFileWithBundle(filePath);++ expect(result.state.content).toContain('File appears to be binary (contains null byte)');+ });+});diff --git a/packages/file-loaders/src/loadFile.test.ts b/packages/file-loaders/src/loadFile.test.tsindex 2b6c10e5ee9..9dc6b96d83e 100644--- a/packages/file-loaders/src/loadFile.test.ts+++ b/packages/file-loaders/src/loadFile.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import path from 'node:path';@@ -83,6 +83,57 @@ describe('loadFile', () => {}});+ it('surfaces a loader that reports failure through error pages at the document level', async () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const tempDir = await mkdtemp(path.join(tmpdir(), 'lobe-file-loaders-'));++ try {+ // `stat` succeeds on a directory, then TextLoader's `readFile` fails with+ // EISDIR and returns an error page instead of throwing.+ const dir = path.join(tempDir, 'looks-like-a-file.txt');+ await mkdir(dir);++ const doc = await loadFile(dir);++ expect(doc.content).toBe('');+ expect(doc.pages?.[0].metadata.error).toContain('Failed to load text file');+ expect(doc.metadata.error).toContain('Failed to load text file');+ } finally {+ errorSpy.mockRestore();+ await rm(tempDir, { force: true, recursive: true });+ }+ });++ it('keeps a partially failed load successful when some pages loaded', async () => {+ vi.resetModules();+ vi.doMock('./loaders', () => ({+ getFileLoader: async () =>+ class PartialLoader {+ async loadPages() {+ return [+ { charCount: 2, lineCount: 1, metadata: {}, pageContent: 'ok' },+ { charCount: 0, lineCount: 0, metadata: { error: 'page 2 broken' }, pageContent: '' },+ ];+ }++ async aggregateContent(pages: { pageContent: string }[]) {+ return pages.map((page) => page.pageContent).join('');+ }+ },+ }));++ try {+ const { loadFile: loadFileWithMock } = await import('./loadFile');+ const doc = await loadFileWithMock(fp('test.txt'));++ expect(doc.content).toBe('ok');+ expect(doc.metadata.error).toBeUndefined();+ } finally {+ vi.doUnmock('./loaders');+ vi.resetModules();+ }+ });+it('allows overriding metadata via second parameter', async () => {const file = fp('test.txt');const override = {diff --git a/packages/file-loaders/src/loadFile.ts b/packages/file-loaders/src/loadFile.tsindex 94157cc5c4a..f375c79b1dd 100644--- a/packages/file-loaders/src/loadFile.ts+++ b/packages/file-loaders/src/loadFile.ts@@ -141,6 +141,7 @@ export const loadFile = async (let pages: DocumentPage[];let aggregatedContent = '';let loaderError: string | undefined;+ let pageError: string | undefined;let aggregationError: string | undefined;let metadataError: string | undefined;let loaderSpecificMetadata: any | undefined;@@ -158,6 +159,14 @@ export const loadFile = async (pages = await loaderInstance.loadPages(filePath);log('Pages loaded successfully, count:', pages.length);+ // Loaders report a whole-file failure as error pages instead of throwing.+ // Surface it at the document level, where callers look, so a failed load+ // is not mistaken for an empty file. A mix of good and failed pages (a+ // PDF with one broken page) still counts as a successful load.+ if (pages.length > 0 && pages.every((page) => page.metadata?.error)) {+ pageError = [...new Set(pages.map((page) => page.metadata.error))].join('; ');+ }+try {// 2. Aggregate content using the instancelog('Aggregating content with loader:', LoaderClass.name);@@ -231,7 +240,8 @@ export const loadFile = async (// Combine all potential errorsconst combinedError =- [fsError, loaderError, aggregationError, metadataError].filter(Boolean).join('; ') || undefined;+ [fsError, loaderError, pageError, aggregationError, metadataError].filter(Boolean).join('; ') ||+ undefined;if (combinedError) log('Combined errors:', combinedError);// Construct the final FileDocumentdiff --git a/packages/file-loaders/src/loaders/ipynb/index.ts b/packages/file-loaders/src/loaders/ipynb/index.tsindex 8aa10797f59..76a67f0fa62 100644--- a/packages/file-loaders/src/loaders/ipynb/index.ts+++ b/packages/file-loaders/src/loaders/ipynb/index.ts@@ -1,9 +1,9 @@import { readFile } from 'node:fs/promises';+import { sniffBinaryBuffer } from '@lobechat/utils/isBinaryContent';import debug from 'debug';import type { DocumentPage, FileLoaderInterface } from '../../types';-import { sniffBinaryBuffer } from '../../utils/isBinaryContent';const log = debug('file-loaders:ipynb');@@ -51,7 +51,8 @@ interface Notebook {* make the scan quadratic over the remaining text.*/const ANSI_RE =- /\u001B\[[\d:;?]*[\u0020-\u002F]*[\u0040-\u007E]|\u001B\][^\u0007\u001B\u009C]{0,256}(?:\u0007|\u001B\\)?|\u001B[\u0021-\u002F]{0,2}[\u0030-\u007E]|\u001B|\u0007|\u009C/g;+ // eslint-disable-next-line no-control-regex+ /\u001B\[[\d:;?]*[\u0020-\u002F]*[\u0040-\u007E]|\u001B\][^\u0007\u001B\u009C]{0,256}(?:\u0007|\u001B\\)?|\u001B[\u0021-\u002F]{0,2}[\u0030-\u007E]|[\u001B\u0007\u009C]/g;/*** RFC 2397 data URIs: the scheme is case-insensitive, the media type and* any number of `;attribute=value` parameters use the RFC 2045 token@@ -62,6 +63,7 @@ const ANSI_RE =*/const MIME_TOKEN = '[^\\s()<>@,;:\\\\"/\\[\\]?=]+';const DATA_URI_RE = new RegExp(+ // eslint-disable-next-line regexp/no-useless-escape, regexp/no-dupe-characters-character-class`data:(${MIME_TOKEN}/${MIME_TOKEN})?(?:;${MIME_TOKEN}=${MIME_TOKEN})*;base64,([\\d+/=A-Za-z]{256,})`,'gi',);@@ -75,7 +77,7 @@ const DATA_URI_RE = new RegExp(const BASE64_RUN_RE = /[\d+/=A-Za-z]{32,}(?:(?:"[\s,]*"|\\n|\r?\n)+[\d+/=A-Za-z]{32,})*/g;/** The same separator runs, captured, so a split keeps them byte for byte. */const BASE64_SEPARATOR_RE = /((?:"[\s,]*"|\\n|\r?\n)+)/;-const NON_BASE64_RE = /[^\d+/=A-Za-z]/g;+const NON_BASE64_RE = /[^\d+/=A-Z]/gi;const BASE64_SCRUB_THRESHOLD = 1024;/**diff --git a/packages/file-loaders/src/loaders/text/index.ts b/packages/file-loaders/src/loaders/text/index.tsindex 9c04ec8a2f9..602519b9675 100644--- a/packages/file-loaders/src/loaders/text/index.ts+++ b/packages/file-loaders/src/loaders/text/index.ts@@ -1,9 +1,13 @@import { readFile } from 'node:fs/promises';+// Import straight from `@lobechat/utils`, not through a local re-export. In+// the single-file CLI bundle, a re-export that is also reachable from a lazily+// imported loader becomes a lazy module, and this eager loader then sees an+// uninitialized `undefined` binding (lobehub/lobehub#19934).+import { detectUtf16NoBom } from '@lobechat/utils/detectUtf16';import debug from 'debug';import type { DocumentPage, FileLoaderInterface } from '../../types';-import { detectUtf16NoBom } from '../../utils/detectUtf16';const log = debug('file-loaders:text');diff --git a/packages/file-loaders/src/utils/detectUtf16.ts b/packages/file-loaders/src/utils/detectUtf16.tsdeleted file mode 100644index cb5f88b586c..00000000000--- a/packages/file-loaders/src/utils/detectUtf16.ts+++ /dev/null@@ -1,2 +0,0 @@-// Shared with browser file previews so encoding detection stays consistent.-export { detectUtf16NoBom, type Utf16Variant } from '@lobechat/utils/detectUtf16';diff --git a/packages/local-file-shell/src/file/__tests__/readSniffFailure.test.ts b/packages/local-file-shell/src/file/__tests__/readSniffFailure.test.tsnew file mode 100644index 00000000000..b20ff252c9e--- /dev/null+++ b/packages/local-file-shell/src/file/__tests__/readSniffFailure.test.ts@@ -0,0 +1,54 @@+import fs from 'node:fs';+import { mkdir, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import type * as fileLoadersModule from '@lobechat/file-loaders';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { readLocalFile } from '../read';++const { sniffBinaryFile } = vi.hoisted(() => ({ sniffBinaryFile: vi.fn() }));++vi.mock('@lobechat/file-loaders', async (importOriginal) => ({+ ...(await importOriginal<typeof fileLoadersModule>()),+ sniffBinaryFile,+}));++describe('readLocalFile when the binary sniff throws', () => {+ const tmpDir = path.join(os.tmpdir(), 'local-file-shell-sniff-test-' + process.pid);+ const filePath = path.join(tmpDir, 'notes');++ beforeEach(async () => {+ await mkdir(tmpDir, { recursive: true });+ await writeFile(filePath, 'hello\nworld\n');+ });++ afterEach(() => {+ sniffBinaryFile.mockReset();+ fs.rmSync(tmpDir, { force: true, recursive: true });+ });++ it('reports a defect in the sniffer instead of reading the file unchecked', async () => {+ // What the CLI bundle hit in #19934: the helper was an uninitialized binding.+ sniffBinaryFile.mockRejectedValue(new TypeError('sniffBinaryFile is not a function'));++ const result = await readLocalFile({ path: filePath });++ expect(result.content).toBe(+ 'Error: Failed to check whether the file is binary: sniffBinaryFile is not a function',+ );+ expect(result.totalCharCount).toBe(0);+ });++ it('falls through to loading the file when the sniff hits an IO error', async () => {+ sniffBinaryFile.mockRejectedValue(+ Object.assign(new Error('EMFILE: too many open files'), { code: 'EMFILE' }),+ );++ const result = await readLocalFile({ path: filePath });++ expect(result.content).toContain('hello');+ expect(result.totalCharCount).toBe('hello\nworld\n'.length);+ });+});diff --git a/packages/local-file-shell/src/file/read.ts b/packages/local-file-shell/src/file/read.tsindex d7e64ff7611..d2ea9033860 100644--- a/packages/local-file-shell/src/file/read.ts+++ b/packages/local-file-shell/src/file/read.ts@@ -100,8 +100,17 @@ export async function readLocalFile({`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.+ } catch (error) {+ // A file that cannot be opened is not fatal here; loadFile reports the+ // real IO error. Anything without an errno code is a defect in the+ // sniffer itself, and swallowing it silently disables binary detection+ // (lobehub/lobehub#19934), so report it instead.+ if (!(error as NodeJS.ErrnoException).code) {+ return buildErrorResult(+ filePath,+ `Error: Failed to check whether the file is binary: ${(error as Error).message}`,+ );+ }}}