🤯 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
✨ feat(file-loaders): support Jupyter notebook (.ipynb) upload with token-efficient markdown conversion (#17855)
Lee Junhobedee6b33203
diff --git a/packages/file-loaders/README.md b/packages/file-loaders/README.mdindex 244d3bffbf2..0672f6f4839 100644--- a/packages/file-loaders/README.md+++ b/packages/file-loaders/README.md@@ -14,6 +14,7 @@ Its primary purpose is to provide a unified interface for reading different file- **Word**: `.docx` files.- **Excel**: `.xlsx`, `.xls` files, with each worksheet as a `Page`.- **PowerPoint**: `.pptx` files, with each slide as a `Page`.+ - **Jupyter Notebook**: `.ipynb` files, converted to markdown (one page per cell); token-heavy outputs become short sized placeholders.- **Standardized Output**: Always returns `Promise<Document>`. A `Document` object represents a loaded file, containing an array of `Page` objects that represent the logical units of the file (pages, slides, worksheets, text blocks, etc.).- **Hierarchical Structure**: Uses a structure where `Document` contains `Page[]`, better reflecting the original organization of the file.- **Rich Metadata**: Provides detailed metadata at both `Document` and `Page` levels, including file information, content statistics, and structural information.diff --git a/packages/file-loaders/README.zh-CN.md b/packages/file-loaders/README.zh-CN.mdindex 98905b8f3e0..aed8b09e6a4 100644--- a/packages/file-loaders/README.zh-CN.md+++ b/packages/file-loaders/README.zh-CN.md@@ -14,6 +14,7 @@- **Word**: `.docx` 文件。- **Excel**: `.xlsx`, `.xls` 文件,每个工作表作为一个 `Page`。- **PowerPoint**: `.pptx` 文件,每个幻灯片作为一个 `Page`。+ - **Jupyter Notebook**: `.ipynb` 文件,转换为 markdown(每个单元格一页);高 token 输出会被替换为简短占位符。- **标准化输出**: 始终返回 `Promise<Document>`。 `Document` 对象代表一个加载的文件,其内部包含一个 `Page` 数组,代表文件的各个逻辑单元(页、幻灯片、工作表、文本块等)。- **层级结构**: 采用 `Document` 包含 `Page[]` 的结构,更好地反映文件原始组织方式。- **丰富的元数据**: 在 `Document` 和 `Page` 层面提供详细的元数据,包括文件信息、内容统计和结构信息。diff --git a/packages/file-loaders/src/index.ts b/packages/file-loaders/src/index.tsindex aa0fc390fd6..9be76115281 100644--- a/packages/file-loaders/src/index.ts+++ b/packages/file-loaders/src/index.ts@@ -1,5 +1,6 @@export * from './blackList';export * from './loadFile';+export { convertIpynbToMarkdown, scrubIpynbFallbackText } from './loaders/ipynb';export * from './types';export * from './utils/isBinaryContent';export * from './utils/isTextReadableFile';diff --git a/packages/file-loaders/src/loadFile.test.ts b/packages/file-loaders/src/loadFile.test.tsindex 47651307a9b..2b6c10e5ee9 100644--- a/packages/file-loaders/src/loadFile.test.ts+++ b/packages/file-loaders/src/loadFile.test.ts@@ -61,6 +61,28 @@ describe('loadFile', () => {}});+ it('surfaces a binary .ipynb rejection at the document level', async () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const tempDir = await mkdtemp(path.join(tmpdir(), 'lobe-file-loaders-'));++ try {+ const file = path.join(tempDir, 'renamed.ipynb');+ await writeFile(file, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0x1a, 0x0a]));++ const doc = await loadFile(file);++ // The document-level error is what `readFile` / callers check; a+ // page-only error would be read as a successful empty file.+ expect(doc.metadata.error).toContain('Binary content in .ipynb file');+ expect(doc.content).toBe('');+ expect(doc.pages).toHaveLength(1);+ expect(doc.pages?.[0].metadata.error).toContain('Binary content in .ipynb file');+ } finally {+ errorSpy.mockRestore();+ await rm(tempDir, { force: true, recursive: true });+ }+ });+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 304d45ae9a1..94157cc5c4a 100644--- a/packages/file-loaders/src/loadFile.ts+++ b/packages/file-loaders/src/loadFile.ts@@ -42,6 +42,10 @@ const getFileType = (filePath: string): SupportedFileType | undefined => {// Handle specific non-text or complex typeslog(`Checking specific types for extension: '${extension}'`);switch (extension) {+ case 'ipynb': {+ log('File type identified as ipynb');+ return 'ipynb';+ }case 'pdf': {log('File type identified as pdf');return 'pdf';diff --git a/packages/file-loaders/src/loaders/index.ts b/packages/file-loaders/src/loaders/index.tsindex 6454fb1d28e..f4aab8c16d5 100644--- a/packages/file-loaders/src/loaders/index.ts+++ b/packages/file-loaders/src/loaders/index.ts@@ -27,6 +27,10 @@ const lazyFileLoaders: Record<Exclude<SupportedFileType, 'txt'>, LazyLoaderFactoconst { ExcelLoader } = await import('./excel');return ExcelLoader;},+ ipynb: async () => {+ const { IpynbLoader } = await import('./ipynb');+ return IpynbLoader;+ },pdf: async () => {// Polyfill DOMMatrix for Node.js environment before importing pdfjs-dist// pdfjs-dist 5.x uses DOMMatrix at module initialization which doesn't exist in Node.jsdiff --git a/packages/file-loaders/src/loaders/ipynb/fixtures/binary.ipynb b/packages/file-loaders/src/loaders/ipynb/fixtures/binary.ipynbnew file mode 100644index 00000000000..7506821a5a2Binary files /dev/null and b/packages/file-loaders/src/loaders/ipynb/fixtures/binary.ipynb differdiff --git a/packages/file-loaders/src/loaders/ipynb/fixtures/invalid.ipynb b/packages/file-loaders/src/loaders/ipynb/fixtures/invalid.ipynbnew file mode 100644index 00000000000..56c8e280338--- /dev/null+++ b/packages/file-loaders/src/loaders/ipynb/fixtures/invalid.ipynb@@ -0,0 +1 @@+{"hello": "world"}diff --git a/packages/file-loaders/src/loaders/ipynb/fixtures/legacy-v3.ipynb b/packages/file-loaders/src/loaders/ipynb/fixtures/legacy-v3.ipynbnew file mode 100644index 00000000000..e677a5c936c--- /dev/null+++ b/packages/file-loaders/src/loaders/ipynb/fixtures/legacy-v3.ipynb@@ -0,0 +1,48 @@+{+ "nbformat": 3,+ "nbformat_minor": 0,+ "worksheets": [+ {+ "cells": [+ {+ "cell_type": "code",+ "input": "plot()",+ "outputs": [+ {+ "output_type": "display_data",+ "png": [+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ ]+ }+ ]+ }+ ]+ }+ ]+}diff --git a/packages/file-loaders/src/loaders/ipynb/fixtures/test.ipynb b/packages/file-loaders/src/loaders/ipynb/fixtures/test.ipynbnew file mode 100644index 00000000000..39f827c2aa0--- /dev/null+++ b/packages/file-loaders/src/loaders/ipynb/fixtures/test.ipynb@@ -0,0 +1,102 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Sample Notebook\n",+ "\n",+ "A tiny fixture covering common cell and output types."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 1,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "hello\n"+ ]+ }+ ],+ "source": [+ "print('hello')"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "metadata": {},+ "outputs": [+ {+ "data": {+ "text/html": [+ "<style>.df { color: red; }</style>",+ "<table><tr><td>1</td></tr></table>"+ ],+ "text/plain": [+ " a\n",+ "0 1"+ ]+ },+ "execution_count": 2,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "df.head(1)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "metadata": {},+ "outputs": [+ {+ "data": {+ "image/png": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ },+ "metadata": {},+ "output_type": "display_data"+ }+ ],+ "source": [+ "plot()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "metadata": {},+ "outputs": [+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ " 10%|#\r 50%|#####\r100%|##########\n",+ "\u001b[32mdone\u001b[0m\n"+ ]+ }+ ],+ "source": [+ "train()"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"+ },+ "language_info": {+ "name": "python",+ "version": "3.11.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}diff --git a/packages/file-loaders/src/loaders/ipynb/index.test.ts b/packages/file-loaders/src/loaders/ipynb/index.test.tsnew file mode 100644index 00000000000..5c90d2fb1ab--- /dev/null+++ b/packages/file-loaders/src/loaders/ipynb/index.test.ts@@ -0,0 +1,1098 @@+import path from 'node:path';++import { beforeEach, describe, expect, it } from 'vitest';++import type { FileLoaderInterface } from '../../types';+import { IpynbLoader, convertIpynbToMarkdown, scrubIpynbFallbackText } from './index';++const fixturePath = (filename: string) => path.join(__dirname, `./fixtures/${filename}`);++const makeNotebook = (cells: unknown[]) =>+ JSON.stringify({+ cells,+ metadata: {+ kernelspec: { display_name: 'Python 3', name: 'python3' },+ language_info: { name: 'python', version: '3.11.0' },+ },+ nbformat: 4,+ nbformat_minor: 5,+ });++describe('convertIpynbToMarkdown', () => {+ it('returns null for invalid JSON or non-notebook JSON', () => {+ expect(convertIpynbToMarkdown('not json')).toBeNull();+ expect(convertIpynbToMarkdown('{"foo": 1}')).toBeNull();+ });++ it('returns null for legacy nbformat v3', () => {+ // A cells array is required to reach the nbformat gate at all — without+ // it the earlier missing-cells check returns first and this branch would+ // go unpinned.+ expect(+ convertIpynbToMarkdown(+ JSON.stringify({ cells: [{ cell_type: 'markdown', source: 'hi' }], nbformat: 3 }),+ ),+ ).toBeNull();+ });++ it('keeps markdown cells and full code sources with execution counts', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ { cell_type: 'markdown', metadata: {}, source: ['# Title\n', 'text'] },+ {+ cell_type: 'code',+ execution_count: 3,+ metadata: {},+ outputs: [],+ source: 'x = 1\nprint(x)',+ },+ ]),+ )!;+ expect(md).toContain('> Jupyter notebook · kernel: Python 3 · language: python 3.11.0');+ expect(md).toContain('# Title\ntext');+ expect(md).toContain('**In [3]:**');+ expect(md).toContain('```python\nx = 1\nprint(x)\n```');+ });++ it('replaces image outputs with a sized placeholder', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 1,+ metadata: {},+ outputs: [+ { data: { 'image/png': 'A'.repeat(2048) }, metadata: {}, output_type: 'display_data' },+ ],+ source: 'plt.show()',+ },+ ]),+ )!;+ expect(md).toContain('![image/png output — 2 KB, omitted]');+ expect(md).not.toContain('AAAA');+ });++ it('keeps script-free html minus its style block and drops the text/plain twin', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 2,+ metadata: {},+ outputs: [+ {+ data: {+ 'text/html': [+ '<style>.df { color: red; }</style>',+ '<table><tr><td>1</td></tr></table>',+ ],+ 'text/plain': ' a\n0 1',+ },+ metadata: {},+ output_type: 'execute_result',+ },+ ],+ source: 'df',+ },+ ]),+ )!;+ expect(md).toContain('<table><tr><td>1</td></tr></table>');+ expect(md).not.toContain('<style>');+ expect(md).not.toContain('color: red');+ expect(md).not.toContain('0 1');+ });++ it('replaces script-bearing html outputs with a placeholder', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 4,+ metadata: {},+ outputs: [+ {+ data: { 'text/html': '<div id="p"></div><script>window.Plotly = {};</script>' },+ metadata: {},+ output_type: 'display_data',+ },+ ],+ source: 'fig.show()',+ },+ ]),+ )!;+ expect(md).toContain('[interactive HTML output (script)');+ expect(md).not.toContain('<script');+ });++ it('replaces widget views with a placeholder', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 5,+ metadata: {},+ outputs: [+ {+ data: {+ 'application/vnd.jupyter.widget-view+json': { model_id: 'abc', version_major: 2 },+ 'text/plain': 'HBox(children=…)',+ },+ metadata: {},+ output_type: 'display_data',+ },+ ],+ source: 'tqdm(range(10))',+ },+ ]),+ )!;+ expect(md).toContain('`[interactive widget — omitted]`');+ expect(md).not.toContain('HBox');+ });++ it('scrubs long base64 data uris inside script-free html (Audio/Image embeds)', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 8,+ metadata: {},+ outputs: [+ {+ data: {+ 'text/html':+ '<audio controls="controls"><source src="data:audio/wav;base64,' ++ 'U'.repeat(2048) ++ '" type="audio/wav" /></audio>',+ },+ metadata: {},+ output_type: 'display_data',+ },+ ],+ source: 'ipd.Audio(x, rate=16000)',+ },+ ]),+ )!;+ expect(md).toContain('<audio');+ expect(md).toContain('data:audio/wav;base64,[2 KB omitted]');+ expect(md).not.toContain('UUUU');+ });++ it('strips ansi codes and collapses \r progress lines in streams', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 6,+ metadata: {},+ outputs: [+ {+ name: 'stdout',+ output_type: 'stream',+ text: ' 10%|#\r 50%|#####\r100%|##########\nDone: \u001B[32mok\u001B[0m',+ },+ ],+ source: 'train()',+ },+ ]),+ )!;+ expect(md).toContain('100%|##########');+ expect(md).not.toContain(' 10%');+ expect(md).toContain('Done: ok');+ expect(md).not.toContain('\u001B');+ });++ it('keeps error name, value and the full traceback minus ansi', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 7,+ metadata: {},+ outputs: [+ {+ ename: 'ValueError',+ evalue: 'boom',+ output_type: 'error',+ traceback: ['\u001B[0;31mValueError\u001B[0m: boom', 'very long frame line'],+ },+ ],+ source: 'raise ValueError("boom")',+ },+ ]),+ )!;+ expect(md).toContain('**Error:** `ValueError: boom`');+ expect(md).toContain('ValueError: boom\nvery long frame line');+ });+});++describe('IpynbLoader', () => {+ let loader: FileLoaderInterface;++ beforeEach(() => {+ loader = new IpynbLoader();+ });++ it('should load pages correctly', async () => {+ const pages = await loader.loadPages(fixturePath('test.ipynb'));++ // 1 notebook header block + 5 cells+ expect(pages).toHaveLength(6);+ expect(pages[0].pageContent).toBe(+ '> Jupyter notebook · kernel: Python 3 · language: python 3.11.0',+ );+ expect(pages[1].metadata).toEqual({ chunkIndex: 1, totalChunks: 6 });+ });++ it('should aggregate content correctly', async () => {+ const pages = await loader.loadPages(fixturePath('test.ipynb'));+ const content = await loader.aggregateContent(pages);++ expect(content).toContain('# Sample Notebook');+ expect(content).toContain('**In [1]:**');+ expect(content).toContain('<table><tr><td>1</td></tr></table>');+ expect(content).not.toContain('<style>');+ // the text/plain twin of the html output is dropped+ expect(content).not.toContain('0 1');+ expect(content).toContain('![image/png output — 2 KB, omitted]');+ expect(content).not.toContain('AAAA');+ // progress rewrites keep only the final frame, ansi codes are stripped+ expect(content).toContain('100%|##########');+ expect(content).not.toContain(' 10%');+ expect(content).toContain('done');+ });++ it('should fall back to raw text for non-notebook JSON', async () => {+ const pages = await loader.loadPages(fixturePath('invalid.ipynb'));++ expect(pages).toHaveLength(1);+ expect(pages[0].pageContent.trim()).toBe('{"hello": "world"}');+ expect(pages[0].metadata).toEqual({ lineNumberEnd: 2, lineNumberStart: 1 });+ });+});++describe('convertIpynbToMarkdown hardening', () => {+ const streamCell = (text: string | string[]) => ({+ cell_type: 'code',+ execution_count: 1,+ metadata: {},+ outputs: [{ name: 'stdout', output_type: 'stream', text }],+ source: 'run()',+ });++ it('keeps CRLF stream lines instead of dropping them', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([streamCell(['Accuracy: 0.97\r\n', 'Loss: 0.03\r\n'])]),+ )!;+ expect(md).toContain('Accuracy: 0.97');+ expect(md).toContain('Loss: 0.03');+ expect(md).toContain('**Output:**');+ });++ it('accepts a BOM-prefixed notebook', () => {+ const md = convertIpynbToMarkdown(+ '\uFEFF' + makeNotebook([{ cell_type: 'markdown', metadata: {}, source: '# Title' }]),+ );+ expect(md).not.toBeNull();+ expect(md).toContain('# Title');+ });++ it('returns null for malformed cells instead of throwing', () => {+ expect(convertIpynbToMarkdown('{"nbformat":4,"cells":[null]}')).toBeNull();+ expect(+ convertIpynbToMarkdown(+ '{"nbformat":4,"cells":[{"cell_type":"code","outputs":[null],"source":"x"}]}',+ ),+ ).toBeNull();+ });++ it('preserves text/markdown outputs', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 3,+ metadata: {},+ outputs: [+ {+ data: { 'text/markdown': '## Result\n- accuracy 0.97' },+ metadata: {},+ output_type: 'display_data',+ },+ ],+ source: 'render(report)',+ },+ ]),+ )!;+ expect(md).toContain('**Output:**\n## Result\n- accuracy 0.97');+ });++ it('keeps script-free svg output and replaces script-bearing svg', () => {+ const kept = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 4,+ metadata: {},+ outputs: [+ {+ data: { 'image/svg+xml': '<svg><text>LABEL</text></svg>' },+ metadata: {},+ output_type: 'display_data',+ },+ ],+ source: 'plot()',+ },+ ]),+ )!;+ expect(kept).toContain('<svg><text>LABEL</text></svg>');++ const replaced = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 5,+ metadata: {},+ outputs: [+ {+ data: { 'image/svg+xml': '<svg><script>evil()</script></svg>' },+ metadata: {},+ output_type: 'display_data',+ },+ ],+ source: 'plot()',+ },+ ]),+ )!;+ expect(replaced).toContain('[svg output (script)');+ expect(replaced).not.toContain('<script');+ });++ it('widens code fences when the source contains a fence', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 6,+ metadata: {},+ outputs: [],+ source: '# fenced\n```\nx = 1',+ },+ ]),+ )!;+ expect(md).toContain('````python');+ expect(md).toContain('\n````');+ });++ it('strips unterminated style blocks', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 7,+ metadata: {},+ outputs: [+ {+ data: { 'text/html': '<table><tr><td>DATA</td></tr></table><style>.a{}' },+ metadata: {},+ output_type: 'execute_result',+ },+ ],+ source: 'df',+ },+ ]),+ )!;+ expect(md).toContain('<table><tr><td>DATA</td></tr></table>');+ expect(md).not.toContain('<style>');+ expect(md).not.toContain('.a{}');+ });++ it('strips every escape on pathological OSC-heavy streams', () => {+ const osc = '\u001B]a'.repeat(10_000) + '\u0007\ntail';+ const md = convertIpynbToMarkdown(makeNotebook([streamCell(osc)]))!;+ expect(md).toContain('tail');+ expect(md).not.toContain('\u001B');+ expect(md).not.toContain('\u0007');+ });++ it('keeps the last visible frame when a stream ends in repeated returns', () => {+ const md = convertIpynbToMarkdown(makeNotebook([streamCell('done\r\r')]))!;+ expect(md).toContain('done');+ });++ it('widens fences on a cell with a very large number of runs', () => {+ const body = '# x ```\n'.repeat(50_000);+ const md = convertIpynbToMarkdown(+ makeNotebook([+ { cell_type: 'code', execution_count: 9, metadata: {}, outputs: [], source: body },+ ]),+ );+ expect(md).not.toBeNull();+ expect(md).toContain('````python');+ });++ it('returns null when a cell source has an unreadable shape', () => {+ expect(+ convertIpynbToMarkdown('{"nbformat":4,"cells":[{"cell_type":"markdown","source":42}]}'),+ ).toBeNull();+ expect(convertIpynbToMarkdown('{"nbformat":4,"cells":[{"source":"x"}]}')).toBeNull();+ });++ it('collapses base64 wrapped across a json string array in the fallback helper', () => {+ const lines = Array.from({ length: 27 }, () => 'A'.repeat(76));+ const scrubbed = scrubIpynbFallbackText('{"png": ["' + lines.join('", "') + '"]}');+ expect(scrubbed).not.toContain('AAAA');+ expect(scrubbed).toContain('[base64 payload — 2 KB, omitted]');+ });++ it('leaves short base64-looking strings untouched', () => {+ const short = '{"id": "' + 'A'.repeat(64) + '"}';+ expect(scrubIpynbFallbackText(short)).toBe(short);+ });++ it('collapses long base64 runs in the raw-text fallback helper', () => {+ const scrubbed = scrubIpynbFallbackText('{"png": "' + 'A'.repeat(2048) + '"}');+ expect(scrubbed).not.toContain('AAAA');+ expect(scrubbed).toContain('[base64 payload — 2 KB, omitted]');+ });++ it('strips escapes outside the CSI and OSC families', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ streamCell([+ '\u001B(Bcharset reset\n',+ '\u001B[38:2:255:0:0mtruecolor subparams\u001B[0m\n',+ '\u001Bcterminal reset\n',+ ]),+ ]),+ )!;+ expect(md).not.toContain('\u001B');+ expect(md).toContain('charset reset');+ expect(md).toContain('truecolor subparams');+ expect(md).toContain('terminal reset');+ });++ it('keeps a text/plain-only result as a fenced block', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 4,+ metadata: {},+ outputs: [{ data: { 'text/plain': ['4'] }, metadata: {}, output_type: 'execute_result' }],+ source: '2 + 2',+ },+ ]),+ )!;+ expect(md).toContain('**Output:**\n```\n4\n```');+ });++ it('prefers the image placeholder over its text/plain twin', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 5,+ metadata: {},+ outputs: [+ {+ data: {+ 'image/png': 'A'.repeat(1366),+ 'text/plain': '<Figure size 640x480 with 1 Axes>',+ },+ metadata: {},+ output_type: 'execute_result',+ },+ ],+ source: 'plt.plot(x)',+ },+ ]),+ )!;+ expect(md).toContain('![image/png output — 1 KB, omitted]');+ expect(md).not.toContain('<Figure');+ });++ it('fences raw cells', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([{ cell_type: 'raw', metadata: {}, source: '.. raw directive\n body' }]),+ )!;+ expect(md).toContain('```\n.. raw directive\n body\n```');+ });++ it('scrubs data uris pasted into a markdown cell', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'markdown',+ metadata: {},+ source: ' + ')',+ },+ ]),+ )!;+ expect(md).toContain('');+ expect(md).not.toContain('VVVV');+ });++ it('treats uppercase script tags as script-bearing html', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 6,+ metadata: {},+ outputs: [+ {+ data: { 'text/html': '<div></div><SCRIPT>window.Bokeh = {};</SCRIPT>' },+ metadata: {},+ output_type: 'display_data',+ },+ ],+ source: 'show(p)',+ },+ ]),+ )!;+ expect(md).toContain('[interactive HTML output (script)');+ expect(md).not.toContain('window.Bokeh');+ });++ it('strips styles with attributes and more than one style block', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 7,+ metadata: {},+ outputs: [+ {+ data: {+ 'text/html':+ '<style scoped>.a { color: red; }</style>' ++ '<table><tr><td>KEEP</td></tr></table>' ++ '<style type="text/css">.b { color: blue; }</style><p>TAIL</p>',+ },+ metadata: {},+ output_type: 'execute_result',+ },+ ],+ source: 'df.style',+ },+ ]),+ )!;+ expect(md).toContain('<table><tr><td>KEEP</td></tr></table>');+ expect(md).toContain('<p>TAIL</p>');+ expect(md).not.toContain('color: red');+ expect(md).not.toContain('color: blue');+ });++ it('preserves tags that merely start with style', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 9,+ metadata: {},+ outputs: [+ {+ data: {+ 'text/html': '<stylesheet>KEEP</stylesheet><styles>ALSO</styles><p>after</p>',+ },+ metadata: {},+ output_type: 'execute_result',+ },+ ],+ source: 'df',+ },+ ]),+ )!;+ expect(md).toContain('<stylesheet>KEEP</stylesheet>');+ expect(md).toContain('<styles>ALSO</styles>');+ expect(md).toContain('<p>after</p>');+ });++ it('keeps indices aligned when the html contains case-expanding unicode', () => {+ // Turkish dotted I expands to two code units under toLowerCase, so any+ // scanner that lowercases a copy for indexOf desynchronizes its slices.+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 9,+ metadata: {},+ outputs: [+ {+ data: {+ 'text/html':+ '<p>' + '\u0130'.repeat(10) + 'KEEP</p><style>.x{color:red}</style><p>TAIL</p>',+ },+ metadata: {},+ output_type: 'execute_result',+ },+ ],+ source: 'df',+ },+ ]),+ )!;+ expect(md).toContain('KEEP</p><p>TAIL</p>');+ expect(md).not.toContain('color:red');+ });++ it('survives a pathological run of style openers in linear time', () => {+ // 120k bare openers with no closing bracket: a quadratic scanner blows the+ // test timeout here, and none of them is a complete tag so all survive.+ const html = '<style'.repeat(120_000);+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 9,+ metadata: {},+ outputs: [{ data: { 'text/html': html }, metadata: {}, output_type: 'execute_result' }],+ source: 'df',+ },+ ]),+ )!;+ expect(md).toContain('<style<style');+ });++ it('strips a very large number of terminated style blocks', () => {+ const html = '<style>.x{color:red}</style>a'.repeat(50_000) + '<p>END</p>';+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 9,+ metadata: {},+ outputs: [{ data: { 'text/html': html }, metadata: {}, output_type: 'execute_result' }],+ source: 'df',+ },+ ]),+ )!;+ expect(md).toContain('<p>END</p>');+ expect(md).not.toContain('color:red');+ expect(md).toContain('aaaa');+ });++ it('keeps base64-alphabet text lines intact in the fallback helper', () => {+ // Sixteen 64-char hex digests joined by escaped newlines: base64-alphabet+ // only, but not the fixed 76-column wrapping base64.encodebytes emits.+ const digests = Array.from({ length: 16 }, () => 'abcdef0123456789'.repeat(4)).join('\\n');+ const raw = '{"hashes": "' + digests + '"}';+ expect(scrubIpynbFallbackText(raw)).toBe(raw);+ });++ it('merges array elements that end with an escaped newline', () => {+ // v3 split_lines-style arrays keep the newline at the end of every+ // element, so two separators sit back to back between payload runs.+ const line = 'A'.repeat(76);+ const raw = '{"png":["' + Array.from({ length: 14 }, () => line + '\\n').join('", "') + '"]}';+ const scrubbed = scrubIpynbFallbackText(raw);+ expect(scrubbed).toContain('[base64 payload — 798 B, omitted]');+ expect(scrubbed).not.toContain('AAAA');+ });++ it('merges 76-column payloads wrapped with physical newlines', () => {+ // An invalid-JSON file is scrubbed as plain text, where encodebytes+ // output is wrapped with real newlines rather than escaped ones.+ const raw = Array.from({ length: 20 }, () => 'A'.repeat(76)).join('\n');+ const scrubbed = scrubIpynbFallbackText(raw);+ expect(scrubbed).toContain('[base64 payload — 1 KB, omitted]');+ expect(scrubbed).not.toContain('AAAA');+ });++ it('keeps a json array of hex digests intact in the fallback helper', () => {+ // Quoted-array separators join base64-alphabet runs too, so the fixed+ // 76-column rule has to apply there as well or a digest list is deleted.+ const digest = 'abcdef0123456789'.repeat(4);+ const raw = '{"hashes": ["' + Array.from({ length: 16 }, () => digest).join('", "') + '"]}';+ expect(scrubIpynbFallbackText(raw)).toBe(raw);+ });++ it('collapses 76-column payloads regardless of the separator kind', () => {+ // 15 lines of 76 chars alternating escaped newlines and quoted-array+ // separators: still the canonical wrapped shape, still one blob.+ const line = 'A'.repeat(76);+ const parts: string[] = [];+ for (let index = 0; index < 15; index++) {+ parts.push(line, index % 2 === 0 ? '\\n' : '", "');+ }+ parts.pop();+ const scrubbed = scrubIpynbFallbackText('{"png": "' + parts.join('') + '"}');+ expect(scrubbed).toContain('[base64 payload — 855 B, omitted]');+ expect(scrubbed).not.toContain('AAAA');+ });++ it('reports the exact byte size of newline-wrapped payloads', () => {+ // 15 lines of 76 chars = 1140 payload chars -> floor(1140 * 3 / 4) = 855.+ // The two-character escapes are separators and must not count as payload.+ const wrapped = Array.from({ length: 15 }, () => 'A'.repeat(76)).join('\\n');+ const scrubbed = scrubIpynbFallbackText('{"png": "' + wrapped + '"}');+ expect(scrubbed).toContain('[base64 payload — 855 B, omitted]');+ expect(scrubbed).not.toContain('AAAA');+ });++ it('discounts trailing padding from reported base64 sizes', () => {+ // A valid padded payload: 1364 chars (a multiple of four) ending in '=='+ // decode to 1364 * 3 / 4 - 2 = 1021 bytes.+ const scrubbed = scrubIpynbFallbackText('{"blob": "' + 'Q'.repeat(1362) + '=="}');+ expect(scrubbed).toContain('[base64 payload — 1021 B, omitted]');+ });++ it('never reports a negative size for an equals-sign flood', () => {+ // '=' x 1024 is garbage; trailing padding is capped at two so the size+ // stays positive, and the exact figure is not part of the contract.+ const scrubbed = scrubIpynbFallbackText('{"x": "' + '='.repeat(1024) + '"}');+ expect(scrubbed).toMatch(/\[base64 payload — \d+ B, omitted\]/);+ });++ it('scrubs data uris with media-type parameters or uppercase markers', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'markdown',+ metadata: {},+ source:+ ' ++ ')  ++ ')',+ },+ ]),+ )!;+ expect(md).not.toContain('VVVV');+ expect(md).not.toContain('WWWW');+ expect((md.match(/omitted/g) ?? []).length).toBe(2);+ });++ it('scrubs data uris with any number of media-type parameters', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'markdown',+ metadata: {},+ source: ' + ')',+ },+ ]),+ )!;+ expect(md).not.toContain('VVVV');+ expect(md).toContain('omitted');+ });++ it('scrubs data uris whose parameters use the full rfc 2045 token grammar', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'markdown',+ metadata: {},+ source:+ " ++ ')  ++ ')  ++ ';base64,' ++ 'Y'.repeat(2048) ++ ')',+ },+ ]),+ )!;+ expect(md).not.toContain('VVVV');+ expect(md).not.toContain('WWWW');+ expect(md).not.toContain('YYYY');+ expect((md.match(/omitted/g) ?? []).length).toBe(3);+ });++ it('keeps the code fence intact when notebook metadata is adversarial', () => {+ const md = convertIpynbToMarkdown(+ JSON.stringify({+ cells: [+ { cell_type: 'code', execution_count: 1, metadata: {}, outputs: [], source: 'safe()' },+ ],+ metadata: { language_info: { name: 'python\n```\n# injected' } },+ nbformat: 4,+ }),+ )!;+ expect(md).toContain('```python\nsafe()\n```');+ expect(md.split('\n')[0]).toBe('> Jupyter notebook · language: python # injected');+ });++ it('falls back when a source array contains non-strings', () => {+ expect(+ convertIpynbToMarkdown(+ '{"nbformat":4,"cells":[{"cell_type":"markdown","source":[{"critical":"x"}]}]}',+ ),+ ).toBeNull();+ });++ it('removes bell characters and bounds runaway osc bodies', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([streamCell('\u001B]0;' + 'A'.repeat(260) + '\u0007tail')]),+ )!;+ expect(md).not.toContain('\u001B');+ expect(md).not.toContain('\u0007');+ // The 256-char body bound consumes escape and bell bytes but must keep the+ // overflow text itself.+ expect(md).toContain('AAAAtail');+ });++ it('preserves the source of forward-compatible cell types', () => {+ const md = convertIpynbToMarkdown(+ '{"nbformat":4,"cells":[{"cell_type":"future","source":"SECRET"}]}',+ )!;+ expect(md).toContain('```\nSECRET\n```');+ });++ it('falls back when nbformat is missing or not an integer', () => {+ // nbformat is a required integer field; a stringly-typed or absent one is+ // not a saved v4 notebook, and treating it as one would let an unknown+ // cell smuggle an unscrubbed payload past the raw-text fallback.+ expect(convertIpynbToMarkdown('{"cells":[{"cell_type":"markdown","source":"hi"}]}')).toBeNull();+ expect(+ convertIpynbToMarkdown('{"nbformat":"3","cells":[{"cell_type":"future","source":"x"}]}'),+ ).toBeNull();+ for (const bad of ['"4"', '4.5', 'true', '[4]']) {+ expect(+ convertIpynbToMarkdown(+ '{"nbformat":' + bad + ',"cells":[{"cell_type":"markdown","source":"hi"}]}',+ ),+ ).toBeNull();+ }+ });++ it('drops non-string elements from output text instead of rendering them', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 1,+ metadata: {},+ outputs: [{ name: 'stdout', output_type: 'stream', text: ['ok', { critical: 'x' }] }],+ source: 'x',+ },+ ]),+ )!;+ expect(md).toContain('ok');+ expect(md).not.toContain('object Object');+ });++ it('accepts whitespace before the closing style bracket', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 9,+ metadata: {},+ outputs: [+ {+ data: { 'text/html': '<style>.s{color:red}</style ><p>KEEP</p>' },+ metadata: {},+ output_type: 'execute_result',+ },+ ],+ source: 'df',+ },+ ]),+ )!;+ expect(md).toContain('<p>KEEP</p>');+ expect(md).not.toContain('color:red');+ });++ it('preserves tags that merely start with script', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 9,+ metadata: {},+ outputs: [+ {+ data: { 'text/html': '<scripture>KEEP</scripture>' },+ metadata: {},+ output_type: 'execute_result',+ },+ ],+ source: 'df',+ },+ ]),+ )!;+ expect(md).toContain('<scripture>KEEP</scripture>');+ });++ it('treats non-ascii whitespace as content, not a tag boundary', () => {+ // U+00A0 after `<script` or inside `</style >` is not HTML whitespace:+ // the former is plain content and the latter does not close the tag.+ const nbspScript = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 9,+ metadata: {},+ outputs: [+ {+ data: { 'text/html': '<script\u00A0x>KEEP</script\u00A0x>' },+ metadata: {},+ output_type: 'execute_result',+ },+ ],+ source: 'df',+ },+ ]),+ )!;+ expect(nbspScript).toContain('KEEP');++ const nbspStyle = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 9,+ metadata: {},+ outputs: [+ {+ data: { 'text/html': '<style>x</style\u00A0><p>GONE</p>' },+ metadata: {},+ output_type: 'execute_result',+ },+ ],+ source: 'df',+ },+ ]),+ )!;+ expect(nbspStyle).not.toContain('GONE');+ });++ it('strips an osc body terminated by the 8-bit st', () => {+ // The short body proves the ST byte ends the body scan: without the+ // exclusion the body would swallow the terminator and TAIL with it.+ const md = convertIpynbToMarkdown(makeNotebook([streamCell('\u001B]0;title\u009CTAIL')]))!;+ expect(md).toContain('TAIL');+ expect(md).not.toContain('title');+ expect(md).not.toContain('\u009C');++ // An over-long body hits the 256-char bound instead: escape and both+ // terminator bytes still vanish while the overflow text survives.+ const long = convertIpynbToMarkdown(+ makeNotebook([streamCell('\u001B]0;' + 'A'.repeat(255) + '\u009CTAIL')]),+ )!;+ expect(long).toContain('TAIL');+ expect(long).not.toContain('\u009C');+ expect(long).not.toContain('AAAA');+ });++ it('reports multiline array image payload sizes without their newlines', () => {+ const line = 'A'.repeat(76) + '\n';+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 9,+ metadata: {},+ outputs: [+ {+ data: { 'image/png': Array.from({ length: 14 }, () => line) },+ metadata: {},+ output_type: 'display_data',+ },+ ],+ source: 'plt.show()',+ },+ ]),+ )!;+ expect(md).toContain('![image/png output — 798 B, omitted]');+ });++ it('keeps text/latex outputs fenced', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 10,+ metadata: {},+ outputs: [+ {+ data: { 'text/latex': '$e^{i\\pi}=-1$' },+ metadata: {},+ output_type: 'execute_result',+ },+ ],+ source: 'expr',+ },+ ]),+ )!;+ expect(md).toContain('**Output:**\n```\n$e^{i\\pi}=-1$\n```');+ });++ it('reports the exact svg script placeholder', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 11,+ metadata: {},+ outputs: [+ {+ data: { 'image/svg+xml': '<svg><SCRIPT>a</SCRIPT></svg>' },+ metadata: {},+ output_type: 'display_data',+ },+ ],+ source: 'plot()',+ },+ ]),+ )!;+ expect(md).toContain('`[svg output (script) — 29 chars, omitted]`');+ });++ it('reports script placeholder sizes in characters', () => {+ const html = '<script>' + 'x'.repeat(500) + '</script>';+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 11,+ metadata: {},+ outputs: [{ data: { 'text/html': html }, metadata: {}, output_type: 'display_data' }],+ source: 'fig.show()',+ },+ ]),+ )!;+ expect(md).toContain('`[interactive HTML output (script) — 517 chars, omitted]`');+ });++ it('widens the fence past a four-backtick run inside the source', () => {+ const md = convertIpynbToMarkdown(+ makeNotebook([+ {+ cell_type: 'code',+ execution_count: 8,+ metadata: {},+ outputs: [],+ source: 'text = """\n````\n"""',+ },+ ]),+ )!;+ expect(md).toContain('`````python\n');+ expect(md).toContain('\n`````');+ });+});++describe('IpynbLoader fallbacks', () => {+ let loader: FileLoaderInterface;++ beforeEach(() => {+ loader = new IpynbLoader();+ });++ it('falls back to scrubbed raw text for legacy v3 notebooks', async () => {+ const pages = await loader.loadPages(fixturePath('legacy-v3.ipynb'));+ expect(pages).toHaveLength(1);+ expect(pages[0].pageContent).not.toContain('AAAA');+ expect(pages[0].pageContent).toContain('[base64 payload —');+ expect(pages[0].pageContent).toContain('"nbformat": 3');+ });++ it('rejects binary content masquerading as a notebook', async () => {+ await expect(loader.loadPages(fixturePath('binary.ipynb'))).rejects.toThrow(+ /Binary content in \.ipynb file: \d+(\.\d+)?% non-printable chars/,+ );+ });+});diff --git a/packages/file-loaders/src/loaders/ipynb/index.ts b/packages/file-loaders/src/loaders/ipynb/index.tsnew file mode 100644index 00000000000..8aa10797f59--- /dev/null+++ b/packages/file-loaders/src/loaders/ipynb/index.ts@@ -0,0 +1,501 @@+import { readFile } from 'node:fs/promises';++import debug from 'debug';++import type { DocumentPage, FileLoaderInterface } from '../../types';+import { sniffBinaryBuffer } from '../../utils/isBinaryContent';++const log = debug('file-loaders:ipynb');++/**+ * `<script` must open a real tag — `<scripture>` is content, not a script.+ * The boundary set is the HTML tokenizer's ASCII whitespace (TAB/LF/FF/CR/+ * SPACE) plus `/` and `>`; JavaScript `\\s` would wrongly admit NBSP.+ */+const SCRIPT_TAG_RE = /<script[\t\n\f\r />]/i;++/* Minimal nbformat v4 shapes (https://nbformat.readthedocs.io/en/latest/format_description.html) */+interface NotebookOutput {+ data?: Record<string, unknown>;+ ename?: string;+ evalue?: string;+ output_type: string;+ text?: string | string[];+ traceback?: string[];+}++interface NotebookCell {+ cell_type: string;+ execution_count?: number | null;+ outputs?: NotebookOutput[];+ source?: string | string[];+}++interface Notebook {+ cells?: NotebookCell[];+ metadata?: {+ kernelspec?: { display_name?: string; name?: string };+ language_info?: { name?: string; version?: string };+ };+ nbformat?: number;+}++/**+ * Escape sequences, in match order: CSI (parameter bytes include `:`+ * subparameters and the final byte is any of `@`-`~`), OSC terminated by BEL /+ * ST (or end of input), the two-byte families (charset designation such as+ * `ESC ( B`, plus Fp/Fs sequences such as `ESC c`), and finally a bare escape+ * so none can survive into the text, plus stray BEL and C1 ST bytes (the+ * terminators an over-long OSC body leaves behind). The OSC body excludes further escapes and+ * every other branch is length-bounded, so one unterminated sequence cannot+ * 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;+/**+ * RFC 2397 data URIs: the scheme is case-insensitive, the media type and+ * any number of `;attribute=value` parameters use the RFC 2045 token+ * grammar (everything but tspecials, space and controls — so apostrophes+ * and tildes are legal), and all of it must be matched or a valid URI+ * slips past the scrub. `;` is a tspecial, so each parameter is consumed+ * exactly once and the scan stays linear.+ */+const MIME_TOKEN = '[^\\s()<>@,;:\\\\"/\\[\\]?=]+';+const DATA_URI_RE = new RegExp(+ `data:(${MIME_TOKEN}/${MIME_TOKEN})?(?:;${MIME_TOKEN}=${MIME_TOKEN})*;base64,([\\d+/=A-Za-z]{256,})`,+ 'gi',+);+/**+ * A base64 payload in raw text appears as one contiguous run, a run split+ * across a JSON string array, or a run wrapped by newlines — escaped+ * (`base64.encodebytes` output inside JSON) or physical (the same output in+ * a plain file). Array elements can end with an escaped newline, so runs of+ * consecutive separators count as one boundary.+ */+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 BASE64_SCRUB_THRESHOLD = 1024;++/**+ * nbformat stores text as either a string or a list of line strings. Output+ * values are not validated up front the way cell sources are, so non-string+ * list elements are dropped here rather than rendered as `[object Object]`.+ */+const joinSource = (source?: unknown): string =>+ Array.isArray(source)+ ? source.filter((part): part is string => typeof part === 'string').join('')+ : typeof source === 'string'+ ? source+ : '';++/**+ * Strip ANSI escapes and collapse carriage-return progress rewrites. tqdm and+ * friends redraw the same line via `\r`; Jupyter renders only the final state,+ * so keeping the text after the last `\r` of each line reproduces exactly what+ * the notebook displays while dropping the invisible intermediate frames.+ * CRLF line endings are normalized first so they read as plain newlines+ * instead of empty rewrite frames, and a trailing `\r` keeps its last+ * non-empty frame.+ */+const cleanStreamText = (text: string): string =>+ text+ .replaceAll(ANSI_RE, '')+ .replaceAll('\r\n', '\n')+ .split('\n')+ .map((line) => {+ // Keep the last frame that actually rendered something, so a stream+ // ending in one or more bare carriage returns does not lose its text.+ const frames = line.split('\r').filter((frame) => frame !== '');+ return frames.at(-1) ?? '';+ })+ .join('\n');++/**+ * Strip `<style>…</style>` blocks with a single forward scan. `<style` must+ * be followed by whitespace, `/` or `>` so tags that merely start with the+ * word (`<stylesheet>`) survive, the closing tag may carry whitespace before+ * its bracket, and an unterminated opener drops the rest of the string,+ * matching how a browser parses it. A regex with `[^>]*` here is+ * quadratic on repeated openers — each candidate rescans the remaining+ * suffix — so the scan is done with indexOf instead.+ */+const STYLE_BOUNDARY = new Set([9, 10, 12, 13, 32, 47, 62]); // ws, /, >+const stripStyleTags = (html: string): string => {+ // Literal sticky searches on the original string: lowercasing a copy for+ // indexOf would desynchronize indices, because toLowerCase can change the+ // string length (Turkish dotted I expands to two code units).+ const openRe = /<style/gi;+ const closeRe = /<\/style[\t\n\f\r ]*>/gi;+ let result = '';+ let pos = 0;+ while (pos < html.length) {+ openRe.lastIndex = pos;+ const open = openRe.exec(html);+ if (open === null) {+ result += html.slice(pos);+ break;+ }+ if (!STYLE_BOUNDARY.has(html.charCodeAt(open.index + 6))) {+ result += html.slice(pos, open.index + 6);+ pos = open.index + 6;+ continue;+ }+ result += html.slice(pos, open.index);+ closeRe.lastIndex = open.index;+ const close = closeRe.exec(html);+ if (close === null) break;+ pos = close.index + close[0].length;+ }+ return result;+};++const humanSize = (bytes: number): string =>+ bytes >= 1024 ? `${Math.round(bytes / 1024)} KB` : `${bytes} B`;++/** Markup placeholders report character counts — the text was never base64. */+const humanChars = (chars: number): string =>+ chars >= 1024 ? `${Math.round(chars / 1024)}k chars` : `${chars} chars`;++/**+ * Decoded byte count of a base64 payload. Whitespace and other stray bytes+ * are not payload, and only the trailing `=` run counts as padding — capped+ * at two, because a valid payload never carries more.+ */+const base64Bytes = (payload: string): number => {+ const clean = payload.replaceAll(NON_BASE64_RE, '');+ const padding = Math.min(2, (clean.match(/=*$/) ?? [''])[0].length);+ return Math.floor((clean.length * 3) / 4) - padding;+};++/**+ * Replace long base64 `data:` URIs with a sized placeholder while keeping the+ * surrounding markup. IPython.display.Audio/Image/Video embed their payload as+ * a data URI inside otherwise script-free HTML (e.g. `<audio><source+ * src="data:audio/wav;base64,...">`), which would slip past the script guard.+ * Short data URIs (tiny inline icons) are left alone.+ */+const scrubDataUris = (text: string): string =>+ text.replaceAll(+ DATA_URI_RE,+ (_match, mime, payload) =>+ `data:${mime ?? 'unknown'};base64,[${humanSize(base64Bytes(payload))} omitted]`,+ );++/**+ * Fallback used when the input is not convertible notebook JSON: keep the raw+ * text readable but collapse long base64 runs (embedded images/audio) into+ * sized placeholders so an unconvertible notebook cannot flood the context+ * with undecodable payload. Exported for the chunking pipeline, which needs+ * the same guarantee on its raw-text fallback path.+ */+const base64Placeholder = (payload: string): string =>+ `[base64 payload — ${humanSize(base64Bytes(payload))}, omitted]`;++export const scrubIpynbFallbackText = (raw: string): string =>+ raw.replaceAll(BASE64_RUN_RE, (match) => {+ // Splitting on the captured separators leaves the pure base64 segments+ // at the even indices and the separators themselves at the odd ones, so+ // untouched parts are re-emitted byte for byte.+ const parts = match.split(BASE64_SEPARATOR_RE);+ if (parts.length > 1) {+ // A separated payload is merged into one blob only in the fixed+ // 76-column shape `base64.encodebytes` emits — regardless of the+ // separator kind. Anything else — say a JSON array of 64-char hex+ // digests, which is base64-alphabet-only data — is judged segment by+ // segment so surrounding content is never swallowed.+ const segments = parts.filter((_, index) => index % 2 === 0);+ const payload = segments.join('');+ const wrapped = segments.slice(0, -1).every((segment) => segment.length === 76);+ if (wrapped && payload.length >= BASE64_SCRUB_THRESHOLD) return base64Placeholder(payload);+ return parts+ .map((part, index) =>+ index % 2 === 0 && part.length >= BASE64_SCRUB_THRESHOLD ? base64Placeholder(part) : part,+ )+ .join('');+ }+ if (match.length < BASE64_SCRUB_THRESHOLD) return match;+ return base64Placeholder(match);+ });++/** Collapse metadata text to one fence-safe line for the header blockquote. */+const singleLine = (text: string): string => text.replaceAll(/[`\r\n]+/g, ' ').trim();++/** Fenced code block whose fence is longer than any backtick run inside. */+const fence = (body: string, language = ''): string => {+ // Iterative max: spreading a match list of many thousands of runs into+ // Math.max would overflow the call stack on a pathological cell.+ let longest = 0;+ for (const run of body.match(/`{3,}/g) ?? []) if (run.length > longest) longest = run.length;+ const ticks = '`'.repeat(longest > 0 ? longest + 1 : 3);+ return [ticks + language, body, ticks].join('\n');+};++const convertOutput = (output: NotebookOutput): string => {+ switch (output.output_type) {+ case 'stream': {+ const body = cleanStreamText(joinSource(output.text));+ return body.trim() ? fence(body) : '';+ }++ case 'error': {+ // Tracebacks are kept in full — only ANSI color codes are removed.+ const traceback = cleanStreamText(+ (Array.isArray(output.traceback) ? output.traceback : [])+ .filter((line): line is string => typeof line === 'string')+ .join('\n'),+ );+ return [+ `**Error:** \`${output.ename ?? ''}: ${output.evalue ?? ''}\``,+ fence(traceback),+ ].join('\n');+ }++ case 'display_data':+ case 'execute_result': {+ const data = output.data ?? {};++ // Widget views only carry a model id; the (potentially multi-MB) state+ // blob lives in notebook-level metadata, which this loader never emits.+ if ('application/vnd.jupyter.widget-view+json' in data)+ return '`[interactive widget — omitted]`';++ const html = data['text/html'];+ if (html !== undefined) {+ const htmlText = joinSource(html);+ // Script-bearing HTML (plotly / bokeh / folium) embeds whole JS+ // bundles — exactly the token blowup this loader exists to avoid.+ // Script-free HTML (pandas tables) stays, minus its <style> block.+ if (SCRIPT_TAG_RE.test(htmlText))+ return `\`[interactive HTML output (script) — ${humanChars(htmlText.length)}, omitted]\``;+ // `text/plain` twin (pandas emits both) is intentionally dropped here.+ return scrubDataUris(stripStyleTags(htmlText)).trim();+ }++ // SVG output (matplotlib's svg backend) is fully readable markup —+ // keep it under the same script guard as HTML.+ const svg = data['image/svg+xml'];+ if (svg !== undefined) {+ const svgText = joinSource(svg);+ if (SCRIPT_TAG_RE.test(svgText))+ return `\`[svg output (script) — ${humanChars(svgText.length)}, omitted]\``;+ return scrubDataUris(svgText).trim();+ }++ for (const mime of Object.keys(data)) {+ if (mime.startsWith('image/')) {+ // Embedded output images are anonymous base64 — unreadable as text+ // tokens for an LLM, so record that one existed and its weight.+ const size = base64Bytes(joinSource(data[mime]));+ return `![${mime} output — ${humanSize(size)}, omitted]`;+ }+ }++ // Markdown renders as-is; any other textual mime is kept fenced.+ const markdown = data['text/markdown'];+ if (markdown !== undefined) return scrubDataUris(joinSource(markdown));++ for (const mime of Object.keys(data)) {+ if (mime.startsWith('text/')) {+ const body = joinSource(data[mime]);+ return body.trim() ? fence(body) : '';+ }+ }++ const mimes = Object.keys(data).join(', ');+ return `\`[${mimes || 'unknown'} output — omitted]\``;+ }++ default: {+ return '';+ }+ }+};++/**+ * nbformat requires a string `cell_type` and a string / string-list `source`.+ * Anything else is malformed: the caller falls back to raw text rather than+ * silently emitting a cell whose content could not be read.+ */+const isNotebookCell = (cell: unknown): cell is NotebookCell => {+ if (!cell || typeof cell !== 'object') return false;+ const { cell_type: cellType, source } = cell as NotebookCell;+ if (typeof cellType !== 'string') return false;+ return (+ source === undefined ||+ typeof source === 'string' ||+ // Every element must be a string — `joinSource` would otherwise render+ // objects as `[object Object]`, silently destroying the cell.+ (Array.isArray(source) && source.every((part) => typeof part === 'string'))+ );+};++/** Convert one notebook cell into a markdown block (`undefined` → skip). */+const convertCell = (cell: NotebookCell, language: string): string | undefined => {+ const source = joinSource(cell.source);++ switch (cell.cell_type) {+ case 'markdown': {+ // Attachment payloads (base64 dict) are simply never emitted; the+ // `` references in the source keep the image names.+ // Inline data URIs pasted directly into the cell are scrubbed the same+ // way as HTML outputs.+ return scrubDataUris(source);+ }++ case 'raw': {+ return fence(scrubDataUris(source));+ }++ case 'code': {+ const header = `**In [${cell.execution_count ?? ' '}]:**`;+ const blocks = [`${header}\n${fence(source, language)}`];+ const outputs = (cell.outputs ?? []).map(convertOutput).filter(Boolean);+ if (outputs.length > 0) blocks.push(`**Output:**\n${outputs.join('\n\n')}`);+ return blocks.join('\n\n');+ }++ default: {+ // nbformat allows forward-compatible cell types; their source is still+ // a multiline string, so preserving it fenced beats deleting the cell.+ return source.trim() ? fence(scrubDataUris(source)) : undefined;+ }+ }+};++/**+ * Convert a Jupyter notebook (nbformat v4 JSON) into markdown blocks, one per+ * cell (plus a one-line kernel/language header). Returns `null` when the input+ * is not v4-compatible notebook JSON — or when any cell is malformed — so+ * callers can fall back to plain text.+ */+const convertIpynbToBlocks = (raw: string): string[] | null => {+ let notebook: Notebook;+ try {+ // A UTF-8 BOM would make JSON.parse throw; strip it like TextDecoder does.+ notebook = JSON.parse(raw.replace(/^\uFEFF/, ''));+ } catch {+ return null;+ }+ if (!notebook || typeof notebook !== 'object' || !Array.isArray(notebook.cells)) return null;+ // nbformat is a required integer field; legacy v3 (and anything that is+ // not a saved v4+ notebook) falls back to scrubbed raw text instead.+ if (!Number.isInteger(notebook.nbformat) || (notebook.nbformat as number) < 4) return null;+ if (!notebook.cells.every(isNotebookCell)) return null;++ try {+ const languageInfo = notebook.metadata?.language_info;+ const languageName = typeof languageInfo?.name === 'string' ? languageInfo.name : undefined;+ // The fence info string renders verbatim, so it is reduced to one safe+ // leading token — notebook metadata must not be able to close the fence.+ const language = languageName?.match(/^[\w#+.-]+/)?.[0] ?? 'python';+ const kernel =+ notebook.metadata?.kernelspec?.display_name ?? notebook.metadata?.kernelspec?.name;++ const headerBits = ['Jupyter notebook'];+ if (typeof kernel === 'string' && kernel) headerBits.push(`kernel: ${singleLine(kernel)}`);+ if (languageName)+ headerBits.push(+ `language: ${singleLine(languageName)}${+ typeof languageInfo?.version === 'string' && languageInfo.version+ ? ` ${singleLine(languageInfo.version)}`+ : ''+ }`,+ );++ const blocks = [`> ${headerBits.join(' · ')}`];+ for (const cell of notebook.cells) {+ const block = convertCell(cell, language);+ if (block !== undefined && block.trim()) blocks.push(block);+ }+ return blocks;+ } catch {+ // Malformed cells/outputs (e.g. null entries) — treat as non-convertible.+ return null;+ }+};++/**+ * Full-document variant of {@link convertIpynbToBlocks}. Exported for the+ * chunking pipeline (`src/libs/document-loaders`), which converts the notebook+ * to markdown and then reuses the markdown splitter.+ */+export const convertIpynbToMarkdown = (raw: string): string | null => {+ const blocks = convertIpynbToBlocks(raw);+ return blocks === null ? null : blocks.join('\n\n');+};++/**+ * Raised when the file is not text at all. `loadFile` only copies errors it+ * catches itself into `FileDocument.metadata.error`, and the local `readFile`+ * tool decides success from that field, so this rejection has to escape+ * `loadPages` instead of being reported as a page-level error.+ */+class BinaryNotebookError extends Error {}++/**+ * Loader for Jupyter notebooks (.ipynb). Preserves code/markdown/raw cell+ * sources and textual outputs while replacing token-heavy payloads (base64+ * images and long inline data URIs, widget state, HTML/SVG that carries a+ * `<script>` tag) with short placeholders.+ */+export class IpynbLoader implements FileLoaderInterface {+ async loadPages(filePath: string): Promise<DocumentPage[]> {+ log('Loading ipynb file:', filePath);+ try {+ const buffer = await readFile(filePath);++ // A renamed binary would otherwise flow through the raw-text fallback;+ // apply the same sniff the plain-text path uses.+ const sniff = sniffBinaryBuffer(buffer.subarray(0, 8192));+ if (sniff.isBinary) {+ log('Rejecting binary content: %s', sniff.reason);+ throw new BinaryNotebookError(`Binary content in .ipynb file: ${sniff.reason}`);+ }++ const raw = buffer.toString('utf8').replace(/^\uFEFF/, '');+ const blocks = convertIpynbToBlocks(raw);++ if (blocks === null) {+ // Not valid nbformat v4 JSON — keep the upload usable as plain text,+ // minus any embedded base64 payloads.+ log('Not nbformat v4 JSON, falling back to scrubbed raw text');+ const fallback = scrubIpynbFallbackText(raw);+ const lines = fallback.split('\n');+ return [+ {+ charCount: fallback.length,+ lineCount: lines.length,+ metadata: { lineNumberEnd: lines.length, lineNumberStart: 1 },+ pageContent: fallback,+ },+ ];+ }++ log('Converted notebook into %d blocks', blocks.length);+ return blocks.map((block, index) => ({+ charCount: block.length,+ lineCount: block.split('\n').length,+ metadata: { chunkIndex: index, totalChunks: blocks.length },+ pageContent: block,+ }));+ } catch (e) {+ const error = e as Error;+ if (error instanceof BinaryNotebookError) throw error;+ console.error(`Error loading ipynb file ${filePath}: ${error.message}`);+ return [+ {+ charCount: 0,+ lineCount: 0,+ metadata: { error: `Failed to load ipynb file: ${error.message}` },+ pageContent: '',+ },+ ];+ }+ }++ async aggregateContent(pages: DocumentPage[]): Promise<string> {+ return pages.map((page) => page.pageContent).join('\n\n');+ }+}diff --git a/packages/file-loaders/src/types.ts b/packages/file-loaders/src/types.tsindex 7216d59064f..9821c4d2af7 100644--- a/packages/file-loaders/src/types.ts+++ b/packages/file-loaders/src/types.ts@@ -1,5 +1,5 @@// Define supported file types - consider using an enum or const assertion-export type SupportedFileType = 'pdf' | 'doc' | 'docx' | 'txt' | 'excel' | 'pptx'; // | 'pptx' | 'latex' | 'epub' | 'code' | 'markdown';+export type SupportedFileType = 'pdf' | 'doc' | 'docx' | 'txt' | 'excel' | 'pptx' | 'ipynb'; // | 'pptx' | 'latex' | 'epub' | 'code' | 'markdown';/*** Represents a complete loaded file, including file-level information and all its pages/chunks.diff --git a/packages/file-loaders/src/utils/isTextReadableFile.ts b/packages/file-loaders/src/utils/isTextReadableFile.tsindex 65d568a5c93..770a4806f48 100644--- a/packages/file-loaders/src/utils/isTextReadableFile.ts+++ b/packages/file-loaders/src/utils/isTextReadableFile.ts@@ -81,7 +81,7 @@ export const TEXT_READABLE_FILE_TYPES = [* 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'];+export const SPECIAL_PARSED_FILE_TYPES = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'pptx', 'ipynb'];/*** Determine if a file can be read as text based on its extension.diff --git a/packages/openapi/src/services/file.service.ts b/packages/openapi/src/services/file.service.tsindex ec4d376b97f..90ba1c510ff 100644--- a/packages/openapi/src/services/file.service.ts+++ b/packages/openapi/src/services/file.service.ts@@ -1058,6 +1058,7 @@ export class FileUploadService extends BaseService {'.xml','.csv','.tsv',+ '.ipynb','.pdf','.doc','.docx',diff --git a/src/libs/document-loaders/loaders/index.ts b/src/libs/document-loaders/loaders/index.tsindex 43b86e9721b..2d6af993acf 100644--- a/src/libs/document-loaders/loaders/index.ts+++ b/src/libs/document-loaders/loaders/index.ts@@ -1,3 +1,5 @@+import { convertIpynbToMarkdown, scrubIpynbFallbackText } from '@lobechat/file-loaders';+import { SUPPORT_TEXT_LIST } from '../file';import { SUPPORTED_LANGUAGES, type SupportedLanguage } from '../splitter';import { type DocumentChunk, type FileLoaderType } from '../types';@@ -64,6 +66,15 @@ export class ChunkingLoader {return await EPubLoader(content);}+ case 'ipynb': {+ // Notebook JSON → markdown so chunks carry semantic text instead+ // of base64 payloads; non-nbformat-v4 files fall back to raw text.+ const markdown = convertIpynbToMarkdown(txt);+ return markdown === null+ ? await TextLoader(scrubIpynbFallbackText(txt))+ : await MarkdownLoader(markdown);+ }+default: {throw new Error(`Unsupported file type [${type}], please check your file is supported, or create report issue here: https://github.com/lobehub/lobe-chat/discussions/3550`,@@ -104,6 +115,10 @@ export class ChunkingLoader {return 'epub';}+ if (filename.endsWith('ipynb')) {+ return 'ipynb';+ }+const ext = filename.split('.').pop();if (ext && SUPPORTED_LANGUAGES.includes(ext as SupportedLanguage)) {diff --git a/src/libs/document-loaders/types.ts b/src/libs/document-loaders/types.tsindex 1b7b24f0504..a8e379785ca 100644--- a/src/libs/document-loaders/types.ts+++ b/src/libs/document-loaders/types.ts@@ -13,4 +13,5 @@ export type FileLoaderType =| 'text'| 'latex'| 'csv'- | 'epub';+ | 'epub'+ | 'ipynb';diff --git a/src/store/file/slices/chat/uploadGuard.ts b/src/store/file/slices/chat/uploadGuard.tsindex f22b64076aa..7c30d54cbc5 100644--- a/src/store/file/slices/chat/uploadGuard.ts+++ b/src/store/file/slices/chat/uploadGuard.ts@@ -44,6 +44,7 @@ const SUPPORTED_CHAT_DOCUMENT_EXTENSIONS = new Set(['htm','html','ini',+ 'ipynb','java','js','json',