Skip to content

Commit 61d17bd

Browse files
committed
Serve breakpoint changes on the notebook stream
1 parent cdca36e commit 61d17bd

15 files changed

Lines changed: 359 additions & 26 deletions

File tree

‎marimo/_core/handlers.py‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
from marimo._core.result import Err, Ok, Result
2020

2121
if TYPE_CHECKING:
22+
from collections.abc import Awaitable, Callable
23+
2224
from marimo._core.backend import RequestInfo
2325
from marimo._core.operations import Mutations, NotebookBridge
2426

@@ -231,15 +233,32 @@ async def dispatch(
231233
context: _ContextT,
232234
) -> Reply:
233235
"""Serve a call once per idempotency key."""
236+
return await dispatch_mutation(
237+
mutations,
238+
call,
239+
notebook_id=None
240+
if isinstance(call, api.Host.Create.Call)
241+
else call.params.notebook_id,
242+
key=call.headers.idempotency_key,
243+
handle=lambda: served.handle(call, context),
244+
)
245+
246+
247+
async def dispatch_mutation(
248+
mutations: Mutations,
249+
call: msgspec.Struct,
250+
*,
251+
notebook_id: str | None,
252+
key: str,
253+
handle: Callable[[], Awaitable[api.Result]],
254+
) -> Reply:
234255
try:
235256
outcome = await mutations.execute(
236257
str(call.__struct_config__.tag),
237-
notebook_id=None
238-
if isinstance(call, api.Host.Create.Call)
239-
else call.params.notebook_id,
240-
key=call.headers.idempotency_key,
258+
notebook_id=notebook_id,
259+
key=key,
241260
payload=call,
242-
call=lambda: served.handle(call, context),
261+
call=handle,
243262
)
244263
except HostError as e:
245264
failure = e.problem()

