From cda99d5495b7486a9ced086111bde1332d025acf Mon Sep 17 00:00:00 2001 From: Qslia <49663251+qslia@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:48:51 +0800 Subject: [PATCH] fix(notebook): open an empty .ipynb file as an empty notebook (#7395) New File named x.ipynb (or touch, or an agent) creates an empty file, which the notebook editor refused with 'Invalid notebook JSON: EOF while parsing a value'. It now reads as an empty nbformat 4 notebook, as in PyCharm; saving it unchanged leaves the file alone and an edit writes a real notebook. This covers every way an empty notebook file can appear, so New File needs no template of its own. Co-authored-by: qslia <49663251+qslia@users.noreply.github.com> --- crates/ide-notebook/src/document.rs | 9 ++++++++- crates/ide-notebook/tests/document.rs | 23 +++++++++++++++++++++++ src/features/project-tree/operations.ts | 18 ++++++++++++++++-- 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/crates/ide-notebook/src/document.rs b/crates/ide-notebook/src/document.rs index 85d7661f6..c845a5282 100644 --- a/crates/ide-notebook/src/document.rs +++ b/crates/ide-notebook/src/document.rs @@ -147,7 +147,11 @@ impl NotebookDocument { pub fn from_text(path: PathBuf, text: String) -> IdeResult { let text: Arc = text.into(); - let (root, prefix, suffix) = Node::parse(text.clone())?; + // An empty file (New File named `x.ipynb`, `touch`) opens as an empty notebook, as in + // PyCharm; it is written as one once edited and saved. + let parsed = + if text.trim_start_matches('\u{feff}').trim().is_empty() { EMPTY_NOTEBOOK.into() } else { text.clone() }; + let (root, prefix, suffix) = Node::parse(parsed)?; validate_notebook(&root)?; let nodes = root.get("cells").and_then(Node::array).expect("validated cells"); let mut persisted = HashMap::::new(); @@ -365,6 +369,9 @@ fn source(node: &Node) -> IdeResult { } } +/// What an empty `.ipynb` file reads as, formatted as Jupyter writes it. +const EMPTY_NOTEBOOK: &str = "{\n \"cells\": [],\n \"metadata\": {},\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"; + fn validate_notebook(root: &Node) -> IdeResult<()> { if root.members().is_none() || uint_field(root, "nbformat") != Some(4) diff --git a/crates/ide-notebook/tests/document.rs b/crates/ide-notebook/tests/document.rs index da320e590..e044770c6 100644 --- a/crates/ide-notebook/tests/document.rs +++ b/crates/ide-notebook/tests/document.rs @@ -43,6 +43,29 @@ fn two_code_cells() -> NotebookDocument { }).to_string()) } +/// New File named `x.ipynb` creates an empty file: it opens as an empty notebook, saving it +/// unchanged leaves it empty, and an edit saves a real notebook. +#[test] +fn an_empty_file_opens_as_an_empty_notebook() { + let dir = tempfile::tempdir().unwrap(); + for text in ["", "\n", "\u{feff}"] { + let path = dir.path().join("new.ipynb"); + std::fs::write(&path, text).unwrap(); + let mut doc = NotebookDocument::load(&path).unwrap(); + let snapshot = doc.snapshot(); + assert!(snapshot.cells.is_empty() && !snapshot.dirty); + assert_eq!((snapshot.nbformat, snapshot.nbformat_minor), (4, 5)); + doc.save().unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), text.as_bytes()); + + apply(&mut doc, NotebookEdit::InsertCell { after: None, cell_type: "code".into() }); + doc.save().unwrap(); + let saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!((saved["nbformat"].clone(), saved["cells"].as_array().unwrap().len()), (json!(4), 1)); + assert!(NotebookDocument::load(&path).is_ok()); + } +} + #[test] fn noop_save_preserves_all_bytes_for_utf8_bom_crlf_and_no_final_newline() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/features/project-tree/operations.ts b/src/features/project-tree/operations.ts index 348c76a6b..f2a9a1bd2 100644 --- a/src/features/project-tree/operations.ts +++ b/src/features/project-tree/operations.ts @@ -318,8 +318,22 @@ export async function commitEditing(name: string): Promise { const path = joinPath(editing.parent, newRelPath(editing, name) ?? name); startEditing(null); try { - if (editing.nodeKind === "file") await fs.createFile(path); - else await fs.createDir(path); + if (editing.nodeKind === "file") { + if (/\.ipynb$/i.test(path)) { + const notebook = { + cells: [], + metadata: {}, + nbformat: 4, + nbformat_minor: 5, + }; + + await fs.createFileBytes(path, new TextEncoder().encode(`${JSON.stringify(notebook, null, 2)}\n`)); + } else { + await fs.createFile(path); + } + } else { + await fs.createDir(path); + } // Every folder of a Python package gets an `__init__.py`, as in PyCharm. if (editing.pkg === "python") { const dirs: string[] = [];