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
+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/);
});
});