‎marimo/_server/api/endpoints/execution.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -479,7 +479,28 @@ async def set_breakpoints(
479479
schema:
480480
$ref: "#/components/schemas/SuccessResponse"
481481
"""
482-
return await dispatch_control_request(request, SetBreakpointsRequest)
482+
from marimo._server.extensions.breakpoints import _generated as api
483+
484+
state = AppState(request)
485+
body = await parse_request(request, cls=SetBreakpointsRequest)
486+
enforce_consumer_capability(state, body.as_command())
487+
notebook = state.notebook_for_session(state.require_current_session())
488+
if notebook is None or state.host_context is None:
489+
return await dispatch_control_request(request, body.as_command())
490+
extensions = await state.host_context.bridge.extensions(notebook.id)
491+
await extensions.handle(
492+
api.Replace.Call(
493+
params=api.Replace.Params(notebook_id=notebook.id),
494+
headers=api.Replace.Headers(idempotency_key=str(uuid4())),
495+
body=api.ReplaceBreakpointsRequest(
496+
cells={
497+
cell: tuple(lines)
498+
for cell, lines in body.breakpoints.items()
499+
}
500+
),
501+
)
502+
)
503+
return SuccessResponse()
483504

484505

485506
@router.post("/restart_session")

‎marimo/_server/extensions/api.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Copyright 2026 Marimo. All rights reserved.
2+
"""Notebook extension operations and events served by marimo."""
3+
4+
from __future__ import annotations
5+
6+
from typing import TYPE_CHECKING, TypeAlias
7+
8+
from marimo._core.stream import event_name
9+
from marimo._server.extensions.breakpoints import _generated as breakpoints
10+
11+
if TYPE_CHECKING:
12+
from marimo._core import protocol
13+
from marimo._server.host.bridge import SessionBridge
14+
15+
Call: TypeAlias = breakpoints.Call
16+
Operation: TypeAlias = type[breakpoints.Replace]
17+
OPERATIONS = breakpoints.OPERATIONS
18+
KINDS = frozenset({event_name(breakpoints.MarimoBreakpointsEvent)})
19+
20+
21+
async def handle(call: Call, bridge: SessionBridge) -> protocol.api.Result:
22+
extensions = await bridge.extensions(call.params.notebook_id)
23+
return await extensions.handle(call)
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Copyright 2026 Marimo. All rights reserved.
2+
"""Breakpoint requests for the notebook's attached runtime."""
3+
4+
from __future__ import annotations
5+
6+
from contextlib import contextmanager
7+
from typing import TYPE_CHECKING
8+
9+
from marimo._core import protocol
10+
from marimo._core.errors import Conflict, Invalid, NoRuntime
11+
from marimo._core.result import Ok
12+
from marimo._runtime.commands import SetBreakpointsCommand
13+
from marimo._server.extensions.breakpoints import _generated as api
14+
from marimo._types.ids import CellId_t
15+
16+
if TYPE_CHECKING:
17+
from collections.abc import Iterator
18+
19+
from marimo._server.extensions.scope import NotebookScope
20+
21+
22+
class Breakpoints(api.Handlers):
23+
"""Keep the breakpoint set shared by editors of one notebook.
24+
25+
The record identifies the runtime it belongs to. Editors recover it
26+
on reconnect, and a new runtime starts with an empty set.
27+
"""
28+
29+
def __init__(self, scope: NotebookScope[api.Breakpoints]) -> None:
30+
self._scope = scope
31+
32+
@contextmanager
33+
def bind_runtime(self, runtime_id: protocol.RuntimeId) -> Iterator[None]:
34+
"""Publish an empty set on attach and drop the record on detach.
35+
36+
Connected editors discard the old set when they see the runtime end.
37+
"""
38+
self._scope.put(api.Breakpoints(runtime_id=runtime_id, cells={}))
39+
try:
40+
yield
41+
finally:
42+
self._scope.clear()
43+
44+
async def replace(self, call: api.Replace.Call) -> api.Replace.Result:
45+
"""Replace all breakpoints in the current runtime and return its record.
46+
47+
Lines are one-based. Duplicates count once and an empty `cells`
48+
mapping clears the set. An unchanged set returns the current
49+
record without queuing a command or publishing an event.
50+
51+
Raises `NoRuntime` when the notebook has no live runtime and
52+
`Conflict` while the runtime is starting or stopping. An empty
53+
cell ID raises `Invalid`.
54+
"""
55+
runtime = self._scope.notebook.live_runtime
56+
if runtime is None:
57+
raise NoRuntime("The notebook has no live runtime")
58+
current = self._scope.record
59+
if current is None or not isinstance(
60+
runtime.state, protocol.RuntimeReady
61+
):
62+
raise Conflict("The runtime is not ready")
63+
if "" in call.body.cells:
64+
raise Invalid("A breakpoint cell id must be nonempty")
65+
cells = {
66+
cell: tuple(sorted(set(lines)))
67+
for cell, lines in call.body.cells.items()
68+
if lines
69+
}
70+
if cells != current.cells:
71+
self._scope.runtime.send(
72+
SetBreakpointsCommand(
73+
breakpoints={
74+
CellId_t(cell): list(lines)
75+
for cell, lines in cells.items()
76+
}
77+
)
78+
)
79+
current = self._scope.put(
80+
api.Breakpoints(runtime_id=runtime.id, cells=cells),
81+
request_id=call.headers.idempotency_key,
82+
)
83+
return Ok(current)
84+
85+
86+
@contextmanager
87+
def open( # noqa: A001
88+
scope: NotebookScope[api.Breakpoints],
89+
) -> Iterator[Breakpoints]:
90+
"""Serve calls with one handler across this notebook's runtime changes."""
91+
state = Breakpoints(scope)
92+
with scope.runtime.while_ready(state.bind_runtime):
93+
yield state

‎marimo/_server/extensions/notebook.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@
77
from typing import TYPE_CHECKING, TypeVar
88

99
from marimo import _loggers
10+
from marimo._server.extensions.breakpoints import (
11+
_generated as breakpoint_api,
12+
extension as breakpoints,
13+
)
1014
from marimo._server.extensions.scope import NotebookScope
1115

1216
if TYPE_CHECKING:
@@ -16,6 +20,7 @@
1620
from marimo._core import protocol
1721
from marimo._core.notebook import Notebook
1822
from marimo._core.stream import RoutedEvent
23+
from marimo._server.extensions.api import Call
1924
from marimo._server.extensions.scope import EventFactory, RuntimeAccess
2025
from marimo._session.session import Session
2126

@@ -38,6 +43,13 @@ def __init__(self, notebook: Notebook) -> None:
3843
self._bound = ExitStack()
3944
self._snapshots: list[Callable[[], RoutedEvent | None]] = []
4045
self._runtimes: list[RuntimeAccess] = []
46+
self._breakpoints = self.install(
47+
breakpoints.open, breakpoint_api.event
48+
)
49+
50+
async def handle(self, call: Call) -> protocol.api.Result:
51+
"""Dispatch a decoded call to the handler installed on this notebook."""
52+
return await breakpoint_api.handle(self._breakpoints, call)
4153

4254
def install(
4355
self,

‎marimo/_server/host/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# Copyright 2026 Marimo. All rights reserved.
22
"""Host API routes and session integration for `marimo edit`."""
33

4+
from marimo._server.extensions import api as extensions
5+
46
HOST_API_PATH = "/api/marimo/v1"
57
"""Host API path relative to the server's base URL."""
68

@@ -11,6 +13,7 @@
1113
"notebook.open",
1214
"notebook.edit",
1315
"notebook.emit",
16+
*(op.ID for op in extensions.OPERATIONS),
1417
"notebook.save",
1518
"runtime.start",
1619
"runtime.stop",

‎marimo/_server/host/index.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ def untitled(self, key: str) -> protocol.Notebook:
191191
op
192192
for op in OPERATIONS
193193
if op in {"notebook.edit", "notebook.emit", "input.reply"}
194-
or op.startswith("runtime.")
194+
or op.startswith(("runtime.", "notebook.extensions."))
195195
),
196196
modified_at=None,
197197
)

