Initial commit: opencode_bridge JupyterLab extension (Slices 1-3.5)

A JupyterLab extension that bridges the cell UI to a local OpenCode Serve
process. The extension is a dual package: a Python server extension
exposed under /opencode-bridge/*, plus a TypeScript frontend that
registers per-cell toolbars.

Backend (Python, tornado)
- Slice 1: config + auth + OpenCode HTTP client (tornado.httpclient,
  no aiohttp). 4 settings in schema/plugin.json (url, user, password,
  request timeout).
- Slice 2: handlers for /hello, /health, /providers, /edit.
- Slice 2.1 (correction): SessionManager with 1 notebook = 1 session
  mapping, async-safe via per-path locks, 404 recovery via invalidate().
  Two new endpoints: GET /sessions, DELETE /session?notebook=<path>.
- 32 pytest tests pass.

Frontend (TypeScript, JupyterLab 4.6)
- src/types.ts: CellContext, OpenCodeRequest/Response, OpenCodeSettings.
- src/context/cell_context.ts: extract CellContext from a CodeCell +
  its parent NotebookPanel, structured error collection.
- src/api/opencode_client.ts: callOpenCodeEdit, callOpenCodeProviders.
- src/components/opencode_cell_footer.ts: OpenCodeCellFooter Widget
  implementing ICellFooter with 3 buttons (optimize / fix / edit),
  resolved via this.parent instanceof CodeCell. NOT cellToolbar
  (does not exist in JL 4.6) and NOT Widget.findParent (removed in
  @lumino/widgets 2.x).
- src/components/opencode_cell_factory.ts: Cell.ContentFactory
  subclass returning the OpenCodeCellFooter.
- src/components/opencode_installer.ts: installOpenCodeEverywhere
  patches every notebook (existing + new) to use the custom factory.
- src/index.ts: registers the factory, loads settings, fetches
  /providers on activation and logs the list to the console.
- 23 jest tests pass (mocked JupyterLab boundary, pnpm path safe).

Settings
- 6 fields: 3 auth (url/user/password) + 1 timeout + 2 model selection
  (provider/model). Provider list is fetched at startup from
  /opencode-bridge/providers and printed to the browser console so
  users can copy values into Settings Editor.

Docs
- design.md: 6 sections covering architecture, UI flow, API contract,
  TS skeletons, session management (v0.2.1 correction), and
  provider/model selection (v0.2.2 addition).
- CLAUDE.md: agent guidance for working in this repo.
- TODO.md: remaining work for Slices 4-7 + v0.4+ backlog.

CI
- Gitea release workflow at .github/workflows/build.yml.
- Bark notification helper (non-fatal on failure).

Generated artefacts ignored: opencode_bridge/labextension/, _version.py,
*.tsbuildinfo, junit.xml, test.ipynb scratch notebook.
This commit is contained in:
tao.chen
2026-07-22 19:07:58 +08:00
commit c919c95842
61 changed files with 26642 additions and 0 deletions
+154
View File
@@ -0,0 +1,154 @@
import type { CodeCell, ICodeCellModel } from '@jupyterlab/cells';
import type { NotebookPanel } from '@jupyterlab/notebook';
import { collectErrorOutputs, extractCellContext } from '../context/cell_context';
function makeMockOutputs(items: unknown[]): ICodeCellModel['outputs'] {
return {
get length() {
return items.length;
},
get(i: number) {
return items[i];
},
// Other IObservableList methods are unused in collectErrorOutputs.
} as unknown as ICodeCellModel['outputs'];
}
function makeMockModel(overrides: {
id?: string;
type?: 'code' | 'markdown' | 'raw';
source?: string;
outputs?: unknown[];
}): ICodeCellModel {
return {
id: overrides.id ?? 'cell-1',
type: overrides.type ?? 'code',
sharedModel: {
getSource: () => overrides.source ?? '',
},
outputs: makeMockOutputs(overrides.outputs ?? []),
} as unknown as ICodeCellModel;
}
function makeMockCell(source: string, errorOutputs: unknown[] = []): CodeCell {
return { model: makeMockModel({ source, outputs: errorOutputs }) } as CodeCell;
}
function makeMockNotebook(cells: CodeCell[]): { widgets: CodeCell[] } {
return { widgets: cells };
}
function makeMockPanel(
notebook: { widgets: CodeCell[] },
path: string
): NotebookPanel {
return {
context: { path } as NotebookPanel['context'],
content: notebook as unknown as NotebookPanel['content'],
} as unknown as NotebookPanel;
}
describe('collectErrorOutputs', () => {
it('returns null when there are no outputs', () => {
const model = makeMockModel({ outputs: [] });
expect(collectErrorOutputs(model)).toBeNull();
});
it('returns null when outputs are non-error', () => {
const model = makeMockModel({
outputs: [{ type: 'stream', text: 'hello' }],
});
expect(collectErrorOutputs(model)).toBeNull();
});
it('extracts the first error output', () => {
const errOut = {
type: 'error',
ename: 'ValueError',
evalue: 'bad value',
traceback: ['line 1', 'line 2'],
};
const model = makeMockModel({ outputs: [errOut] });
const result = collectErrorOutputs(model);
expect(result).toEqual({
ename: 'ValueError',
evalue: 'bad value',
traceback: ['line 1', 'line 2'],
});
});
it('handles missing traceback gracefully', () => {
const model = makeMockModel({
outputs: [{ type: 'error', ename: 'E', evalue: 'v' }],
});
const result = collectErrorOutputs(model);
expect(result?.traceback).toEqual([]);
});
});
describe('extractCellContext', () => {
it('returns null when cell is not in notebook', () => {
const cell = makeMockCell('x = 1');
const other = makeMockCell('y = 2');
const notebook = makeMockNotebook([other]);
const panel = makeMockPanel(notebook, 'foo.ipynb');
expect(extractCellContext(cell, panel)).toBeNull();
});
it('extracts source, language, and indices', () => {
const cell = makeMockCell('x = 1');
const notebook = makeMockNotebook([cell]);
const panel = makeMockPanel(notebook, 'foo.ipynb');
const ctx = extractCellContext(cell, panel);
expect(ctx).toMatchObject({
notebookPath: 'foo.ipynb',
cellId: 'cell-1',
language: 'python',
cellIndex: 0,
totalCells: 1,
source: 'x = 1',
previousCode: null,
error: null,
});
});
it('captures the previous cell source as previousCode', () => {
const prev = makeMockCell('import os');
const cell = makeMockCell('os.getcwd()');
const notebook = makeMockNotebook([prev, cell]);
const panel = makeMockPanel(notebook, 'foo.ipynb');
const ctx = extractCellContext(cell, panel);
expect(ctx?.previousCode).toBe('import os');
expect(ctx?.cellIndex).toBe(1);
expect(ctx?.totalCells).toBe(2);
});
it('includes the error when the cell has an error output', () => {
const cell = makeMockCell('1/0', [
{
type: 'error',
ename: 'ZeroDivisionError',
evalue: 'division by zero',
traceback: ['Traceback...'],
},
]);
const notebook = makeMockNotebook([cell]);
const panel = makeMockPanel(notebook, 'foo.ipynb');
const ctx = extractCellContext(cell, panel);
expect(ctx?.error).toEqual({
ename: 'ZeroDivisionError',
evalue: 'division by zero',
traceback: ['Traceback...'],
});
});
it('returns null when given null cell or panel', () => {
expect(
extractCellContext(
null as unknown as CodeCell,
makeMockPanel(makeMockNotebook([]), 'x.ipynb')
)
).toBeNull();
});
});
+33
View File
@@ -0,0 +1,33 @@
import { DEFAULT_OPENCODE_SETTINGS, readOpenCodeSettings } from '../types';
describe('opencode_bridge types', () => {
it('returns defaults when given empty composite', () => {
const s = readOpenCodeSettings({});
expect(s).toEqual(DEFAULT_OPENCODE_SETTINGS);
expect(s.opencodeProvider).toBe('');
expect(s.opencodeModel).toBe('');
});
it('overrides defaults with user values', () => {
const s = readOpenCodeSettings({
opencodeServerUrl: 'http://x:1',
opencodeProvider: 'anthropic',
opencodeModel: 'claude-sonnet-4-20250514'
});
expect(s.opencodeServerUrl).toBe('http://x:1');
expect(s.opencodeProvider).toBe('anthropic');
expect(s.opencodeModel).toBe('claude-sonnet-4-20250514');
expect(s.opencodeServerUser).toBe(
DEFAULT_OPENCODE_SETTINGS.opencodeServerUser
);
});
it('treats empty string provider/model as "use default"', () => {
const s = readOpenCodeSettings({
opencodeProvider: '',
opencodeModel: ''
});
expect(s.opencodeProvider).toBe('');
expect(s.opencodeModel).toBe('');
});
});
+156
View File
@@ -0,0 +1,156 @@
/**
* Unit tests for OpenCodeCellFooter DOM rendering and button disabled states.
*
* 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).
*/
// Mock the heavy JupyterLab modules BEFORE importing the component.
// (jest.mock is hoisted by Jest, but listing it before imports is clearer.)
jest.mock('@jupyterlab/cells', () => ({
CodeCell: class CodeCell {}
}));
jest.mock('@jupyterlab/apputils', () => ({
Notification: {
info: jest.fn(),
error: jest.fn(),
success: jest.fn(),
warning: jest.fn()
}
}));
jest.mock('@lumino/widgets', () => {
class Widget {
public node: HTMLElement = document.createElement('div');
public addClass(cls: string): void {
this.node.classList.add(cls);
}
public id: string = '';
public parent: Widget | null = null;
protected onAfterAttach(_msg: unknown): void {
/* overridden by subclass */
}
protected onBeforeDetach(_msg: unknown): void {
/* overridden by subclass */
}
}
return { Widget };
});
import { OpenCodeCellFooter } from '../components/opencode_cell_footer';
import { CodeCell } from '@jupyterlab/cells';
function makeFakeOutputs(items: any[]): any {
return {
get length() {
return items.length;
},
get(i: number) {
return items[i];
}
};
}
function makeFakeCell(
source: string,
errorOutputs: any[] = [],
notebookPath = 'foo.ipynb',
cellIndex = 0,
totalCells = 1
): CodeCell {
const model: any = {
id: 'cell-test',
type: 'code',
sharedModel: {
getSource: () => source
},
outputs: makeFakeOutputs(errorOutputs),
// Signal stubs so the component can connect/disconnect without crashing.
contentChanged: { connect: jest.fn(), disconnect: jest.fn() },
stateChanged: { connect: jest.fn(), disconnect: jest.fn() }
};
const cell = new (CodeCell as unknown as new () => CodeCell)();
(cell as any).model = model;
// Build a fake parent chain: cell -> notebook -> panel.
const notebook: any = { widgets: [] as CodeCell[] };
const panel: any = {
context: { path: notebookPath },
content: notebook
};
for (let i = 0; i < cellIndex; i++) {
notebook.widgets.push({ model: { sharedModel: { getSource: () => '' } } } as any);
}
notebook.widgets.push(cell);
for (let i = cellIndex + 1; i < totalCells; i++) {
notebook.widgets.push({ model: { sharedModel: { getSource: () => '' } } } as any);
}
// The footer's helper walks `cell.parent` looking for a widget with
// `context` + `content.widgets`. The cell's grandparent (notebook) is what
// matches in real JupyterLab. We mirror that here.
Object.defineProperty(cell, 'parent', { value: notebook, configurable: true });
Object.defineProperty(notebook, 'parent', { value: panel, configurable: true });
return cell as CodeCell;
}
describe('OpenCodeCellFooter', () => {
it('renders 3 buttons', () => {
const footer = new OpenCodeCellFooter();
const btns = footer.node.querySelectorAll('button');
expect(btns.length).toBe(3);
expect(btns[0].textContent).toBe('✨ 优化');
expect(btns[1].textContent).toBe('🐛 排错');
expect(btns[2].textContent).toBe('🪄 编辑');
});
it('disables all buttons when no cell is attached', () => {
const footer = new OpenCodeCellFooter();
const btns = footer.node.querySelectorAll('button');
btns.forEach((b: HTMLButtonElement) => {
expect(b.disabled).toBe(true);
});
});
it('enables optimize and edit when a cell is attached; fix stays disabled without an error', () => {
const cell = makeFakeCell('x = 1', [], 'foo.ipynb', 0, 1);
const footer = new OpenCodeCellFooter();
Object.defineProperty(footer, 'parent', { value: cell, configurable: true });
(footer as any).onAfterAttach({} as any);
const btns = footer.node.querySelectorAll('button');
const optimize = btns[0] as HTMLButtonElement;
const fix = btns[1] as HTMLButtonElement;
const edit = btns[2] as HTMLButtonElement;
expect(optimize.disabled).toBe(false);
expect(fix.disabled).toBe(true);
expect(edit.disabled).toBe(false);
});
it('enables the fix button when the attached cell has an error output', () => {
const cell = makeFakeCell(
'1/0',
[
{
type: 'error',
ename: 'ZeroDivisionError',
evalue: 'div by zero',
traceback: []
}
],
'foo.ipynb',
0,
1
);
const footer = new OpenCodeCellFooter();
Object.defineProperty(footer, 'parent', { value: cell, configurable: true });
(footer as any).onAfterAttach({} as any);
const btns = footer.node.querySelectorAll('button');
const fix = btns[1] as HTMLButtonElement;
expect(fix.disabled).toBe(false);
});
});
+223
View File
@@ -0,0 +1,223 @@
import { ServerConnection } from '@jupyterlab/services';
import { callOpenCodeEdit, callOpenCodeProviders } from '../api/opencode_client';
import type { OpenCodeRequest } from '../types';
jest.mock('@jupyterlab/services', () => {
const actual = jest.requireActual('@jupyterlab/services');
return {
...actual,
ServerConnection: {
...actual.ServerConnection,
makeRequest: jest.fn(),
},
};
});
const mockedMakeRequest = ServerConnection.makeRequest as jest.MockedFunction<
typeof ServerConnection.makeRequest
>;
function mockServerSettings(): ServerConnection.ISettings {
return {
baseUrl: 'http://localhost:8888',
wsUrl: 'ws://localhost:8888',
token: 'test',
init: { headers: { 'X-Test': '1' } },
fetch: {} as unknown as typeof fetch,
RequestClass: {} as unknown as typeof Request,
Headers: {} as unknown as typeof Headers,
appendToken: false,
pageUrl: '',
settings: {} as unknown as ServerConnection.ISettings,
displayName: 'JupyterLab',
handleError: () => undefined,
requestHeaders: {},
wsHeaders: {},
userSettings: {},
} as unknown as ServerConnection.ISettings;
}
function mockResponse(overrides: {
ok: boolean;
status: number;
statusText: string;
text: string;
}): Response {
return {
ok: overrides.ok,
status: overrides.status,
statusText: overrides.statusText,
text: async () => overrides.text,
headers: {} as unknown as Headers,
json: async () => JSON.parse(overrides.text),
url: '',
redirected: false,
type: 'basic',
body: null,
bodyUsed: false,
arrayBuffer: async () => new ArrayBuffer(0),
blob: async () => new Blob(),
formData: async () => new FormData(),
clone: () => mockResponse(overrides),
} as unknown as Response;
}
const sampleRequest: OpenCodeRequest = {
mode: 'edit',
prompt: 'add type hints',
context: {
notebookPath: 'foo.ipynb',
cellId: 'cell-1',
language: 'python',
cellIndex: 0,
totalCells: 1,
source: 'def foo(x): return x',
previousCode: null,
error: null,
},
};
describe('callOpenCodeEdit', () => {
beforeEach(() => {
mockedMakeRequest.mockReset();
});
it('POSTs to /opencode-bridge/edit with JSON body', async () => {
const respBody = {
ok: true,
mode: 'edit',
finalSource: 'def foo(x: int) -> int: return x',
sessionId: 'sid',
notebookPath: 'foo.ipynb',
};
mockedMakeRequest.mockResolvedValue(
mockResponse({ ok: true, status: 200, statusText: 'OK', text: JSON.stringify(respBody) })
);
const settings = mockServerSettings();
const resp = await callOpenCodeEdit(sampleRequest, settings);
expect(mockedMakeRequest).toHaveBeenCalledWith(
'http://localhost:8888/opencode-bridge/edit',
expect.objectContaining({
method: 'POST',
body: JSON.stringify(sampleRequest),
headers: { 'Content-Type': 'application/json' },
}),
settings
);
expect(resp.ok).toBe(true);
if (resp.ok) {
expect(resp.finalSource).toContain('int');
}
});
it('returns failure response when server returns ok: false', async () => {
mockedMakeRequest.mockResolvedValue(
mockResponse({
ok: false,
status: 502,
statusText: 'Bad Gateway',
text: JSON.stringify({ ok: false, error: 'opencode down' }),
})
);
const resp = await callOpenCodeEdit(sampleRequest, mockServerSettings());
expect(resp.ok).toBe(false);
if (!resp.ok) {
expect(resp.error).toBe('opencode down');
}
});
it('throws on network error', async () => {
mockedMakeRequest.mockRejectedValue(new Error('ECONNREFUSED'));
await expect(
callOpenCodeEdit(sampleRequest, mockServerSettings())
).rejects.toThrow(/network error/);
});
it('throws on empty response body', async () => {
mockedMakeRequest.mockResolvedValue(
mockResponse({ ok: true, status: 200, statusText: 'OK', text: '' })
);
await expect(
callOpenCodeEdit(sampleRequest, mockServerSettings())
).rejects.toThrow(/empty response/);
});
});
describe('callOpenCodeProviders', () => {
beforeEach(() => {
mockedMakeRequest.mockReset();
});
it('GETs /opencode-bridge/providers and returns parsed JSON', async () => {
const respBody = {
providers: [
{ id: 'anthropic', models: [{ id: 'claude-sonnet-4-20250514' }] },
{ id: 'openai', models: [{ id: 'gpt-4' }, { id: 'gpt-3.5-turbo' }] }
]
};
mockedMakeRequest.mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
text: async () => JSON.stringify(respBody),
json: async () => respBody,
headers: {} as any,
url: '',
redirected: false,
type: 'basic',
body: null,
bodyUsed: false,
arrayBuffer: async () => new ArrayBuffer(0),
blob: async () => new Blob(),
formData: async () => new FormData(),
clone: function () { return this; }
} as any);
const settings = mockServerSettings();
const resp = await callOpenCodeProviders(settings);
expect(mockedMakeRequest).toHaveBeenCalledWith(
'http://localhost:8888/opencode-bridge/providers',
expect.objectContaining({ method: 'GET' }),
settings
);
expect(resp.providers).toHaveLength(2);
expect(resp.providers[0].id).toBe('anthropic');
expect(resp.providers[1].models).toHaveLength(2);
});
it('throws on non-2xx response', async () => {
mockedMakeRequest.mockResolvedValue({
ok: false,
status: 502,
statusText: 'Bad Gateway',
text: async () => '',
json: async () => null,
headers: {} as any,
url: '',
redirected: false,
type: 'basic',
body: null,
bodyUsed: false,
arrayBuffer: async () => new ArrayBuffer(0),
blob: async () => new Blob(),
formData: async () => new FormData(),
clone: function () { return this; }
} as any);
await expect(
callOpenCodeProviders(mockServerSettings())
).rejects.toThrow(/502/);
});
it('throws on network error', async () => {
mockedMakeRequest.mockRejectedValue(new Error('ECONNREFUSED'));
await expect(
callOpenCodeProviders(mockServerSettings())
).rejects.toThrow(/network error/);
});
});