Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
569c79c
NIS bridge: serve from a worker thread so NIS stays responsive; refus…
qquais Oct 15, 2026
6b80dce
NIS event log and live terminal monitor, opened by the NIS MCP server
qquais Oct 15, 2026
d1172b5
docs: NIS bridge results on the scope 2026-10-15 and the live monitor
qquais Oct 15, 2026
432e6f7
NIS monitor: make the launch test run off Windows
qquais Oct 15, 2026
f39449e
tests: NIS worker-thread entry, optical configs, event log and monitor
qquais Oct 16, 2026
46ae12c
tests: e-stop, data paths and the mock NIS backend
qquais Oct 16, 2026
8e7ea7c
tests: stage positions, Ti2 SDK and Baumer camera against fake hardwa…
qquais Oct 16, 2026
075ddf9
tests: move_xy, raw_move_xy and timelapse
qquais Oct 16, 2026
ac08624
tests: mosaic against a simulated stage, camera and agar scene
qquais Oct 16, 2026
b8dff3e
tests: worm_follow detection, setup and tracking against a simulated …
qquais Oct 16, 2026
1b3f5cc
tests: harness conversation loops; note the image-pruning gap as a st…
qquais Oct 16, 2026
ac9ccd7
tests: STOP panel and Windows mutex paths against fake tkinter and ke…
qquais Oct 16, 2026
fe68088
tests: Ti2 inventory/config tooling and the NIS port probe
qquais Oct 16, 2026
08f5664
tests: hardware experiment scripts and python -m entry points
qquais Oct 16, 2026
899ea93
tests: timelapse edge cases, server entry points and remaining branches
qquais Oct 16, 2026
312db82
CI: real OpenCV in the test extra, coverage report with a 90% floor
qquais Oct 16, 2026
2306801
tests: AML18 survey and tracking on a synthetic worm scene
qquais Oct 16, 2026
2e6e77d
tests: analysis scripts (worm survey/tracking, Physarum series, sound…
qquais Oct 16, 2026
b8ba5b2
CI: test extra uses scipy/scikit-image ranges so Python 3.11 can install
qquais Oct 16, 2026
2757161
pyproject: fix the comma after the scipy range
qquais Oct 16, 2026
21e98fa
harness: prune camera frames held inside tool_result blocks
qquais Oct 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@ jobs:
# needed to import the Claude loops for the approval-gate tests (no
# API key required - no model is ever called).
- run: pip install -e ".[harness,test]"
- run: python -m pytest -v tests # -v names each test in the log
# -v names each test in the log; the coverage table shows what no test
# reaches. The floor is a tripwire, not a target: it only catches a
# large untested addition.
- run: >
python -m pytest -v tests
--cov=acquisition --cov=harness --cov=mcp_server --cov=timelapse --cov=analysis
--cov-report=term-missing --cov-fail-under=90
# The MCP server must import on a core-only install (the camera and
# SDK stacks are lazy imports) - fail the build if that regresses.
# (tests/test_mcp_server.py goes further and actually runs it.)
Expand Down
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,8 @@ eaa_integration/*.sqlite-wal
# Nikon Ti2 SDK documentation, originals and samples extracted from the
# Nikon installers. Licensed with SDK access - kept local, not published.
docs/nikon-sdk/

# coverage
.coverage
coverage.xml
htmlcov/
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ unchanged. Setup, safety rules and the on-scope test plan:

```
python -m acquisition.backends.nis_bridge status # by hand, while the bridge job runs
python -m acquisition.nis_monitor # live view: status + every action (logs/nis/)
confocal-mcp-nis # the MCP server
python -m mcp_server.server_nis # same, from a source checkout
```
Expand Down
54 changes: 43 additions & 11 deletions acquisition/backends/nis_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
# python -m acquisition.backends.nis_bridge status
# python -m acquisition.backends.nis_bridge move 100 0
# python -m acquisition.backends.nis_bridge objective "Plan Fluor 10x Ph1 DLL"
# python -m acquisition.backends.nis_bridge optconfs
# python -m acquisition.backends.nis_bridge capture D:\...\check.nd2
# python -m acquisition.backends.nis_bridge nd-run "C. elegans 3h"
# python -m acquisition.backends.nis_bridge nd-finish
Expand All @@ -18,6 +19,10 @@
# the NIS side having been updated. Stopping an ND run (nd-finish) and
# shutting the bridge down are always allowed - they only end things.
#
# Every action here is also written to the NIS event log
# (acquisition/nis_events.py), which `python -m acquisition.nis_monitor`
# shows live. Status reads are not logged (the monitor polls them).
#
# CONFOCAL_NIS_BRIDGE_URL overrides the address (default
# http://127.0.0.1:8766).
# ------------------------------------------------------------
Expand All @@ -28,10 +33,11 @@
import json
import os
import sys
import time
import urllib.error
import urllib.request

from acquisition import estop
from acquisition import estop, nis_events

DEFAULT_URL = "http://127.0.0.1:8766"

Expand Down Expand Up @@ -67,31 +73,55 @@ def _call(self, method: str, path: str, body: dict | None = None,
def status(self) -> dict:
return self._call("GET", "/status")

def _act(self, action: str, params: dict, send, guarded: bool = True) -> dict:
"""Run one action and write it to the NIS event log (nis_events.py):
a "start" line, then "ok", "failed", "refused" or "error"."""
nis_events.record(action, "start", params=params)
t0 = time.time()
try:
if guarded:
estop.check()
result = send()
except estop.EStopEngaged as e:
nis_events.record(action, "refused", params=params, message=str(e))
raise
except BridgeUnavailable as e:
nis_events.record(action, "error", params=params, message=str(e))
raise
phase = "failed" if "error" in result else "ok"
nis_events.record(action, phase, params=params, result=result,
elapsed_s=round(time.time() - t0, 1))
return result

def optical_configs(self) -> dict:
return self._call("GET", "/optconfs")

# Motion / acquisition: e-stop checked before anything is sent
def move_relative(self, dx_um: float, dy_um: float) -> dict:
estop.check()
return self._call("POST", "/move", {"dx": dx_um, "dy": dy_um})
return self._act("move", {"dx": dx_um, "dy": dy_um},
lambda: self._call("POST", "/move", {"dx": dx_um, "dy": dy_um}))

def change_objective(self, name: str) -> dict:
estop.check()
return self._call("POST", "/objective", {"name": name})
return self._act("objective", {"name": name},
lambda: self._call("POST", "/objective", {"name": name}))

def capture(self, path: str) -> dict:
estop.check()
return self._call("POST", "/capture", {"path": path}, timeout_s=300)
return self._act("capture", {"path": path},
lambda: self._call("POST", "/capture", {"path": path}, timeout_s=300))

def nd_run(self, experiment: str, timeout_s: float = 7200.0) -> dict:
# ND_RunExperiment may block until the run ends (unverified), so
# the answer can take as long as the run itself.
estop.check()
return self._call("POST", "/nd/run", {"experiment": experiment}, timeout_s=timeout_s)
return self._act("nd_run", {"experiment": experiment},
lambda: self._call("POST", "/nd/run", {"experiment": experiment},
timeout_s=timeout_s))

# Always allowed: these only end things
def nd_finish(self) -> dict:
return self._call("POST", "/nd/finish")
return self._act("nd_finish", {}, lambda: self._call("POST", "/nd/finish"), guarded=False)

def shutdown(self) -> dict:
return self._call("POST", "/shutdown")
return self._act("shutdown", {}, lambda: self._call("POST", "/shutdown"), guarded=False)


def main() -> None:
Expand All @@ -103,6 +133,7 @@ def main() -> None:
m.add_argument("dx", type=float); m.add_argument("dy", type=float)
o = sub.add_parser("objective", help="exact name as listed by status (4x/10x only)")
o.add_argument("name")
sub.add_parser("optconfs", help="list the optical configurations")
c = sub.add_parser("capture", help="capture one image and save it as .nd2")
c.add_argument("path")
r = sub.add_parser("nd-run", help="load a saved ND experiment by name and run it")
Expand All @@ -116,6 +147,7 @@ def main() -> None:
out = {"status": lambda: b.status(),
"move": lambda: b.move_relative(a.dx, a.dy),
"objective": lambda: b.change_objective(a.name),
"optconfs": lambda: b.optical_configs(),
"capture": lambda: b.capture(a.path),
"nd-run": lambda: b.nd_run(a.experiment),
"nd-finish": lambda: b.nd_finish(),
Expand Down
48 changes: 40 additions & 8 deletions acquisition/nis_bridge/bridge_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# POST /move {"dx", "dy"} relative XY move, um
# POST /objective {"name"} Stg_SetNosepiecePosition (turns the turret) then ChangeObjective
# (NIS calibration), allow-listed names only
# GET /optconfs names of the optical configurations (read-only)
# POST /capture {"path"} Capture, save as ND2, close the document
# POST /nd/run {"experiment"} ND_LoadExperiment + ND_RunExperiment(0)
# POST /nd/finish ND_FinishExperiment (stop after this loop)
Expand All @@ -39,10 +40,14 @@
# (Docs/nis/eng_ar on the microscope PC). A macro char* is wchar_t* in
# this build (limpy passes WaitText's text as c_wchar_p).
#
# THREADING. NIS is not known to be thread-safe, so every NIS call runs on
# the job's own thread in run(); the HTTP threads only queue requests and
# wait for the answer. A call that takes long (ND_RunExperiment may block
# until the run ends - unverified) delays the requests queued behind it.
# THREADING. A JOBS Python task runs on NIS's main thread, and serving there
# froze NIS (2026-10-15). So run() starts serve() on a worker thread and
# returns. NIS is not known to be thread-safe, so every NIS call still runs
# on that one worker thread; the HTTP threads only queue requests and wait
# for the answer. Whether macro calls (Ti2 moves, Capture) are allowed off
# the main thread is UNVERIFIED. A call that takes long (ND_RunExperiment
# may block until the run ends - unverified) delays the requests queued
# behind it.
#
# SAFETY, enforced here as well as in the client:
# * motion and acquisition only on POST, so a browser cannot trigger them
Expand Down Expand Up @@ -93,6 +98,8 @@ class Macro:
"GetCurrentObjName": [ct.c_wchar_p],
"Stg_SetNosepiecePosition": [ct.c_int],
"ChangeObjective": [ct.c_wchar_p],
"GetOptConfCount": [],
"GetOptConfName": [ct.c_int, ct.c_wchar_p, ct.c_int],
"Capture": [],
"ImageSaveAs": [ct.c_wchar_p, ct.c_int, ct.c_int],
"CloseCurrentDocument": [ct.c_int],
Expand Down Expand Up @@ -192,6 +199,20 @@ def objective(self, name: str) -> dict:
"nosepiece_before": before["nosepiece_position"],
"nosepiece_after": after["nosepiece_position"]}

def optical_configs(self) -> dict:
names = []
for i in range(0, self.m.GetOptConfCount() + 1): # index base unverified: try 0..n
b = ct.create_unicode_buffer(255)
self.m.GetOptConfName(i, b, 255)
if b.value and b.value not in names:
names.append(b.value)
return {"optical_configs": names}

# No select: SelectOptConf called from this worker thread switched the
# devices ("end success" in NIS's log) and then froze NIS's main thread
# until the bridge was shut down (2026-10-15). Set the optical
# configuration in NIS, or find a way to run it on the UI thread first.

def capture(self, path: str) -> dict:
if (r := self._refuse_if_stopped("capture")):
return r
Expand Down Expand Up @@ -230,6 +251,7 @@ def nd_finish(self) -> dict:
("GET", "/status"): lambda b, body: b.status(),
("POST", "/move"): lambda b, body: b.move(float(body.get("dx", 0)), float(body.get("dy", 0))),
("POST", "/objective"): lambda b, body: b.objective(str(body.get("name", ""))),
("GET", "/optconfs"): lambda b, body: b.optical_configs(),
("POST", "/capture"): lambda b, body: b.capture(str(body.get("path", ""))),
("POST", "/nd/run"): lambda b, body: b.nd_run(str(body.get("experiment", ""))),
("POST", "/nd/finish"): lambda b, body: b.nd_finish(),
Expand Down Expand Up @@ -289,6 +311,10 @@ def serve(bridge: Bridge, port: int = PORT, should_abort=lambda: False,
last_request = time.time()
jobs = queue.Queue()
stop = stop or threading.Event()
# On Windows SO_REUSEADDR (the default here) lets a second bridge bind the
# same port, so re-running the job started a duplicate whose shutdown had
# to be sent twice (seen 2026-10-15). Without it a second run fails to bind.
http.server.ThreadingHTTPServer.allow_reuse_address = False
srv = http.server.ThreadingHTTPServer(("127.0.0.1", port), make_handler(jobs, stop))
threading.Thread(target=srv.serve_forever, daemon=True).start()
print(f"NIS bridge v{VERSION} listening on 127.0.0.1:{srv.server_address[1]}, pid {os.getpid()}")
Expand Down Expand Up @@ -316,7 +342,13 @@ def serve(bridge: Bridge, port: int = PORT, should_abort=lambda: False,

def run(imgs: "tuple[limjob.Image]", Job: "limjob.JobParam", macro: "limjob.MacroParam",
ctx: "limjob.RunContext"):
"""JOBS entry point: serve until POST /shutdown (or the idle backstop).
The Abort button cannot stop it - see the header. The hints are the
JOBS template's own, as strings so this file imports off NIS."""
serve(Bridge(Macro()))
"""JOBS entry point. Serving on the job's own thread froze NIS (step 0 of
docs/nis-bridge.md, 2026-10-15): a Python task runs on NIS's main thread,
so a loop that never returns blocks the UI. So serve on a worker thread
and return at once; the job shows as finished while the bridge keeps
listening. Stop it with POST /shutdown (or the idle backstop). Whether
NIS macro calls work from a non-main thread is UNVERIFIED: try status
first, then the moves. The hints are the JOBS template's own, as strings
so this file imports off NIS."""
threading.Thread(target=serve, args=(Bridge(Macro()),), name="nis-bridge",
daemon=True).start()
100 changes: 100 additions & 0 deletions acquisition/nis_events.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# nis_events.py
# ------------------------------------------------------------
# The NIS event log: one JSON line per thing done through the NIS bridge,
# appended to logs/nis/events-YYYY-MM-DD.jsonl. Whoever drives the bridge
# (the NIS MCP server, a script, the command line) writes here, and
# acquisition/nis_monitor.py tails the file, so the monitor shows what
# Claude is doing from another process.
#
# One action is logged as a "start" line, then one closing line: "ok", or
# "failed" (the bridge refused it or NIS reported an error), "refused" (the
# client's e-stop check stopped it before anything was sent) or "error"
# (the bridge was not reachable). The start line is what lets the monitor
# say "nd_run has been running for 42 s" while the bridge is busy.
#
# Logging must never get in the way of the microscope, so a failed write
# is swallowed.
# ------------------------------------------------------------

from __future__ import annotations

import datetime
import json
from pathlib import Path

from acquisition import paths

PHASES = ("start", "ok", "failed", "refused", "error")


def events_dir() -> Path:
return paths.logs_dir() / "nis"


def events_path(day: datetime.date | None = None) -> Path:
day = day or datetime.date.today()
return events_dir() / f"events-{day.isoformat()}.jsonl"


def record(action: str, phase: str, **fields) -> dict:
"""Append one event and return it. Never raises."""
event = {"ts": datetime.datetime.now().isoformat(timespec="milliseconds"),
"action": action, "phase": phase, **fields}
try:
path = events_path()
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as f:
f.write(json.dumps(event, ensure_ascii=False) + "\n")
except OSError:
pass
return event


def read_from(path: Path, offset: int = 0) -> tuple[list[dict], int]:
"""Events appended to `path` after byte `offset`, and the new offset.
A half-written last line is left for the next call; a missing file is
an empty log."""
try:
with path.open("rb") as f:
f.seek(offset)
data = f.read()
except OSError:
return [], offset
end = data.rfind(b"\n") + 1
events = []
for line in data[:end].splitlines():
try:
events.append(json.loads(line))
except ValueError:
continue
return events, offset + end


def summarize(event: dict) -> str:
"""One short line of detail for an event, for the monitor."""
p, r = event.get("params") or {}, event.get("result") or {}
action, phase = event.get("action"), event.get("phase")
if phase == "start":
return " ".join(f"{k}={v}" for k, v in p.items())
if phase in ("refused", "error"):
return str(event.get("message", ""))
if phase == "failed":
return str(r.get("error", r))
took = f" ({event['elapsed_s']} s)" if "elapsed_s" in event else ""
if action == "move":
return f"{_xy(r.get('before_um'))} -> {_xy(r.get('after_um'))}{took}"
if action == "objective":
return (f"{r.get('before')} -> {r.get('after')}, arrived={r.get('arrived')}"
f", nosepiece {r.get('nosepiece_before')}->{r.get('nosepiece_after')}{took}")
if action == "capture":
return f"saved={r.get('saved')} {r.get('path', '')}{took}"
if action == "nd_run":
return f"nd_running={r.get('nd_running')}{took}"
return took.strip()


def _xy(xy) -> str:
try:
return f"({xy[0]:.1f}, {xy[1]:.1f})"
except (TypeError, IndexError, ValueError):
return "?"
Loading
Loading