feat: single AI action button with inline prompt; replace cell source

This commit is contained in:
tao.chen
2026-07-23 12:47:47 +08:00
parent d03f0fa434
commit 85e16914b5
3 changed files with 196 additions and 97 deletions
+59 -42
View File
@@ -1,12 +1,12 @@
/**
* Unit tests for OpenCodeCellActions DOM rendering and button disabled states.
* Unit tests for OpenCodeCellActions (single AI button) and OpenCodeInlinePrompt
* (inline input panel inside the cell).
*
* Mocks @jupyterlab/cells, @jupyterlab/apputils, and @lumino/widgets at the
* test boundary so the real ESM packages are not loaded (Jest + pnpm can't
* transform the hoisted @jupyterlab/* packages out of the box).
* test boundary so the real ESM packages are not loaded.
*/
jest.mock('@jupyterlab/cells', () => ({
CodeCell: class CodeCell {}
CodeCell: class CodeCell { public node = document.createElement('div'); }
}));
jest.mock('@jupyterlab/apputils', () => ({
@@ -32,12 +32,22 @@ jest.mock('@lumino/widgets', () => {
}
public dispose(): void {
this._isDisposed = true;
if (this.node.parentElement) {
this.node.parentElement.removeChild(this.node);
}
}
public onAfterAttach(msg: any): void {
// no-op for tests
}
public static attach(widget: Widget, host: HTMLElement): void {
host.appendChild(widget.node);
}
}
return { Widget };
});
import { OpenCodeCellActions } from '../components/opencode_cell_actions';
import { OpenCodeInlinePrompt } from '../components/opencode_inline_prompt';
import { CodeCell } from '@jupyterlab/cells';
function makeFakeOutputs(items: any[]): any {
@@ -62,7 +72,8 @@ function makeFakeCell(
id: 'cell-test',
type: 'code',
sharedModel: {
getSource: () => source
getSource: () => source,
setSource: jest.fn()
},
outputs: makeFakeOutputs(errorOutputs),
contentChanged: { connect: jest.fn(), disconnect: jest.fn() },
@@ -71,8 +82,6 @@ function makeFakeCell(
const cell = new (CodeCell as unknown as new () => CodeCell)();
(cell as any).model = model;
// Parent chain: cell -> notebook -> panel (mirrors real JupyterLab, where
// the cell's grandparent Notebook matches the duck-typed panel lookup).
const notebook: any = { widgets: [] as CodeCell[] };
const panel: any = {
context: { path: notebookPath },
@@ -103,61 +112,56 @@ function makeFakeCell(
}
describe('OpenCodeCellActions', () => {
it('renders 3 buttons with the expected labels', () => {
it('renders a single AI button (not 3 buttons)', () => {
const cell = makeFakeCell('x = 1');
const actions = new OpenCodeCellActions(cell);
const btns = actions.node.querySelectorAll('button');
expect(btns.length).toBe(3);
expect(btns[0].textContent).toBe('✨ 优化');
expect(btns[1].textContent).toBe('🐛 排错');
expect(btns[2].textContent).toBe('🪄 编辑');
expect(btns.length).toBe(1);
expect(btns[0].textContent).toContain('🪄');
});
it('disables all buttons when the notebook panel cannot be resolved', () => {
it('disables the button when notebook panel cannot be resolved', () => {
const cell = new (CodeCell as unknown as new () => CodeCell)();
(cell as any).model = {
id: 'orphan',
type: 'code',
sharedModel: { getSource: () => 'x = 1' },
sharedModel: { getSource: () => 'x = 1', setSource: jest.fn() },
outputs: makeFakeOutputs([]),
contentChanged: { connect: jest.fn(), disconnect: jest.fn() },
stateChanged: { connect: jest.fn(), disconnect: jest.fn() }
};
// No parent chain: extractCellContextFromCell must return null.
const actions = new OpenCodeCellActions(cell);
const btns = actions.node.querySelectorAll('button');
btns.forEach((b: HTMLButtonElement) => {
expect(b.disabled).toBe(true);
});
const btn = actions.node.querySelector('button') as HTMLButtonElement;
expect(btn.disabled).toBe(true);
});
it('enables optimize and edit; fix stays disabled without an error', () => {
const cell = makeFakeCell('x = 1', [], 'foo.ipynb', 0, 1);
it('clicking the button attaches an OpenCodeInlinePrompt to the cell', () => {
const cell = makeFakeCell('x = 1');
const actions = new OpenCodeCellActions(cell);
const btns = actions.node.querySelectorAll('button');
expect((btns[0] as HTMLButtonElement).disabled).toBe(false);
expect((btns[1] as HTMLButtonElement).disabled).toBe(true);
expect((btns[2] as HTMLButtonElement).disabled).toBe(false);
// Attach actions to cell so it can resolve parent chain
Object.defineProperty(actions, 'parent', { value: cell, configurable: true });
(actions as any).onAfterAttach({} as any);
const btn = actions.node.querySelector('button') as HTMLButtonElement;
btn.click();
const prompt = cell.node.querySelector(
'.opencode-inline-prompt'
) as HTMLElement;
expect(prompt).not.toBeNull();
});
it('enables the fix button when the cell has an error output', () => {
const cell = makeFakeCell(
'1/0',
[
{
type: 'error',
ename: 'ZeroDivisionError',
evalue: 'div by zero',
traceback: []
}
],
'foo.ipynb',
0,
1
);
it('clicking the button twice detaches the inline prompt', () => {
const cell = makeFakeCell('x = 1');
const actions = new OpenCodeCellActions(cell);
const btns = actions.node.querySelectorAll('button');
expect((btns[1] as HTMLButtonElement).disabled).toBe(false);
Object.defineProperty(actions, 'parent', { value: cell, configurable: true });
(actions as any).onAfterAttach({} as any);
const btn = actions.node.querySelector('button') as HTMLButtonElement;
btn.click();
btn.click();
const prompt = cell.node.querySelector('.opencode-inline-prompt');
expect(prompt).toBeNull();
});
it('disconnects model signals on dispose', () => {
@@ -169,3 +173,16 @@ describe('OpenCodeCellActions', () => {
expect(model.stateChanged.disconnect).toHaveBeenCalled();
});
});
describe('OpenCodeInlinePrompt', () => {
it('renders a textarea, a send and a cancel button', () => {
const cell = makeFakeCell('x = 1');
const prompt = new OpenCodeInlinePrompt(cell, {
onSubmit: jest.fn(),
onCancel: jest.fn(),
disabled: false
});
expect(prompt.node.querySelector('textarea')).not.toBeNull();
expect(prompt.node.querySelectorAll('button').length).toBe(2);
});
});
+78 -55
View File
@@ -1,10 +1,13 @@
/**
* Per-cell actions widget rendered inside JupyterLab's native Cell toolbar
* (top-right of the active cell, next to the move up/down buttons).
* Per-cell AI action button rendered inside JupyterLab's native Cell toolbar
* (top-right of the active cell). v2: a single icon button. Clicking it
* toggles an OpenCodeInlinePrompt panel attached to the cell's DOM.
*
* Registered in index.ts via IToolbarWidgetRegistry.addFactory('Cell', ...);
* the toolbar factory passes the owning Cell, so the cell arrives via the
* constructor instead of being resolved from `this.parent` on attach.
* Registered in index.ts via IToolbarWidgetRegistry.addFactory('Cell', ...).
*
* The frontend does NO semantic processing: it gathers the cell's source /
* outputs / error, attaches the user's freeform instruction, and POSTs to
* the server. The server (and the LLM it forwards to) decides what to do.
*/
import type { CodeCell } from '@jupyterlab/cells';
import { Notification } from '@jupyterlab/apputils';
@@ -16,12 +19,13 @@ import { callOpenCodeEdit } from '../api/opencode_client';
import { extractCellContext } from '../context/cell_context';
import type {
CellContext,
OpenCodeMode,
OpenCodeRequest,
OpenCodeResponse,
OpenCodeSettings
} from '../types';
import { OpenCodeInlinePrompt } from './opencode_inline_prompt';
// Module-level runtime injection (set by index.ts after settings load).
let _settings: OpenCodeSettings | null = null;
let _serverSettings: ServerConnection.ISettings | null = null;
@@ -40,6 +44,7 @@ export class OpenCodeCellActions extends Widget {
private _cell: CodeCell;
private _context: CellContext | null = null;
private _status: Status = 'idle';
private _prompt: OpenCodeInlinePrompt | null = null;
constructor(cell: CodeCell) {
super();
@@ -47,6 +52,7 @@ export class OpenCodeCellActions extends Widget {
this.addClass('opencode-cell-actions');
this._cell.model.contentChanged.connect(this._onModelChange, this);
this._cell.model.stateChanged.connect(this._onModelChange, this);
this._render();
this._onModelChange();
}
@@ -56,48 +62,71 @@ export class OpenCodeCellActions extends Widget {
}
this._cell.model.contentChanged.disconnect(this._onModelChange, this);
this._cell.model.stateChanged.disconnect(this._onModelChange, this);
this._hidePrompt();
super.dispose();
}
private _onModelChange(): void {
this._context = extractCellContextFromCell(this._cell);
this._render();
if (this._prompt) {
this._prompt.setDisabled(!this._context || this._status === 'loading');
} else {
this._render();
}
}
private _render(): void {
const node = this.node;
node.textContent = '';
const hasError = !!this._context?.error;
const loading = this._status === 'loading';
const baseDisabled = !this._context || loading;
const baseDisabled = !this._context || this._status === 'loading';
const mkBtn = (
label: string,
mode: OpenCodeMode,
disabled: boolean
): HTMLButtonElement => {
const b = document.createElement('button');
b.className = `opencode-btn opencode-btn-${mode}`;
b.textContent = label;
b.disabled = disabled;
b.title = disabled
? loading
? 'OpenCode: 请求中…'
: 'OpenCode: 等待 cell 上下文…'
: label;
b.addEventListener('click', () => {
void this._onClick(mode);
});
return b;
};
node.appendChild(mkBtn('✨ 优化', 'optimize', baseDisabled));
node.appendChild(mkBtn('🐛 排错', 'fix', baseDisabled || !hasError));
node.appendChild(mkBtn('🪄 编辑', 'edit', baseDisabled));
const btn = document.createElement('button');
btn.className = 'opencode-btn opencode-btn-ai';
btn.textContent = '🪄 AI 智能编辑';
btn.disabled = baseDisabled;
btn.title = baseDisabled
? 'OpenCode: 等待 cell 上下文…'
: '让 AI 修改这个 cell 的代码';
btn.addEventListener('click', () => {
this._togglePrompt();
});
node.appendChild(btn);
}
private async _onClick(mode: OpenCodeMode): Promise<void> {
private _togglePrompt(): void {
if (this._prompt) {
this._hidePrompt();
} else {
this._showPrompt();
}
}
private _showPrompt(): void {
if (this._prompt) {
return;
}
const prompt = new OpenCodeInlinePrompt(this._cell, {
disabled: !this._context || this._status === 'loading',
onSubmit: (text: string) => {
void this._onSubmit(text);
},
onCancel: () => {
this._hidePrompt();
}
});
Widget.attach(prompt, this._cell.node);
this._prompt = prompt;
}
private _hidePrompt(): void {
if (this._prompt) {
this._prompt.dispose();
this._prompt = null;
}
}
private async _onSubmit(text: string): Promise<void> {
if (!this._context) {
return;
}
@@ -106,46 +135,42 @@ export class OpenCodeCellActions extends Widget {
return;
}
let prompt = '';
if (mode === 'edit') {
const input = window.prompt('请输入编辑指令:');
if (input === null) {
return;
}
prompt = input;
}
const request: OpenCodeRequest = {
mode,
prompt,
prompt: text,
context: this._context,
providerId: _settings.opencodeProvider || undefined,
modelId: _settings.opencodeModel || undefined
};
this._status = 'loading';
this._render();
if (this._prompt) {
this._prompt.setDisabled(true);
}
try {
const resp = await callOpenCodeEdit(request, _serverSettings);
this._handleResponse(resp);
} catch (e) {
this._status = 'idle';
this._render();
Notification.error(`OpenCode ${mode} 失败: ${(e as Error).message}`);
if (this._prompt) {
this._prompt.setDisabled(false);
}
Notification.error(`OpenCode 失败: ${(e as Error).message}`);
}
}
private _handleResponse(resp: OpenCodeResponse): void {
this._status = 'idle';
this._render();
if (resp.ok) {
const len = resp.finalSource.length;
this._cell.model.sharedModel.setSource(resp.finalSource);
Notification.info(
`OpenCode ${resp.mode} 完成 (${len} chars). ` +
`Diff 面板将在 Slice 4 中提供。Session: ${resp.sessionId.slice(0, 8)}`
`OpenCode 完成 (${resp.finalSource.length} chars). Session: ${resp.sessionId.slice(0, 8)}`
);
this._hidePrompt();
} else {
if (this._prompt) {
this._prompt.setDisabled(false);
}
Notification.error(`OpenCode 错误: ${resp.error}`);
}
}
@@ -153,14 +178,12 @@ export class OpenCodeCellActions extends Widget {
/**
* Resolve a CodeCell's parent NotebookPanel by walking the parent chain,
* then build the CellContext. (Unchanged from the old footer helper; the
* `Widget.findParent` helper was removed in @lumino/widgets 2.x.)
* then build the CellContext.
*/
function extractCellContextFromCell(cell: CodeCell): CellContext | null {
let node: Widget | null = cell.parent;
let notebookPanel: NotebookPanel | null = null;
while (node) {
// Use duck-typing: a notebook panel has `context.path` and `content.widgets`.
const candidate = node as any;
if (
candidate.context &&
+59
View File
@@ -0,0 +1,59 @@
/**
* Inline prompt widget attached to a cell's DOM when the AI button is clicked.
* Renders a textarea + send/cancel buttons. The owning cell is passed so
* we can resolve the cell context at submit time. submit/cancel are
* callbacks owned by OpenCodeCellActions.
*/
import { CodeCell } from '@jupyterlab/cells';
import { Widget } from '@lumino/widgets';
export interface IOpenCodeInlinePromptOptions {
onSubmit: (text: string) => void;
onCancel: () => void;
disabled: boolean;
}
export class OpenCodeInlinePrompt extends Widget {
private _textarea: HTMLTextAreaElement;
private _sendBtn: HTMLButtonElement;
private _cancelBtn: HTMLButtonElement;
constructor(
_cell: CodeCell,
options: IOpenCodeInlinePromptOptions
) {
super();
this.addClass('opencode-inline-prompt');
this._textarea = document.createElement('textarea');
this._textarea.placeholder = '向 AI 描述你想要的修改…';
this._textarea.rows = 3;
this._sendBtn = document.createElement('button');
this._sendBtn.className = 'opencode-btn-send';
this._sendBtn.textContent = '🚀 发送';
this._sendBtn.disabled = options.disabled;
this._sendBtn.addEventListener('click', () => {
const text = this._textarea.value;
if (text.trim()) {
options.onSubmit(text);
}
});
this._cancelBtn = document.createElement('button');
this._cancelBtn.className = 'opencode-btn-cancel';
this._cancelBtn.textContent = '✕ 取消';
this._cancelBtn.addEventListener('click', () => {
options.onCancel();
});
const actions = document.createElement('div');
actions.className = 'opencode-inline-actions';
actions.appendChild(this._sendBtn);
actions.appendChild(this._cancelBtn);
this.node.appendChild(this._textarea);
this.node.appendChild(actions);
}
setDisabled(disabled: boolean): void {
this._sendBtn.disabled = disabled;
}
}