diff --git a/docs/plans/issue135_viewer_bind_implementation_20260929.md b/docs/plans/issue135_viewer_bind_implementation_20260929.md new file mode 100644 index 0000000000..8adf21c08e --- /dev/null +++ b/docs/plans/issue135_viewer_bind_implementation_20260929.md @@ -0,0 +1,11 @@ +# Managed viewer bind implementation checkpoint + +Replaces the planning-only state of PR #159; relates to #135. The connection address remains `StreamingDefaults.host`. The independently declared `StreamingDefaults.listen_host` defaults to `127.0.0.1` and projects through the existing `ViewerProcessLaunchConfig` into both detached Napari/Fiji entrypoints. Both server constructors pass that declaration to the existing ZMQ endpoint owner, which derives and binds data and control sockets. Explicit interfaces and `*` remain supported; IPC ignores the bind host. Externally owned viewers are connected to, not rebound by this change. + +No new catalog, registry, launch store, or string-switch router was introduced. The existing Napari process-launch comparison includes the listen address for a process the lifecycle owns. External viewers retain their own listener policy: their connection reuse checks Qt font DPI but does not request a listener change or restart. Missing old wire declarations fail decoding rather than acquiring a compatibility default. + +Focused source verification: 46 tests passed in 3.58 seconds across `test_viewer_listener_binding.py`, `test_streaming_config_factory_registry.py`, and `test_viewer_protocol.py`. The network cases construct real Napari/Fiji server owners and bind their actual data/control sockets, asserting `ZMQ_LAST_ENDPOINT` for loopback, explicit wildcard, and IPC. They do not start the GUI or Fiji JVM. The detached argument test verifies connection host and bind host remain independent. + +Outstanding acceptance: actual fresh detached Napari process through the installed user entrypoint, both OS listeners observed, and image/control response; existing external-viewer reuse through that same live path; explicit remote bind in a controlled environment. Installed source remains unchanged while the blind H003 run is active. This checkpoint is an implementation draft, not a live-readiness claim. Heavy validation is serialized with the issue batch's resource lock. + +Follow-up ownership check: local versus external listener reuse is now owned by `ViewerProcessLaunchConfig.matches_existing_viewer`, with a regression proving an external wildcard listener is not rejected/restarted because the local launch default is loopback. The focused suite now passes 47 tests in 3.01 seconds; two additional Napari launch/report tests passed separately. New listener tests pass Ruff; broad existing modules retain pre-existing lint findings, not a claimed lint-clean baseline. H003 is now frozen and its viewer slot released; fresh installed-viewer validation is the next acceptance step. diff --git a/docs/plans/issue135_viewer_bind_receipt_20260929.md b/docs/plans/issue135_viewer_bind_receipt_20260929.md new file mode 100644 index 0000000000..cdec7214d9 --- /dev/null +++ b/docs/plans/issue135_viewer_bind_receipt_20260929.md @@ -0,0 +1,25 @@ +# #135: Managed viewer listen address + +**Plan status:** provisional design, not a fix. **Source:** `OpenHCSDev/openhcs` `main` `0c7b898f852a8bedc0e1bc38b93f36088d301808`; external/ZMQRuntime gitlink `1d3b32f4fcead23d5d2079c975eb2ae7646a1478`. **Issue contract:** a localhost-requested managed TCP viewer must not expose its control endpoint on every network interface; a remotely addressable viewer remains a separate supported capability when explicitly chosen. + +## Determining facts and consumers + +- `openhcs/core/config.py:982–1010` calls `StreamingDefaults.host` the **viewer host** for client connection and permits remote TCP. `openhcs/core/streaming_config_factory.py:118–125,168–187` projects it into `ViewerTransportEndpoint` and runtime config. +- `openhcs/runtime/viewer_protocol.py:671–699` defines launch requests without a listen address; `:1289–1330` builds the client-facing runtime endpoint. `openhcs/runtime/napari_stream_visualizer.py:83–97` constructs detached arguments without a host. +- `openhcs/runtime/napari_viewer_server.py:5890–5926` constructs the server request; `:5540–5565` unconditionally gives the ZMQ parent `host="*"`. The reported `ss` observation in #135 is consistent with this source. The inherited parent binds data and control sockets; check both at the pinned dependency implementation before applying. +- `openhcs/runtime/fiji_viewer_server.py:1972` also passes `"*"`. This is a separate viewer family and a potential same-policy crossing, not automatically a regression covered by the Napari report. `openhcs/runtime/zmq_config.py:24–47` already distinguishes execution-server `client_host` and `server_host`; do not copy execution settings into viewer policy without evidence. + +## Required answers and provisional relation + +For a **locally launched** viewer, what address may the two TCP sockets bind, and what address do clients use? Candidate `R*`: the authorized listen-interface declaration must determine both the data and control bind addresses; the existing viewer transport endpoint determines connection/routing. These are different questions even if both are `127.0.0.1`. For IPC, bind-host selection must not change the local socket contract. For an **externally owned** remote viewer, OpenHCS may connect without launching or rebinding it; verify lifecycle behavior before deciding that a remote host is invalid at local launch. Unknown/OPEN: how the launch manager distinguishes local versus external ownership, exact ZMQRuntime bind propagation, Fiji parity, existing-viewer reuse, IPv6, and Windows TCP behavior. No missing class or inheritance edge is claimed. + +## Candidate owner and falsifiers + +Prefer an explicit viewer launch/bind policy carried through the existing `StreamingViewerRuntimeConfig` → managed lifecycle → detached server request, while retaining client `ViewerTransportEndpoint.host` for connection. **Do not silently reinterpret `host` as a bind interface**; remote connections and old configurations would answer different questions. Check whether the existing ZMQRuntime endpoint can carry this distinction before creating any new wrapper. The new-case test is a viewer reachable by an explicit remote host: connection host can vary without accidentally opening an all-interfaces listener when the viewer is started locally. A second falsifier is reused externally managed viewer state, which should not be killed/rebound just to honor a local setting. + +## Implementation and proof gates before promotion from draft + +1. Trace the pinned ZMQRuntime `StreamingVisualizerServer` bind and control-port policy, launcher argument serialization, Napari and Fiji lifecycles, and all other `host="*"` viewer sites. Obtain a complete contextual NRA scan and source class census if prescribing a broader owner move; log scan mode, coverage and raw record exclusions. The completed *runtime-subpackage* census/overlay is not that scan. +2. Choose/document default listen policy and explicit opt-in for remote binding with the owner if current configuration does not establish it. External ZMQ/OS socket semantics are authoritative contracts; no blanket compatibility ban may remove remote support. +3. On a real, fresh TCP viewer, assert both data and control listeners are loopback-bound for a loopback request; test an explicit remote-bind route and connection/reporting consistency. Exercise IPC, external-viewer reuse and failure cleanup. A mock asserting only constructor arguments is insufficient. +4. Gate completion on observed socket listeners and behavioral tests at the pushed SHA; review crossings with drafts #153/#154 and any Fiji equivalent. No code migration or CLI behavior is certified by this planning PR. diff --git a/docs/plans/open_issue_surface_index_20260929.md b/docs/plans/open_issue_surface_index_20260929.md new file mode 100644 index 0000000000..5f2f7424ab --- /dev/null +++ b/docs/plans/open_issue_surface_index_20260929.md @@ -0,0 +1,25 @@ +# Open issue surfaces: first planning cut + +**Source baseline:** `OpenHCSDev/openhcs` `main` at `0c7b898f852a8bedc0e1bc38b93f36088d301808` (2026-09-29). This is a triage index, not an architecture audit or permission to rewrite. The source checkout is an isolated worktree; the primary checkout is dirty and was not edited. Open PRs #153–#157, #151, #125 and #110 were inventoried before this cut. + +## Evidence and limits + +The Python 3.14.2 refactor-audit scripts parsed `openhcs/runtime`: 18,078 code lines, census headline 3.1 per 1,000 lines; overlay reported five `isinstance_switch`, three `raw_shape`, three `god_class`, nine `god_function` and 27 *heuristic* `dead_module` leads. These package-level counts are **not** evidence for any issue below, and entrypoints may be wrongly called dead. No complete NRA `--json --raw-findings --json-payload full` scan was completed, so there is no global detector coverage, class-first corpus or admitted `R*`. Issue reports are observations to verify at the implementation head. No migrations or DSL operations are proposed here. + +| Surface | Reported problem and present evidence | Ownership question / first gate | Crossing | +|---|---|---|---| +| [#135](https://github.com/OpenHCSDev/openhcs/issues/135) managed viewer bind | `StreamingDefaults.host` is a client address; `NapariViewerServer` passes `host="*"` for both sockets. [Focused receipt](issue135_viewer_bind_receipt_20260929.md). | Distinguish requested connection host from an authorized listen interface; test real TCP socket and remote-viewer reuse before deciding topology. | Draft #154 viewer control, #153 viewer result route; Fiji's separate server also passes `"*"`. | +| [#140](https://github.com/OpenHCSDev/openhcs/issues/140) execution terminality | The [independent investigation receipt in draft PR #160](https://github.com/OpenHCSDev/openhcs/pull/160) is not part of this branch. Pinned ZMQRuntime already has FAILED transitions and waiter handling; failure mechanism is OPEN. | Reproduce matching execution ID and inspect status/transport after fault, then name the broken owner. | #157 edits OpenHCS server and result path; pinned external/ZMQRuntime is a separate repository. | +| [#133](https://github.com/OpenHCSDev/openhcs/issues/133) measurement subject | Issue reports inspection/compile acceptance followed by runtime `_declared_subject` rejection. Source trace not yet performed. | Determine which artifact declaration establishes subject relation; require one compile/inspection validation at the correct phase, retain runtime integrity guard as appropriate. | #153 result inspection, #157 runtime export. | +| [#132](https://github.com/OpenHCSDev/openhcs/issues/132) Bio-Formats and ROI cost | Issue reports 16 CZI containers opened for one-axis work; comment establishes ZIP contour fragments are not biological objects. Source trace not yet performed. | Separate source-discovery filtering from label→contour→ZIP projection. Profile and preserve parent label/geometry identity before optimizing either. | Materialization #156 and result review #153; no proof these PRs touch the same code. | +| [#138](https://github.com/OpenHCSDev/openhcs/issues/138) native benchmark bootstrap | Issue reports absent pinned headless CellProfiler 4.2.8.1 / Python 3.9 / JDK 11 bootstrap. Source trace not yet performed. | A reproducible oracle environment receipt is distinct from an OpenHCS result; specify build constraints and a JVM/Pipeline acceptance check. | #155 consumes fresh native baselines but does not supply installation bootstrap. | +| [#131](https://github.com/OpenHCSDev/openhcs/issues/131) suspected MCP retention | Issue has a one-time memory snapshot, no growth slope or clean baseline. Source trace not yet performed. | Isolate MCP requests, import/native footprint, caches, separate execution server and host tmpfs swap before attributing retained memory. | MCP operation/benchmark work; do not delete other users' temporary files. | + +## Order and coordination + +1. Investigate #135's exposed TCP bind and #140's reported unbounded waiter in disjoint worktrees. Both have draft planning PRs, **not fixes**. Preserve actual external transport semantics and reject unsupported claims of equivalence. +2. Trace #133's compile/runtime declaration and #138's benchmark bootstrap independently; do not let #155's reproducibility figures substitute for environment creation. +3. Profile #132's two stages separately. Investigate #131 only with a clean, bounded process baseline, never as a presumed leak. +4. Write a fresh, scoped receipt at dispatch for each remaining surface against that day's main and overlapping PR heads. Run complete contextual NRA analysis where an ownership claim needs it; record `scan_status`, omissions, raw records and OPEN edges. If resource limits prevent it, keep design provisional, do not call the scan complete. + +No common new abstraction has yet been justified by multiple verified surfaces. Existing transport endpoints, artifact declarations, viewer lifecycle and status records are *candidates to inspect*, not licenses to create a parallel registry or an all-purpose base class. Each surface owner owns its own PR/worktree and coordinates file crossings directly. Tests protect observable bind, failure, subject, fidelity or benchmark behavior, not an imagined class layout; existing external protocol contracts remain binding. diff --git a/docs/validation/viewer_current_main_integration_20260930.rst b/docs/validation/viewer_current_main_integration_20260930.rst new file mode 100644 index 0000000000..fa17021a83 --- /dev/null +++ b/docs/validation/viewer_current_main_integration_20260930.rst @@ -0,0 +1,154 @@ +Managed viewer checkpoint against current main +============================================= + +Integration owner: parent blind-analysis thread, existing OpenHCS PR159 and +paired ZMQRuntime PR7. The isolated persistent integration tree normally merges +main65b2ed101 and the existing159 implementation; no original author tree or +dirty primary edit was changed. The gitlink conflict is resolved to actual +dependency merge2c68a114, descending from both40f9edb and main3374aa8. + +The existing atomic acquisition owner admits the new launch declaration before +returning a healthy managed viewer. The existing common lifecycle owns matching +for both Napari and Fiji. Its replaced Napari-only implementation, early manager +return and redundant no-argument matching forwarder are deleted. External +attachment does not acquire launch/rebind authority over the foreign process. +These are IMPL-4 and BOUND-2 corrections, not a second cache or viewer-kind switch. + +Current-main review also reproduced a real RGB source-window defect. The +8x9x3 RGB test declares source domain8x9/channel-axis2, but the streaming request +validated trailing dimensions9x3 and rejected the image before dispatch. It now +queries ImagePayloadMetadata.spatial_shape_yx, the existing channel/plane-aware +authority. A payload without Y/X remains rejected. Scalar and crop controls are +retained. Transport errors while reading an external launch declaration now +fail reuse admission rather than escaping as an uncaught zmq.Again. + +The compatibility-only fixture now controls the required active launch response +instead of contacting a real foreign endpoint42. The fake native-entrypoint +fixture supplies its orthogonal-widget boundary; the real widget remains enabled +in production. This prevents that fake QApplication from constructing a real +QWidget and aborting the test process. The new dock is explicitly asserted in +the event-order test, not disabled behind a product flag. + +Evidence and limits +------------------- + +The reviewed candidate was installed serially in the existing Python3.12 venv +using offline shared build cache, no dependencies, new environment, Fiji or JDK +download. Install5.90s/peak147188KiB, only OpenHCS and ZMQRuntime replaced. +Ordinary imports with PYTHONPATH unset resolve this OpenHCS tree and its exact +ZMQ submodule; ArrayBridge remains the installed409 wheel. It is an installed +candidate, not merged-main or live acceptance. + +Twenty-six dependency cases pass in2.61s: viewer acquisition, ACK startup and +progress annotation. One hundred thirteen installed core/viewer/Fiji checks +passed in6.80s after the RGB and transport corrections. Three fake native +entrypoint checks pass in5.04s,137 unrelated tests deselected. Two warnings are +disabled pytest-asyncio configuration. XMLs and original failures are retained +under the parent issue-batch ledger. The first invocation failed to find the +project test plugin from another working directory; rerunning from this actual +tree fixed that test discovery issue, without a package/source-path workaround. + +The wider Napari suite still reports other failures and its Qt-dependent tests +need separate diagnosis. Its initial process abort was a real QWidget under the +fake QApplication, not an observed crash of the user's X session. No claim that +all tests pass or that the ordinary fresh viewer is accepted. + +Original packaged structural screening at407fc3be versus main65 records5145 +metrics and two positive GodClassExcess leads: FijiViewerServer+1 and common +ManagedViewerLifecycleMixin+2. No guard waiver/pass or global NRA claim. Deleting +the redundant matching forwarder addresses real duplicate invocation structure; +a fresh committed-head screening and the remaining Fiji lead are still required. +No class is moved to a helper or mixin merely to evade the metric. + +Live acceptance uses only a tiny two-channel64x64 synthetic fixture generated +by the existing check_viewer_feature_measurement_live.make_fixture helper. +The isolated :88/5794 slot was vacant before dispatch; snapshots, source-aligned +state, OS listeners and reuse by a second fresh MCP process are required. +Every UI/viewer operation goes through actual MCP. Preserve any uncertain +dispatch without replay. Freeze evidence before closing only the proved test +viewer through its exposed lifecycle capability. + +Protected H002 GUI/runtime/viewer and original in-memory undo/history remain +unchanged. Retained5690 still has the separate geometry-source mismatch tracked +in issue280. A synthetic viewer cannot establish biological QA or solve that +protected-state cutover. The full ZIP R0/L0/S1-S8 and blind-analysis goal remain +active and incomplete. Hosted CI waiting is not imposed. + +Actual installed live checkpoint +------------------------------- + +Frozen source4cfe230f9, exact dependency2c68a114. A fresh nonresident MCP3247237 +reports this exact installed source, ready resources and no stale paths, then +discovers the full-surface stream capability and streams two64x64 synthetic +images on isolated display:88. Both real OS listeners belong to viewer3247334 +and bind only127.0.0.1:5794 and127.0.0.1:6794. Typed state is observed, image +route and native Y/X axes are present, and the actual opened bitmap shows the +expected gradient and native controls. + +A second fresh nonresident MCP3251697 successfully streams the same retained +fixture through external attachment, observes typed state, captures another +bitmap and closes the test viewer through openhcs_close_viewer_window. That +response reports succeeded/endpoint_terminated. Both listeners and all three +owned processes are independently absent after terminal completion; no OS +signal was used. Original protected H002 processes remain unchanged. Both +bitmaps were opened by the parent. Their camera zoom differs1.349 versus +2.529375 with unchanged center/canvas; this is not a matched biological QA set +or a claim of preserving presentation across streaming. + +Final installed core/viewer/Fiji regression rerun:113 pass6.45s, zero skips and +deselections, on the committed4cfe source with PYTHONPATH unset. Three fake +native-entrypoint checks pass separately,137 unrelated cases deselected. +The wider Napari suite remains failed; its scope is not exonerated. + +Post-correction original screening retains5145metrics and just the Fiji class ++1 lead. Its exact new line is projection of launch_config.process_launch into +the existing control context, not another policy/registry or dispatch. The +common lifecycle's redundant forwarding member is genuinely removed. Paired +dependency screening retains158metrics and one ForeignAbsenceProbe lead on +``not instance.visualizer.is_running``. This queries the original nominal +visualizer health contract, rather than reconstructing another owner's state +from optional/private fields. Neither screening is called a pass and no guard +was weakened. These original report limits remain part of full R0 acceptance; +locally tested installed/live checkpoint shipment is distinct from whole-plan +completion, under the owner's explicit CI-deferral and checkpoint requirements. + +The first client batch contained a local JSON quoting error before any stream +dispatch. Its original response is preserved; source confirms argument parsing +precedes tool dispatch. The next batch supplied corrected local input, never +replayed an uncertain mutation. Misclassification as a transport error is now +tracked separately in issue283. The RGB source defect is tracked in issue282, +whose original failing counterexample is retained and now passes. + +Durable small fixture, original/fresh client responses and both captures live +under tests/runtime_diagnostics/viewer_admission_live_20260930. No private XDG +configuration/cache is published. Resources after closing the test viewer: +17.5GiB available RAM,14.4GiB swap warning and20.3GiB home free. Removed only +300KiB of older verified disposable build/diagnostic scratch; all source, saved +history and durable receipts remain. No new scientific runtime or agent fleet. + +Current-main shipment checkpoint +------------------------------- + +Normally merged performance main cad1ed2bd without conflicts. The earlier wider +Napari failures are now diagnosed and fixed in test fixtures, not waived: state, +navigation and native intensity tests supplied incomplete Dims/camera doubles. +They now use Napari's own Dims and Camera models with representative ranges; +the nonzero current_step is assigned through its real setter. All original +assertions remain, plus explicit displayed-axis/order/canvas projections. +Production state projection still trusts the original native contracts directly; +no attribute-default fallback or extra dispatch was added (BOUND-7). + +The offscreen Qt run terminated at GLX context creation, with no complete XML. +Its observation is retained separately from the original fake-QApplication +abort. The actual native Qt tests succeed using existing isolated display :88 +and software GL. The coherent current-main installed-source shard passes all +253 Napari/core/viewer/Fiji cases in12.77s, zero skips/deselections, with only +two disabled pytest-asyncio configuration warnings. Durable result: +parent ledger viewer-current-main-final-253-20260930.xml. Intermediate failed +XMLs remain there too. No hosted CI wait or full-plan guard-pass claim. + +The earlier actual MCP launch/external-attach/state/bitmap/close journey proves +the unchanged viewer implementation; it does not evaluate biological accuracy. +Paired ZMQRuntime PR7 is now merged at2aa6d21c, code-identical to this reviewed +2c68a114 pin. Retained H002 history and issue280 remain protected. The full ZIP +refactors, reference boundaries and autonomous scientific acceptance stay open. diff --git a/external/zmqruntime b/external/zmqruntime index 0f9e840a9e..2c68a114bc 160000 --- a/external/zmqruntime +++ b/external/zmqruntime @@ -1 +1 @@ -Subproject commit 0f9e840a9ed526f0a2b87a660393f5b7c34fc9eb +Subproject commit 2c68a114bc7121e6e72124edbaaf321cccc1a2b7 diff --git a/openhcs/core/config.py b/openhcs/core/config.py index 8aaa01daba..64f7bd695c 100644 --- a/openhcs/core/config.py +++ b/openhcs/core/config.py @@ -1003,6 +1003,14 @@ class StreamingDefaults(Enableable, StepWellFilterConfig): IPC transports remain local regardless of this value. """ + listen_host: Annotated[NonBlankString, abbreviation("listen")] = "127.0.0.1" + """Interface for a locally launched viewer's TCP data and control sockets. + + The default keeps managed viewers local. Set an explicit interface or + ``*`` to permit remote clients. This does not change the connection host + above, rebind an externally owned viewer, or affect IPC transport. + """ + transport_mode: Annotated[TransportMode, abbreviation("transport")] = ( get_default_transport_mode() ) @@ -1167,7 +1175,10 @@ class NapariStreamingConfig( def viewer_process_launch_config(self) -> ViewerProcessLaunchConfig: """Project Napari's process-global Qt setting onto viewer launch.""" - return ViewerProcessLaunchConfig(qt_font_dpi=self.font_dpi) + return ViewerProcessLaunchConfig( + qt_font_dpi=self.font_dpi, + listen_host=self.listen_host, + ) @abbreviation("fiji") diff --git a/openhcs/core/streaming_config_factory.py b/openhcs/core/streaming_config_factory.py index 6e7325728a..4ed05c6089 100644 --- a/openhcs/core/streaming_config_factory.py +++ b/openhcs/core/streaming_config_factory.py @@ -80,6 +80,7 @@ class ViewerProcessLaunchField(str, Enum): """Wire fields projected from the viewer process-launch declaration.""" QT_FONT_DPI = "qt_font_dpi" + LISTEN_HOST = "listen_host" @dataclass(frozen=True, slots=True) @@ -87,18 +88,40 @@ class ViewerProcessLaunchConfig: """Process-global settings that must exist before viewer construction.""" qt_font_dpi: int | None = None + listen_host: str = "127.0.0.1" def __post_init__(self) -> None: + if not isinstance(self.listen_host, str): + raise TypeError("Viewer listen host must be a string.") + if not self.listen_host.strip(): + raise ValueError("Viewer listen host must not be blank.") if self.qt_font_dpi is not None and self.qt_font_dpi <= 0: raise ValueError("Viewer Qt font DPI must be positive when provided.") - def to_wire_mapping(self) -> dict[str, int | None]: + def to_wire_mapping(self) -> dict[str, str | int | None]: """Project the launch declaration onto the viewer control boundary.""" return { ViewerProcessLaunchField.QT_FONT_DPI.value: self.qt_font_dpi, + ViewerProcessLaunchField.LISTEN_HOST.value: self.listen_host, } + def matches_existing_viewer( + self, + active: "ViewerProcessLaunchConfig", + *, + owns_process: bool, + ) -> bool: + """Require local bind policy only for a process this lifecycle owns. + + An externally owned viewer's listen interface is not a client launch + setting: accepting its connection must not request a rebind/restart. + """ + + return self.qt_font_dpi == active.qt_font_dpi and ( + not owns_process or self.listen_host == active.listen_host + ) + @classmethod def from_wire_mapping( cls, @@ -111,7 +134,10 @@ def from_wire_mapping( not isinstance(value, int) or isinstance(value, bool) ): raise TypeError("Viewer Qt font DPI must be an integer or None.") - return cls(qt_font_dpi=value) + return cls( + qt_font_dpi=value, + listen_host=payload[ViewerProcessLaunchField.LISTEN_HOST.value], + ) @dataclass(frozen=True, slots=True) @@ -190,7 +216,7 @@ def viewer_runtime_config( def viewer_process_launch_config(self) -> ViewerProcessLaunchConfig: """Return process-launch settings owned by this viewer declaration.""" - return ViewerProcessLaunchConfig() + return ViewerProcessLaunchConfig(listen_host=self.listen_host) def viewer_surface( self, diff --git a/openhcs/core/viewer_streaming_service.py b/openhcs/core/viewer_streaming_service.py index d867b82b5a..c1822b8a5a 100644 --- a/openhcs/core/viewer_streaming_service.py +++ b/openhcs/core/viewer_streaming_service.py @@ -102,9 +102,11 @@ def require_image_window( projection: VirtualWorkspaceSourceProjection, ) -> None: """Admit the original source window, including a declared bounded crop.""" - image_payload_metadata(image).source_spatial_domain.require_image_window( - image_payload_data(image).shape[-2:] - ) + metadata = image_payload_metadata(image) + shape_yx = metadata.spatial_shape_yx(image) + if shape_yx is None: + raise ValueError("Streamed image requires declared spatial Y/X axes.") + metadata.source_spatial_domain.require_image_window(shape_yx) @dataclass(frozen=True, slots=True) @@ -200,6 +202,7 @@ def get_or_create_visualizer( from openhcs.runtime.viewer_protocol import ( ViewerGraphicalSessionUnavailableError, ViewerLaunchContext, + ViewerProcessLaunchAdmission, ) resolved_launch_context = ( @@ -216,25 +219,6 @@ def get_or_create_visualizer( stop=True, force=True, ) - else: - managed_viewer = manager.get_viewer( - config.viewer_type.wire_value, - config.port, - ) - if managed_viewer is not None: - return managed_viewer - - external_viewer = StreamingViewerLifecycle._create_managed_visualizer( - filemanager=filemanager, - config=config, - visualizer_config=visualizer_config, - transport_config=transport_config, - launch_context=resolved_launch_context, - ) - if external_viewer.existing_viewer_is_ready(): - external_viewer.lifecycle_state.mark_connected_external() - return external_viewer - created_viewer: ManagedViewerLifecycleMixin | None = None def create_viewer() -> ManagedViewerLifecycleMixin: @@ -246,6 +230,8 @@ def create_viewer() -> ManagedViewerLifecycleMixin: transport_config=transport_config, launch_context=resolved_launch_context, ) + if not fresh and created_viewer.existing_viewer_is_ready(): + created_viewer.lifecycle_state.mark_connected_external() return created_viewer try: @@ -255,6 +241,9 @@ def create_viewer() -> ManagedViewerLifecycleMixin: factory=create_viewer, wait_for_ready=True, ready_timeout=ready_timeout, + reuse_admission=ViewerProcessLaunchAdmission( + config.viewer_process_launch_config() + ), ) except ViewerGraphicalSessionUnavailableError: raise diff --git a/openhcs/runtime/fiji_stream_visualizer.py b/openhcs/runtime/fiji_stream_visualizer.py index 68e2cba8c5..bf1fc21183 100644 --- a/openhcs/runtime/fiji_stream_visualizer.py +++ b/openhcs/runtime/fiji_stream_visualizer.py @@ -65,6 +65,7 @@ def detached_server_arguments( ).append( DetachedViewerPythonExpression.symbol("transport_mode"), DetachedViewerPythonExpression.symbol("OPENHCS_ZMQ_CONFIG"), + DetachedViewerPythonExpression.literal(self.process_launch.listen_host), ) def start_viewer(self, async_mode: bool = False) -> None: diff --git a/openhcs/runtime/fiji_viewer_server.py b/openhcs/runtime/fiji_viewer_server.py index 8131843923..cc7e6c931a 100644 --- a/openhcs/runtime/fiji_viewer_server.py +++ b/openhcs/runtime/fiji_viewer_server.py @@ -30,6 +30,7 @@ from openhcs.core.config import FijiDisplayConfig from openhcs.core.runtime_plane_projection import RuntimePlaneAxis from openhcs.core.streaming_config_declarations import ViewerType +from openhcs.core.streaming_config_factory import ViewerProcessLaunchConfig from openhcs.runtime.fiji_macro_runtime import ( FijiMacroExecutionRequest, FijiMacroExecutionResponse, @@ -51,11 +52,13 @@ from openhcs.runtime.viewer_protocol import ( FijiPayloadKind, OpenHCSViewerServerABC, + OpenHCSViewerControlMessageType, ViewerBatchContextWireField, ViewerBatchMessageType, ViewerBatchWireField, ViewerComponentValueOrdering, ViewerControlMessageType, + ViewerControlField, ViewerControlReplyHeader, ViewerControlReplyPayload, ViewerControlResponseField, @@ -1216,6 +1219,9 @@ class FijiControlRequestContext: windows: FijiWindowRegistry imagej_runtime: object settlement: FijiBatchSettlementState + process_launch: ViewerProcessLaunchConfig = field( + default_factory=ViewerProcessLaunchConfig + ) class FijiControlMessagePlan(ABC, metaclass=AutoRegisterMeta): @@ -1309,6 +1315,25 @@ def response( ) +class FijiProcessLaunchControlPlan(FijiControlMessagePlan): + """Project the server-owned launch declaration through the common boundary.""" + + wire_value = OpenHCSViewerControlMessageType.PROCESS_LAUNCH.value + + def response( + self, context: FijiControlRequestContext, payload: object | None + ) -> FijiControlMessageResponse: + return FijiControlMessageResponse( + ViewerControlReplyHeader( + ViewerProtocolStatus.SUCCESS, response_type="process_launch_ack" + ), + fields={ + ViewerControlField.PROCESS_LAUNCH.value: + context.process_launch.to_wire_mapping(), + }, + ) + + class FijiSettleControlPlan(FijiControlMessagePlan): """Report exact queued and active Fiji display-batch progress.""" @@ -1969,7 +1994,7 @@ def __init__(self, launch_config: FijiViewerServerLaunchConfig): super().__init__( launch_config.port, viewer_type=ViewerType.FIJI.wire_value, - host="*", + host=launch_config.process_launch.listen_host, log_file_path=launch_config.log_file_path, data_socket_type=zmq.REP, transport_mode=launch_config.transport_mode, @@ -2128,6 +2153,7 @@ def handle_control_message( self.windows, self.ij, self.batch_processor.settlement, + self.launch_config.process_launch, ) ).response_for(message) if response.shutdown_requested: @@ -3139,6 +3165,7 @@ def fiji_viewer_server_process( display_enabled: bool = True, transport_mode: TransportMode = TransportMode.IPC, zmq_config: ZMQConfig | None = None, + listen_host: str = "127.0.0.1", ): """ Fiji viewer server process function. @@ -3152,6 +3179,7 @@ def fiji_viewer_server_process( log_file_path: Path to log file (for client discovery via ping/pong) transport_mode: ZMQ transport mode (IPC or TCP) zmq_config: ZMQ configuration object (optional, uses default if None) + listen_host: Explicit TCP bind interface; defaults to local-only """ server = None try: @@ -3166,6 +3194,7 @@ def fiji_viewer_server_process( display_enabled=display_enabled, transport_mode=transport_mode, zmq_config=zmq_config, + process_launch=ViewerProcessLaunchConfig(listen_host=listen_host), ) ) diff --git a/openhcs/runtime/napari_stream_visualizer.py b/openhcs/runtime/napari_stream_visualizer.py index c786a2c6ad..c7cd97eb15 100644 --- a/openhcs/runtime/napari_stream_visualizer.py +++ b/openhcs/runtime/napari_stream_visualizer.py @@ -15,7 +15,6 @@ import logging import threading -from collections.abc import Mapping from pathlib import Path from typing import Optional @@ -25,16 +24,12 @@ from openhcs.core.streaming_config_declarations import ViewerType from openhcs.core.streaming_config_factory import ( StreamingViewerRuntimeConfig, - ViewerProcessLaunchConfig, ) from openhcs.runtime.viewer_protocol import ( DetachedViewerPythonArguments, DetachedViewerPythonExpression, DetachedViewerServerEntrypointSpec, ManagedViewerLifecycleMixin, - OpenHCSViewerControlMessageType, - ViewerControlField, - ViewerControlMessageRequest, ) from openhcs.utils.import_utils import optional_import_or_none @@ -94,32 +89,9 @@ def detached_server_arguments( DetachedViewerPythonExpression.symbol("transport_mode"), DetachedViewerPythonExpression.literal(self.scope_accent_color), DetachedViewerPythonExpression.literal(self.process_launch.qt_font_dpi), + DetachedViewerPythonExpression.literal(self.process_launch.listen_host), ) - def existing_viewer_matches_process_launch(self) -> bool: - """Require exact process-global settings before reusing a viewer.""" - - try: - response = ViewerControlMessageRequest( - endpoint=self.runtime_endpoint, - message_type=(OpenHCSViewerControlMessageType.PROCESS_LAUNCH.value), - ).send() - if not response.succeeded(): - return False - wire_config = response.payload[ViewerControlField.PROCESS_LAUNCH.value] - if not isinstance(wire_config, Mapping): - raise TypeError( - "Napari process-launch response must contain a mapping." - ) - active_config = ViewerProcessLaunchConfig.from_wire_mapping(wire_config) - except Exception as error: - logger.warning( - "Napari viewer process-launch compatibility check failed: %s", - error, - ) - return False - return active_config == self.process_launch - def start_viewer(self, async_mode: bool = True): """ Starts the Napari viewer in a separate process. diff --git a/openhcs/runtime/napari_viewer_server.py b/openhcs/runtime/napari_viewer_server.py index 53fefab5b8..7eb36fcaef 100644 --- a/openhcs/runtime/napari_viewer_server.py +++ b/openhcs/runtime/napari_viewer_server.py @@ -5929,7 +5929,7 @@ def __init__(self, request: NapariViewerServerRequest): super().__init__( request.port, viewer_type=ViewerType.NAPARI.wire_value, - host="*", + host=request.process_launch.listen_host, log_file_path=request.log_file_path, data_socket_type=zmq.REP, transport_mode=request.transport_mode, @@ -6268,6 +6268,7 @@ def run_napari_viewer_process( transport_mode: TransportMode = TransportMode.IPC, scope_accent_color: str | None = None, font_dpi: int | None = None, + listen_host: str = "127.0.0.1", ) -> None: """ Napari viewer process entry point. Runs in a separate process. @@ -6281,6 +6282,7 @@ def run_napari_viewer_process( transport_mode: ZMQ transport mode (IPC or TCP) scope_accent_color: Exact UI-owned scope accent used to frame this window font_dpi: Explicit Qt font DPI applied before viewer construction + listen_host: Explicit TCP bind interface; defaults to local-only """ import polystore from openhcs.runtime.import_authority import OpenHCSRuntimeImportAuthority @@ -6299,7 +6301,10 @@ def run_napari_viewer_process( replace_layers=replace_layers, log_file_path=log_file_path, transport_mode=transport_mode, - process_launch=ViewerProcessLaunchConfig(qt_font_dpi=font_dpi), + process_launch=ViewerProcessLaunchConfig( + qt_font_dpi=font_dpi, + listen_host=listen_host, + ), ) # Create ZMQ server instance (inherits from ZMQServer ABC) diff --git a/openhcs/runtime/viewer_protocol.py b/openhcs/runtime/viewer_protocol.py index f1549bac42..39e6e7abbb 100644 --- a/openhcs/runtime/viewer_protocol.py +++ b/openhcs/runtime/viewer_protocol.py @@ -30,6 +30,7 @@ ) from zmqruntime.streaming import StreamingVisualizerServer, VisualizerProcessManager from zmqruntime.transport import resolve_transport_mode +from zmqruntime.viewer_state import ViewerReuseAdmissionABC from openhcs.runtime.import_authority import ( OpenHCSRuntimeImportAuthority, ) @@ -1289,6 +1290,24 @@ def send(self) -> ViewerControlResponse: context.term() +@dataclass(frozen=True, slots=True) +class ViewerProcessLaunchAdmission(ViewerReuseAdmissionABC): + """Admit a new OpenHCS launch request inside atomic managed acquisition.""" + + requested: ViewerProcessLaunchConfig + + def require_reusable(self, visualizer: VisualizerProcessManager) -> None: + if not isinstance(visualizer, ManagedViewerLifecycleMixin): + raise TypeError("OpenHCS reuse requires a managed OpenHCS lifecycle.") + if not visualizer.matches_requested_process_launch(self.requested): + raise RuntimeError( + f"{visualizer.viewer_process_label} viewer on port " + f"{visualizer.required_port} does not match the requested " + f"process launch {self.requested!r}. The existing viewer is " + "unchanged; explicitly request a fresh viewer to replace it." + ) + + class ManagedViewerLifecycleMixin( VisualizerProcessManager, ExecutionVisualizerABC, @@ -1416,7 +1435,7 @@ def existing_viewer_is_ready(self) -> bool: timeout_ms=request.timeout_ms, require_ready=request.require_ready, ).require_match() - if not self.existing_viewer_matches_process_launch(): + if not self.matches_requested_process_launch(self.process_launch): logging.getLogger(type(self).__module__).warning( "%s viewer on port %s has a different process-launch " "declaration and cannot be reused.", @@ -1434,10 +1453,38 @@ def existing_viewer_is_ready(self) -> bool: return False return True - def existing_viewer_matches_process_launch(self) -> bool: - """Return whether a reachable viewer matches process-global settings.""" + def matches_requested_process_launch( + self, requested: ViewerProcessLaunchConfig + ) -> bool: + """Compare a new request with this lifecycle's actual active launch. - return True + Owned processes were launched from this immutable declaration. External + processes report their declaration through the shared control boundary; + a client does not gain authority over their listening interface. + """ + owns_process = self.owned_viewer_process_is_alive() + try: + active = self.process_launch if owns_process else self.active_process_launch() + return requested.matches_existing_viewer(active, owns_process=owns_process) + except (RuntimeError, TypeError, ValueError, KeyError, zmq.ZMQError) as error: + logging.getLogger(type(self).__module__).warning( + "%s viewer process-launch check failed: %s", + self.viewer_process_label, error, + ) + return False + + def active_process_launch(self) -> ViewerProcessLaunchConfig: + """Decode the process-global declaration once at its wire boundary.""" + response = ViewerControlMessageRequest( + endpoint=self.runtime_endpoint, + message_type=OpenHCSViewerControlMessageType.PROCESS_LAUNCH.value, + ).send() + if not response.succeeded(): + raise RuntimeError("Viewer did not admit process-launch inspection.") + wire_config = response.payload[ViewerControlField.PROCESS_LAUNCH.value] + if not isinstance(wire_config, Mapping): + raise TypeError("Viewer process-launch response must contain a mapping.") + return ViewerProcessLaunchConfig.from_wire_mapping(wire_config) def wait_for_ready(self, timeout: float = 10.0) -> bool: """Wait for the viewer endpoint to bind and report ready.""" diff --git a/tests/runtime_diagnostics/viewer_admission_live_20260930/captures-reused/20260930T132110280409Z_napari_5794_OpenHCS_Napari_Visualization.png b/tests/runtime_diagnostics/viewer_admission_live_20260930/captures-reused/20260930T132110280409Z_napari_5794_OpenHCS_Napari_Visualization.png new file mode 100644 index 0000000000..08ae55c9dc Binary files /dev/null and b/tests/runtime_diagnostics/viewer_admission_live_20260930/captures-reused/20260930T132110280409Z_napari_5794_OpenHCS_Napari_Visualization.png differ diff --git a/tests/runtime_diagnostics/viewer_admission_live_20260930/captures/20260930T131815752112Z_napari_5794_OpenHCS_Napari_Visualization.png b/tests/runtime_diagnostics/viewer_admission_live_20260930/captures/20260930T131815752112Z_napari_5794_OpenHCS_Napari_Visualization.png new file mode 100644 index 0000000000..f0a2357154 Binary files /dev/null and b/tests/runtime_diagnostics/viewer_admission_live_20260930/captures/20260930T131815752112Z_napari_5794_OpenHCS_Napari_Visualization.png differ diff --git a/tests/runtime_diagnostics/viewer_admission_live_20260930/first-client-parser-failure.jsonl b/tests/runtime_diagnostics/viewer_admission_live_20260930/first-client-parser-failure.jsonl new file mode 100644 index 0000000000..c090d49f82 --- /dev/null +++ b/tests/runtime_diagnostics/viewer_admission_live_20260930/first-client-parser-failure.jsonl @@ -0,0 +1,68 @@ +{ + "errors": [], + "results": [ + { + "mcp_error": false, + "payloads": [ + { + "automatic_recovery_on_reconnect": false, + "errors": [], + "installation_pointer_available": null, + "installation_pointer_changed_since_import": false, + "installation_pointer_path": null, + "missing_packaged_resource_paths": [], + "openhcs_version": "0.8.6", + "packaged_resource_count": 56, + "packaged_resources_ready": true, + "reconnect_owner": null, + "reconnect_required": false, + "recovery_reason": "current", + "restart_command": [], + "restart_command_is_stable": false, + "restart_hint": null, + "restart_required": false, + "retry_after_reconnect": false, + "schema_version": "openhcs.agent.v1", + "server_current_mtime_ns": 1790772771376925738, + "server_import_mtime_ns": 1790772771376925738, + "server_process_id": 3244873, + "server_source_changed_since_import": false, + "server_source_path": "/home/ts/wt/openhcs-viewer-live-20260930/openhcs/mcp/server.py", + "service": "openhcs.mcp", + "stale_source_paths": [], + "started_at_unix": 1790774184.4063082, + "status": "ok", + "warnings": [] + } + ], + "tool": "openhcs_health_check" + } + ], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} +{ + "errors": [ + { + "causes": [ + { + "exception_type": "JSONDecodeError", + "message": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)" + } + ], + "code": "mcp_transport_failed", + "exception_type": "JSONDecodeError", + "hint": "The fresh OpenHCS MCP subprocess did not complete the requested stdio exchange. The dev client captures a bounded server stderr tail on transport failures so startup tracebacks remain visible without noisy successful calls.", + "message": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)", + "phase": "call_tool", + "server_stderr_tail": null + } + ], + "results": [], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} diff --git a/tests/runtime_diagnostics/viewer_admission_live_20260930/first-client.jsonl b/tests/runtime_diagnostics/viewer_admission_live_20260930/first-client.jsonl new file mode 100644 index 0000000000..93c3263a99 --- /dev/null +++ b/tests/runtime_diagnostics/viewer_admission_live_20260930/first-client.jsonl @@ -0,0 +1,811 @@ +{ + "errors": [], + "results": [ + { + "mcp_error": false, + "payloads": [ + { + "automatic_recovery_on_reconnect": false, + "errors": [], + "installation_pointer_available": null, + "installation_pointer_changed_since_import": false, + "installation_pointer_path": null, + "missing_packaged_resource_paths": [], + "openhcs_version": "0.8.6", + "packaged_resource_count": 56, + "packaged_resources_ready": true, + "reconnect_owner": null, + "reconnect_required": false, + "recovery_reason": "current", + "restart_command": [], + "restart_command_is_stable": false, + "restart_hint": null, + "restart_required": false, + "retry_after_reconnect": false, + "schema_version": "openhcs.agent.v1", + "server_current_mtime_ns": 1790772771376925738, + "server_import_mtime_ns": 1790772771376925738, + "server_process_id": 3247237, + "server_source_changed_since_import": false, + "server_source_path": "/home/ts/wt/openhcs-viewer-live-20260930/openhcs/mcp/server.py", + "service": "openhcs.mcp", + "stale_source_paths": [], + "started_at_unix": 1790774285.2953663, + "status": "ok", + "warnings": [] + } + ], + "tool": "openhcs_health_check" + } + ], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} +{ + "errors": [], + "results": [ + { + "mcp_error": false, + "payloads": [ + { + "capabilities": [ + { + "data_exposure": [ + "local_plate_path", + "plate_virtual_image_path", + "plate_source_image_path", + "result_artifact_names", + "viewer_connection" + ], + "description": "Resolves image or ROI result records by virtual path, source path, result path, basename, or bounded inventory query, then streams them to a managed viewer through the same core service used by the Image Browser. Set result_directory to reopen retained native results independently of their output location; plate_path supplies the original source context. ROI reopening requires persisted source metadata, not filename guesses.", + "input_type": "PlateFileStreamRequest", + "kind": "tool", + "name": "openhcs_stream_plate_files_to_viewer", + "output_type": "PlateFileStreamResult", + "read_only": false, + "required_extras": [ + "viz" + ], + "requires_network": false, + "role": "primary", + "runtime_requirements": [ + "napari_or_fiji_viewer_runtime" + ], + "security_requirements": [ + "AgentPathPolicy readable root" + ], + "side_effects": [ + "launches_or_updates_managed_viewer" + ], + "target_context": "plate_path", + "title": "Stream plate files to viewer", + "visibility": "beginner", + "workflow_group": "plate_data", + "workflow_stage": "data_preparation" + }, + { + "data_exposure": [ + "ui_selected_plate_path", + "plate_virtual_image_path", + "plate_source_image_path", + "result_artifact_names", + "viewer_connection" + ], + "description": "Reads the current PlateManager selection from the running UI bridge, resolves selected/source/output image or ROI records through the same inventory API as openhcs_ui_query_selected_plate_files, then streams them to a managed viewer.", + "input_type": "SelectedPlateFileStreamRequest", + "kind": "tool", + "name": "openhcs_ui_stream_selected_plate_files_to_viewer", + "output_type": "SelectedPlateFileStreamResult", + "read_only": true, + "required_extras": [ + "viz" + ], + "requires_network": false, + "role": "mode_variant", + "runtime_requirements": [ + "running_openhcs_ui_bridge", + "napari_or_fiji_viewer_runtime" + ], + "security_requirements": [ + "ui_bridge_auth_token", + "AgentPathPolicy readable root" + ], + "side_effects": [], + "target_context": "ui_selected_plate", + "title": "Stream selected plate files to viewer", + "visibility": "standard", + "workflow_group": "ui_selected_plate", + "workflow_stage": "data_preparation" + } + ], + "matched_count": 2, + "next_offset": null, + "query": { + "has_side_effects": null, + "kind": null, + "limit": 12, + "offset": 0, + "role": null, + "side_effect_contains": null, + "target_context": null, + "text": "managed viewer", + "visibility": null, + "workflow_group": null, + "workflow_stage": null + }, + "returned_count": 2, + "schema_version": "openhcs.agent.v1", + "surface_profile": "full" + } + ], + "tool": "openhcs_search_capabilities" + } + ], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} +{ + "errors": [], + "results": [ + { + "mcp_error": false, + "payloads": [ + { + "connection": { + "host": "127.0.0.1", + "persistent": true, + "port": 5794, + "transport_mode": "tcp" + }, + "detected_microscope_type": "openhcsdata", + "errors": [], + "handler_class": "OpenHCSMicroscopeHandler", + "parser_class": "SourceSchemaFilenameParser", + "plate_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate", + "requested_microscope_type": "auto", + "requested_paths": [], + "resolved_records": [ + { + "file_format": null, + "full_path": null, + "full_virtual_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/A01_s001_w1_z001_t001.tif", + "key": "A01_s001_w1_z001_t001.tif", + "kind": "image", + "metadata": { + "channel": 1, + "extension": ".tif", + "filename": "A01_s001_w1_z001_t001.tif", + "full_virtual_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/A01_s001_w1_z001_t001.tif", + "modified": "2026-09-30T09:13:48", + "site": 1, + "size": "8.2 KB", + "source_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel1.tif", + "timepoint": 1, + "type": "Image", + "virtual_path": "A01_s001_w1_z001_t001.tif", + "well": "A01", + "z_index": 1 + }, + "preview": null, + "relative_path": null, + "source_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel1.tif", + "virtual_path": "A01_s001_w1_z001_t001.tif" + }, + { + "file_format": null, + "full_path": null, + "full_virtual_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/A01_s001_w2_z002_t001.tif", + "key": "A01_s001_w2_z002_t001.tif", + "kind": "image", + "metadata": { + "channel": 2, + "extension": ".tif", + "filename": "A01_s001_w2_z002_t001.tif", + "full_virtual_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/A01_s001_w2_z002_t001.tif", + "modified": "2026-09-30T09:13:48", + "site": 1, + "size": "8.2 KB", + "source_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel2.tif", + "timepoint": 1, + "type": "Image", + "virtual_path": "A01_s001_w2_z002_t001.tif", + "well": "A01", + "z_index": 2 + }, + "preview": null, + "relative_path": null, + "source_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel2.tif", + "virtual_path": "A01_s001_w2_z002_t001.tif" + } + ], + "schema_version": "openhcs.agent.v1", + "skipped_records": [], + "status_messages": [ + "Loading chunk 1/1 (2 images)...", + "Streamed 2 images to Napari" + ], + "streamed_image_paths": [ + "A01_s001_w1_z001_t001.tif", + "A01_s001_w2_z002_t001.tif" + ], + "streamed_roi_paths": [], + "viewer_config_key": "napari_streaming_config", + "viewer_type": "napari", + "warnings": [] + } + ], + "tool": "openhcs_stream_plate_files_to_viewer" + } + ], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} +{ + "errors": [], + "results": [ + { + "mcp_error": false, + "payloads": [ + { + "active_dimension_label_route": "origin_manual_kind_manual_projection_selected_images_2279edf51d62e30c88170a053918455cf4575618753b42fb99afb6149c7e1fc1", + "axis_labels": [ + "site", + "channel", + "z_index", + "timepoint", + "well", + "y", + "x" + ], + "component_group_count": 1, + "component_item_count": 2, + "connection": { + "host": "127.0.0.1", + "persistent": true, + "port": 5794, + "transport_mode": "tcp" + }, + "current_step": [ + 0, + 0, + 0, + 0, + 0, + 39, + 49 + ], + "errors": [], + "layer_count": 1, + "layers": [ + { + "axis_component_values": { + "channel": [ + 1, + 2 + ], + "z_index": [ + 1, + 2 + ] + }, + "axis_labels": [ + "site", + "channel", + "z_index", + "timepoint", + "well", + "y", + "x" + ], + "axis_offsets": [ + 0, + 0 + ], + "component_value_count": 2, + "component_values": [ + { + "channel": 1, + "site": 1, + "timepoint": 1, + "well": "A01", + "z_index": 1 + }, + { + "channel": 2, + "site": 1, + "timepoint": 1, + "well": "A01", + "z_index": 2 + } + ], + "component_values_truncated": false, + "data_shape": [ + 1, + 2, + 2, + 1, + 1, + 80, + 100 + ], + "data_types": [ + "image" + ], + "feature_row_count": 0, + "item_count": 2, + "labels": { + "channel": [ + "Ch 1", + "Ch 2" + ], + "z_index": [ + "Z 1", + "Z 2" + ] + }, + "mounted": true, + "native_intensity": { + "contrast_limits": [ + 0.0, + 693.0 + ], + "gamma": 1.0 + }, + "native_transform": { + "scale": [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 2.0, + 3.0 + ], + "translate": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "payload_summaries": [ + { + "components": { + "channel": 1, + "site": 1, + "timepoint": 1, + "well": "A01", + "z_index": 1 + }, + "data_type": "image", + "dtype": "uint16", + "max": 693, + "min": 0, + "nonzero_count": 4095, + "nonzero_example_coordinates": [ + [ + 0, + 1 + ], + [ + 4, + 17 + ], + [ + 8, + 34 + ], + [ + 12, + 51 + ], + [ + 17, + 4 + ], + [ + 21, + 21 + ], + [ + 25, + 38 + ], + [ + 29, + 55 + ], + [ + 34, + 8 + ], + [ + 38, + 25 + ], + [ + 42, + 42 + ], + [ + 46, + 59 + ], + [ + 51, + 12 + ], + [ + 55, + 29 + ], + [ + 59, + 46 + ], + [ + 63, + 63 + ] + ], + "nonzero_max_coordinate": [ + 63, + 63 + ], + "nonzero_min_coordinate": [ + 0, + 0 + ], + "path": "A01_s001_w1_z001_t001.tif", + "payload_type": "ndarray", + "shape": [ + 64, + 64 + ], + "size": 4096, + "source_spatial_shape_yx": [ + 80, + 100 + ], + "spatial_origin_yx": [ + 7, + 11 + ] + }, + { + "components": { + "channel": 2, + "site": 1, + "timepoint": 1, + "well": "A01", + "z_index": 2 + }, + "data_type": "image", + "dtype": "uint16", + "max": 80, + "min": 5, + "nonzero_count": 4096, + "nonzero_example_coordinates": [ + [ + 0, + 0 + ], + [ + 4, + 17 + ], + [ + 8, + 34 + ], + [ + 12, + 51 + ], + [ + 17, + 4 + ], + [ + 21, + 21 + ], + [ + 25, + 38 + ], + [ + 29, + 55 + ], + [ + 34, + 8 + ], + [ + 38, + 25 + ], + [ + 42, + 42 + ], + [ + 46, + 59 + ], + [ + 51, + 12 + ], + [ + 55, + 29 + ], + [ + 59, + 46 + ], + [ + 63, + 63 + ] + ], + "nonzero_max_coordinate": [ + 63, + 63 + ], + "nonzero_min_coordinate": [ + 0, + 0 + ], + "path": "A01_s001_w2_z002_t001.tif", + "payload_type": "ndarray", + "shape": [ + 64, + 64 + ], + "size": 4096, + "source_spatial_shape_yx": [ + 80, + 100 + ], + "spatial_origin_yx": [ + 7, + 11 + ] + } + ], + "payload_summaries_truncated": false, + "payload_summary_count": 2, + "pending_update": false, + "producer_identities": [ + { + "artifact_kind": null, + "invocation_key": null, + "origin": "manual", + "output_key": "selected_images", + "output_kind": "manual", + "pipeline_position": null, + "projection_key": "selected_images_2279edf51d62e30c88170a053918455cf4575618753b42fb99afb6149c7e1fc1", + "step_name": null, + "step_scope_id": null + } + ], + "route_key": "origin_manual_kind_manual_projection_selected_images_2279edf51d62e30c88170a053918455cf4575618753b42fb99afb6149c7e1fc1", + "routed_component_coordinates": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ] + ], + "routed_component_values": { + "channel": [ + 1, + 2 + ], + "z_index": [ + 1, + 2 + ] + }, + "scalar_labels": [ + "Site 1", + "T 1", + "Well A01" + ], + "selected": true, + "selected_data_indices": [], + "stack_axes": [ + "channel", + "z_index" + ], + "title": "selected_images", + "visible": true + } + ], + "native_dimensions": { + "camera_angles": [ + 0.0, + 0.0, + 90.0 + ], + "canvas_size": [ + 962, + 426 + ], + "displayed_axes": [ + "y", + "x" + ], + "ndisplay": 2, + "order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6 + ], + "point": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 78.0, + 147.0 + ] + }, + "native_viewport": { + "center": [ + 0.0, + 79.0, + 148.5 + ], + "zoom": 1.349 + }, + "observed": true, + "response": {}, + "schema_version": "openhcs.agent.v1", + "viewer": { + "title": "OpenHCS Napari Visualization", + "viewer_type": "napari" + }, + "viewer_ndim": 7, + "warnings": [] + } + ], + "tool": "openhcs_get_viewer_window_state" + } + ], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} +{ + "errors": [], + "results": [ + { + "mcp_error": false, + "payloads": [ + { + "capture_scope": "widget", + "captured": true, + "connection": { + "host": "127.0.0.1", + "persistent": true, + "port": 5794, + "transport_mode": "tcp" + }, + "errors": [], + "frame_condition": "immediate", + "height": 950, + "observation_timeout_s": 5.0, + "output_dir_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures", + "resource": { + "mime_type": "image/png", + "path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures/20260930T131815752112Z_napari_5794_OpenHCS_Napari_Visualization.png", + "sha256": "af10d4def4dd0e67e31ccd8425b5850a3b0df5cfd43b9c726f8b8f4621226be4", + "size_bytes": 78836, + "title": "OpenHCS Napari Visualization", + "uri": "file:///home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures/20260930T131815752112Z_napari_5794_OpenHCS_Napari_Visualization.png" + }, + "response": { + "height": 950, + "native_dimensions": { + "camera_angles": [ + 0.0, + 0.0, + 90.0 + ], + "canvas_size": [ + 962, + 426 + ], + "displayed_axes": [ + "y", + "x" + ], + "ndisplay": 2, + "order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6 + ], + "point": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 78.0, + 147.0 + ] + }, + "resource": { + "mime_type": "image/png", + "path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures/20260930T131815752112Z_napari_5794_OpenHCS_Napari_Visualization.png", + "sha256": "af10d4def4dd0e67e31ccd8425b5850a3b0df5cfd43b9c726f8b8f4621226be4", + "size_bytes": 78836, + "title": "OpenHCS Napari Visualization", + "uri": "file:///home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures/20260930T131815752112Z_napari_5794_OpenHCS_Napari_Visualization.png" + }, + "snapshot": { + "capture_scope": "widget", + "connection": { + "host": "127.0.0.1", + "persistent": true, + "port": 5794, + "transport_mode": "tcp" + }, + "frame_condition": "immediate", + "include_response": true, + "observation_timeout_s": 5.0, + "output_dir_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures", + "timeout_ms": 5000 + }, + "status": "success", + "type": "screenshot_ack", + "viewer": { + "title": "OpenHCS Napari Visualization", + "type": "napari" + }, + "width": 1440 + }, + "schema_version": "openhcs.agent.v1", + "viewer": { + "title": "OpenHCS Napari Visualization", + "viewer_type": "napari" + }, + "warnings": [], + "width": 1440 + } + ], + "tool": "openhcs_viewer_snapshot_window" + } + ], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} diff --git a/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/openhcs_metadata.json b/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/openhcs_metadata.json new file mode 100644 index 0000000000..17d3a27138 --- /dev/null +++ b/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/openhcs_metadata.json @@ -0,0 +1,169 @@ +{ + "subdirectories": { + ".": { + "microscope_handler_name": "source_bindings", + "source_filename_parser_name": "SourceSchemaFilenameParser", + "grid_dimensions": [], + "pixel_size": 1, + "image_files": [ + "A01_s001_w1_z001_t001.tif", + "A01_s001_w2_z002_t001.tif" + ], + "sites": { + "1": null + }, + "channels": { + "1": null, + "2": null + }, + "z_indexes": { + "1": null, + "2": null + }, + "timepoints": { + "1": null + }, + "wells": { + "A01": null + }, + "available_backends": { + "disk": true + }, + "workspace_mapping": { + "A01_s001_w1_z001_t001.tif": { + "backend": "disk", + "backend_address": "synthetic-channel1.tif", + "source_axis_indices": [] + }, + "A01_s001_w2_z002_t001.tif": { + "backend": "disk", + "backend_address": "synthetic-channel2.tif", + "source_axis_indices": [] + } + }, + "source_metadata": { + "A01_s001_w1_z001_t001.tif": { + "site": "1", + "channel": "1", + "z_index": "1", + "timepoint": "1", + "well": "A01" + }, + "A01_s001_w2_z002_t001.tif": { + "site": "1", + "channel": "2", + "z_index": "2", + "timepoint": "1", + "well": "A01" + } + }, + "source_projection": [ + { + "virtual_path": "A01_s001_w1_z001_t001.tif", + "address": { + "site": "1", + "channel": "1", + "z_index": "1", + "timepoint": "1", + "well": "A01" + }, + "ref": { + "backend": "disk", + "backend_address": "synthetic-channel1.tif", + "source_axis_indices": [] + }, + "projection_role": "primary_plane", + "image_metadata": { + "source_voxel_spacing": { + "values_zyx": [ + 2.0, + 3.0 + ], + "unit": "relative" + }, + "source_spatial_domain": { + "origin_yx": [ + 7, + 11 + ], + "source_shape_yx": [ + 80, + 100 + ], + "fill_value": 0, + "value_name": "Dense array" + }, + "source_provenance": { + "source_path": null, + "source_component_metadata": null, + "source_image_provenance_planes": [], + "source_image_names": [] + }, + "intensity_scale": 65535.0, + "source_dtype": "uint16", + "unit_interval_intensity": null, + "source_plane_intensity_scales": [], + "source_plane_dtypes": [], + "physical_border_edges_yx": null, + "mask_defines_border": null, + "source_channel_axis": null, + "plane_axis": null + } + }, + { + "virtual_path": "A01_s001_w2_z002_t001.tif", + "address": { + "site": "1", + "channel": "2", + "z_index": "2", + "timepoint": "1", + "well": "A01" + }, + "ref": { + "backend": "disk", + "backend_address": "synthetic-channel2.tif", + "source_axis_indices": [] + }, + "projection_role": "primary_plane", + "image_metadata": { + "source_voxel_spacing": { + "values_zyx": [ + 2.0, + 3.0 + ], + "unit": "relative" + }, + "source_spatial_domain": { + "origin_yx": [ + 7, + 11 + ], + "source_shape_yx": [ + 80, + 100 + ], + "fill_value": 0, + "value_name": "Dense array" + }, + "source_provenance": { + "source_path": null, + "source_component_metadata": null, + "source_image_provenance_planes": [], + "source_image_names": [] + }, + "intensity_scale": 65535.0, + "source_dtype": "uint16", + "unit_interval_intensity": null, + "source_plane_intensity_scales": [], + "source_plane_dtypes": [], + "physical_border_edges_yx": null, + "mask_defines_border": null, + "source_channel_axis": null, + "plane_axis": null + } + } + ], + "main": true + } + } +} \ No newline at end of file diff --git a/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel1.tif b/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel1.tif new file mode 100644 index 0000000000..2140c3f55d Binary files /dev/null and b/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel1.tif differ diff --git a/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel2.tif b/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel2.tif new file mode 100644 index 0000000000..5abd8ad723 Binary files /dev/null and b/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel2.tif differ diff --git a/tests/runtime_diagnostics/viewer_admission_live_20260930/second-client.jsonl b/tests/runtime_diagnostics/viewer_admission_live_20260930/second-client.jsonl new file mode 100644 index 0000000000..048c85c758 --- /dev/null +++ b/tests/runtime_diagnostics/viewer_admission_live_20260930/second-client.jsonl @@ -0,0 +1,725 @@ +{ + "errors": [], + "results": [ + { + "mcp_error": false, + "payloads": [ + { + "automatic_recovery_on_reconnect": false, + "errors": [], + "installation_pointer_available": null, + "installation_pointer_changed_since_import": false, + "installation_pointer_path": null, + "missing_packaged_resource_paths": [], + "openhcs_version": "0.8.6", + "packaged_resource_count": 56, + "packaged_resources_ready": true, + "reconnect_owner": null, + "reconnect_required": false, + "recovery_reason": "current", + "restart_command": [], + "restart_command_is_stable": false, + "restart_hint": null, + "restart_required": false, + "retry_after_reconnect": false, + "schema_version": "openhcs.agent.v1", + "server_current_mtime_ns": 1790772771376925738, + "server_import_mtime_ns": 1790772771376925738, + "server_process_id": 3251697, + "server_source_changed_since_import": false, + "server_source_path": "/home/ts/wt/openhcs-viewer-live-20260930/openhcs/mcp/server.py", + "service": "openhcs.mcp", + "stale_source_paths": [], + "started_at_unix": 1790774468.7693572, + "status": "ok", + "warnings": [] + } + ], + "tool": "openhcs_health_check" + } + ], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} +{ + "errors": [], + "results": [ + { + "mcp_error": false, + "payloads": [ + { + "connection": { + "host": "127.0.0.1", + "persistent": true, + "port": 5794, + "transport_mode": "tcp" + }, + "detected_microscope_type": "openhcsdata", + "errors": [], + "handler_class": "OpenHCSMicroscopeHandler", + "parser_class": "SourceSchemaFilenameParser", + "plate_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate", + "requested_microscope_type": "auto", + "requested_paths": [], + "resolved_records": [ + { + "file_format": null, + "full_path": null, + "full_virtual_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/A01_s001_w1_z001_t001.tif", + "key": "A01_s001_w1_z001_t001.tif", + "kind": "image", + "metadata": { + "channel": 1, + "extension": ".tif", + "filename": "A01_s001_w1_z001_t001.tif", + "full_virtual_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/A01_s001_w1_z001_t001.tif", + "modified": "2026-09-30T09:13:48", + "site": 1, + "size": "8.2 KB", + "source_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel1.tif", + "timepoint": 1, + "type": "Image", + "virtual_path": "A01_s001_w1_z001_t001.tif", + "well": "A01", + "z_index": 1 + }, + "preview": null, + "relative_path": null, + "source_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel1.tif", + "virtual_path": "A01_s001_w1_z001_t001.tif" + }, + { + "file_format": null, + "full_path": null, + "full_virtual_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/A01_s001_w2_z002_t001.tif", + "key": "A01_s001_w2_z002_t001.tif", + "kind": "image", + "metadata": { + "channel": 2, + "extension": ".tif", + "filename": "A01_s001_w2_z002_t001.tif", + "full_virtual_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/A01_s001_w2_z002_t001.tif", + "modified": "2026-09-30T09:13:48", + "site": 1, + "size": "8.2 KB", + "source_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel2.tif", + "timepoint": 1, + "type": "Image", + "virtual_path": "A01_s001_w2_z002_t001.tif", + "well": "A01", + "z_index": 2 + }, + "preview": null, + "relative_path": null, + "source_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/plate/synthetic-channel2.tif", + "virtual_path": "A01_s001_w2_z002_t001.tif" + } + ], + "schema_version": "openhcs.agent.v1", + "skipped_records": [], + "status_messages": [ + "Loading chunk 1/1 (2 images)...", + "Streamed 2 images to Napari" + ], + "streamed_image_paths": [ + "A01_s001_w1_z001_t001.tif", + "A01_s001_w2_z002_t001.tif" + ], + "streamed_roi_paths": [], + "viewer_config_key": "napari_streaming_config", + "viewer_type": "napari", + "warnings": [] + } + ], + "tool": "openhcs_stream_plate_files_to_viewer" + } + ], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} +{ + "errors": [], + "results": [ + { + "mcp_error": false, + "payloads": [ + { + "active_dimension_label_route": "origin_manual_kind_manual_projection_selected_images_2279edf51d62e30c88170a053918455cf4575618753b42fb99afb6149c7e1fc1", + "axis_labels": [ + "site", + "channel", + "z_index", + "timepoint", + "well", + "y", + "x" + ], + "component_group_count": 1, + "component_item_count": 2, + "connection": { + "host": "127.0.0.1", + "persistent": true, + "port": 5794, + "transport_mode": "tcp" + }, + "current_step": [ + 0, + 0, + 0, + 0, + 0, + 39, + 49 + ], + "errors": [], + "layer_count": 1, + "layers": [ + { + "axis_component_values": { + "channel": [ + 1, + 2 + ], + "z_index": [ + 1, + 2 + ] + }, + "axis_labels": [ + "site", + "channel", + "z_index", + "timepoint", + "well", + "y", + "x" + ], + "axis_offsets": [ + 0, + 0 + ], + "component_value_count": 2, + "component_values": [ + { + "channel": 1, + "site": 1, + "timepoint": 1, + "well": "A01", + "z_index": 1 + }, + { + "channel": 2, + "site": 1, + "timepoint": 1, + "well": "A01", + "z_index": 2 + } + ], + "component_values_truncated": false, + "data_shape": [ + 1, + 2, + 2, + 1, + 1, + 80, + 100 + ], + "data_types": [ + "image" + ], + "feature_row_count": 0, + "item_count": 2, + "labels": { + "channel": [ + "Ch 1", + "Ch 2" + ], + "z_index": [ + "Z 1", + "Z 2" + ] + }, + "mounted": true, + "native_intensity": { + "contrast_limits": [ + 0.0, + 693.0 + ], + "gamma": 1.0 + }, + "native_transform": { + "scale": [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 2.0, + 3.0 + ], + "translate": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "payload_summaries": [ + { + "components": { + "channel": 1, + "site": 1, + "timepoint": 1, + "well": "A01", + "z_index": 1 + }, + "data_type": "image", + "dtype": "uint16", + "max": 693, + "min": 0, + "nonzero_count": 4095, + "nonzero_example_coordinates": [ + [ + 0, + 1 + ], + [ + 4, + 17 + ], + [ + 8, + 34 + ], + [ + 12, + 51 + ], + [ + 17, + 4 + ], + [ + 21, + 21 + ], + [ + 25, + 38 + ], + [ + 29, + 55 + ], + [ + 34, + 8 + ], + [ + 38, + 25 + ], + [ + 42, + 42 + ], + [ + 46, + 59 + ], + [ + 51, + 12 + ], + [ + 55, + 29 + ], + [ + 59, + 46 + ], + [ + 63, + 63 + ] + ], + "nonzero_max_coordinate": [ + 63, + 63 + ], + "nonzero_min_coordinate": [ + 0, + 0 + ], + "path": "A01_s001_w1_z001_t001.tif", + "payload_type": "ndarray", + "shape": [ + 64, + 64 + ], + "size": 4096, + "source_spatial_shape_yx": [ + 80, + 100 + ], + "spatial_origin_yx": [ + 7, + 11 + ] + }, + { + "components": { + "channel": 2, + "site": 1, + "timepoint": 1, + "well": "A01", + "z_index": 2 + }, + "data_type": "image", + "dtype": "uint16", + "max": 80, + "min": 5, + "nonzero_count": 4096, + "nonzero_example_coordinates": [ + [ + 0, + 0 + ], + [ + 4, + 17 + ], + [ + 8, + 34 + ], + [ + 12, + 51 + ], + [ + 17, + 4 + ], + [ + 21, + 21 + ], + [ + 25, + 38 + ], + [ + 29, + 55 + ], + [ + 34, + 8 + ], + [ + 38, + 25 + ], + [ + 42, + 42 + ], + [ + 46, + 59 + ], + [ + 51, + 12 + ], + [ + 55, + 29 + ], + [ + 59, + 46 + ], + [ + 63, + 63 + ] + ], + "nonzero_max_coordinate": [ + 63, + 63 + ], + "nonzero_min_coordinate": [ + 0, + 0 + ], + "path": "A01_s001_w2_z002_t001.tif", + "payload_type": "ndarray", + "shape": [ + 64, + 64 + ], + "size": 4096, + "source_spatial_shape_yx": [ + 80, + 100 + ], + "spatial_origin_yx": [ + 7, + 11 + ] + } + ], + "payload_summaries_truncated": false, + "payload_summary_count": 2, + "pending_update": false, + "producer_identities": [ + { + "artifact_kind": null, + "invocation_key": null, + "origin": "manual", + "output_key": "selected_images", + "output_kind": "manual", + "pipeline_position": null, + "projection_key": "selected_images_2279edf51d62e30c88170a053918455cf4575618753b42fb99afb6149c7e1fc1", + "step_name": null, + "step_scope_id": null + } + ], + "route_key": "origin_manual_kind_manual_projection_selected_images_2279edf51d62e30c88170a053918455cf4575618753b42fb99afb6149c7e1fc1", + "routed_component_coordinates": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ] + ], + "routed_component_values": { + "channel": [ + 1, + 2 + ], + "z_index": [ + 1, + 2 + ] + }, + "scalar_labels": [ + "Site 1", + "T 1", + "Well A01" + ], + "selected": true, + "selected_data_indices": [], + "stack_axes": [ + "channel", + "z_index" + ], + "title": "selected_images", + "visible": true + } + ], + "native_dimensions": { + "camera_angles": [ + 0.0, + 0.0, + 90.0 + ], + "canvas_size": [ + 962, + 426 + ], + "displayed_axes": [ + "y", + "x" + ], + "ndisplay": 2, + "order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6 + ], + "point": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 78.0, + 147.0 + ] + }, + "native_viewport": { + "center": [ + 0.0, + 79.0, + 148.5 + ], + "zoom": 2.529375 + }, + "observed": true, + "response": {}, + "schema_version": "openhcs.agent.v1", + "viewer": { + "title": "OpenHCS Napari Visualization", + "viewer_type": "napari" + }, + "viewer_ndim": 7, + "warnings": [] + } + ], + "tool": "openhcs_get_viewer_window_state" + } + ], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} +{ + "errors": [], + "results": [ + { + "mcp_error": false, + "payloads": [ + { + "capture_scope": "widget", + "captured": true, + "connection": { + "host": "127.0.0.1", + "persistent": true, + "port": 5794, + "transport_mode": "tcp" + }, + "errors": [], + "frame_condition": "immediate", + "height": 950, + "observation_timeout_s": 5.0, + "output_dir_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures-reused", + "resource": { + "mime_type": "image/png", + "path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures-reused/20260930T132110280409Z_napari_5794_OpenHCS_Napari_Visualization.png", + "sha256": "e6da1cc37613ef6faf4d4bd1d3c8b503e9d2f53f7fb315c661cd34b8e62735f3", + "size_bytes": 79585, + "title": "OpenHCS Napari Visualization", + "uri": "file:///home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures-reused/20260930T132110280409Z_napari_5794_OpenHCS_Napari_Visualization.png" + }, + "response": { + "height": 950, + "native_dimensions": { + "camera_angles": [ + 0.0, + 0.0, + 90.0 + ], + "canvas_size": [ + 962, + 426 + ], + "displayed_axes": [ + "y", + "x" + ], + "ndisplay": 2, + "order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6 + ], + "point": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 78.0, + 147.0 + ] + }, + "resource": { + "mime_type": "image/png", + "path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures-reused/20260930T132110280409Z_napari_5794_OpenHCS_Napari_Visualization.png", + "sha256": "e6da1cc37613ef6faf4d4bd1d3c8b503e9d2f53f7fb315c661cd34b8e62735f3", + "size_bytes": 79585, + "title": "OpenHCS Napari Visualization", + "uri": "file:///home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures-reused/20260930T132110280409Z_napari_5794_OpenHCS_Napari_Visualization.png" + }, + "snapshot": { + "capture_scope": "widget", + "connection": { + "host": "127.0.0.1", + "persistent": true, + "port": 5794, + "transport_mode": "tcp" + }, + "frame_condition": "immediate", + "include_response": true, + "observation_timeout_s": 5.0, + "output_dir_path": "/home/ts/wt/openhcs-viewer-live-20260930/tests/runtime_diagnostics/viewer_admission_live_20260930/captures-reused", + "timeout_ms": 5000 + }, + "status": "success", + "type": "screenshot_ack", + "viewer": { + "title": "OpenHCS Napari Visualization", + "type": "napari" + }, + "width": 1440 + }, + "schema_version": "openhcs.agent.v1", + "viewer": { + "title": "OpenHCS Napari Visualization", + "viewer_type": "napari" + }, + "warnings": [], + "width": 1440 + } + ], + "tool": "openhcs_viewer_snapshot_window" + } + ], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} +{ + "errors": [], + "results": [ + { + "mcp_error": false, + "payloads": [ + { + "endpoint_terminated": true, + "succeeded": true + } + ], + "tool": "openhcs_close_viewer_window" + } + ], + "server": { + "command": "/home/ts/code/projects/openhcs/.venv/bin/python", + "module": "openhcs.mcp" + } +} diff --git a/tests/unit/test_fiji_viewer_server.py b/tests/unit/test_fiji_viewer_server.py index e82ad00172..e244a846f1 100644 --- a/tests/unit/test_fiji_viewer_server.py +++ b/tests/unit/test_fiji_viewer_server.py @@ -14,6 +14,7 @@ NapariDisplayConfig, ) from openhcs.core.runtime_plane_projection import RuntimePlaneAxis +from openhcs.core.streaming_config_factory import ViewerProcessLaunchConfig from openhcs.runtime import fiji_viewer_server as fiji_viewer_server_module from openhcs.runtime.fiji_macro_runtime import ( FijiMacroExecutionRequest, @@ -55,6 +56,7 @@ ViewerObjectDisplayConfigInput, ) from openhcs.runtime.viewer_protocol import ( + OpenHCSViewerControlMessageType, ViewerControlMessageType, ViewerControlResponse, ViewerSettlePhase, @@ -218,6 +220,18 @@ def test_fiji_control_dispatch_registry_is_module_local_and_eager() -> None: assert registry[ViewerControlMessageType.SETTLE.value] is FijiSettleControlPlan +def test_fiji_process_launch_control_reports_server_owned_declaration() -> None: + active = ViewerProcessLaunchConfig(listen_host="*") + response = FijiControlMessageAuthority( + FijiControlRequestContext( + FijiWindowRegistry(), object(), FijiBatchSettlementState(), active + ) + ).response_for({"type": OpenHCSViewerControlMessageType.PROCESS_LAUNCH.value}) + wire = response.to_wire_mapping() + assert wire["status"] == "success" + assert ViewerProcessLaunchConfig.from_wire_mapping(wire["process_launch"]) == active + + def test_fiji_intensity_window_control_fails_closed_as_unsupported() -> None: response = FijiControlMessageAuthority( FijiControlRequestContext( diff --git a/tests/unit/test_napari_streaming_handlers.py b/tests/unit/test_napari_streaming_handlers.py index 3db8a010d5..19ac374c38 100644 --- a/tests/unit/test_napari_streaming_handlers.py +++ b/tests/unit/test_napari_streaming_handlers.py @@ -7,6 +7,7 @@ import numpy as np import pytest +from napari.components import Camera, Dims from napari.layers.shapes._shapes_constants import ShapeType from polystore.streaming.identity import StreamProducerIdentity from polystore.streaming_constants import StreamingDataType @@ -713,7 +714,8 @@ def test_napari_viewer_state_projection_filters_and_bounds_layer_details(): ) viewer = _FakeViewer() - viewer.dims.axis_labels = ("site", "y", "x") + viewer.dims = Dims(ndim=3, axis_labels=("site", "y", "x")) + viewer.camera = Camera() projection = napari_viewer_server.NapariViewerStateProjection( server=server, viewer=viewer, @@ -727,6 +729,9 @@ def test_napari_viewer_state_projection_filters_and_bounds_layer_details(): state = projection.to_wire_mapping() + assert state["native_dimensions"]["order"] == (0, 1, 2) + assert state["native_dimensions"]["displayed_axes"] == ("y", "x") + assert state["native_dimensions"]["canvas_size"] is None assert state["layer_count"] == 1 layer = state["layers"][0] assert layer["route_key"] == "payload-route" @@ -744,7 +749,8 @@ def test_napari_viewer_state_projection_filters_and_bounds_layer_details(): def test_napari_state_control_message_honors_state_request_payload(): napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") viewer = _FakeViewer() - viewer.dims.axis_labels = ("site", "y", "x") + viewer.dims = Dims(ndim=3, axis_labels=("site", "y", "x")) + viewer.camera = Camera() layer = type( "Layer", (), @@ -2384,6 +2390,12 @@ def test_napari_navigation_control_selects_visible_layer_and_route_local_axes(): napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") viewer = _FakeViewer() + viewer.dims = Dims( + ndim=4, + range=((0, 3, 1), (0, 1, 1), (0, 19, 1), (0, 19, 1)), + ) + viewer.dims.current_step = (3, 0, 0, 0) + viewer.camera = Camera() layer = type( "Layer", (), @@ -2446,6 +2458,8 @@ def test_napari_navigation_visibility_change_preserves_selected_label_route(): napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") viewer = _FakeViewer() + viewer.dims = Dims(ndim=3, range=((0, 1, 1), (0, 19, 1), (0, 19, 1))) + viewer.camera = Camera() selected_layer = type( "Layer", (), @@ -3390,6 +3404,10 @@ class Window: def resize(width, height): events.append(("window_resize", width, height)) + @staticmethod + def add_dock_widget(widget, *, name, area): + events.append(("native_dock", name, area)) + self.window = Window() application = FakeApplication() @@ -3398,6 +3416,14 @@ def resize(width, height): monkeypatch.setattr(napari_viewer_server, "NapariViewerServer", FakeServer) monkeypatch.setattr(napari_viewer_server, "QTimer", FakeTimer) + from openhcs.runtime import napari_orthogonal_widget + + monkeypatch.setattr( + napari_orthogonal_widget, + "OpenHCSOrthogonalWidget", + lambda _server: (events.append("orthogonal_surface_open") or object()), + ) + class FakeQtEnvironmentPolicy: def __init__(self, *, font_dpi=None): events.append(("qt_environment_policy", font_dpi)) @@ -3441,6 +3467,8 @@ def test_napari_entrypoint_publishes_endpoints_from_live_qt_event_loop(monkeypat assert entrypoint_error is None assert events.index("qt_environment_applied") < events.index("viewer_construct") + assert events.index("viewer_construct") < events.index("orthogonal_surface_open") + assert ("native_dock", "OpenHCS Spatial Planes", "right") in events assert events.index("startup_callback_queued") < events.index("event_loop_enter") assert events.index("result_selection_surface_open") < events.index( "startup_callback_queued" @@ -3566,8 +3594,9 @@ def test_napari_runtime_launch_carries_the_projected_scope_accent(): log_file=Path("/tmp/napari-6200.log") ) - assert arguments.expressions[-2].source == "'#1464c8'" - assert arguments.expressions[-1].source == "None" + assert arguments.expressions[-3].source == "'#1464c8'" + assert arguments.expressions[-2].source == "None" + assert arguments.expressions[-1].source == "'127.0.0.1'" def test_napari_roi_manager_selects_authoritative_shapes_members(qtbot): @@ -6098,7 +6127,13 @@ def test_native_image_intensity_command_preserves_data_and_navigation(): ) viewer = _FakeViewer() - viewer.dims.axis_labels = ("a", "b", "y", "x") + viewer.dims = Dims( + ndim=4, + axis_labels=("a", "b", "y", "x"), + range=((0, 3, 1), (0, 1, 1), (0, 3, 1), (0, 7, 1)), + ) + viewer.dims.current_step = (3, 0, 0, 0) + viewer.camera = Camera() pixels = np.arange(32, dtype=np.uint16).reshape(4, 8) layer = Image( pixels, scale=(0.65, 0.65), translate=(2, 3), contrast_limits=(0, 100) diff --git a/tests/unit/test_streaming_config_factory_registry.py b/tests/unit/test_streaming_config_factory_registry.py index cc92132f02..2e7b98e48d 100644 --- a/tests/unit/test_streaming_config_factory_registry.py +++ b/tests/unit/test_streaming_config_factory_registry.py @@ -35,3 +35,15 @@ def test_viewer_identity_parses_only_at_the_wire_boundary() -> None: assert ViewerType.from_wire_value("fiji") is ViewerType.FIJI with pytest.raises(ValueError): ViewerType.from_wire_value("FijiViewerDeclaration") + + +@pytest.mark.parametrize("viewer_type", tuple(ViewerType), ids=lambda item: item.value) +def test_viewer_listen_interface_is_independent_of_connection_host(viewer_type): + config_type = StreamingConfig.config_type_for_viewer(viewer_type) + config = config_type(host="remote.example", listen_host="127.0.0.1") + runtime = config.viewer_runtime_config() + assert runtime.transport_endpoint.host == "remote.example" + assert runtime.process_launch.listen_host == "127.0.0.1" + + exposed = config_type(host="127.0.0.1", listen_host="*") + assert exposed.viewer_runtime_config().process_launch.listen_host == "*" diff --git a/tests/unit/test_streaming_service.py b/tests/unit/test_streaming_service.py index c8a316d40d..588da9dde3 100644 --- a/tests/unit/test_streaming_service.py +++ b/tests/unit/test_streaming_service.py @@ -19,6 +19,7 @@ from polystore.virtual_workspace import SourcePixelRef from polystore.zmq_config import POLYSTORE_ZMQ_CONFIG from zmqruntime.viewer_protocol import ViewerBatchWireField, ViewerWireField +from zmqruntime.viewer_state import ViewerStateManager from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ObjectLabelsArtifactType @@ -67,6 +68,7 @@ from openhcs.runtime.viewer_protocol import ( DetachedViewerLaunchFailure, DetachedViewerServerEntrypointSpec, + ManagedViewerLifecycleMixin, ViewerControlMessageRequest, ViewerControlResponse, ViewerLaunchContext, @@ -218,10 +220,10 @@ def test_napari_viewer_reuse_requires_matching_process_launch(monkeypatch) -> No } ), ) - assert visualizer.existing_viewer_matches_process_launch() + assert visualizer.matches_requested_process_launch(visualizer.process_launch) active_launch = ViewerProcessLaunchConfig(qt_font_dpi=120) - assert not visualizer.existing_viewer_matches_process_launch() + assert not visualizer.matches_requested_process_launch(visualizer.process_launch) @pytest.mark.parametrize("config", (GlobalPipelineConfig(), PipelineConfig())) @@ -1221,29 +1223,33 @@ def test_stream_rois_rejects_unresolved_source_plane_metadata() -> None: ) -def test_streaming_viewer_lifecycle_attaches_existing_viewer_without_restart( - monkeypatch, -) -> None: - class FakeManager: - def get_viewer(self, viewer_type: str, port: int): - del viewer_type, port - return None - - def release_viewer( - self, viewer_type: str, port: int, *, stop: bool, force: bool - ): - raise AssertionError("fresh release should not run for non-fresh attach") - +@pytest.fixture +def lifecycle_manager(monkeypatch): + # Exercise the real manager/acquisition path without starting or stopping + # any real viewer, endpoint, Qt application or foreign process. + monkeypatch.setattr(ViewerStateManager, "_instance", None) monkeypatch.setattr( - "zmqruntime.ViewerStateManager.get_instance", - lambda: FakeManager(), + ManagedViewerLifecycleMixin, "is_running", property(lambda self: True) ) monkeypatch.setattr( - "zmqruntime.get_or_create_viewer", - lambda **_kwargs: (_ for _ in ()).throw( - AssertionError("viewer restart path used") - ), + ManagedViewerLifecycleMixin, "wait_for_ready", lambda self, timeout: True + ) + monkeypatch.setattr( + ManagedViewerLifecycleMixin, "force_stop", + lambda self: self.lifecycle_state.mark_stopped(), + ) + monkeypatch.setattr( + ManagedViewerLifecycleMixin, "start", + lambda self: (_ for _ in ()).throw(AssertionError("must not restart")), ) + manager = ViewerStateManager.get_instance() + yield manager + manager.stop_all_viewers() + + +def test_streaming_viewer_lifecycle_attaches_existing_viewer_without_restart( + monkeypatch, lifecycle_manager, +) -> None: monkeypatch.setattr( NapariStreamVisualizer, "existing_viewer_is_ready", @@ -1276,23 +1282,10 @@ def release_viewer( ) def test_streaming_viewer_lifecycle_projects_launch_context_for_every_viewer( monkeypatch, + lifecycle_manager, config, visualizer_type, ) -> None: - class FakeManager: - def get_viewer(self, viewer_type: str, port: int): - del viewer_type, port - return None - - def release_viewer( - self, viewer_type: str, port: int, *, stop: bool, force: bool - ): - raise AssertionError("fresh release should not run for non-fresh attach") - - monkeypatch.setattr( - "zmqruntime.ViewerStateManager.get_instance", - lambda: FakeManager(), - ) monkeypatch.setattr( visualizer_type, "existing_viewer_is_ready", @@ -1360,36 +1353,51 @@ def fail_after_factory(*, factory, **_kwargs): assert str(error.value.log_file) in str(error.value) -def test_streaming_viewer_lifecycle_reuses_manager_owned_viewer(monkeypatch) -> None: - existing_viewer = FakeViewer() - - class FakeManager: - def get_viewer(self, viewer_type: str, port: int): - assert viewer_type == "napari" - assert port == 5563 - return existing_viewer - - def release_viewer( - self, viewer_type: str, port: int, *, stop: bool, force: bool - ): - raise AssertionError("fresh release should not run for non-fresh reuse") - +@pytest.mark.parametrize("config_type", (NapariStreamingConfig, FijiStreamingConfig)) +@pytest.mark.parametrize( + ("owns_process", "requested_host", "reusable"), + ((True, "127.0.0.1", False), (True, "*", True), (False, "127.0.0.1", True)), +) +def test_streaming_viewer_lifecycle_admits_new_launch_inside_managed_acquisition( + monkeypatch, lifecycle_manager, config_type, owns_process, requested_host, reusable +) -> None: + active_config = config_type(enabled=True, port=5563, persistent=True, listen_host="*") + existing_viewer = active_config.create_visualizer(FakeFileManager()) + existing_viewer.lifecycle_state.mark_connected_external() monkeypatch.setattr( - "zmqruntime.ViewerStateManager.get_instance", - lambda: FakeManager(), + ManagedViewerLifecycleMixin, "owned_viewer_process_is_alive", + lambda self: owns_process, + ) + monkeypatch.setattr( + ViewerControlMessageRequest, "send", + lambda self: ViewerControlResponse({ + "status": "success", + "process_launch": active_config.viewer_process_launch_config().to_wire_mapping(), + }), + ) + lifecycle_manager.get_or_create_viewer( + active_config.viewer_type.wire_value, 5563, lambda: existing_viewer ) monkeypatch.setattr( - NapariStreamingConfig, + config_type, "create_visualizer", - lambda self, filemanager, visualizer_config=None: (_ for _ in ()).throw( - AssertionError("external viewer probe should not run") + lambda *args, **kwargs: (_ for _ in ()).throw( + AssertionError("managed reuse must not construct another viewer") ), ) - viewer = StreamingViewerLifecycle.get_or_create_visualizer( - filemanager=FakeFileManager(), - config=NapariStreamingConfig(enabled=True, port=5563, persistent=True), - fresh=False, + requested = config_type( + enabled=True, port=5563, persistent=True, listen_host=requested_host ) - - assert viewer is existing_viewer + if reusable: + assert StreamingViewerLifecycle.get_or_create_visualizer( + filemanager=FakeFileManager(), config=requested, fresh=False, + ) is existing_viewer + else: + with pytest.raises(RuntimeError, match="does not match the requested process launch"): + StreamingViewerLifecycle.get_or_create_visualizer( + filemanager=FakeFileManager(), config=requested, fresh=False, + ) + assert lifecycle_manager.get_viewer( + active_config.viewer_type.wire_value, 5563 + ) is existing_viewer diff --git a/tests/unit/test_viewer_listener_binding.py b/tests/unit/test_viewer_listener_binding.py new file mode 100644 index 0000000000..4428c562ac --- /dev/null +++ b/tests/unit/test_viewer_listener_binding.py @@ -0,0 +1,94 @@ +"""Exercise real data/control socket binding without constructing a GUI/JVM.""" + +from pathlib import Path + +import pytest +import zmq +from zmqruntime.config import TransportMode +from zmqruntime.transport import DataControlPortPairAuthority + +from openhcs.core.config import StreamingConfig +from openhcs.core.streaming_config_declarations import ViewerType +from openhcs.core.streaming_config_factory import ViewerProcessLaunchConfig +from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG + + +def napari_server(port, mode, listen_host): + from openhcs.runtime.napari_viewer_server import NapariViewerServer + from openhcs.runtime.viewer_protocol import NapariViewerServerRequest + + return NapariViewerServer( + NapariViewerServerRequest( + port=port, + viewer_title="Listener binding test", + transport_mode=mode, + process_launch=ViewerProcessLaunchConfig(listen_host=listen_host), + ) + ) + + +def fiji_server(port, mode, listen_host): + from openhcs.runtime.fiji_viewer_server import ( + FijiViewerServer, + FijiViewerServerLaunchConfig, + ) + + return FijiViewerServer( + FijiViewerServerLaunchConfig( + port=port, + fiji_viewer_title="Listener binding test", + fiji_display_config=None, + transport_mode=mode, + process_launch=ViewerProcessLaunchConfig(listen_host=listen_host), + ) + ) + + +@pytest.mark.parametrize("server_factory", (napari_server, fiji_server)) +@pytest.mark.parametrize( + "mode,listen_host,expected_prefix", + ( + (TransportMode.TCP, "127.0.0.1", "tcp://127.0.0.1:"), + (TransportMode.TCP, "*", "tcp://0.0.0.0:"), + (TransportMode.IPC, "remote.example", "ipc://"), + ), +) +def test_server_binds_both_real_sockets_to_declared_interface( + server_factory, mode, listen_host, expected_prefix +): + pair = DataControlPortPairAuthority.acquire( + OPENHCS_ZMQ_CONFIG, + transport_mode=mode, + ) + server = server_factory(pair.data_port, mode, listen_host) + context = zmq.Context() + sockets = [] + try: + sockets.append(server.bind_data_socket(context)) + sockets.append(server.bind_control_socket(context)) + for socket in sockets: + endpoint = socket.getsockopt_string(zmq.LAST_ENDPOINT) + assert endpoint.startswith(expected_prefix), endpoint + finally: + for socket in sockets: + socket.close(linger=0) + context.term() + if server.ack_socket is not None: + server.ack_socket.close(linger=0) + server.endpoint.cleanup(server.config) + + +@pytest.mark.parametrize("viewer_type", tuple(ViewerType)) +def test_detached_launch_projects_listener_from_process_declaration(viewer_type): + config = StreamingConfig.config_type_for_viewer(viewer_type)( + host="remote.example", + listen_host="192.0.2.1", + transport_mode=TransportMode.TCP, + ) + visualizer = viewer_type.declaration.visualizer_type()( + filemanager=object(), + runtime_config=config.viewer_runtime_config(), + ) + arguments = visualizer.detached_server_arguments(log_file=Path("viewer.log")) + assert visualizer.runtime_endpoint.host == "remote.example" + assert arguments.expressions[-1].source == "'192.0.2.1'" diff --git a/tests/unit/test_viewer_protocol.py b/tests/unit/test_viewer_protocol.py index ab1cde6f80..7c9cd31268 100644 --- a/tests/unit/test_viewer_protocol.py +++ b/tests/unit/test_viewer_protocol.py @@ -360,6 +360,7 @@ def detached_server_arguments( viewer_type=ViewerType.NAPARI, ) ) + monkeypatch.setattr(viewer, "active_process_launch", lambda: viewer.process_launch) observed_application = OPENHCS_ENDPOINT_APPLICATION def compatibility(_endpoint, *, timeout_ms, require_ready=True): @@ -375,15 +376,15 @@ def compatibility(_endpoint, *, timeout_ms, require_ready=True): monkeypatch.setattr( viewer, - "existing_viewer_matches_process_launch", - lambda: False, + "matches_requested_process_launch", + lambda _requested: False, ) assert not viewer.existing_viewer_is_ready() monkeypatch.setattr( viewer, - "existing_viewer_matches_process_launch", - lambda: True, + "matches_requested_process_launch", + lambda _requested: True, ) observed_application = EndpointApplication( @@ -667,7 +668,7 @@ def test_viewer_qt_environment_policy_applies_platform_rows(): def test_viewer_process_launch_config_round_trips_exact_wire_declaration(): - config = ViewerProcessLaunchConfig(qt_font_dpi=96) + config = ViewerProcessLaunchConfig(qt_font_dpi=96, listen_host="192.0.2.1") assert ( ViewerProcessLaunchConfig.from_wire_mapping(config.to_wire_mapping()) == config @@ -680,6 +681,22 @@ def test_viewer_process_launch_config_round_trips_exact_wire_declaration(): with pytest.raises(ValueError): ViewerProcessLaunchConfig(qt_font_dpi=0) + with pytest.raises(TypeError, match="listen host must be a string"): + ViewerProcessLaunchConfig.from_wire_mapping( + {"qt_font_dpi": None, "listen_host": True} + ) + with pytest.raises(ValueError, match="listen host must not be blank"): + ViewerProcessLaunchConfig(listen_host=" ") + + +def test_listener_match_respects_existing_process_ownership(): + requested = ViewerProcessLaunchConfig(qt_font_dpi=96) + externally_bound = ViewerProcessLaunchConfig(qt_font_dpi=96, listen_host="*") + assert requested.matches_existing_viewer(externally_bound, owns_process=False) + assert not requested.matches_existing_viewer(externally_bound, owns_process=True) + different_dpi = ViewerProcessLaunchConfig(qt_font_dpi=120, listen_host="*") + assert not requested.matches_existing_viewer(different_dpi, owns_process=False) + def test_projected_graphical_viewer_replaces_noninteractive_qt_platform(): launch_context = ViewerLaunchContext.projected_graphical_session(