Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
239 changes: 239 additions & 0 deletions integration-tests/cli/notebook-edit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import {
TestRig,
createToolCallErrorMessage,
printDebugInfo,
validateModelOutput,
} from '../test-helper.js';

type NotebookCell = {
id?: string;
cell_type: 'code' | 'markdown' | 'raw';
metadata: Record<string, unknown>;
source: string | string[];
execution_count?: number | null;
outputs?: unknown[];
};

type NotebookContent = {
cells: NotebookCell[];
metadata: Record<string, unknown>;
nbformat: number;
nbformat_minor: number;
};

const sourceText = (source: string | string[]) =>
Array.isArray(source) ? source.join('') : source;

const promptPath = (filePath: string) => filePath.split(path.sep).join('/');

const readNotebook = (rig: TestRig, fileName: string): NotebookContent =>
JSON.parse(rig.readFile(fileName)) as NotebookContent;

const baseNotebook = (cells: NotebookCell[]): NotebookContent => ({
cells,
metadata: {
kernelspec: {
display_name: 'Python 3',
language: 'python',
name: 'python3',
},
language_info: {
name: 'python',
},
},
nbformat: 4,
nbformat_minor: 5,
});

const expectReadThenNotebookEdit = (rig: TestRig, result: string) => {
const logs = rig.readToolLogs();
const foundTools = logs.map((t) => t.toolRequest.name);
const readIndex = foundTools.findIndex((name) => name === 'read_file');
const notebookEditIndex = foundTools.findIndex(
(name) => name === 'notebook_edit',
);

if (readIndex === -1 || notebookEditIndex === -1) {
printDebugInfo(rig, result, { foundTools });
}

expect(
readIndex,
createToolCallErrorMessage('read_file', foundTools, result),
).toBeGreaterThanOrEqual(0);
expect(
notebookEditIndex,
createToolCallErrorMessage('notebook_edit', foundTools, result),
).toBeGreaterThan(readIndex);
};

const expectNoSuccessfulRawNotebookWrites = (
rig: TestRig,
notebookFileName: string,
) => {
const rawNotebookWrites = rig
.readToolLogs()
.filter(
(log) =>
['edit', 'write_file'].includes(log.toolRequest.name) &&
log.toolRequest.success &&
log.toolRequest.args.includes(notebookFileName),
);

expect(rawNotebookWrites).toEqual([]);
};

