fix(editor): stop the bridge interrupting long cells; calmer loading veil

marimo interrupts the kernel when the client of /api/kernel/execute
disconnects. The bridge's scratch calls had client timeouts (the 5 s watchdog
ping: 10 s; the idle probe: 15 s), so any cell that ran longer than that - a
use() of a child notebook - was killed with KeyboardInterrupt and the
product was missing. Scratch calls now wait without a timeout and the
watchdog asks /api/sessions instead.

The loading veil's swell is one long wave and its dots are dimmer.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
NiJingzhe
2026-10-11 22:47:29 +08:00
parent 4d14615e96
commit 058310f2ca
4 changed files with 84 additions and 22 deletions
+13 -9
View File
@@ -7,8 +7,12 @@ const RING = [0, 1, 2, 5, 8, 7, 6, 3];
const STEP = 8; // dot pitch, CSS px
const DOT = 2; // dot size, CSS px
/** Dot brightness in four steps (a 2-bit look), and the colour of the crest. */
const LEVELS = [0.05, 0.14, 0.3, 0.6];
/** Dot brightness in four steps (a 2-bit look), kept low: the veil should sit
* behind the window, not compete with it. The brightest step is the crest. */
const LEVELS = [0.03, 0.075, 0.13, 0.22];
/** One long swell: wavelength 2π/WAVE_NUMBER ≈ 780 px, a period of ≈ 7 s. */
const WAVE_NUMBER = 0.008;
const WAVE_SPEED = 0.0009;
/** A gray veil over the whole workspace while the model is being made: a
* dot-matrix with a ripple that spreads from the middle, and a small retro
@@ -41,11 +45,11 @@ export function LoadingMask({ active, message }: { active: boolean; message: str
<div
role="status"
aria-live="polite"
className="absolute inset-0 z-50 flex cursor-progress items-center justify-center bg-[#1b1b1b]/80"
className="absolute inset-0 z-50 flex cursor-progress items-center justify-center bg-[#1b1b1b]/75"
>
<Ripple />
<div className="relative w-[280px] border-2 border-white bg-black shadow-[6px_6px_0_0_rgba(255,255,255,0.18)]">
<div className="flex h-6 items-center justify-between bg-white px-2 text-[11px] font-bold uppercase tracking-[0.18em] text-black">
<div className="relative w-[280px] border-2 border-white/80 bg-black shadow-[6px_6px_0_0_rgba(255,255,255,0.1)]">
<div className="flex h-6 items-center justify-between bg-white/85 px-2 text-[11px] font-bold uppercase tracking-[0.18em] text-black">
<span>loading</span>
<span className="tabular-nums">
{minutes}:{seconds}
@@ -130,10 +134,10 @@ function Ripple() {
for (let y = STEP / 2; y < height; y += STEP) {
for (let x = STEP / 2; x < width; x += STEP) {
const distance = Math.hypot(x - cx, y - cy);
// rings spreading outwards, fading with distance
const wave = (Math.sin(distance * 0.05 - time * 0.0035) + 1) / 2;
const strength = wave * (1 - 0.65 * Math.min(distance / reach, 1));
const level = Math.min(LEVELS.length - 1, Math.floor(strength * LEVELS.length * 1.15));
// a long swell spreading outwards, fading gently with distance
const wave = (Math.sin(distance * WAVE_NUMBER - time * WAVE_SPEED) + 1) / 2;
const strength = wave * (1 - 0.4 * Math.min(distance / reach, 1));
const level = Math.min(LEVELS.length - 1, Math.floor(strength * LEVELS.length));
paths[level].rect(x - DOT / 2, y - DOT / 2, DOT, DOT);
}
}
+24 -6
View File
@@ -195,6 +195,18 @@ class MarimoKernel:
self._ws_thread.start()
time.sleep(1.0)
def session_exists(self) -> bool:
"""Whether marimo still has this bridge's session.
Unlike a scratch snippet this never touches the kernel, so it can be
asked while a cell runs.
"""
try:
with urllib.request.urlopen(f"{self.marimo_url}/api/sessions", timeout=5) as response:
return SESSION_ID in json.loads(response.read())
except (urllib.error.URLError, OSError, ValueError):
return False
def _on_message(self, message: str | bytes) -> None:
try:
data = json.loads(message)
@@ -389,7 +401,6 @@ class MarimoKernel:
)
return self.execute(
_driver(" for __c in ctx.cells:\n ctx.run_cell(__c.id)\n ctx.run_cell('setup')"),
timeout=300,
)
def stale_cells(self) -> list[str]:
@@ -427,7 +438,7 @@ class MarimoKernel:
)
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if "SCA-IDLE" in (self.execute(probe, timeout=15).get("log") or ""):
if "SCA-IDLE" in (self.execute(probe).get("log") or ""):
return True
time.sleep(0.2)
return False
@@ -462,7 +473,6 @@ class MarimoKernel:
" print('SCA-PUBLISHED', _p.definition_id, _p.definition_kind)\n"
"except Exception as _e:\n"
" print('SCA-PUBLISH-ERROR', type(_e).__name__ + ':', str(_e).splitlines()[0] if str(_e) else '')\n",
timeout=180,
)
for line in (result.get("log") or "").splitlines():
if line.startswith("SCA-PUBLISHED "):
@@ -474,8 +484,16 @@ class MarimoKernel:
# -- driving --------------------------------------------------------------------
def execute(self, code: str, timeout: float = 120.0) -> dict:
"""Run a scratch snippet in the kernel; returns {success, output, log}."""
def execute(self, code: str, timeout: float | None = None) -> dict:
"""Run a scratch snippet in the kernel; returns {success, output, log}.
The snippet queues behind whatever the kernel is running, and the call
waits for it. There is deliberately no client-side timeout by default:
marimo interrupts the KERNEL when the client of ``/api/kernel/execute``
disconnects, whatever the kernel is running at that moment, so a call
that gave up after 10 s killed any cell that ran longer (a ``use`` of a
child notebook, a big rebuild).
"""
self._own_calls += 1
started = time.monotonic()
try:
@@ -487,7 +505,7 @@ class MarimoKernel:
first = next((line for line in code.splitlines() if line.strip()), "")[:70]
print(f"[sca edit] {time.strftime('%H:%M:%S')}.{int(time.time() * 1000) % 1000:03d} kernel {self._own_ended - started:6.2f}s {first}", file=sys.stderr, flush=True)
def _execute(self, code: str, timeout: float) -> dict:
def _execute(self, code: str, timeout: float | None) -> dict:
body = json.dumps({"code": code}).encode("utf-8")
request = urllib.request.Request(
f"{self.marimo_url}/api/kernel/execute",
+5 -7
View File
@@ -193,8 +193,8 @@ class WorkspaceState:
def watch_kernel(self) -> None:
"""Auto-heal: the marimo python session can die on crashes or
external file edits while the marimo SERVER process stays alive
(`kernel.alive` is blind to that). Probe the session with scratch
pings; two consecutive failures mean the session is gone — restart.
(`kernel.alive` is blind to that). Ask marimo whether it still has our
session; two consecutive misses mean it is gone — restart.
"""
failures = 0
while True:
@@ -205,11 +205,9 @@ class WorkspaceState:
if not kernel.alive:
self.hub.broadcast({"type": "status", "error": "marimo server exited — restarting kernel"})
break
try:
result = kernel.execute("print('sca-ping')", timeout=10)
failures = failures + 1 if result.get("success") is False else 0
except Exception:
failures += 1
# Not a scratch snippet: one queued behind a long cell and given
# up on interrupts the kernel (see MarimoKernel.execute).
failures = 0 if kernel.session_exists() else failures + 1
if failures >= 2:
self.hub.broadcast({"type": "status", "error": "kernel session lost — restarting"})
break
+42
View File
@@ -523,3 +523,45 @@ class WatchedFilesTest(unittest.TestCase):
self.assertIn(root / "data" / "profile.dxf", mtimes)
self.assertIn(root / "data" / "child.csv", mtimes) # a child's data: its cells rerun
self.assertIn(root / "child.py", mtimes)
@unittest.skipUnless(os.environ.get("SCA_EDITOR_E2E"), "set SCA_EDITOR_E2E=1 to boot a marimo kernel")
class LongCellTest(unittest.TestCase):
"""A cell that runs longer than the bridge's probes must not be interrupted by them."""
def test_a_long_cell_survives_the_bridge_polling_the_kernel(self) -> None:
import threading
import uvicorn
from simplecadapi.editor.server import create_app
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp).resolve()
path = root / "slow.py"
path.write_text(
"# /// script\n# [tool.simplecadapi]\n# id = \"slow\"\n# ///\n"
"import marimo\n\napp = marimo.App()\n\nwith app.setup:\n import simplecadapi as scad\n\n\n"
"@app.cell\ndef _():\n import time\n time.sleep(22)\n done = 1\n return (done,)\n"
)
state = WorkspaceState(root)
state.port = 17735
app = create_app(state)
server = uvicorn.Server(uvicorn.Config(app, port=state.port, log_level="error"))
threading.Thread(target=server.run, daemon=True).start()
state.hub.attach_loop(__import__("asyncio").new_event_loop())
try:
# start_kernel waits for the notebook to go idle with scratch probes while the
# cell sleeps: they used to time out after 15 s and interrupt the cell.
state.start_kernel(path)
kernel = state.kernel
assert kernel is not None
self.assertTrue(kernel.session_exists())
cell = next(c for c in kernel.list_cells() if "time.sleep" in c["code"])
self.assertEqual(cell["status"], "idle")
self.assertEqual(cell["errors"], [])
self.assertIn("DONE 1", kernel.execute("print('DONE', done)").get("log", "").upper())
finally:
if state.kernel is not None:
state.kernel.stop()
server.should_exit = True