napari-zenapi-streaming 0.0.2__tar.gz → 0.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/CHANGELOG.md +22 -0
  2. {napari_zenapi_streaming-0.0.2/src/napari_zenapi_streaming.egg-info → napari_zenapi_streaming-0.0.3}/PKG-INFO +26 -16
  3. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/README.md +25 -15
  4. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/pyproject.toml +1 -1
  5. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/ZEN_pipeline.py +50 -20
  6. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/ZEN_ui.py +74 -13
  7. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/__init__.py +1 -1
  8. napari_zenapi_streaming-0.0.3/src/napari_zen_streaming/_tests/test_experiment_stream_filter.py +440 -0
  9. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_initial_experiment_selection.py +1 -0
  10. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_live_preview.py +6 -3
  11. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/main.py +4 -2
  12. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3/src/napari_zenapi_streaming.egg-info}/PKG-INFO +26 -16
  13. napari_zenapi_streaming-0.0.2/src/napari_zen_streaming/_tests/test_experiment_stream_filter.py +0 -139
  14. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/LICENSE +0 -0
  15. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/MANIFEST.in +0 -0
  16. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/setup.cfg +0 -0
  17. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/ZEN_config.py +0 -0
  18. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/ZEN_init.py +0 -0
  19. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/ZEN_omezarr.py +0 -0
  20. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/ZEN_stream2omezarr.py +0 -0
  21. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/ZEN_utils.py +0 -0
  22. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_logging.py +0 -0
  23. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_scene_geometry.py +0 -0
  24. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/__init__.py +0 -0
  25. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_config.py +0 -0
  26. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_display_completion.py +0 -0
  27. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_experiment_xml.py +0 -0
  28. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_hcs_ui_option.py +0 -0
  29. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_logging.py +0 -0
  30. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_omezarr_viewer.py +0 -0
  31. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_progress_reporting.py +0 -0
  32. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_runtime_pixel_type.py +0 -0
  33. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_scene_geometry.py +0 -0
  34. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_tests/test_scene_mosaic.py +0 -0
  35. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/_widget.py +0 -0
  36. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/misc.py +0 -0
  37. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zen_streaming/napari.yaml +0 -0
  38. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zenapi_streaming.egg-info/SOURCES.txt +0 -0
  39. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zenapi_streaming.egg-info/dependency_links.txt +0 -0
  40. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zenapi_streaming.egg-info/entry_points.txt +0 -0
  41. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zenapi_streaming.egg-info/requires.txt +0 -0
  42. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.3}/src/napari_zenapi_streaming.egg-info/top_level.txt +0 -0
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.0.3 - 2026-11-18
4
+
5
+ ### Fixed
6
+
7
+ - Closing or removing the Experiment Selector dock now closes its pixel
8
+ stream subscriptions and cancels owned background tasks, including the
9
+ dedicated OME-ZARR writer. The ZEN acquisition and napari remain open.
10
+ - Start-selected Display mode no longer subscribes before Start is clicked.
11
+ The selected experiment ID is armed before subscription and acquisition,
12
+ retained through trailing-frame delivery, and cleared after finalization
13
+ when the reader returns to an unsubscribed idle state.
14
+ - Mode and channel-filter changes no longer arm an idle selected-experiment
15
+ reader. Passive watch mode continues to subscribe immediately.
16
+ - Serialize reader transitions to prevent duplicate listeners during
17
+ overlapping shutdown, mode changes, and repeated acquisitions.
18
+
19
+ ### Added
20
+
21
+ - Stream-lifecycle regression tests covering idle modes, mode and channel
22
+ changes, experiment filtering, repeated runs, failed starts, dock closure
23
+ and removal, dedicated-writer cancellation, and embedded worker shutdown.
24
+
3
25
  ## 0.0.2 - 2026-11-17
4
26
 
5
27
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: napari-zenapi-streaming
3
- Version: 0.0.2
3
+ Version: 0.0.3
4
4
  Summary: ZEN API streaming plugin for napari