describe('notebook_edit integration', () => {
let rig: TestRig;

afterEach(async () => {
await rig?.cleanup();
});

it('replaces a code cell after reading the notebook and clears stale outputs', async () => {
rig = new TestRig();
await rig.setup('notebook edit replace code cell clears outputs');

const fileName = 'analysis.ipynb';
const notebookPath = rig.createFile(
fileName,
JSON.stringify(
baseNotebook([
{
id: 'intro',
cell_type: 'markdown',
metadata: {},
source: ['# Analysis\n'],
},
{
id: 'load-data',
cell_type: 'code',
metadata: {},
source: ['old_value = 1\n', 'print(old_value)\n'],
execution_count: 7,
outputs: [
{
output_type: 'stream',
name: 'stdout',
text: ['1\n'],
},
],
},
]),
null,
1,
),
);

const prompt = `Read the notebook at ${promptPath(notebookPath)} with read_file first.
Then use notebook_edit, not edit or write_file, to replace the code cell whose id is load-data.
Set the new source exactly to:

result = 41 + 1
print(result)

Do not change any other cell.`;

const result = await rig.run(prompt);

expectReadThenNotebookEdit(rig, result);
expectNoSuccessfulRawNotebookWrites(rig, fileName);
validateModelOutput(result, null, 'Notebook replace');

const notebook = readNotebook(rig, fileName);
const target = notebook.cells.find((cell) => cell.id === 'load-data');

expect(target).toBeDefined();
expect(target?.cell_type).toBe('code');
expect(sourceText(target!.source).trimEnd()).toBe(
'result = 41 + 1\nprint(result)',
);
expect(target?.execution_count).toBeNull();
expect(target?.outputs).toEqual([]);
expect(sourceText(notebook.cells[0]!.source)).toBe('# Analysis\n');
});

it('inserts a markdown cell and deletes a target cell using notebook_edit', async () => {
rig = new TestRig();
await rig.setup('notebook edit insert and delete cells');

const fileName = 'workflow.ipynb';
const notebookPath = rig.createFile(
fileName,
JSON.stringify(
baseNotebook([
{
id: 'intro',
cell_type: 'markdown',
metadata: {},
source: ['# Workflow\n'],
},
{
id: 'remove-me',
cell_type: 'markdown',
metadata: {},
source: ['This temporary cell should be deleted.\n'],
},
{
id: 'calculate',
cell_type: 'code',
metadata: {},
source: ['value = 10\n'],
execution_count: null,
outputs: [],
},
]),
null,
1,
),
);

const insertedMarkdown =
'## Inserted Note\nThis cell was inserted by NotebookEdit.';
const prompt = `Read the notebook at ${promptPath(notebookPath)} with read_file first.
Then use notebook_edit, not edit or write_file, for both changes:
1. Insert a markdown cell after the cell whose id is intro. Its source must be exactly:

${insertedMarkdown}

2. Delete the cell whose id is remove-me.
Do not change the calculate code cell.`;

const result = await rig.run(prompt);

expectReadThenNotebookEdit(rig, result);
expectNoSuccessfulRawNotebookWrites(rig, fileName);
validateModelOutput(result, null, 'Notebook insert/delete');

const successfulNotebookEdits = rig
.readToolLogs()
.filter(
(log) =>
log.toolRequest.name === 'notebook_edit' && log.toolRequest.success,
);
expect(successfulNotebookEdits.length).toBeGreaterThanOrEqual(2);

const notebook = readNotebook(rig, fileName);
const cellIds = notebook.cells.map((cell) => cell.id);
const insertedCell = notebook.cells.find((cell) =>
sourceText(cell.source).includes('Inserted Note'),
);

expect(cellIds).toHaveLength(3);
expect(cellIds).not.toContain('remove-me');
expect(notebook.cells[0]?.id).toBe('intro');
expect(insertedCell).toBeDefined();
expect(insertedCell?.cell_type).toBe('markdown');
expect(sourceText(insertedCell!.source).trimEnd()).toBe(insertedMarkdown);
expect(notebook.cells.at(-1)?.id).toBe('calculate');
expect(sourceText(notebook.cells.at(-1)!.source)).toBe('value = 10\n');
});
});
2 changes: 2 additions & 0 deletions packages/cli/src/config/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2124,6 +2124,7 @@ describe('loadCliConfig with includeDirectories', () => {
expect(config.getCoreTools()).toEqual([
ToolNames.READ_FILE,
ToolNames.EDIT,
ToolNames.NOTEBOOK_EDIT,
ToolNames.SHELL,
]);
expect(config.getDisableAllHooks()).toBe(true);
Expand All @@ -2142,6 +2143,7 @@ describe('loadCliConfig with includeDirectories', () => {
expect(config.getCoreTools()).toEqual([
ToolNames.READ_FILE,
ToolNames.EDIT,
ToolNames.NOTEBOOK_EDIT,
ToolNames.SHELL,
]);
});
Expand Down
27 changes: 20 additions & 7 deletions packages/core/src/config/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,12 @@ describe('Server Config (config.ts)', () => {
(ToolRegistry.prototype.registerFactory as Mock).mock.calls.map(
(call) => call[0],
),
).toEqual([ToolNames.READ_FILE, ToolNames.EDIT, ToolNames.SHELL]);
).toEqual([
ToolNames.READ_FILE,
ToolNames.EDIT,
ToolNames.NOTEBOOK_EDIT,
ToolNames.SHELL,
]);
});
});

Expand Down Expand Up @@ -1369,20 +1374,26 @@ describe('Server Config (config.ts)', () => {
expect(config.getCoreTools()).toEqual([
ToolNames.READ_FILE,
ToolNames.EDIT,
ToolNames.NOTEBOOK_EDIT,
ToolNames.SHELL,
]);
expect(
(registerToolMock as Mock).mock.calls.map((call) => call[0]),
).toEqual([ToolNames.READ_FILE, ToolNames.EDIT, ToolNames.SHELL]);
).toEqual([
ToolNames.READ_FILE,
ToolNames.EDIT,
ToolNames.NOTEBOOK_EDIT,
ToolNames.SHELL,
]);
});