‎marimo/_server/host/notebook_api.py‎

Lines changed: 33 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,15 @@
2121
HostHandlers,
2222
NotebookHandlers,
2323
dispatch,
24+
dispatch_mutation,
2425
)
2526
from marimo._core.result import Ok
2627
from marimo._messaging.notification import ConsumerCapabilities
2728
from marimo._runtime.commands import HTTPRequest
2829
from marimo._server.api.auth import TOKEN_QUERY_PARAM
2930
from marimo._server.api.deps import AppState, AppStateBase
3031
from marimo._server.api.utils import format_url_host, open_url_in_browser
32+
from marimo._server.extensions import api as extensions
3133
from marimo._server.host.auth import bearer_matches
3234
from marimo._server.tokens import AuthToken
3335
from marimo._types.ids import ConsumerId
@@ -42,6 +44,8 @@
4244

4345
LOGGER = _loggers.marimo_logger()
4446
api = protocol.api
47+
_Operation = api.Operation | extensions.Operation
48+
_OPERATIONS = (*api.OPERATIONS, *extensions.OPERATIONS)
4549

4650
# The operations a host's catalog serves, which the editor does not.
4751
_CATALOG: tuple[api.Operation, ...] = (
@@ -213,9 +217,9 @@ def _open_quietly(browser: str, url: str) -> None:
213217

214218

215219
def _endpoint(
216-
operation: api.Operation,
220+
operation: _Operation,
217221
) -> Callable[[Request], Awaitable[Response]]:
218-
kind: type[api.Call] = operation.Call
222+
kind: type[api.Call | extensions.Call] = operation.Call
219223

220224
async def handle(request: Request) -> Response:
221225
# Assemble the call from the request's parts, the shape the client
@@ -233,28 +237,36 @@ async def handle(request: Request) -> Response:
233237
return problem(
234238
"invalid-request", "This operation takes no body"
235239
)
236-
call: api.Call = msgspec.convert(parts, type=kind)
240+
call: api.Call | extensions.Call = msgspec.convert(
241+
parts, type=kind
242+
)
237243
except msgspec.DecodeError as e:
238244
return problem("invalid-request", str(e))
239245
host = _context(request)
240-
session = AppState(request).get_current_session()
241-
notebook_id = request.path_params.get("notebook_id")
242-
status, body = await dispatch(
243-
host.mutations,
244-
host.api,
245-
call,
246-
ServerContext(
246+
if isinstance(call, extensions.Call):
247+
status, body = await dispatch_mutation(
248+
host.mutations,
249+
call,
250+
notebook_id=call.params.notebook_id,
251+
key=call.headers.idempotency_key,
252+
handle=lambda: extensions.handle(call, host.bridge),
253+
)
254+
else:
255+
session = AppState(request).get_current_session()
256+
notebook_id = request.path_params.get("notebook_id")
257+
context = ServerContext(
247258
request=_submitting_request(request),
248-
# Only the notebook's own editor can answer a prompt.
249259
allow_input=(
250260
session is not None
251261
and notebook_id is not None
252262
and host.bridge.session_for_notebook(notebook_id)
253263
is session
254264
),
255265
app=request.app,
256-
),
257-
)
266+
)
267+
status, body = await dispatch(
268+
host.mutations, host.api, call, context
269+
)
258270
return _response(status, body)
259271

260272
return handle
@@ -279,7 +291,7 @@ def operation_routes() -> list[Route]:
279291
"""Serve each operation at its path in the spec."""
280292
return [
281293
Route(operation.PATH, _endpoint(operation), methods=[operation.METHOD])
282-
for operation in api.OPERATIONS
294+
for operation in _OPERATIONS
283295
]
284296

285297

@@ -291,13 +303,13 @@ def editor_notebook_routes(prefix: str) -> list[Route]:
291303
_editor_endpoint(operation),
292304
methods=[operation.METHOD],
293305
)
294-
for operation in api.OPERATIONS
306+
for operation in _OPERATIONS
295307
if operation not in _CATALOG
296308
]
297309