5
5
  Author-email: "Krijn H. van der Steen" <k.h.vandersteen@umcutrecht.nl>, Sebastian Rhode <sebastian.rhode@zeiss.com>
6
6
  License-Expression: BSD-3-Clause
@@ -94,18 +94,21 @@ When finished the resulting OME-ZARR, created from the ZEN pixel stream can be s
94
94
 
95
95
  ## Current status
96
96
 
97
- - Release: **0.0.2** ([release notes](_release_notes/v0.0.2.md)).
97
+ - Release: **0.0.3** ([release notes](_release_notes/v0.0.3.md)).
98
98
  - Project phase: alpha / MVP
99
99
  - Primary OS target: Windows for ZEN Blue and the ZEN API Gateway
100
100
  - Python target: `>=3.12, <3.15`
101
101
 
102
- ### What's new in 0.0.2
102
+ ### What's new in 0.0.3
103
103
 
104
- - Original GRAY8/GRAY16 pixels in Display mode, without per-tile stretching.
105
- - Optional stream-only viewing with channel filtering and no final mosaic.
106
- - Scrollable experiment controls for smaller plugin docks.
107
- - OME-Zarr 0.6 output and collection-opening fixes. Reading older OME-Zarr
108
- acquisitions now requires explicit conversion outside the plugin.
104
+ - Closing the Experiment Selector dock stops its stream listeners and
105
+ background tasks, including an active dedicated OME-ZARR writer, without
106
+ stopping the acquisition in ZEN or closing napari.
107
+ - Start-selected Display mode waits for Start before subscribing, filters
108
+ frames by the selected experiment ID, and disconnects after finalization.
109
+ - Mode changes, channel-filter changes, and repeated runs no longer
110
+ accidentally open idle or duplicate stream subscriptions.
111
+ - Watch mode still listens immediately for experiments started in ZEN.
109
112
 
110
113
  ## Known limitations
111
114
 
@@ -250,16 +253,16 @@ without confirming redistribution rights.
250
253
  For a published PyPI release:
251
254
 
252
255
  ```powershell
253
- python -m pip install "napari-zenapi-streaming==0.0.2" "napari[pyqt6]" "PyQt6>=6.7,<6.10"
256
+ python -m pip install "napari-zenapi-streaming==0.0.3" "napari[pyqt6]" "PyQt6>=6.7,<6.10"
254
257
  ```
255
258
 
256
259
  To upgrade an existing environment with compatible ZEN wheels installed:
257
260
 
258
261
  ```powershell
259
- python -m pip install --upgrade "napari-zenapi-streaming==0.0.2"
262
+ python -m pip install --upgrade "napari-zenapi-streaming==0.0.3"
260
263
  ```
261
264
 
262
- Restart napari after upgrading. Version 0.0.2 writes OME-Zarr 0.6 and does not
265
+ Restart napari after upgrading. Version 0.0.3 writes OME-Zarr 0.6 and does not
263
266
  automatically migrate older stores. Use a reader that supports 0.6.
264
267
 
265
268
  From this checkout, install the plugin:
@@ -475,6 +478,9 @@ python -m napari_zen_streaming.main --ui-start true \
475
478
 
476
479
  The plugin UI exposes three stream modes. Connecting the plugin never starts
477
480
  an acquisition; only clicking Start in a start-capable mode does so.
481
+ Closing the **Experiment Selector** dock stops its stream subscriptions and
482
+ background tasks without stopping the acquisition in ZEN or closing napari.
483
+ Open the plugin again to establish a new connection.
478
484
 
479
485
  #### Display: watch ZEN experiment (index 0)
480
486
 
@@ -485,6 +491,8 @@ The channel filter offers All channels or labels 1-16 (ZEN indices 0-15).
485
491
  #### Display: start selected experiment (index 1)
486
492
 
487
493
  The Start button loads and triggers the selected experiment via the ZEN API.
