Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: add POST /api/kernel/focus_cell endpoint for external editor integration (#8497)

bri.dineenf03094b75e46
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 564699de4e..c571b11e69 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -255,6 +255,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
models.SuccessResponse,
models.UpdateCellConfigRequest,
models.UpdateCellIdsRequest,
+ models.FocusCellRequest,
models.UpdateUIElementValuesRequest,
models.UpdateUIElementRequest,
models.UpdateUserConfigRequest,
diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.py
index 25dacf035b..b52147cf00 100644
--- a/marimo/_server/api/endpoints/editing.py
+++ b/marimo/_server/api/endpoints/editing.py
@@ -6,7 +6,10 @@ from typing import TYPE_CHECKING
from starlette.authentication import requires
from marimo._cli.sandbox import SandboxMode
-from marimo._messaging.notification import UpdateCellIdsNotification
+from marimo._messaging.notification import (
+ FocusCellNotification,
+ UpdateCellIdsNotification,
+)
from marimo._server.api.deps import AppState
from marimo._server.api.utils import (
dispatch_control_request,
@@ -18,6 +21,7 @@ from marimo._server.models.models import (
BaseResponse,
CodeCompletionRequest,
DeleteCellRequest,
+ FocusCellRequest,
FormatCellsRequest,
FormatResponse,
InstallPackagesRequest,
@@ -122,6 +126,38 @@ async def sync_cell_ids(request: Request) -> BaseResponse:
return SuccessResponse()
[email protected]("/focus_cell")
+@requires("edit")
+async def focus_cell(request: Request) -> BaseResponse:
+ """
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ schema:
+ type: string
+ required: true
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/FocusCellRequest"
+ responses:
+ 200:
+ description: Focus a cell in kiosk-mode consumers
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/SuccessResponse"
+ """
+ app_state = AppState(request)
+ body = await parse_request(request, cls=FocusCellRequest)
+ app_state.require_current_session().notify(
+ FocusCellNotification(cell_id=body.cell_id),
+ from_consumer_id=None,
+ )
+ return SuccessResponse()
+
+
@router.post("/format")
@requires("edit")
async def format_cell(request: Request) -> FormatResponse:
diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.py
index edb861b4a3..7521cb45bb 100644
--- a/marimo/_server/models/models.py
+++ b/marimo/_server/models/models.py
@@ -242,6 +242,10 @@ class UpdateCellIdsRequest(msgspec.Struct, rename="camel"):
cell_ids: list[CellId_t]
+class FocusCellRequest(msgspec.Struct, rename="camel"):
+ cell_id: CellId_t
+
+
class ExecuteCellsRequest(msgspec.Struct, rename="camel"):
# ids of cells to run
cell_ids: list[CellId_t]
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 39a3af0d92..5f0df4d840 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -1834,6 +1834,14 @@ components:
- cell_id
title: FocusCellNotification
type: object
+ FocusCellRequest:
+ properties:
+ cellId:
+ type: string
+ required:
+ - cellId
+ title: FocusCellRequest
+ type: object
FormatCellsRequest:
properties:
codes:
@@ -5875,6 +5883,26 @@ paths:
schema:
$ref: '#/components/schemas/SuccessResponse'
description: Delete a cell
+ /api/kernel/focus_cell:
+ post:
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/FocusCellRequest'
+ responses:
+ 200:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SuccessResponse'
+ description: Focus a cell in kiosk-mode consumers
/api/kernel/format:
post:
requestBody:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index c222776aa1..1a8c73239e 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -1625,6 +1625,47 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/kernel/focus_cell": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ post: {
+ parameters: {
+ query?: never;
+ header: {
+ "Marimo-Session-Id": string;
+ };
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["FocusCellRequest"];
+ };
+ };
+ responses: {
+ /** @description Focus a cell in kiosk-mode consumers */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SuccessResponse"];
+ };
+ };
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/kernel/format": {
parameters: {
query?: never;
@@ -4270,6 +4311,10 @@ export interface components {
/** @enum {unknown} */
op: "focus-cell";
};
+ /** FocusCellRequest */
+ FocusCellRequest: {
+ cellId: string;
+ };
/** FormatCellsRequest */
FormatCellsRequest: {
codes: {
diff --git a/tests/_server/api/endpoints/test_editing.py b/tests/_server/api/endpoints/test_editing.py
index de276dc239..fe52f97138 100644
--- a/tests/_server/api/endpoints/test_editing.py
+++ b/tests/_server/api/endpoints/test_editing.py
@@ -1,10 +1,12 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import json
import sys
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, MagicMock, patch
+import anyio
import pytest
from marimo._dependencies.dependencies import DependencyManager
@@ -13,7 +15,7 @@ from tests._server.mocks import token_header, with_session
HAS_FORMATTER = DependencyManager.ruff.has() or DependencyManager.black.has()
if TYPE_CHECKING:
- from starlette.testclient import TestClient
+ from starlette.testclient import TestClient, WebSocketTestSession
SESSION_ID = "session-123"
HEADERS = {
@@ -22,6 +24,18 @@ HEADERS = {
}
+def _receive_json_with_timeout(
+ websocket: WebSocketTestSession, timeout_seconds: float = 0.5
+) -> dict[str, object]:
+ async def receive() -> dict[str, object]:
+ with anyio.fail_after(timeout_seconds):
+ message = await websocket._send_rx.receive()
+ websocket._raise_on_close(message)
+ return json.loads(message["text"])
+
+ return websocket.portal.call(receive)
+
+
@with_session(SESSION_ID)
def test_code_autocomplete(client: TestClient) -> None:
response = client.post(
@@ -190,3 +204,43 @@ def test_stdin(client: TestClient) -> None:
assert response.status_code == 200, response.text
assert response.headers["content-type"] == "application/json"
assert "success" in response.json()
+
+
+@with_session(SESSION_ID)
+def test_focus_cell(client: TestClient) -> None:
+ response = client.post(
+ "/api/kernel/focus_cell",
+ headers=HEADERS,
+ json={"cellId": "some-cell-id"},
+ )
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"] == "application/json"
+ assert "success" in response.json()
+
+
+@with_session(SESSION_ID)
+def test_focus_cell_notifies_same_session_kiosk_consumer(
+ client: TestClient,
+) -> None:
+ cell_id = "some-cell-id"
+ auth_token = token_header("fake-token")
+ with client.websocket_connect(
+ f"/ws?session_id={SESSION_ID}&kiosk=true&access_token=fake-token",
+ headers=auth_token,
+ ) as websocket:
+ data = websocket.receive_json()
+ assert data["op"] == "kernel-ready"
+ assert data["data"]["kiosk"] is True
+
+ response = client.post(
+ "/api/kernel/focus_cell",
+ headers=HEADERS,
+ json={"cellId": cell_id},
+ )
+ assert response.status_code == 200, response.text
+
+ message = _receive_json_with_timeout(websocket)
+ assert message == {
+ "op": "focus-cell",
+ "data": {"op": "focus-cell", "cell_id": cell_id},
+ }