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
+36
View File
@@ -0,0 +1,36 @@
try:
from ._version import __version__
except ImportError:
# Fallback when using the package in dev mode without installing
# in editable mode with pip. It is highly recommended to install
# the package from a stable release or in editable mode: https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs
import warnings
warnings.warn("Importing 'opencode_bridge' outside a proper installation.")
__version__ = "dev"
from .routes import setup_route_handlers
def _jupyter_labextension_paths():
return [{
"src": "labextension",
"dest": "opencode_bridge"
}]
def _jupyter_server_extension_points():
return [{
"module": "opencode_bridge"
}]
def _load_jupyter_server_extension(server_app):
"""Registers the API handler to receive HTTP requests from the frontend extension.
Parameters
----------
server_app: jupyterlab.labapp.LabApp
JupyterLab application instance
"""
setup_route_handlers(server_app.web_app)
name = "opencode_bridge"
server_app.log.info(f"Registered {name} server extension")
+51
View File
@@ -0,0 +1,51 @@
"""Configuration resolution for the opencode-bridge extension.
Priority order (highest to lowest):
1. jupyter settings dict (from schema/plugin.json)
2. Environment variables (OPENCODE_BRIDGE_URL, _USER, _PASSWORD)
3. Built-in defaults
"""
from __future__ import annotations
import os
from typing import NamedTuple, Optional, Tuple
ENV_URL = "OPENCODE_BRIDGE_URL"
ENV_USER = "OPENCODE_BRIDGE_USER"
ENV_PASSWORD = "OPENCODE_BRIDGE_PASSWORD"
DEFAULT_URL = "http://127.0.0.1:4096"
DEFAULT_USER = "opencode"
DEFAULT_REQUEST_TIMEOUT = 120
class OpenCodeConfig(NamedTuple):
url: str
user: str
password: str
request_timeout_seconds: int = DEFAULT_REQUEST_TIMEOUT
@property
def auth(self) -> Optional[Tuple[str, str]]:
"""Return (user, password) for HTTP Basic Auth, or None if no password set."""
if not self.password:
return None
return (self.user, self.password)
def resolve_config(jupyter_settings: dict) -> OpenCodeConfig:
"""Resolve OpenCode connection config from jupyter settings + env + defaults."""
bridge = jupyter_settings.get("opencode_bridge", {}) or {}
return OpenCodeConfig(
url=bridge.get("opencodeServerUrl") or os.environ.get(ENV_URL) or DEFAULT_URL,
user=bridge.get("opencodeServerUser") or os.environ.get(ENV_USER) or DEFAULT_USER,
password=(
bridge.get("opencodeServerPassword")
or os.environ.get(ENV_PASSWORD)
or ""
),
request_timeout_seconds=int(
bridge.get("requestTimeoutSeconds", DEFAULT_REQUEST_TIMEOUT)
),
)
+106
View File
@@ -0,0 +1,106 @@
"""Async HTTP client for the local OpenCode server."""
import json
from typing import Any, Optional
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.httputil import HTTPHeaders
from .config import OpenCodeConfig
class OpenCodeError(Exception):
"""Raised when an OpenCode API request fails."""
class OpenCodeClient:
def __init__(
self,
config: OpenCodeConfig,
http_client: Optional[AsyncHTTPClient] = None,
) -> None:
self._config = config
self._http_client = http_client or AsyncHTTPClient()
async def health(self) -> dict[str, Any]:
return await self._request("GET", "/global/health")
async def list_providers(self) -> list[dict[str, Any]]:
return await self._request("GET", "/config/providers")
async def create_session(self, title: str) -> dict[str, Any]:
return await self._request("POST", "/session", {"title": title})
async def send_message_sync(
self,
session_id: str,
parts: list[dict[str, Any]],
provider_id: Optional[str] = None,
model_id: Optional[str] = None,
system: Optional[str] = None,
) -> dict[str, Any]:
body: dict[str, Any] = {"parts": parts}
if provider_id is not None and model_id is not None:
body["model"] = {"providerID": provider_id, "modelID": model_id}
if system is not None:
body["system"] = system
return await self._request(
"POST",
"/session/%s/message" % session_id,
body,
)
async def abort(self, session_id: str) -> bool:
result = await self._request("POST", "/session/%s/abort" % session_id)
return result is not None
async def delete_session(self, session_id: str) -> bool:
result = await self._request("DELETE", "/session/%s" % session_id)
return result is not None
@property
def endpoint(self) -> str:
return self._config.url
async def _request(
self,
method: str,
path: str,
body: Optional[dict[str, Any]] = None,
) -> Optional[Any]:
url = self._config.url + path
headers = HTTPHeaders(
{
"Content-Type": "application/json",
"Accept": "application/json",
}
)
request_kwargs: dict[str, Any] = {
"method": method,
"headers": headers,
"request_timeout": self._config.request_timeout_seconds,
}
if body is not None:
request_kwargs["body"] = json.dumps(body).encode("utf-8")
request = HTTPRequest(url, **request_kwargs)
fetch_kwargs: dict[str, str] = {}
if self._config.auth is not None:
fetch_kwargs["auth_username"] = self._config.auth[0]
fetch_kwargs["auth_password"] = self._config.auth[1]
response = await self._http_client.fetch(request, **fetch_kwargs)
if 200 <= response.code < 300:
if not response.body:
return True
return json.loads(response.body.decode("utf-8"))
if response.code == 404:
return None
response_body = response.body.decode("utf-8") if response.body else ""
raise OpenCodeError(
"OpenCode request %s %s failed with status %s: %s"
% (method, url, response.code, response_body)
)
+263
View File
@@ -0,0 +1,263 @@
import json
import logging
from jupyter_server.base.handlers import APIHandler
from jupyter_server.utils import url_path_join
import tornado
from .config import resolve_config
from .opencode_client import OpenCodeClient, OpenCodeError
from .session_manager import SessionManager
log = logging.getLogger("opencode_bridge.routes")
MODE_SYSTEM_PROMPTS = {
"optimize": (
"你是一个代码优化专家。请基于用户提供的代码上下文,"
"返回只包含优化后代码的回复,不要任何解释或 markdown 围栏。"
),
"fix": (
"你是一个 Python 排错专家。用户给出了一段产生错误的代码和 traceback,"
"请返回只包含修复后代码的回复,不要任何解释或 markdown 围栏。"
),
"edit": (
"你是一个代码编辑助手。基于用户的指令修改给定代码,"
"返回只包含修改后完整代码的回复,不要任何解释或 markdown 围栏。"
),
}
def make_client(handler: APIHandler) -> OpenCodeClient:
"""Factory for OpenCodeClient. Tests monkey-patch this."""
cfg = resolve_config(handler.settings.get("opencode_bridge", {}))
return OpenCodeClient(cfg)
def get_session_manager(handler: APIHandler) -> SessionManager:
"""Return the SessionManager singleton for this web app, creating on first use.
Stored in handler.settings["opencode_bridge_session_manager"] so it survives
across requests but is per-server-instance. Tests monkey-patch this.
"""
sm = handler.settings.get("opencode_bridge_session_manager")
if sm is None:
def client_factory() -> OpenCodeClient:
cfg = resolve_config(handler.settings.get("opencode_bridge", {}))
return OpenCodeClient(cfg)
sm = SessionManager(client_factory)
handler.settings["opencode_bridge_session_manager"] = sm
return sm
def _build_request_body(mode: str, prompt: str, context: dict) -> dict:
"""Build full request body for OpenCode POST /session/:id/message.
Returns dict with 'parts' (list) and 'system' (str) keys.
"""
system = MODE_SYSTEM_PROMPTS[mode]
parts: list[dict] = []
if context.get("previousCode"):
parts.append({
"type": "text",
"text": "<previous_cell>\n%s\n</previous_cell>\n" % context["previousCode"],
})
error = context.get("error")
if error:
parts.append({
"type": "text",
"text": (
"<traceback>\n%s: %s\n" % (error["ename"], error["evalue"])
+ "\n".join(error.get("traceback", []))
+ "\n</traceback>\n"
),
})
parts.append({
"type": "text",
"text": "<cell language='%s'>\n%s\n</cell>\n" % (
context.get("language", "python"),
context["source"],
),
})
if mode == "edit" and prompt:
parts.append({"type": "text", "text": "<instruction>\n%s\n</instruction>" % prompt})
return {"parts": parts, "system": system}
def _strip_code_fence(s: str) -> str:
"""Strip ```language ... ``` fences from LLM output."""
s = s.strip()
if s.startswith("```"):
lines = s.split("\n")
if lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].startswith("```"):
lines = lines[:-1]
return "\n".join(lines).strip()
return s
class HelloRouteHandler(APIHandler):
# The following decorator should be present on all verb methods (head, get, post,
# patch, put, delete, options) to ensure only authorized user can request the
# Jupyter server
@tornado.web.authenticated
def get(self):
self.finish(json.dumps({
"data": (
"Hello, world!"
" This is the '/opencode-bridge/hello' endpoint."
" Try visiting me in your browser!"
),
}))
class HealthHandler(APIHandler):
@tornado.web.authenticated
async def get(self):
try:
client = make_client(self)
data = await client.health()
self.finish(json.dumps({
"ok": data.get("healthy", False),
"version": data.get("version"),
"endpoint": client.endpoint,
}))
except Exception as e:
log.exception("health check failed")
self.set_status(503)
self.finish(json.dumps({
"ok": False,
"error": str(e),
"endpoint": make_client(self).endpoint,
}))
class ProvidersHandler(APIHandler):
@tornado.web.authenticated
async def get(self):
try:
data = await make_client(self).list_providers()
self.finish(json.dumps(data))
except Exception as e:
log.exception("providers list failed")
self.set_status(502)
self.finish(json.dumps({"error": str(e)}))
class EditHandler(APIHandler):
@tornado.web.authenticated
async def post(self):
try:
body = json.loads(self.request.body)
mode = body["mode"]
prompt = body.get("prompt", "")
context = body["context"]
provider_id = body.get("providerId") or None
model_id = body.get("modelId") or None
notebook_path = context.get("notebookPath", "")
except (KeyError, json.JSONDecodeError) as e:
self.set_status(400)
self.finish(json.dumps({"error": "bad request: %s" % e}))
return
if not notebook_path:
self.set_status(400)
self.finish(json.dumps({"error": "missing context.notebookPath"}))
return
client = make_client(self)
sm = get_session_manager(self)
try:
sid = await sm.get_or_create(notebook_path)
request_body = _build_request_body(mode, prompt, context)
result = await client.send_message_sync(
sid,
request_body["parts"],
provider_id=provider_id,
model_id=model_id,
system=request_body["system"],
)
text_parts = [
p.get("text", "")
for p in result.get("parts", [])
if p.get("type") == "text"
]
final_source = _strip_code_fence("\n".join(text_parts).strip())
self.finish(json.dumps({
"ok": True,
"mode": mode,
"finalSource": final_source,
"sessionId": sid,
"notebookPath": notebook_path,
}))
except OpenCodeError as e:
# If session is invalid on OpenCode side, invalidate cache.
# 404 / 410 / "session not found" -> next get_or_create will recreate.
if "404" in str(e) or "not found" in str(e).lower():
sm.invalidate(notebook_path)
log.warning("invalidated dead session for %s", notebook_path)
log.exception("edit failed")
self.set_status(502)
self.finish(json.dumps({"ok": False, "error": str(e)}))
except Exception as e:
log.exception("edit failed")
self.set_status(502)
self.finish(json.dumps({"ok": False, "error": str(e)}))
# NO finally delete — session is reused per notebook.
class SessionListHandler(APIHandler):
"""List all active notebook -> session mappings. Debug endpoint."""
@tornado.web.authenticated
def get(self):
sm = get_session_manager(self)
self.finish(json.dumps({"sessions": sm.list_sessions()}))
class SessionReleaseHandler(APIHandler):
"""Release the OpenCode session for a specific notebook.
Query param: notebook=<notebook path, URL-encoded>
"""
@tornado.web.authenticated
async def delete(self):
notebook_path = self.get_query_argument("notebook", "")
if not notebook_path:
self.set_status(400)
self.finish(json.dumps({"error": "missing 'notebook' query parameter"}))
return
sm = get_session_manager(self)
deleted = await sm.release(notebook_path)
self.finish(json.dumps({
"ok": True,
"notebookPath": notebook_path,
"deleted": deleted,
}))
def setup_route_handlers(web_app):
host_pattern = ".*$"
base_url = web_app.settings["base_url"]
handlers = [
(url_path_join(base_url, "opencode-bridge", "hello"), HelloRouteHandler),
(url_path_join(base_url, "opencode-bridge", "health"), HealthHandler),
(url_path_join(base_url, "opencode-bridge", "providers"), ProvidersHandler),
(url_path_join(base_url, "opencode-bridge", "edit"), EditHandler),
(url_path_join(base_url, "opencode-bridge", "sessions"), SessionListHandler),
(url_path_join(base_url, "opencode-bridge", "session"), SessionReleaseHandler),
]
web_app.add_handlers(host_pattern, handlers)
+90
View File
@@ -0,0 +1,90 @@
"""Per-notebook session manager for OpenCode.
Maps notebookPath -> OpenCode sessionID. Lazy create on first use.
Async-safe via per-path asyncio.Lock. No automatic cleanup.
"""
from __future__ import annotations
import asyncio
import logging
from typing import Callable
from .opencode_client import OpenCodeClient
log = logging.getLogger("opencode_bridge.session_manager")
ClientFactory = Callable[[], OpenCodeClient]
class SessionManager:
"""Tracks one OpenCode session per notebook path.
Threading/async model:
- Multiple coroutines may call get_or_create for the same notebook.
- First call creates; subsequent calls return the same sessionID.
- Per-notebook asyncio.Lock prevents double-create under concurrency.
- Locks remain in the map; they may be needed again for the same path.
"""
def __init__(self, client_factory: ClientFactory) -> None:
self._client_factory = client_factory
self._sessions: dict[str, str] = {} # notebookPath -> sessionID
self._locks: dict[str, asyncio.Lock] = {} # notebookPath -> lock
self._titles: dict[str, str] = {} # notebookPath -> title (for debug)
async def get_or_create(self, notebook_path: str) -> str:
"""Return session ID for the notebook, creating one if needed.
Idempotent for the same path. Different paths get different sessions.
"""
existing = self._sessions.get(notebook_path)
if existing is not None:
return existing
lock = self._locks.setdefault(notebook_path, asyncio.Lock())
async with lock:
existing = self._sessions.get(notebook_path)
if existing is not None:
return existing
client = self._client_factory()
session = await client.create_session(
title="jupyter:%s" % notebook_path
)
sid = session["id"]
self._sessions[notebook_path] = sid
self._titles[notebook_path] = notebook_path
log.info("created opencode session %s for %s", sid, notebook_path)
return sid
async def release(self, notebook_path: str) -> bool:
"""Delete session and remove from map. Returns True if a session existed."""
sid = self._sessions.pop(notebook_path, None)
self._titles.pop(notebook_path, None)
self._locks.pop(notebook_path, None)
if sid is None:
return False
try:
client = self._client_factory()
return await client.delete_session(sid)
except Exception:
log.warning(
"failed to delete opencode session %s for %s", sid, notebook_path
)
return False
def invalidate(self, notebook_path: str) -> bool:
"""Drop the cached sessionID without calling OpenCode. Returns True if removed.
Use this when an upstream error indicates the session is dead (e.g., 404).
"""
sid = self._sessions.pop(notebook_path, None)
self._titles.pop(notebook_path, None)
return sid is not None
def has_session(self, notebook_path: str) -> bool:
return notebook_path in self._sessions
def list_sessions(self) -> list[dict]:
return [
{"notebookPath": path, "sessionId": sid}
for path, sid in sorted(self._sessions.items())
]
+1
View File
@@ -0,0 +1 @@
"""Python unit tests for opencode_bridge."""
+149
View File
@@ -0,0 +1,149 @@
"""Tests for opencode_bridge.opencode_client."""
import json
from io import BytesIO
import pytest
import tornado.httpclient
import tornado.httputil
from opencode_bridge.config import OpenCodeConfig
from opencode_bridge.opencode_client import OpenCodeClient, OpenCodeError
class MockHTTPClient:
def __init__(self) -> None:
self.calls: list[dict] = []
self.responses: list[tuple[int, object]] = []
async def fetch(self, request, **kwargs) -> tornado.httpclient.HTTPResponse:
self.calls.append({"request": request, "kwargs": kwargs})
status, body = self.responses.pop(0)
buffer = BytesIO(json.dumps(body).encode("utf-8"))
return tornado.httpclient.HTTPResponse(
request=request,
code=status,
headers=tornado.httputil.HTTPHeaders(),
buffer=buffer,
)
@pytest.fixture
def base_config() -> OpenCodeConfig:
return OpenCodeConfig(
url="http://127.0.0.1:4096",
user="opencode",
password="",
request_timeout_seconds=120,
)
def _make_client(config: OpenCodeConfig, responses: list[tuple[int, object]]) -> tuple[OpenCodeClient, MockHTTPClient]:
mock = MockHTTPClient()
mock.responses = responses
return OpenCodeClient(config, http_client=mock), mock
@pytest.mark.asyncio
async def test_health_gets_global_health(base_config: OpenCodeConfig) -> None:
client, mock = _make_client(base_config, [(200, {"status": "ok"})])
result = await client.health()
assert result == {"status": "ok"}
assert len(mock.calls) == 1
call = mock.calls[0]
assert call["request"].url == "http://127.0.0.1:4096/global/health"
assert call["request"].method == "GET"
@pytest.mark.asyncio
async def test_create_session_posts_title(base_config: OpenCodeConfig) -> None:
client, mock = _make_client(base_config, [(200, {"id": "s1"})])
result = await client.create_session("foo")
assert result == {"id": "s1"}
call = mock.calls[0]
assert call["request"].url == "http://127.0.0.1:4096/session"
assert call["request"].method == "POST"
body = json.loads(call["request"].body.decode("utf-8"))
assert body == {"title": "foo"}
@pytest.mark.asyncio
async def test_auth_in_fetch_kwargs_when_password_set(base_config: OpenCodeConfig) -> None:
config = base_config._replace(password="secret")
client, mock = _make_client(config, [(200, {"status": "ok"})])
await client.health()
call = mock.calls[0]
assert call["kwargs"].get("auth_username") == "opencode"
assert call["kwargs"].get("auth_password") == "secret"
@pytest.mark.asyncio
async def test_auth_not_in_fetch_kwargs_when_password_empty(base_config: OpenCodeConfig) -> None:
client, mock = _make_client(base_config, [(200, {"status": "ok"})])
await client.health()
call = mock.calls[0]
assert "auth_username" not in call["kwargs"]
assert "auth_password" not in call["kwargs"]
@pytest.mark.asyncio
async def test_send_message_sync_includes_model_when_provider_and_model_given(
base_config: OpenCodeConfig,
) -> None:
client, mock = _make_client(base_config, [(200, {"done": True})])
parts = [{"type": "text", "text": "hello"}]
result = await client.send_message_sync("s1", parts, provider_id="p1", model_id="m1")
assert result == {"done": True}
call = mock.calls[0]
assert call["request"].url == "http://127.0.0.1:4096/session/s1/message"
body = json.loads(call["request"].body.decode("utf-8"))
assert body["parts"] == parts
assert body["model"] == {"providerID": "p1", "modelID": "m1"}
@pytest.mark.asyncio
async def test_send_message_sync_omits_model_when_provider_or_model_missing(
base_config: OpenCodeConfig,
) -> None:
client, mock = _make_client(base_config, [(200, {"done": True})])
parts = [{"type": "text", "text": "hello"}]
result = await client.send_message_sync("s1", parts)
assert result == {"done": True}
call = mock.calls[0]
body = json.loads(call["request"].body.decode("utf-8"))
assert body["parts"] == parts
assert "model" not in body
@pytest.mark.asyncio
async def test_send_message_sync_includes_system_when_provided() -> None:
"""system param is forwarded into the request body when not None."""
config = OpenCodeConfig(url="http://x:1", user="u", password="")
mock = MockHTTPClient()
mock.responses.append((200, {"info": {}, "parts": []}))
client = OpenCodeClient(config, http_client=mock)
await client.send_message_sync("sid", [{"type": "text", "text": "hi"}], system="be brief")
assert len(mock.calls) == 1
body = json.loads(mock.calls[0]["request"].body.decode("utf-8"))
assert body["system"] == "be brief"
assert body["parts"] == [{"type": "text", "text": "hi"}]
@pytest.mark.asyncio
async def test_delete_session_returns_bool_by_status(base_config: OpenCodeConfig) -> None:
client, mock = _make_client(base_config, [(200, True), (404, False)])
assert await client.delete_session("s1") is True
assert await client.delete_session("s1") is False
assert len(mock.calls) == 2
assert mock.calls[0]["request"].method == "DELETE"
assert mock.calls[0]["request"].url == "http://127.0.0.1:4096/session/s1"
@pytest.mark.asyncio
async def test_non_2xx_response_raises_with_body(base_config: OpenCodeConfig) -> None:
client, mock = _make_client(base_config, [(500, {"error": "boom"})])
with pytest.raises(OpenCodeError) as exc_info:
await client.health()
assert "boom" in str(exc_info.value)
+54
View File
@@ -0,0 +1,54 @@
"""Tests for opencode_bridge.config."""
from opencode_bridge.config import OpenCodeConfig, resolve_config
def test_all_defaults() -> None:
config = resolve_config({})
assert config.url == "http://127.0.0.1:4096"
assert config.user == "opencode"
assert config.password == ""
assert config.request_timeout_seconds == 120
def test_env_url_overrides_default(monkeypatch) -> None:
monkeypatch.setenv("OPENCODE_BRIDGE_URL", "http://x:1")
config = resolve_config({})
assert config.url == "http://x:1"
def test_jupyter_settings_override_env(monkeypatch) -> None:
monkeypatch.setenv("OPENCODE_BRIDGE_URL", "http://x:1")
settings = {"opencode_bridge": {"opencodeServerUrl": "http://y:2"}}
config = resolve_config(settings)
assert config.url == "http://y:2"
def test_all_env_vars(monkeypatch) -> None:
monkeypatch.setenv("OPENCODE_BRIDGE_URL", "http://x:1")
monkeypatch.setenv("OPENCODE_BRIDGE_USER", "u")
monkeypatch.setenv("OPENCODE_BRIDGE_PASSWORD", "p")
config = resolve_config({})
assert config.url == "http://x:1"
assert config.user == "u"
assert config.password == "p"
def test_auth_none_when_password_empty() -> None:
config = resolve_config({})
assert config.auth is None
def test_auth_when_password_set() -> None:
config = OpenCodeConfig(
url="http://127.0.0.1:4096",
user="opencode",
password="secret",
)
assert config.auth == ("opencode", "secret")
def test_request_timeout_from_settings() -> None:
settings = {"opencode_bridge": {"requestTimeoutSeconds": 300}}
config = resolve_config(settings)
assert config.request_timeout_seconds == 300
+198
View File
@@ -0,0 +1,198 @@
import json
class FakeOpenCodeClient:
"""Drop-in replacement for OpenCodeClient with recording + canned responses."""
def __init__(self):
self.calls = []
self.session_id = "fake-session-123"
self.health_response = {"healthy": True, "version": "0.1.0"}
self.providers_response = {"providers": [{"id": "anthropic", "models": [{"id": "claude"}]}]}
self.message_response = {
"info": {"id": "msg-1"},
"parts": [{"type": "text", "text": "def foo():\n return 42\n"}],
}
@property
def endpoint(self):
return "http://fake-opencode"
async def health(self):
self.calls.append(("health",))
return self.health_response
async def list_providers(self):
self.calls.append(("list_providers",))
return self.providers_response
async def create_session(self, title):
self.calls.append(("create_session", title))
return {"id": self.session_id, "title": title}
async def send_message_sync(self, session_id, parts, provider_id=None, model_id=None, system=None):
self.calls.append(("send_message_sync", session_id, parts, system))
return self.message_response
async def delete_session(self, session_id):
self.calls.append(("delete_session", session_id))
return True
class FakeSessionManager:
"""Drop-in replacement for SessionManager with recording."""
def __init__(self, session_id: str = "fake-session-123") -> None:
self._session_id = session_id
self.calls: list = []
async def get_or_create(self, notebook_path: str) -> str:
self.calls.append(("get_or_create", notebook_path))
return self._session_id
async def release(self, notebook_path: str) -> bool:
self.calls.append(("release", notebook_path))
return True
def list_sessions(self) -> list:
return [
{"notebookPath": path, "sessionId": sid}
for path, sid in sorted(self._sessions.items())
]
def invalidate(self, notebook_path: str) -> bool:
self.calls.append(("invalidate", notebook_path))
return True
async def test_hello(jp_fetch):
# When
response = await jp_fetch("opencode-bridge", "hello")
# Then
assert response.code == 200
payload = json.loads(response.body)
assert payload == {
"data": (
"Hello, world!"
" This is the '/opencode-bridge/hello' endpoint."
" Try visiting me in your browser!"
),
}
async def test_health_handler(monkeypatch, jp_fetch):
fake = FakeOpenCodeClient()
monkeypatch.setattr("opencode_bridge.routes.make_client", lambda h: fake)
response = await jp_fetch("opencode-bridge", "health")
assert response.code == 200
payload = json.loads(response.body)
assert payload["ok"] is True
assert payload["version"] == "0.1.0"
assert ("health",) in fake.calls
async def test_providers_handler(monkeypatch, jp_fetch):
fake = FakeOpenCodeClient()
monkeypatch.setattr("opencode_bridge.routes.make_client", lambda h: fake)
response = await jp_fetch("opencode-bridge", "providers")
assert response.code == 200
payload = json.loads(response.body)
assert "providers" in payload
assert payload["providers"][0]["id"] == "anthropic"
assert ("list_providers",) in fake.calls
async def test_edit_handler(monkeypatch, jp_fetch):
fake = FakeOpenCodeClient()
monkeypatch.setattr("opencode_bridge.routes.make_client", lambda h: fake)
fake_sm = FakeSessionManager(session_id="fake-session-123")
monkeypatch.setattr(
"opencode_bridge.routes.get_session_manager", lambda h: fake_sm
)
body = json.dumps({
"mode": "edit",
"prompt": "Add type hints",
"context": {
"notebookPath": "test.ipynb",
"cellId": "cell-1",
"language": "python",
"cellIndex": 0,
"totalCells": 1,
"source": "def foo(): return 42\n",
"previousCode": None,
"error": None,
},
})
response = await jp_fetch(
"opencode-bridge", "edit",
method="POST",
body=body,
)
assert response.code == 200
payload = json.loads(response.body)
assert payload["ok"] is True
assert payload["finalSource"] == "def foo():\n return 42"
assert payload["sessionId"] == "fake-session-123"
assert payload["notebookPath"] == "test.ipynb"
# Session manager was used, not direct create/delete on client
call_names = [c[0] for c in fake.calls]
assert "create_session" not in call_names
assert "delete_session" not in call_names
assert "send_message_sync" in call_names
# send_message_sync received the session ID from the manager
send_call = [c for c in fake.calls if c[0] == "send_message_sync"][0]
assert send_call[1] == "fake-session-123"
# system prompt was passed
assert "你是一个代码编辑助手" in send_call[3]
# SessionManager.get_or_create was called with the notebook path
sm_call_names = [c[0] for c in fake_sm.calls]
assert sm_call_names == ["get_or_create"]
assert fake_sm.calls[0][1] == "test.ipynb"
async def test_session_list_handler(monkeypatch, jp_fetch):
fake_sm = FakeSessionManager()
fake_sm._sessions = {
"foo.ipynb": "sid-1",
"bar.ipynb": "sid-2",
} # direct injection
monkeypatch.setattr(
"opencode_bridge.routes.get_session_manager", lambda h: fake_sm
)
response = await jp_fetch("opencode-bridge", "sessions")
assert response.code == 200
payload = json.loads(response.body)
assert "sessions" in payload
paths = {s["notebookPath"] for s in payload["sessions"]}
assert paths == {"foo.ipynb", "bar.ipynb"}
async def test_session_release_handler(monkeypatch, jp_fetch):
fake = FakeOpenCodeClient()
monkeypatch.setattr("opencode_bridge.routes.make_client", lambda h: fake)
fake_sm = FakeSessionManager()
monkeypatch.setattr(
"opencode_bridge.routes.get_session_manager", lambda h: fake_sm
)
response = await jp_fetch(
"opencode-bridge", "session",
method="DELETE",
params={"notebook": "foo.ipynb"},
)
assert response.code == 200
payload = json.loads(response.body)
assert payload["ok"] is True
assert payload["notebookPath"] == "foo.ipynb"
assert payload["deleted"] is True
assert ("release", "foo.ipynb") in fake_sm.calls
@@ -0,0 +1,135 @@
"""Unit tests for SessionManager — no Jupyter server fixture."""
from __future__ import annotations
import pytest
from opencode_bridge.session_manager import SessionManager
class FakeClient:
"""Mimics OpenCodeClient just enough for SessionManager."""
def __init__(self, session_id: str = "sid-from-fake") -> None:
self._session_id = session_id
self.calls: list = []
async def create_session(self, title: str) -> dict:
self.calls.append(("create_session", title))
return {"id": self._session_id, "title": title}
async def delete_session(self, session_id: str) -> bool:
self.calls.append(("delete_session", session_id))
return True
@pytest.mark.asyncio
async def test_get_or_create_first_call_creates_session():
client = FakeClient()
sm = SessionManager(lambda: client)
sid = await sm.get_or_create("foo.ipynb")
assert sid == "sid-from-fake"
assert sm.has_session("foo.ipynb")
assert client.calls == [("create_session", "jupyter:foo.ipynb")]
@pytest.mark.asyncio
async def test_get_or_create_second_call_returns_same_sid():
client = FakeClient()
sm = SessionManager(lambda: client)
sid1 = await sm.get_or_create("foo.ipynb")
sid2 = await sm.get_or_create("foo.ipynb")
assert sid1 == sid2
# Only ONE create_session call total
create_calls = [c for c in client.calls if c[0] == "create_session"]
assert len(create_calls) == 1
@pytest.mark.asyncio
async def test_different_notebooks_get_different_sessions():
client1 = FakeClient(session_id="sid-1")
client2 = FakeClient(session_id="sid-2")
factories = [client1, client2]
sm = SessionManager(lambda: factories.pop(0) if factories else client1)
sid1 = await sm.get_or_create("foo.ipynb")
sid2 = await sm.get_or_create("bar.ipynb")
assert sid1 == "sid-1"
assert sid2 == "sid-2"
@pytest.mark.asyncio
async def test_release_returns_true_and_clears_session():
client = FakeClient()
sm = SessionManager(lambda: client)
await sm.get_or_create("foo.ipynb")
deleted = await sm.release("foo.ipynb")
assert deleted is True
assert not sm.has_session("foo.ipynb")
assert ("delete_session", "sid-from-fake") in client.calls
@pytest.mark.asyncio
async def test_release_returns_false_when_no_session():
client = FakeClient()
sm = SessionManager(lambda: client)
deleted = await sm.release("never-existed.ipynb")
assert deleted is False
assert client.calls == []
@pytest.mark.asyncio
async def test_get_or_create_after_release_creates_new_session():
client = FakeClient()
sm = SessionManager(lambda: client)
sid1 = await sm.get_or_create("foo.ipynb")
await sm.release("foo.ipynb")
sid2 = await sm.get_or_create("foo.ipynb")
# Same fake client returns same ID, but two create_session calls happened
assert sid1 == sid2
create_calls = [c for c in client.calls if c[0] == "create_session"]
assert len(create_calls) == 2
@pytest.mark.asyncio
async def test_invalidate_drops_cached_sid_without_calling_opencode():
client = FakeClient()
sm = SessionManager(lambda: client)
await sm.get_or_create("foo.ipynb")
calls_before = len(client.calls)
removed = sm.invalidate("foo.ipynb")
assert removed is True
assert not sm.has_session("foo.ipynb")
# No additional calls to client
assert len(client.calls) == calls_before
def test_list_sessions_empty():
sm = SessionManager(lambda: FakeClient())
assert sm.list_sessions() == []
@pytest.mark.asyncio
async def test_list_sessions_returns_all_mappings():
client = FakeClient()
sm = SessionManager(lambda: client)
await sm.get_or_create("a.ipynb")
# Manually inject a second to test listing
sm._sessions["b.ipynb"] = "sid-b"
listing = sm.list_sessions()
paths = {s["notebookPath"] for s in listing}
assert paths == {"a.ipynb", "b.ipynb"}
@pytest.mark.asyncio
async def test_concurrent_get_or_create_does_not_double_create():
"""Two concurrent calls for the same path must share one session."""
import asyncio
client = FakeClient()
sm = SessionManager(lambda: client)
sids = await asyncio.gather(
sm.get_or_create("foo.ipynb"),
sm.get_or_create("foo.ipynb"),
sm.get_or_create("foo.ipynb"),
)
assert sids[0] == sids[1] == sids[2]
create_calls = [c for c in client.calls if c[0] == "create_session"]
assert len(create_calls) == 1, "concurrent get_or_create must not double-create"