494
+ This mode does not subscribe to the pixel stream until Start is clicked, and
495
+ returns to an unsubscribed idle state after the acquisition is finalized.
488
496
  Its XML dimensions are shown in the widget, and the channel filter offers All
489
497
  channels or exactly the channels available in that setup. Until metadata has
490
498
  loaded, only All channels is available. Changing the selected setup reloads
@@ -505,8 +513,9 @@ Both Display modes use the full async streaming pipeline (`ZEN_pipeline.py`):
505
513
  is frozen during acquisition and re-enabled after completion.
506
514
  Stream-only viewing forces the latest-frame preview, retains no history,
507
515
  and leaves the last frame visible without assembling a mosaic.
508
- 2. **Channel filter** – Changing the filter immediately restarts the pipeline
509
- reader. Labels are 1-based, while the gRPC request uses zero-based indices.
516
+ 2. **Channel filter** – Changing the filter restarts an active pipeline reader
517
+ but does not open a stream in an idle start-selected mode. Labels are
518
+ 1-based, while the gRPC request uses zero-based indices.
510
519
  The initial value comes from `ZEN_CHANNEL_INDEX` in `.env`; leave it empty
511
520
  to receive all channels. An out-of-range choice resets to All channels.
512
521
  3. **Completion detection** –
@@ -523,15 +532,16 @@ Both Display modes use the full async streaming pipeline (`ZEN_pipeline.py`):
523
532
  5D layers (`S, T, Z, Y, X`). In overlap regions, pixels from the tile with
524
533
  the higher M index replace pixels from lower-M tiles.
525
534
 
526
- **Experiment identity:** Display mode keeps one
535
+ **Experiment identity:** While watching or acquiring, Display mode keeps one
527
536
  `monitor_all_experiments()` subscription open because the targeted ZEN stream
528
537
  can close when experiment status changes to finished, before trailing pixel
529
538
  payloads have arrived. For a Napari-started acquisition, the plugin loads the
530
539
  experiment first, arms a client-side filter for its `FrameData.experiment_id`,
531
540
  and only then starts acquisition. Frames from other experiments are ignored
532
541
  while that filter is active, including during trailing-frame drain. The filter
533
- is cleared after final restructure so later ZEN-started acquisitions remain
534
- discoverable. A ZEN-started run has no experiment ID known in advance and
542
+ is cleared and the subscription is closed after final restructure. Switch to
543
+ **Display: watch ZEN experiment** to discover independently started runs.
544
+ A ZEN-started run has no experiment ID known in advance and
535
545
  therefore continues to accept the global stream; keep only one such
536
546
  acquisition active at a time.
537
547
 
@@ -42,18 +42,21 @@ When finished the resulting OME-ZARR, created from the ZEN pixel stream can be s
42
42
 
43
43
  ## Current status
44
44
 
45
- - Release: **0.0.2** ([release notes](_release_notes/v0.0.2.md)).
45
+ - Release: **0.0.3** ([release notes](_release_notes/v0.0.3.md)).
46
46
  - Project phase: alpha / MVP
47
47
  - Primary OS target: Windows for ZEN Blue and the ZEN API Gateway
48
48
  - Python target: `>=3.12, <3.15`
49
49
 
50
- ### What's new in 0.0.2
50
+ ### What's new in 0.0.3
51
51
 
52
- - Original GRAY8/GRAY16 pixels in Display mode, without per-tile stretching.
53
- - Optional stream-only viewing with channel filtering and no final mosaic.
54
- - Scrollable experiment controls for smaller plugin docks.
55
- - OME-Zarr 0.6 output and collection-opening fixes. Reading older OME-Zarr
56
- acquisitions now requires explicit conversion outside the plugin.
52
+ - Closing the Experiment Selector dock stops its stream listeners and
53
+ background tasks, including an active dedicated OME-ZARR writer, without
54
+ stopping the acquisition in ZEN or closing napari.
55
+ - Start-selected Display mode waits for Start before subscribing, filters
56
+ frames by the selected experiment ID, and disconnects after finalization.
57
+ - Mode changes, channel-filter changes, and repeated runs no longer
58
+ accidentally open idle or duplicate stream subscriptions.
59
+ - Watch mode still listens immediately for experiments started in ZEN.
57
60
 