298310

299311
def _editor_endpoint(
300-
operation: api.Operation,
312+
operation: _Operation,
301313
) -> Callable[[Request], Awaitable[Response]]:
302314
serve = _endpoint(operation)
303315

@@ -318,7 +330,7 @@ async def handle(request: Request) -> Response:
318330
return handle
319331

320332

321-
def _connection_may_call(request: Request, operation: api.Operation) -> bool:
333+
def _connection_may_call(request: Request, operation: _Operation) -> bool:
322334
"""Whether the connection may issue this notebook operation.
323335
324336
Host commands are system-originated, so enforce connection capabilities
@@ -331,6 +343,10 @@ def _connection_may_call(request: Request, operation: api.Operation) -> bool:
331343
session = app_state.get_current_session()
332344
if session is None:
333345
return False
346+
if operation in extensions.OPERATIONS and session is not _context(
347+
request
348+
).bridge.session_for_notebook(request.path_params["notebook_id"]):
349+
return False
334350
consumer = session.room.get_consumer(ConsumerId(session_id))
335351
capabilities = (
336352
session.room.get_capabilities(consumer)

‎marimo/_server/host/stream_options.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@
66
from typing import TYPE_CHECKING, get_args
77

88
from marimo._core import protocol
9+
from marimo._server.extensions import api as extensions
910

1011
if TYPE_CHECKING:
1112
from starlette.requests import HTTPConnection
1213

1314
OBJECT_KINDS = frozenset(get_args(get_args(protocol.ObjectKind)[0])) | {
14-
"marimo"
15+
"marimo",
16+
*extensions.KINDS,
1517
}
1618

1719

0 commit comments

Comments
 (0)