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 * Mocks @jupyterlab/cells, @jupyterlab/apputils, and @lumino/widgets at the
* test boundary so the real ESM packages are not loaded (Jest + pnpm can't * test boundary so the real ESM packages are not loaded.
* transform the hoisted @jupyterlab/* packages out of the box).
*/ */
jest.mock('@jupyterlab/cells', () => ({ jest.mock('@jupyterlab/cells', () => ({
CodeCell: class CodeCell {} CodeCell: class CodeCell { public node = document.createElement('div'); }
})); }));
jest.mock('@jupyterlab/apputils', () => ({ jest.mock('@jupyterlab/apputils', () => ({
@@ -32,12 +32,22 @@ jest.mock('@lumino/widgets', () => {
} }
public dispose(): void { public dispose(): void {
this._isDisposed = true; 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 }; return { Widget };
}); });
import { OpenCodeCellActions } from '../components/opencode_cell_actions'; import { OpenCodeCellActions } from '../components/opencode_cell_actions';
import { OpenCodeInlinePrompt } from '../components/opencode_inline_prompt';
import { CodeCell } from '@jupyterlab/cells'; import { CodeCell } from '@jupyterlab/cells';
function makeFakeOutputs(items: any[]): any { function makeFakeOutputs(items: any[]): any {
@@ -62,7 +72,8 @@ function makeFakeCell(
id: 'cell-test', id: 'cell-test',
type: 'code', type: 'code',
sharedModel: { sharedModel: {
getSource: () => source getSource: () => source,
setSource: jest.fn()
}, },
outputs: makeFakeOutputs(errorOutputs), outputs: makeFakeOutputs(errorOutputs),
contentChanged: { connect: jest.fn(), disconnect: jest.fn() }, contentChanged: { connect: jest.fn(), disconnect: jest.fn() },
@@ -71,8 +82,6 @@ function makeFakeCell(
const cell = new (CodeCell as unknown as new () => CodeCell)(); const cell = new (CodeCell as unknown as new () => CodeCell)();
(cell as any).model = model; (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 notebook: any = { widgets: [] as CodeCell[] };
const panel: any = { const panel: any = {
context: { path: notebookPath }, context: { path: notebookPath },
@@ -103,61 +112,56 @@ function makeFakeCell(
} }
describe('OpenCodeCellActions', () => { 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 cell = makeFakeCell('x = 1');
const actions = new OpenCodeCellActions(cell); const actions = new OpenCodeCellActions(cell);
const btns = actions.node.querySelectorAll('button'); const btns = actions.node.querySelectorAll('button');
expect(btns.length).toBe(3); expect(btns.length).toBe(1);
expect(btns[0].textContent).toBe('✨ 优化'); expect(btns[0].textContent).toContain('🪄');
expect(btns[1].textContent).toBe('🐛 排错');
expect(btns[2].textContent).toBe('🪄 编辑');
}); });
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)(); const cell = new (CodeCell as unknown as new () => CodeCell)();
(cell as any).model = { (cell as any).model = {
id: 'orphan', id: 'orphan',
type: 'code', type: 'code',
sharedModel: { getSource: () => 'x = 1' }, sharedModel: { getSource: () => 'x = 1', setSource: jest.fn() },
outputs: makeFakeOutputs([]), outputs: makeFakeOutputs([]),
contentChanged: { connect: jest.fn(), disconnect: jest.fn() }, contentChanged: { connect: jest.fn(), disconnect: jest.fn() },
stateChanged: { 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 actions = new OpenCodeCellActions(cell);
const btns = actions.node.querySelectorAll('button'); const btn = actions.node.querySelector('button') as HTMLButtonElement;
btns.forEach((b: HTMLButtonElement) => { expect(btn.disabled).toBe(true);
expect(b.disabled).toBe(true);
});
}); });
it('enables optimize and edit; fix stays disabled without an error', () => { it('clicking the button attaches an OpenCodeInlinePrompt to the cell', () => {
const cell = makeFakeCell('x = 1', [], 'foo.ipynb', 0, 1); const cell = makeFakeCell('x = 1');
const actions = new OpenCodeCellActions(cell); const actions = new OpenCodeCellActions(cell);
const btns = actions.node.querySelectorAll('button'); // Attach actions to cell so it can resolve parent chain
expect((btns[0] as HTMLButtonElement).disabled).toBe(false); Object.defineProperty(actions, 'parent', { value: cell, configurable: true });
expect((btns[1] as HTMLButtonElement).disabled).toBe(true); (actions as any).onAfterAttach({} as any);
expect((btns[2] as HTMLButtonElement).disabled).toBe(false);
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', () => { it('clicking the button twice detaches the inline prompt', () => {
const cell = makeFakeCell( const cell = makeFakeCell('x = 1');
'1/0',
[
{
type: 'error',
ename: 'ZeroDivisionError',
evalue: 'div by zero',
traceback: []
}
],
'foo.ipynb',
0,
1
);
const actions = new OpenCodeCellActions(cell); const actions = new OpenCodeCellActions(cell);
const btns = actions.node.querySelectorAll('button'); Object.defineProperty(actions, 'parent', { value: cell, configurable: true });
expect((btns[1] as HTMLButtonElement).disabled).toBe(false); (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', () => { it('disconnects model signals on dispose', () => {
@@ -169,3 +173,16 @@ describe('OpenCodeCellActions', () => {
expect(model.stateChanged.disconnect).toHaveBeenCalled(); 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);
});
});
+76 -53
View File
@@ -1,10 +1,13 @@
/** /**
* Per-cell actions widget rendered inside JupyterLab's native Cell toolbar * Per-cell AI action button rendered inside JupyterLab's native Cell toolbar
* (top-right of the active cell, next to the move up/down buttons). * (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', ...); * 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. * 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 type { CodeCell } from '@jupyterlab/cells';
import { Notification } from '@jupyterlab/apputils'; import { Notification } from '@jupyterlab/apputils';
@@ -16,12 +19,13 @@ import { callOpenCodeEdit } from '../api/opencode_client';
import { extractCellContext } from '../context/cell_context'; import { extractCellContext } from '../context/cell_context';
import type { import type {
CellContext, CellContext,
OpenCodeMode,
OpenCodeRequest, OpenCodeRequest,
OpenCodeResponse, OpenCodeResponse,
OpenCodeSettings OpenCodeSettings
} from '../types'; } from '../types';
import { OpenCodeInlinePrompt } from './opencode_inline_prompt';
// Module-level runtime injection (set by index.ts after settings load). // Module-level runtime injection (set by index.ts after settings load).
let _settings: OpenCodeSettings | null = null; let _settings: OpenCodeSettings | null = null;
let _serverSettings: ServerConnection.ISettings | null = null; let _serverSettings: ServerConnection.ISettings | null = null;
@@ -40,6 +44,7 @@ export class OpenCodeCellActions extends Widget {
private _cell: CodeCell; private _cell: CodeCell;
private _context: CellContext | null = null; private _context: CellContext | null = null;
private _status: Status = 'idle'; private _status: Status = 'idle';
private _prompt: OpenCodeInlinePrompt | null = null;
constructor(cell: CodeCell) { constructor(cell: CodeCell) {
super(); super();
@@ -47,6 +52,7 @@ export class OpenCodeCellActions extends Widget {
this.addClass('opencode-cell-actions'); this.addClass('opencode-cell-actions');
this._cell.model.contentChanged.connect(this._onModelChange, this); this._cell.model.contentChanged.connect(this._onModelChange, this);
this._cell.model.stateChanged.connect(this._onModelChange, this); this._cell.model.stateChanged.connect(this._onModelChange, this);
this._render();
this._onModelChange(); this._onModelChange();
} }
@@ -56,48 +62,71 @@ export class OpenCodeCellActions extends Widget {
} }
this._cell.model.contentChanged.disconnect(this._onModelChange, this); this._cell.model.contentChanged.disconnect(this._onModelChange, this);
this._cell.model.stateChanged.disconnect(this._onModelChange, this); this._cell.model.stateChanged.disconnect(this._onModelChange, this);
this._hidePrompt();
super.dispose(); super.dispose();
} }
private _onModelChange(): void { private _onModelChange(): void {
this._context = extractCellContextFromCell(this._cell); this._context = extractCellContextFromCell(this._cell);
if (this._prompt) {
this._prompt.setDisabled(!this._context || this._status === 'loading');
} else {
this._render(); this._render();
} }
}
private _render(): void { private _render(): void {
const node = this.node; const node = this.node;
node.textContent = ''; node.textContent = '';
const hasError = !!this._context?.error; const baseDisabled = !this._context || this._status === 'loading';
const loading = this._status === 'loading';
const baseDisabled = !this._context || loading;
const mkBtn = ( const btn = document.createElement('button');
label: string, btn.className = 'opencode-btn opencode-btn-ai';
mode: OpenCodeMode, btn.textContent = '🪄 AI 智能编辑';
disabled: boolean btn.disabled = baseDisabled;
): HTMLButtonElement => { btn.title = baseDisabled
const b = document.createElement('button'); ? 'OpenCode: 等待 cell 上下文…'
b.className = `opencode-btn opencode-btn-${mode}`; : '让 AI 修改这个 cell 的代码';
b.textContent = label; btn.addEventListener('click', () => {
b.disabled = disabled; this._togglePrompt();
b.title = disabled
? loading
? 'OpenCode: 请求中…'
: 'OpenCode: 等待 cell 上下文…'
: label;
b.addEventListener('click', () => {
void this._onClick(mode);
}); });
return b; node.appendChild(btn);
};
node.appendChild(mkBtn('✨ 优化', 'optimize', baseDisabled));
node.appendChild(mkBtn('🐛 排错', 'fix', baseDisabled || !hasError));
node.appendChild(mkBtn('🪄 编辑', 'edit', baseDisabled));
} }
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) { if (!this._context) {
return; return;
} }
@@ -106,46 +135,42 @@ export class OpenCodeCellActions extends Widget {
return; return;
} }
let prompt = '';
if (mode === 'edit') {
const input = window.prompt('请输入编辑指令:');
if (input === null) {
return;
}
prompt = input;
}
const request: OpenCodeRequest = { const request: OpenCodeRequest = {
mode, prompt: text,
prompt,
context: this._context, context: this._context,
providerId: _settings.opencodeProvider || undefined, providerId: _settings.opencodeProvider || undefined,
modelId: _settings.opencodeModel || undefined modelId: _settings.opencodeModel || undefined
}; };
this._status = 'loading'; this._status = 'loading';
this._render(); if (this._prompt) {
this._prompt.setDisabled(true);
}
try { try {
const resp = await callOpenCodeEdit(request, _serverSettings); const resp = await callOpenCodeEdit(request, _serverSettings);
this._handleResponse(resp); this._handleResponse(resp);
} catch (e) { } catch (e) {
this._status = 'idle'; this._status = 'idle';
this._render(); if (this._prompt) {
Notification.error(`OpenCode ${mode} 失败: ${(e as Error).message}`); this._prompt.setDisabled(false);
}
Notification.error(`OpenCode 失败: ${(e as Error).message}`);
} }
} }
private _handleResponse(resp: OpenCodeResponse): void { private _handleResponse(resp: OpenCodeResponse): void {
this._status = 'idle'; this._status = 'idle';
this._render();
if (resp.ok) { if (resp.ok) {
const len = resp.finalSource.length; this._cell.model.sharedModel.setSource(resp.finalSource);
Notification.info( Notification.info(
`OpenCode ${resp.mode} 完成 (${len} chars). ` + `OpenCode 完成 (${resp.finalSource.length} chars). Session: ${resp.sessionId.slice(0, 8)}`
`Diff 面板将在 Slice 4 中提供。Session: ${resp.sessionId.slice(0, 8)}`
); );
this._hidePrompt();
} else { } else {
if (this._prompt) {
this._prompt.setDisabled(false);
}
Notification.error(`OpenCode 错误: ${resp.error}`); 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, * Resolve a CodeCell's parent NotebookPanel by walking the parent chain,
* then build the CellContext. (Unchanged from the old footer helper; the * then build the CellContext.
* `Widget.findParent` helper was removed in @lumino/widgets 2.x.)
*/ */
function extractCellContextFromCell(cell: CodeCell): CellContext | null { function extractCellContextFromCell(cell: CodeCell): CellContext | null {
let node: Widget | null = cell.parent; let node: Widget | null = cell.parent;
let notebookPanel: NotebookPanel | null = null; let notebookPanel: NotebookPanel | null = null;
while (node) { while (node) {
// Use duck-typing: a notebook panel has `context.path` and `content.widgets`.
const candidate = node as any; const candidate = node as any;
if ( if (
candidate.context && 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;
}
}