58
61
  ## Known limitations
59
62
 
@@ -198,16 +201,16 @@ without confirming redistribution rights.
198
201
  For a published PyPI release:
199
202
 
200
203
  ```powershell
201
- python -m pip install "napari-zenapi-streaming==0.0.2" "napari[pyqt6]" "PyQt6>=6.7,<6.10"
204
+ python -m pip install "napari-zenapi-streaming==0.0.3" "napari[pyqt6]" "PyQt6>=6.7,<6.10"
202
205
  ```
203
206
 
204
207
  To upgrade an existing environment with compatible ZEN wheels installed:
205
208
 
206
209
  ```powershell
207
- python -m pip install --upgrade "napari-zenapi-streaming==0.0.2"
210
+ python -m pip install --upgrade "napari-zenapi-streaming==0.0.3"
208
211
  ```
209
212
 
210
- Restart napari after upgrading. Version 0.0.2 writes OME-Zarr 0.6 and does not
213
+ Restart napari after upgrading. Version 0.0.3 writes OME-Zarr 0.6 and does not
211
214
  automatically migrate older stores. Use a reader that supports 0.6.
212
215
 
213
216
  From this checkout, install the plugin:
@@ -423,6 +426,9 @@ python -m napari_zen_streaming.main --ui-start true \
423
426
 
424
427
  The plugin UI exposes three stream modes. Connecting the plugin never starts
425
428
  an acquisition; only clicking Start in a start-capable mode does so.
429
+ Closing the **Experiment Selector** dock stops its stream subscriptions and
430
+ background tasks without stopping the acquisition in ZEN or closing napari.
431
+ Open the plugin again to establish a new connection.
426
432
 
427
433
  #### Display: watch ZEN experiment (index 0)
428
434
 
@@ -433,6 +439,8 @@ The channel filter offers All channels or labels 1-16 (ZEN indices 0-15).
433
439
  #### Display: start selected experiment (index 1)
434
440
 
435
441
  The Start button loads and triggers the selected experiment via the ZEN API.
442
+ This mode does not subscribe to the pixel stream until Start is clicked, and
443
+ returns to an unsubscribed idle state after the acquisition is finalized.
436
444
  Its XML dimensions are shown in the widget, and the channel filter offers All
437
445
  channels or exactly the channels available in that setup. Until metadata has
438
446
  loaded, only All channels is available. Changing the selected setup reloads
@@ -453,8 +461,9 @@ Both Display modes use the full async streaming pipeline (`ZEN_pipeline.py`):
453
461
  is frozen during acquisition and re-enabled after completion.
454
462
  Stream-only viewing forces the latest-frame preview, retains no history,
455
463
  and leaves the last frame visible without assembling a mosaic.
456
- 2. **Channel filter** – Changing the filter immediately restarts the pipeline
457
- reader. Labels are 1-based, while the gRPC request uses zero-based indices.
464
+ 2. **Channel filter** – Changing the filter restarts an active pipeline reader
465
+ but does not open a stream in an idle start-selected mode. Labels are
466
+ 1-based, while the gRPC request uses zero-based indices.
458
467
  The initial value comes from `ZEN_CHANNEL_INDEX` in `.env`; leave it empty
459
468
  to receive all channels. An out-of-range choice resets to All channels.
460
469
  3. **Completion detection** –
@@ -471,15 +480,16 @@ Both Display modes use the full async streaming pipeline (`ZEN_pipeline.py`):
471
480
  5D layers (`S, T, Z, Y, X`). In overlap regions, pixels from the tile with
472
481
  the higher M index replace pixels from lower-M tiles.
473
482
 
474
- **Experiment identity:** Display mode keeps one
483
+ **Experiment identity:** While watching or acquiring, Display mode keeps one
475
484
  `monitor_all_experiments()` subscription open because the targeted ZEN stream
