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:
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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('');
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* HTTP client for the opencode-bridge server extension.
|
||||
*/
|
||||
import { URLExt } from '@jupyterlab/coreutils';
|
||||
import { ServerConnection } from '@jupyterlab/services';
|
||||
|
||||
import type { OpenCodeProvidersResponse, OpenCodeRequest, OpenCodeResponse } from '../types';
|
||||
|
||||
/**
|
||||
* Call POST /opencode-bridge/edit. Returns parsed response (success or failure).
|
||||
* Throws on network error or non-JSON response.
|
||||
*/
|
||||
export async function callOpenCodeEdit(
|
||||
request: OpenCodeRequest,
|
||||
serverSettings: ServerConnection.ISettings
|
||||
): Promise<OpenCodeResponse> {
|
||||
const url = URLExt.join(
|
||||
serverSettings.baseUrl,
|
||||
'opencode-bridge',
|
||||
'edit'
|
||||
);
|
||||
|
||||
const init: RequestInit = {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
};
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await ServerConnection.makeRequest(url, init, serverSettings);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`network error calling opencode-bridge: ${(error as Error).message}`
|
||||
);
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
if (!text) {
|
||||
throw new Error(
|
||||
`empty response from opencode-bridge (status ${response.status})`
|
||||
);
|
||||
}
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`non-JSON response from opencode-bridge (status ${response.status})`
|
||||
);
|
||||
}
|
||||
|
||||
return parsed as OpenCodeResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call GET /opencode-bridge/providers. Returns the parsed JSON response.
|
||||
* Throws on network error or non-2xx status.
|
||||
*/
|
||||
export async function callOpenCodeProviders(
|
||||
serverSettings: ServerConnection.ISettings
|
||||
): Promise<OpenCodeProvidersResponse> {
|
||||
const url = URLExt.join(
|
||||
serverSettings.baseUrl,
|
||||
'opencode-bridge',
|
||||
'providers'
|
||||
);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await ServerConnection.makeRequest(url, { method: 'GET' }, serverSettings);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`network error calling opencode-bridge/providers: ${(error as Error).message}`
|
||||
);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`opencode-bridge/providers failed: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
|
||||
return (await response.json()) as OpenCodeProvidersResponse;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Custom Cell.ContentFactory that adds our OpenCodeCellFooter to every cell.
|
||||
*
|
||||
* One factory instance per notebook; install via `installOpenCodeInNotebook`.
|
||||
*/
|
||||
import { ICellFooter } from '@jupyterlab/cells';
|
||||
import { Notebook } from '@jupyterlab/notebook';
|
||||
|
||||
import { OpenCodeCellFooter } from './opencode_cell_footer';
|
||||
|
||||
export class OpenCodeCellContentFactory extends Notebook.ContentFactory {
|
||||
createCellFooter(): ICellFooter {
|
||||
return new OpenCodeCellFooter();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* Per-cell footer widget: renders 3 buttons (optimize / fix / edit) and
|
||||
* wires them to the opencode-bridge server.
|
||||
*
|
||||
* Resolves its owning CodeCell at onAfterAttach via `this.parent`.
|
||||
* Subscribes to the cell model's contentChanged and stateChanged signals
|
||||
* to keep the context fresh.
|
||||
*/
|
||||
import { CodeCell } from '@jupyterlab/cells';
|
||||
import { Notification } from '@jupyterlab/apputils';
|
||||
import type { NotebookPanel } from '@jupyterlab/notebook';
|
||||
import { ServerConnection } from '@jupyterlab/services';
|
||||
import { Widget } from '@lumino/widgets';
|
||||
|
||||
import { callOpenCodeEdit } from '../api/opencode_client';
|
||||
import { extractCellContext } from '../context/cell_context';
|
||||
import type {
|
||||
CellContext,
|
||||
OpenCodeMode,
|
||||
OpenCodeRequest,
|
||||
OpenCodeResponse,
|
||||
OpenCodeSettings,
|
||||
} from '../types';
|
||||
|
||||
// Module-level runtime injection (set by index.ts after settings load).
|
||||
let _settings: OpenCodeSettings | null = null;
|
||||
let _serverSettings: ServerConnection.ISettings | null = null;
|
||||
|
||||
export function setOpenCodeRuntime(args: {
|
||||
settings: OpenCodeSettings;
|
||||
serverSettings: ServerConnection.ISettings;
|
||||
}): void {
|
||||
_settings = args.settings;
|
||||
_serverSettings = args.serverSettings;
|
||||
}
|
||||
|
||||
type Status = 'idle' | 'loading' | 'error';
|
||||
|
||||
export class OpenCodeCellFooter extends Widget {
|
||||
private _cell: CodeCell | null = null;
|
||||
private _context: CellContext | null = null;
|
||||
private _status: Status = 'idle';
|
||||
private _errorMessage: string | null = null;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.addClass('opencode-cell-footer');
|
||||
this._render();
|
||||
}
|
||||
|
||||
protected onAfterAttach(_msg: unknown): void {
|
||||
const parent = this.parent;
|
||||
if (parent instanceof CodeCell) {
|
||||
this._cell = parent;
|
||||
this._cell.model.contentChanged.connect(this._onModelChange, this);
|
||||
this._cell.model.stateChanged.connect(this._onModelChange, this);
|
||||
this._onModelChange();
|
||||
}
|
||||
}
|
||||
|
||||
protected onBeforeDetach(_msg: unknown): void {
|
||||
if (this._cell) {
|
||||
this._cell.model.contentChanged.disconnect(this._onModelChange, this);
|
||||
this._cell.model.stateChanged.disconnect(this._onModelChange, this);
|
||||
}
|
||||
this._cell = null;
|
||||
}
|
||||
|
||||
private _onModelChange(): void {
|
||||
this._context = this._cell ? extractCellContextFromCell(this._cell) : null;
|
||||
this._render();
|
||||
}
|
||||
|
||||
private _render(): void {
|
||||
const node = this.node;
|
||||
node.textContent = '';
|
||||
|
||||
const hasError = this._context?.error != null;
|
||||
const loading = this._status === 'loading';
|
||||
const baseDisabled = !this._context || 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));
|
||||
|
||||
if (this._status === 'error' && this._errorMessage) {
|
||||
const err = document.createElement('span');
|
||||
err.className = 'opencode-error';
|
||||
err.textContent = this._errorMessage;
|
||||
err.title = this._errorMessage;
|
||||
node.appendChild(err);
|
||||
}
|
||||
}
|
||||
|
||||
private async _onClick(mode: OpenCodeMode): Promise<void> {
|
||||
if (!this._context) {
|
||||
return;
|
||||
}
|
||||
if (!_settings || !_serverSettings) {
|
||||
Notification.error('OpenCode 运行时未初始化,请检查 settings');
|
||||
return;
|
||||
}
|
||||
|
||||
let prompt = '';
|
||||
if (mode === 'edit') {
|
||||
const input = window.prompt('请输入编辑指令:');
|
||||
if (input === null) {
|
||||
return;
|
||||
}
|
||||
prompt = input;
|
||||
}
|
||||
|
||||
const request: OpenCodeRequest = {
|
||||
mode,
|
||||
prompt,
|
||||
context: this._context,
|
||||
providerId: _settings.opencodeProvider || undefined,
|
||||
modelId: _settings.opencodeModel || undefined
|
||||
};
|
||||
|
||||
this._status = 'loading';
|
||||
this._errorMessage = null;
|
||||
this._render();
|
||||
|
||||
try {
|
||||
const resp = await callOpenCodeEdit(request, _serverSettings);
|
||||
this._handleResponse(resp);
|
||||
} catch (e) {
|
||||
this._status = 'error';
|
||||
this._errorMessage = (e as Error).message;
|
||||
this._render();
|
||||
Notification.error(`OpenCode ${mode} 失败: ${this._errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
private _handleResponse(resp: OpenCodeResponse): void {
|
||||
if (resp.ok) {
|
||||
this._status = 'idle';
|
||||
this._render();
|
||||
const len = resp.finalSource.length;
|
||||
Notification.info(
|
||||
`OpenCode ${resp.mode} 完成 (${len} chars). ` +
|
||||
`Diff 面板将在 Slice 4 中提供。Session: ${resp.sessionId.slice(0, 8)}…`
|
||||
);
|
||||
} else {
|
||||
this._status = 'error';
|
||||
this._errorMessage = resp.error;
|
||||
this._render();
|
||||
Notification.error(`OpenCode 错误: ${resp.error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a CodeCell's parent NotebookPanel by walking the parent chain,
|
||||
* then build the CellContext. The footer uses this rather than `Widget.findParent`
|
||||
* because that helper was removed in @lumino/widgets 2.x.
|
||||
*/
|
||||
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 &&
|
||||
candidate.content &&
|
||||
Array.isArray(candidate.content.widgets)
|
||||
) {
|
||||
notebookPanel = candidate;
|
||||
break;
|
||||
}
|
||||
node = node.parent;
|
||||
}
|
||||
if (!notebookPanel) {
|
||||
return null;
|
||||
}
|
||||
return extractCellContext(cell, notebookPanel);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Install the OpenCode cell factory on every notebook tracked by INotebookTracker.
|
||||
*
|
||||
* For already-open notebooks: swap their contentFactory in place. Cells created
|
||||
* after this point will use the new factory. (Cells already created retain their
|
||||
* old factory — that's a known limitation; users must reload the notebook to see
|
||||
* the footer in cells that were created before activation.)
|
||||
*
|
||||
* For future notebooks: listen to `tracker.widgetAdded` and swap on addition.
|
||||
*/
|
||||
import type { INotebookTracker, NotebookPanel } from '@jupyterlab/notebook';
|
||||
|
||||
import { OpenCodeCellContentFactory } from './opencode_cell_factory';
|
||||
|
||||
export function installOpenCodeInNotebook(panel: NotebookPanel): void {
|
||||
if (panel.content.contentFactory instanceof OpenCodeCellContentFactory) {
|
||||
return; // already installed
|
||||
}
|
||||
const existing = panel.content.contentFactory;
|
||||
const editorFactory = (existing as any).editorFactory;
|
||||
const factory = new OpenCodeCellContentFactory({ editorFactory });
|
||||
// contentFactory is readonly in the typings but writable at runtime.
|
||||
(panel.content as any).contentFactory = factory;
|
||||
}
|
||||
|
||||
export function installOpenCodeEverywhere(tracker: INotebookTracker): void {
|
||||
// Patch already-open notebooks.
|
||||
tracker.forEach(panel => {
|
||||
installOpenCodeInNotebook(panel);
|
||||
});
|
||||
// Patch future notebooks.
|
||||
tracker.widgetAdded.connect((_, panel) => {
|
||||
installOpenCodeInNotebook(panel);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Extract a CellContext snapshot from a CodeCell + its parent NotebookPanel.
|
||||
*
|
||||
* Pure functions, no DOM, no signals — testable with plain object mocks.
|
||||
*/
|
||||
import type { CodeCell, ICodeCellModel } from '@jupyterlab/cells';
|
||||
import type { NotebookPanel } from '@jupyterlab/notebook';
|
||||
|
||||
import type { CellContext, ErrorOutput } from '../types';
|
||||
|
||||
/**
|
||||
* Find the first error output in a code cell's outputs.
|
||||
* Returns null if the cell has no error output or is not a code cell.
|
||||
*/
|
||||
export function collectErrorOutputs(model: ICodeCellModel): ErrorOutput | null {
|
||||
const outputs = model.outputs;
|
||||
for (let i = 0; i < outputs.length; i++) {
|
||||
const out = outputs.get(i);
|
||||
if (out && out.type === 'error') {
|
||||
const e = out as {
|
||||
ename?: unknown;
|
||||
evalue?: unknown;
|
||||
traceback?: unknown;
|
||||
};
|
||||
return {
|
||||
ename: String(e.ename ?? ''),
|
||||
evalue: String(e.evalue ?? ''),
|
||||
traceback: Array.isArray(e.traceback) ? (e.traceback as string[]) : [],
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a CellContext from a CodeCell and its parent NotebookPanel.
|
||||
* Returns null if essential data is missing.
|
||||
*
|
||||
* @param cell The code cell to inspect.
|
||||
* @param panel The notebook panel that contains the cell.
|
||||
*/
|
||||
export function extractCellContext(
|
||||
cell: CodeCell,
|
||||
panel: NotebookPanel
|
||||
): CellContext | null {
|
||||
if (!cell || !panel) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cells = panel.content.widgets;
|
||||
const cellIndex = cells ? cells.indexOf(cell) : -1;
|
||||
if (cellIndex < 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const totalCells = cells ? cells.length : 0;
|
||||
const previousCell = cellIndex > 0 ? cells[cellIndex - 1] : null;
|
||||
const previousCode = previousCell
|
||||
? previousCell.model.sharedModel.getSource()
|
||||
: null;
|
||||
|
||||
// Language: use 'python' as default for code cells.
|
||||
// Future improvement: read from kernel info_reply.
|
||||
const language = 'python';
|
||||
|
||||
let error: ErrorOutput | null = null;
|
||||
if (cell.model.type === 'code') {
|
||||
error = collectErrorOutputs(cell.model as ICodeCellModel);
|
||||
}
|
||||
|
||||
return {
|
||||
notebookPath: panel.context.path,
|
||||
cellId: cell.model.id,
|
||||
language,
|
||||
cellIndex,
|
||||
totalCells,
|
||||
source: cell.model.sharedModel.getSource(),
|
||||
previousCode,
|
||||
error,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
JupyterFrontEnd,
|
||||
JupyterFrontEndPlugin
|
||||
} from '@jupyterlab/application';
|
||||
|
||||
import { INotebookTracker } from '@jupyterlab/notebook';
|
||||
import { ISettingRegistry } from '@jupyterlab/settingregistry';
|
||||
|
||||
import { installOpenCodeEverywhere } from './components/opencode_installer';
|
||||
import { setOpenCodeRuntime } from './components/opencode_cell_footer';
|
||||
import { requestAPI } from './request';
|
||||
import { readOpenCodeSettings } from './types';
|
||||
import { callOpenCodeProviders } from './api/opencode_client';
|
||||
|
||||
/**
|
||||
* Initialization data for the opencode_bridge extension.
|
||||
*/
|
||||
const plugin: JupyterFrontEndPlugin<void> = {
|
||||
id: 'opencode_bridge:plugin',
|
||||
description: 'A JupyterLab extension bridging the UI to OpenCode Serve.',
|
||||
autoStart: true,
|
||||
optional: [ISettingRegistry],
|
||||
requires: [INotebookTracker],
|
||||
activate: (
|
||||
app: JupyterFrontEnd,
|
||||
tracker: INotebookTracker,
|
||||
settingRegistry: ISettingRegistry | null
|
||||
) => {
|
||||
console.log('JupyterLab extension opencode_bridge is activated!');
|
||||
|
||||
// Install the per-cell footer factory on every notebook.
|
||||
installOpenCodeEverywhere(tracker);
|
||||
|
||||
// Load settings + push into toolbar module.
|
||||
if (settingRegistry) {
|
||||
void settingRegistry
|
||||
.load(plugin.id)
|
||||
.then(settings => {
|
||||
const bridge = readOpenCodeSettings(settings.composite);
|
||||
setOpenCodeRuntime({
|
||||
settings: bridge,
|
||||
serverSettings: app.serviceManager.serverSettings
|
||||
});
|
||||
console.log('opencode_bridge settings loaded:', bridge);
|
||||
|
||||
void callOpenCodeProviders(app.serviceManager.serverSettings)
|
||||
.then(data => {
|
||||
const lines: string[] = ['[opencode_bridge] Available OpenCode providers:'];
|
||||
for (const p of data.providers) {
|
||||
const models = p.models.map(m => m.id).join(', ');
|
||||
lines.push(` - ${p.id}: ${models || '(no models)'}`);
|
||||
}
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(lines.join('\n'));
|
||||
})
|
||||
.catch(reason => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(
|
||||
'[opencode_bridge] Could not fetch providers (is the opencode-bridge server extension enabled and opencode serve running?):',
|
||||
reason
|
||||
);
|
||||
});
|
||||
})
|
||||
.catch(reason => {
|
||||
console.error('Failed to load settings for opencode_bridge.', reason);
|
||||
});
|
||||
}
|
||||
|
||||
requestAPI<unknown>('hello', app.serviceManager.serverSettings)
|
||||
.then(data => {
|
||||
console.log('hello endpoint:', data);
|
||||
})
|
||||
.catch(reason => {
|
||||
console.error(
|
||||
`The opencode_bridge server extension appears to be missing.\n${reason}`
|
||||
);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default plugin;
|
||||
@@ -0,0 +1,51 @@
|
||||
import { URLExt } from '@jupyterlab/coreutils';
|
||||
|
||||
import { ServerConnection } from '@jupyterlab/services';
|
||||
|
||||
/**
|
||||
* Call the server extension
|
||||
*
|
||||
* @param endPoint API REST end point for the extension
|
||||
* @param serverSettings The server settings to use for the request
|
||||
* @param init Initial values for the request
|
||||
* @returns The response body interpreted as JSON
|
||||
*/
|
||||
export async function requestAPI<T>(
|
||||
endPoint: string,
|
||||
serverSettings: ServerConnection.ISettings,
|
||||
init: RequestInit = {}
|
||||
): Promise<T> {
|
||||
// Make request to Jupyter API
|
||||
const requestUrl = URLExt.join(
|
||||
serverSettings.baseUrl,
|
||||
'opencode-bridge', // our server extension's API namespace
|
||||
endPoint
|
||||
);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await ServerConnection.makeRequest(
|
||||
requestUrl,
|
||||
init,
|
||||
serverSettings
|
||||
);
|
||||
} catch (error) {
|
||||
throw new ServerConnection.NetworkError(error as any);
|
||||
}
|
||||
|
||||
let data: any = await response.text();
|
||||
|
||||
if (data.length > 0) {
|
||||
try {
|
||||
data = JSON.parse(data);
|
||||
} catch (error) {
|
||||
console.log('Not a JSON response body.', response);
|
||||
}
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ServerConnection.ResponseError(response, data.message || data);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Shared types for the opencode-bridge frontend.
|
||||
*
|
||||
* These mirror the Python server's `CellContext` / `OpenCodeRequest` / `OpenCodeResponse`
|
||||
* shapes in `opencode_bridge/routes.py`. Keep them in sync.
|
||||
*/
|
||||
|
||||
export interface ErrorOutput {
|
||||
ename: string;
|
||||
evalue: string;
|
||||
traceback: string[];
|
||||
}
|
||||
|
||||
export interface CellContext {
|
||||
notebookPath: string;
|
||||
cellId: string;
|
||||
language: string;
|
||||
cellIndex: number;
|
||||
totalCells: number;
|
||||
source: string;
|
||||
previousCode: string | null;
|
||||
error: ErrorOutput | null;
|
||||
}
|
||||
|
||||
export type OpenCodeMode = 'optimize' | 'fix' | 'edit';
|
||||
|
||||
export interface OpenCodeRequest {
|
||||
mode: OpenCodeMode;
|
||||
prompt: string;
|
||||
context: CellContext;
|
||||
providerId?: string;
|
||||
modelId?: string;
|
||||
}
|
||||
|
||||
export interface OpenCodeSuccess {
|
||||
ok: true;
|
||||
mode: OpenCodeMode;
|
||||
finalSource: string;
|
||||
sessionId: string;
|
||||
notebookPath: string;
|
||||
}
|
||||
|
||||
export interface OpenCodeFailure {
|
||||
ok: false;
|
||||
error: string;
|
||||
}
|
||||
|
||||
export type OpenCodeResponse = OpenCodeSuccess | OpenCodeFailure;
|
||||
|
||||
/** Frontend view of the 4 schema/plugin.json fields. */
|
||||
export interface OpenCodeSettings {
|
||||
opencodeServerUrl: string;
|
||||
opencodeServerUser: string;
|
||||
opencodeServerPassword: string;
|
||||
requestTimeoutSeconds: number;
|
||||
opencodeProvider: string;
|
||||
opencodeModel: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_OPENCODE_SETTINGS: OpenCodeSettings = {
|
||||
opencodeServerUrl: 'http://127.0.0.1:4096',
|
||||
opencodeServerUser: 'opencode',
|
||||
opencodeServerPassword: '',
|
||||
requestTimeoutSeconds: 120,
|
||||
opencodeProvider: '',
|
||||
opencodeModel: '',
|
||||
};
|
||||
|
||||
export function readOpenCodeSettings(composite: unknown): OpenCodeSettings {
|
||||
const c = (composite ?? {}) as Partial<OpenCodeSettings>;
|
||||
return {
|
||||
opencodeServerUrl: c.opencodeServerUrl || DEFAULT_OPENCODE_SETTINGS.opencodeServerUrl,
|
||||
opencodeServerUser: c.opencodeServerUser || DEFAULT_OPENCODE_SETTINGS.opencodeServerUser,
|
||||
opencodeServerPassword: c.opencodeServerPassword || '',
|
||||
requestTimeoutSeconds:
|
||||
typeof c.requestTimeoutSeconds === 'number'
|
||||
? c.requestTimeoutSeconds
|
||||
: DEFAULT_OPENCODE_SETTINGS.requestTimeoutSeconds,
|
||||
opencodeProvider: c.opencodeProvider || '',
|
||||
opencodeModel: c.opencodeModel || '',
|
||||
};
|
||||
}
|
||||
|
||||
/** Response from GET /opencode-bridge/providers. */
|
||||
export interface OpenCodeProvider {
|
||||
id: string;
|
||||
models: { id: string; [k: string]: unknown }[];
|
||||
}
|
||||
|
||||
export interface OpenCodeProvidersResponse {
|
||||
providers: OpenCodeProvider[];
|
||||
}
|
||||
Reference in New Issue
Block a user