diff --git a/editor-web/src/components/LoadingMask.tsx b/editor-web/src/components/LoadingMask.tsx index e325cf89..9cdd1b3c 100644 --- a/editor-web/src/components/LoadingMask.tsx +++ b/editor-web/src/components/LoadingMask.tsx @@ -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
-
-
+
+
loading {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); } } diff --git a/src/simplecadapi/editor/kernel.py b/src/simplecadapi/editor/kernel.py index d7649643..de3ea37d 100644 --- a/src/simplecadapi/editor/kernel.py +++ b/src/simplecadapi/editor/kernel.py @@ -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", diff --git a/src/simplecadapi/editor/server.py b/src/simplecadapi/editor/server.py index 6d3dcf51..49663416 100644 --- a/src/simplecadapi/editor/server.py +++ b/src/simplecadapi/editor/server.py @@ -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 diff --git a/test/test_editor.py b/test/test_editor.py index 708d4b78..a30c14e6 100644 --- a/test/test_editor.py +++ b/test/test_editor.py @@ -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