476
485
  can close when experiment status changes to finished, before trailing pixel
477
486
  payloads have arrived. For a Napari-started acquisition, the plugin loads the
478
487
  experiment first, arms a client-side filter for its `FrameData.experiment_id`,
479
488
  and only then starts acquisition. Frames from other experiments are ignored
480
489
  while that filter is active, including during trailing-frame drain. The filter
481
- is cleared after final restructure so later ZEN-started acquisitions remain
482
- discoverable. A ZEN-started run has no experiment ID known in advance and
490
+ is cleared and the subscription is closed after final restructure. Switch to
491
+ **Display: watch ZEN experiment** to discover independently started runs.
492
+ A ZEN-started run has no experiment ID known in advance and
483
493
  therefore continues to accept the global stream; keep only one such
484
494
  acquisition active at a time.
485
495
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "napari-zenapi-streaming"
3
- version = "0.0.2"
3
+ version = "0.0.3"
4
4
  description = "ZEN API streaming plugin for napari"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12, <3.15"
@@ -92,9 +92,11 @@ class StreamingPipeline:
92
92
  # and the standalone OME-ZARR writer only receives half of them.
93
93
  self._reader_iter: Any = None
94
94
  self._reader_ready = asyncio.Event()
95
+ self._reader_lock = asyncio.Lock()
95
96
 
96
97
  # Napari-started runs use the perpetual all-experiments transport but
97
- # accept only frames carrying this ID. None preserves ZEN-started mode.
98
+ # accept only frames carrying this ID. None accepts frames in watch
99
+ # mode only.
98
100
  self._target_experiment_id: str | None = None
99
101
 
100
102
  # Processor task processes frames and updates viewer
@@ -109,16 +111,13 @@ class StreamingPipeline:
109
111
  """
110
112
  Start the streaming pipeline.
111
113
 
112
- Creates and starts two concurrent tasks:
113
- 1. Reader task: Pulls frames from ZEN API
114
- 2. Processor task: Processes frames from queue
115
-
116
- Both tasks run concurrently until stop() is called.
114
+ Start the processor and, in watch mode, the pixel reader. Selected
115
+ acquisition modes open their reader only when explicitly armed.
117
116
  """
118
117
  logger.debug("Starting streaming pipeline")
119
118
 
120
- # Start reader and processor tasks concurrently
121
- self.reader_task = asyncio.create_task(self._read_frames())
119
+ # Selected-experiment modes stay disconnected until explicitly armed.
120
+ await self.resume_reader()
122
121
  self.processor_task = asyncio.create_task(self._process_frames())
123
122
 
124
123
  logger.debug("Pipeline started - reader and processor tasks running")
@@ -139,13 +138,8 @@ class StreamingPipeline:
139
138
  # Signal all tasks to stop
140
139
  self.stop_event.set()
141
140
 
142
- # Cancel reader task (blocking on ZEN API async iterator)
143
- if self.reader_task:
144
- self.reader_task.cancel()
145
- try:
146
- await self.reader_task
147
- except asyncio.CancelledError:
148
- logger.debug("Reader task cancelled successfully")
141
+ # Serialize shutdown with any pending mode or channel change.
142
+ await self.suspend_reader()
149
143
 
150
144
  # Wait for queue to empty (process remaining frames)
151
145
  if self.queue:
@@ -298,12 +292,35 @@ class StreamingPipeline:
298
292
 
299
293
  def _accepts_response(self, response: Any) -> bool:
300
294
  """Return whether a streamed frame matches the active target."""
295
+ if not self.reader_enabled:
296
+ return False
301
297
  target = self._target_experiment_id
302
298
  return target is None or response.frame_data.experiment_id == target
303
299
 