it('registers structured_output in bare mode when jsonSchema is set', async () => {
// Bare mode strips the toolset to READ_FILE/EDIT/SHELL, but the
// Bare mode strips the toolset to READ_FILE/EDIT/NOTEBOOK_EDIT/SHELL, but the
// synthetic structured_output tool is the terminal contract for
// --json-schema runs. Without it the model loops until
// maxSessionTurns and exits via the "plain text" failure path —
// expensive in tokens for what's almost always a CI use case. The
// synthetic tool must be registered alongside the bare three.
// synthetic tool must be registered alongside the bare toolset.
const config = new Config({
...baseParams,
bareMode: true,
Expand All @@ -1401,6 +1412,7 @@ describe('Server Config (config.ts)', () => {
).toEqual([
ToolNames.READ_FILE,
ToolNames.EDIT,
ToolNames.NOTEBOOK_EDIT,
ToolNames.SHELL,
ToolNames.STRUCTURED_OUTPUT,
]);
Expand Down Expand Up @@ -1429,8 +1441,8 @@ describe('Server Config (config.ts)', () => {
ToolRegistry: { prototype: { registerFactory: Mock } };
}
).ToolRegistry.prototype.registerFactory;
// Initial bare init registers READ_FILE / EDIT / SHELL /
// STRUCTURED_OUTPUT (asserted by the test above). Reset so we can
// Initial bare init registers READ_FILE / EDIT / NOTEBOOK_EDIT /
// SHELL / STRUCTURED_OUTPUT (asserted by the test above). Reset so we can
// observe ONLY the forSubAgent rebuild's calls.
(registerToolMock as Mock).mockClear();

Expand All @@ -1444,10 +1456,11 @@ describe('Server Config (config.ts)', () => {
(call) => call[0],
);
expect(registeredNames).not.toContain(ToolNames.STRUCTURED_OUTPUT);
// The bare three still register so the subagent has its toolset.
// The bare tools still register so the subagent has its toolset.
expect(registeredNames).toEqual([
ToolNames.READ_FILE,
ToolNames.EDIT,
ToolNames.NOTEBOOK_EDIT,
ToolNames.SHELL,
]);
});
Expand Down
9 changes: 9 additions & 0 deletions packages/core/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,7 @@ export interface ConfigInitializeOptions {
const DEFAULT_BARE_CORE_TOOLS = [
ToolNames.READ_FILE,
ToolNames.EDIT,
ToolNames.NOTEBOOK_EDIT,
ToolNames.SHELL,
];

Expand Down Expand Up @@ -2970,6 +2971,10 @@ export class Config {
const { EditTool } = await import('../tools/edit.js');
return new EditTool(this);
});
await registerLazy(ToolNames.NOTEBOOK_EDIT, async () => {
const { NotebookEditTool } = await import('../tools/notebook-edit.js');
return new NotebookEditTool(this);
});
await registerLazy(ToolNames.SHELL, async () => {
const { ShellTool } = await import('../tools/shell.js');
return new ShellTool(this);
Expand Down Expand Up @@ -3054,6 +3059,10 @@ export class Config {
const { EditTool } = await import('../tools/edit.js');
return new EditTool(this);
});
await registerLazy(ToolNames.NOTEBOOK_EDIT, async () => {
const { NotebookEditTool } = await import('../tools/notebook-edit.js');
return new NotebookEditTool(this);
});
await registerLazy(ToolNames.WRITE_FILE, async () => {
const { WriteFileTool } = await import('../tools/write-file.js');
return new WriteFileTool(this);
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/core/coreToolScheduler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4987,6 +4987,14 @@ describe('extractToolFilePaths', () => {
]);
});

it('extracts notebook_path for notebook_edit', () => {
expect(
extractToolFilePaths('notebook_edit', {
notebook_path: '/proj/analysis.ipynb',
}),
).toEqual(['/proj/analysis.ipynb']);
});

it('extracts filePath for lsp (camelCase convention)', () => {
expect(extractToolFilePaths('lsp', { filePath: '/proj/b.ts' })).toEqual([
'/proj/b.ts',
Expand Down
Loading
Loading