Files
notebook-ai-extension/opencode_bridge/tests/test_session_manager.py
T
tao.chen c919c95842 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.
2026-07-22 19:07:58 +08:00

136 lines
4.4 KiB
Python

"""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"