300
+ @property
301
+ def reader_enabled(self) -> bool:
302
+ """Allow passive watching or one explicitly armed display run."""
303
+ return (
304
+ not self.stop_event.is_set()
305
+ and not self.viewer.closed.is_set()
306
+ and not self.viewer._standalone_zarr_active
307
+ and (
308
+ self.viewer.watch_enabled
309
+ or self._target_experiment_id is not None
310
+ )
311
+ )
312
+
313
+ async def refresh_reader(self) -> None:
314
+ """Apply mode and channel changes without arming an idle reader."""
315
+ async with self._reader_lock:
316
+ await self._suspend_reader()
317
+ self._resume_reader()
318
+
304
319
  async def ensure_reader_ready(self) -> None:
305
320
  """Ensure the perpetual all-experiments stream is armed."""
306
321
  await self.resume_reader()
322
+ if not self.reader_enabled:
323
+ raise RuntimeError("Pixel stream is not armed or has been closed")
307
324
  await self._reader_ready.wait()
308
325
 
309
326
  async def start_targeted_experiment(
@@ -313,23 +330,23 @@ class StreamingPipeline:
313
330
  ) -> str:
314
331
  """Prepare, filter, and start one napari-triggered experiment.
315
332
 
316
- The all-experiments stream is opened first for reliable trailing-frame
317
- delivery. ZEN then loads the experiment, the client-side ID filter is
318
- armed, and only then is acquisition started.
333
+ Load the experiment and arm its ID filter before opening the global
334
+ stream. Keep that stream open through trailing-frame delivery.
319
335
  """
320
- await self.ensure_reader_ready()
321
336
  experiment_id = await self.connection.prepare_experiment(
322
337
  experiment_name,
323
338
  overwrite=overwrite,
324
339
  )
325
340
  self.set_target_experiment(experiment_id)
326
341
  try:
342
+ await self.ensure_reader_ready()
327
343
  await self.connection.start_loaded_experiment(
328
344
  experiment_id,
329
345
  experiment_name,
330
346
  )
331
- except Exception:
347
+ except (Exception, asyncio.CancelledError):
332
348
  self.set_target_experiment(None)
349
+ await self.suspend_reader()
333
350
  raise
334
351
  return experiment_id
335
352
 
@@ -429,6 +446,11 @@ class StreamingPipeline:
429
446
 
430
447
  Safe to call when no reader is running (no-op).
431
448
  """
449
+ async with self._reader_lock:
450
+ await self._suspend_reader()
451
+
452
+ async def _suspend_reader(self) -> None:
453
+ """Close the current reader while holding the lifecycle lock."""
432
454
  if self.reader_task and not self.reader_task.done():
433
455
  self.reader_task.cancel()
434
456
  with contextlib.suppress(asyncio.CancelledError):
@@ -451,6 +473,14 @@ class StreamingPipeline:
451
473
  the next experiment in Display mode. Safe to call when the reader
452
474
  is already running (no-op).
453
475
  """
476
+ async with self._reader_lock:
477
+ self._resume_reader()
478
+
479
+ def _resume_reader(self) -> None:
480
+ """Open an eligible reader while holding the lifecycle lock."""
481
+ if not self.reader_enabled:
482
+ logger.debug("Pixel reader remains idle")
483
+ return
454
484
  if self.reader_task and not self.reader_task.done():
455
485
  logger.debug("Pipeline reader already running – skipping resume")
456
486
  return
@@ -29,13 +29,14 @@ from collections.abc import Callable, Coroutine
29
29
  from dataclasses import replace
30
30
  from datetime import datetime
31
31
  from pathlib import Path
32
+ from threading import Event
32
33
  from typing import Any, cast
33
34
 
34
35
  import napari
35
36
  import numpy as np
36
37
  from napari import Viewer
37
38
  from napari.layers import Image
