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.
91 lines
3.3 KiB
Python
91 lines
3.3 KiB
Python
"""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())
|
|
]
|