38
- from qtpy.QtCore import QObject, QTimer, Signal
39
+ from qtpy.QtCore import QEvent, QObject, QTimer, Signal
39
40
  from qtpy.QtWidgets import (
40
41
  QCheckBox,
41
42
  QComboBox,
@@ -182,6 +183,23 @@ class ViewerSignals(QObject):
182
183
  set_live_preview_option_enabled = Signal(bool)
183
184
  acquisition_warning = Signal(str)
184
185
  start_button_text = Signal(str)
186
+ close_progress = Signal()
187
+
188
+
189
+ class _DockCloseFilter(QObject):
190
+ """Notify the worker loop of dock closure without reading Qt there."""
191
+
192
+ def __init__(self, dock: QWidget, closed: Event) -> None:
193
+ super().__init__(dock)
194
+ self._closed = closed
195
+ dock.installEventFilter(self)
196
+ dock.destroyed.connect(closed.set)
197
+
198
+ def eventFilter(self, watched: QObject, event: QEvent) -> bool:
199
+ """Treat closing or deleting the dock as application shutdown."""
200
+ if event.type() in (QEvent.Close, QEvent.DeferredDelete):
201
+ self._closed.set()
202
+ return super().eventFilter(watched, event)
185
203
 
186
204
 
187
205
  class StreamingViewer:
@@ -215,6 +233,9 @@ class StreamingViewer:
215
233
  The viewer must be initialized in the Qt main thread.
216
234
  """
217
235
  self.config = config
236
+ self.closed = Event()
237
+ self._action_tasks: set[asyncio.Task[None]] = set()
238
+ self.processing_task: asyncio.Task | None = None
218
239
 
219
240
  # Initialize Napari viewer
220
241
  _viewer = napari.current_viewer()
@@ -256,6 +277,7 @@ class StreamingViewer:
256
277
  self._show_acquisition_warning
257
278
  )
258
279
  self.signals.start_button_text.connect(self._set_start_button_text)
280
+ self.signals.close_progress.connect(self._close_progress_bar)
259
281
 
260
282
  # ========== Layer Management ==========
261
283
  # Single streaming layer during acquisition (7D: STMZCYX)
@@ -691,9 +713,10 @@ class StreamingViewer:
691
713
  self.scroll_area = QScrollArea()
692
714
  self.scroll_area.setWidgetResizable(True)
693
715
  self.scroll_area.setWidget(self.dropdown_widget)
694
- self.viewer.window.add_dock_widget(
716
+ dock = self.viewer.window.add_dock_widget(
695
717
  self.scroll_area, name="Experiment Selector", area="right"
696
718
  )
719
+ self._dock_close_filter = _DockCloseFilter(dock, self.closed)
697
720
 
698
721
  logger.debug("Napari viewer initialized")
699
722
 
@@ -744,6 +767,9 @@ class StreamingViewer:
744
767
  # Keep the start button label consistent with the new mode
745
768
  if self.start_button.isEnabled():
746
769
  self._sync_start_button_label()
770
+ pipeline = getattr(self.app, "pipeline", None)
771
+ if pipeline is not None:
772
+ self.safe_execution(pipeline.refresh_reader)
747
773
 
748
774
  def _set_live_latest_preference(self, enabled: bool) -> None:
749
775
  """Store the latest-frame preference for the next acquisition.
@@ -933,12 +959,7 @@ class StreamingViewer:
933
959
  # immediately (not just on next Start click).
934
960
  pipeline = getattr(self.app, "pipeline", None)
935
961
  if pipeline is not None:
936
-
937
- async def _restart_reader() -> None:
938
- await pipeline.suspend_reader()
939
- await pipeline.resume_reader()
940
-
941
- self.safe_execution(_restart_reader)
962
+ self.safe_execution(pipeline.refresh_reader)
942
963
 
943
964
  def _expected_display_frame_count(self) -> int:
944
965
  """Return the expected unique frame count for Display mode."""
@@ -1318,11 +1339,23 @@ class StreamingViewer:
1318
1339
  - Handles absence of running loop gracefully
1319
1340
  """
1320
1341
 
1342
+ async def run_action() -> None:
1343
+ if self.closed.is_set():
1344
+ logger.debug("Skipping action after plugin closure")
1345
+ return
1346
+ task = asyncio.current_task()
1347
+ assert task is not None
1348
+ self._action_tasks.add(task)
1349
+ try:
1350
+ await fn()
1351
+ finally:
1352
+ self._action_tasks.discard(task)
1353
+
1321
1354
  worker_loop = getattr(self.app, "worker_loop", None)
1322
1355
 
1323
1356
  if worker_loop is not None and not worker_loop.is_closed():
1324
1357
  # Embedded mode (plugin) - schedule in worker thread loop
1325
- asyncio.run_coroutine_threadsafe(fn(), worker_loop)
1358
+ asyncio.run_coroutine_threadsafe(run_action(), worker_loop)
1326
1359
  else:
1327
1360
  # Standalone mode - schedule in main loop
1328
1361
  try:
@@ -1330,7 +1363,7 @@ class StreamingViewer:
1330
1363
  logger.debug(
1331
1364
  "Scheduling experiment start in main loop (standalone mode)"
1332
1365
  )
1333
- loop.create_task(fn())
1366
+ loop.create_task(run_action())
1334
1367
  except RuntimeError as e:
1335
1368
  # No running loop - this shouldn't happen
1336
1369
  logger.error(f"No running event loop available: {e}")
@@ -1505,8 +1538,7 @@ class StreamingViewer:
1505
1538
  finally:
1506
1539
  self.current_experiment_id = None
1507
1540
  self._standalone_zarr_active = False
1508
- # Restart the pipeline reader so Display mode
1509
- # works again for the next experiment.
1541
+ # Resume only if the UI has switched to watch mode.
1510
1542
  if pipeline is not None:
1511
1543
  await pipeline.resume_reader()
1512
1544
  self.signals.show_stop_button.emit(False)
@@ -1821,6 +1853,7 @@ class StreamingViewer:
1821
1853
  pipeline = getattr(self.app, "pipeline", None)
1822
1854
  if pipeline is not None:
1823
1855
  pipeline.set_target_experiment(None)
1856
+ self.safe_execution(pipeline.refresh_reader)
1824
1857
  if not self.is_streaming:
1825
1858
  self._release_live_preview_option()
1826
1859
 
@@ -1959,7 +1992,9 @@ class StreamingViewer:
1959
1992
  # Process buffer with lock protection
1960
1993
  if not self.is_processing:
1961
1994
  self.is_processing = True
1962
- asyncio.create_task(self._process_buffer_with_lock())
1995
+ self.processing_task = asyncio.create_task(
1996
+ self._process_buffer_with_lock()
1997
+ )
1963
1998
 
1964
1999
  def _clear_layers(self):
1965
2000
  """Remove only this plugin's layers on the Qt thread."""
@@ -3067,6 +3102,32 @@ class StreamingViewer:
3067
3102
  """
3068
3103
  self.viewer.show()
3069
3104
 
3105
+ async def shutdown(self) -> None:
3106
+ """Cancel owned async work, including any dedicated OME-ZARR reader."""
3107
+ self.closed.set()
3108
+ self.signals.close_progress.emit()
3109
+ tasks = set(self._action_tasks)
3110
+ tasks.update(
3111
+ task
3112
+ for task in (
3113
+ self.status_monitor_task,
3114
+ self.restructure_task,
3115
+ self.processing_task,
3116
+ )
3117
+ if task is not None
3118
+ )
3119
+ for task in tasks:
3120
+ task.cancel()
3121
+ results = await asyncio.gather(*tasks, return_exceptions=True)
3122
+ for result in results:
3123
+ if isinstance(result, Exception):
3124
+ logger.error(
3125
+ "Background task failed during plugin shutdown",
3126
+ exc_info=result,
3127
+ )
3128
+ self.image_buffer.clear()
3129
+ self.metadata_buffer.clear()
3130
+
3070
3131
  def close(self) -> None:
3071
3132
  """
3072
3133
  Close the viewer and perform cleanup.
@@ -2,4 +2,4 @@
2
2
  Napari plugin for ZEN API streaming.
3
3
  """
4
4
 
5
- __version__ = "0.0.2"
5
+ __version__ = "0.0.3"