diff --git a/bec_widgets/applications/main_app.py b/bec_widgets/applications/main_app.py index 89d0cbaa..e96e369c 100644 --- a/bec_widgets/applications/main_app.py +++ b/bec_widgets/applications/main_app.py @@ -342,6 +342,15 @@ class BECMainApp(BECMainWindow): ) tour_steps.append(progress_step) + # Register the BEC server pill if available + if hasattr(self, "_server_status_item"): + server_step = self.guided_tour.register_widget( + widget=self._server_status_item, + title="BEC Server Status", + text="Shows whether the BEC core services are running. Hover over it to see every service with its details and to restart the BEC server.", + ) + tour_steps.append(server_step) + # Register the notification indicator in the status bar if hasattr(self, "notification_indicator"): notif_step = self.guided_tour.register_widget( diff --git a/bec_widgets/widgets/containers/main_window/addons/server_status_item.py b/bec_widgets/widgets/containers/main_window/addons/server_status_item.py new file mode 100644 index 00000000..aad885c1 --- /dev/null +++ b/bec_widgets/widgets/containers/main_window/addons/server_status_item.py @@ -0,0 +1,138 @@ +""" +The BEC server pill for the main window status bar: an icon for the overall state of the core +services with the label "BEC", the number of core services that are down, and the full +BECStatusBox in a card that opens on hover. +""" + +from __future__ import annotations + +from typing import Callable + +from qtpy.QtCore import QSettings +from qtpy.QtWidgets import QWidget + +from bec_widgets.utils.error_popups import SafeSlot +from bec_widgets.utils.hover_card import HoverCard +from bec_widgets.widgets.containers.main_window.addons.status_pill import ( + PillStyle, + StatusPillItem, + ToolIndicator, + ToolSeverity, +) +from bec_widgets.widgets.services.bec_status_box.bec_status_box import BECStatusBox +from bec_widgets.widgets.services.bec_status_box.status_model import ( + RestartState, + ServiceStatusModel, +) + +SETTINGS_PREFIX = "server_status" + + +def server_indicator(model: ServiceStatusModel) -> ToolIndicator: + """ + The pill indicator for the status box model: the overall state, or the restart progress while + a restart runs. The summary is the full state line, for the tooltip and screen readers; the + pill itself only reads "BEC". + + Args: + model(ServiceStatusModel): The model of the status box. + """ + down = model.services_down + tooltip = f"{model.headline}\n{model.detail}".strip() + badge = f"{down} down" if down else None + state = model.restart_state + if state != RestartState.NONE: + severity = { + RestartState.RUNNING: ToolSeverity.INFO, + RestartState.DONE: ToolSeverity.OK, + }.get(state, ToolSeverity.CRITICAL) + return ToolIndicator( + severity=severity, + summary=model.restart_text, + badge=badge, + tooltip=f"{model.restart_text}\n{model.detail}".strip(), + active=state == RestartState.RUNNING, + ) + return ToolIndicator( + severity=model.severity, + summary=model.headline, + badge=badge, + attention=bool(down), + tooltip=tooltip, + ) + + +class ServerStatusCard(HoverCard): + """The hover card of the server pill, with the full BECStatusBox.""" + + def __init__(self, owner: "ServerStatusItem"): + super().__init__(owner, width=380, object_name="server_status_card") + self.status_box = BECStatusBox( + parent=self.card, client=owner.client, rpc_exposed=False, rpc_passthrough_children=False + ) + self.status_box.setMinimumHeight(400) + self.set_content(self.status_box) + + +class ServerStatusItem(StatusPillItem): + """ + Status-bar pill with the overall state of the BEC server, with the full BECStatusBox on hover. + + The status box in the card is the only source of the state: its model drives both the pill + and the card. The pill is the compact icon style (the state icon and "BEC"); the large size is + chosen in its right-click menu and saved per user. + """ + + PILL_STYLE = PillStyle.ICON + PILL_LABEL = "BEC" + DOCK_WIDGET = "BECStatusBox" + + def __init__( + self, + parent: QWidget | None = None, + client=None, + settings: Callable[[], QSettings] | None = None, + **kwargs, + ): + super().__init__( + parent=parent, + client=client, + settings=settings, + settings_prefix=SETTINGS_PREFIX, + **kwargs, + ) + self.status_box = self.card.status_box + self.model = self.status_box.model + self.model.summary_changed.connect(self._update_indicator) + self.model.rows_changed.connect(self._update_indicator) + self.model.restart_changed.connect(self._update_indicator) + # the status box shares one poller with all boxes and pills of the client; the pill counts + # as a viewer only while it is shown, not in hidden windows like the launcher + self.poller = self.status_box.bec_service_status + self.apply_sizes() + self._update_indicator() + + def create_card(self) -> HoverCard: + return ServerStatusCard(self) + + @SafeSlot() + def _update_indicator(self) -> None: + self.set_indicator(server_indicator(self.model)) + + def pill_text(self) -> str: + """The pill label; the state is the icon, the tooltip and the card header.""" + return self.PILL_LABEL + + def showEvent(self, event): # pylint: disable=invalid-name + super().showEvent(event) + self.poller.add_viewer(self) + + def hideEvent(self, event): # pylint: disable=invalid-name + super().hideEvent(event) + self.poller.remove_viewer(self) + + def cleanup(self): + """Stop being a viewer of the poller, close the card's status box, then the pill.""" + self.poller.remove_viewer(self) + self.status_box.close() + super().cleanup() diff --git a/bec_widgets/widgets/containers/main_window/main_window.py b/bec_widgets/widgets/containers/main_window/main_window.py index f0ebe8a5..80613976 100644 --- a/bec_widgets/widgets/containers/main_window/main_window.py +++ b/bec_widgets/widgets/containers/main_window/main_window.py @@ -36,6 +36,7 @@ from bec_widgets.widgets.containers.main_window.addons.notification_center.notif ) from bec_widgets.widgets.containers.main_window.addons.scan_status_item import ScanStatusItem from bec_widgets.widgets.containers.main_window.addons.scroll_label import ScrollLabel +from bec_widgets.widgets.containers.main_window.addons.server_status_item import ServerStatusItem from bec_widgets.widgets.containers.main_window.addons.status_pill import StatusPillItem from bec_widgets.widgets.containers.main_window.addons.web_links import BECWebLinksMixin from bec_widgets.widgets.utility.feedback_dialog.feedback_dialog import FeedbackDialog @@ -149,6 +150,9 @@ class BECMainWindow(BECWidget, QMainWindow): # Add scan_progress bar with display logic self._add_scan_progress_bar() + # BEC server pill: the overall state of the core services, the full status box on hover + self._add_server_status_item() + # Setup NotificationIndicator to bottom right of the status bar self._add_notification_indicator() @@ -217,6 +221,12 @@ class BECMainWindow(BECWidget, QMainWindow): ) self._scan_progress_bar_with_separator = self.add_status_item(self._scan_status_item) + def _add_server_status_item(self): + self._server_status_item = ServerStatusItem( + self, rpc_exposed=False, rpc_passthrough_children=False + ) + self.add_status_item(self._server_status_item) + def add_status_item(self, item: StatusPillItem) -> QWidget: """ Add a status pill to the status bar, after a separator. Every pill has a stretch, but only diff --git a/tests/unit_tests/test_main_widnow.py b/tests/unit_tests/test_main_widnow.py index 74b811e3..584b52ba 100644 --- a/tests/unit_tests/test_main_widnow.py +++ b/tests/unit_tests/test_main_widnow.py @@ -377,7 +377,7 @@ def test_status_bar_holds_several_pills_each_with_its_own_fill(bec_main_window, second.apply_sizes() holder = bec_main_window.add_status_item(second) items = [item for item, _ in bec_main_window._status_items] - assert items == [bec_main_window._scan_status_item, second] + assert items == [bec_main_window._scan_status_item, bec_main_window._server_status_item, second] scan_holder = bec_main_window._scan_progress_bar_with_separator bec_main_window.resize(1400, 300) bec_main_window.show() diff --git a/tests/unit_tests/test_server_status_item.py b/tests/unit_tests/test_server_status_item.py new file mode 100644 index 00000000..ba41fbe1 --- /dev/null +++ b/tests/unit_tests/test_server_status_item.py @@ -0,0 +1,229 @@ +# pylint: skip-file +from unittest import mock + +import pytest +from qtpy.QtCore import QSettings, Qt + +from bec_widgets.tests.utils import create_widget +from bec_widgets.widgets.containers.main_window.addons.server_status_item import ( + ServerStatusItem, + server_indicator, +) +from bec_widgets.widgets.containers.main_window.addons.status_pill import ( + PILL_WIDTHS, + StatusIconPill, + ToolSeverity, +) +from bec_widgets.widgets.services.bec_status_box.bec_status_box import BECStatusBox +from bec_widgets.widgets.services.bec_status_box.status_model import RestartState + +from .test_bec_status_box import _all_services + + +@pytest.fixture +def settings_path(tmp_path): + return str(tmp_path / "server_status.ini") + + +@pytest.fixture +def item(qtbot, mocked_client, settings_path): + widget = create_widget( + qtbot, + ServerStatusItem, + client=mocked_client, + settings=lambda: QSettings(settings_path, QSettings.Format.IniFormat), + ) + yield widget + + +def test_card_holds_the_status_box(item): + assert isinstance(item.card.status_box, BECStatusBox) + assert item.model is item.status_box.model + assert item.card.card.objectName() == "server_status_card" + + +def test_pill_waits_for_services(item): + indicator = item.indicator + assert indicator.summary == "Waiting for BEC services" + assert indicator.severity == ToolSeverity.INFO + assert isinstance(item.pill, StatusIconPill) + assert (item.pill.icon_name, item.pill.text) == ("pending", "BEC") + assert not item.badge_reveal.shown + + +def test_pill_follows_the_core_state(item, qtbot): + item.status_box.update_service_status(*_all_services(extra=["CLIBECClient/abc"])) + assert item.indicator.summary == "All core services running" + assert item.indicator.severity == ToolSeverity.OK + assert item.indicator.badge is None + assert (item.pill.icon_name, item.pill.text) == ("check_circle", "BEC") + assert item.pill.toolTip() == "All core services running\n5/5 core services up · 1 other" + assert item.pill.accessibleName() == "All core services running" + + item.status_box.update_service_status(*_all_services(skip=["ScanBundler", "SciHub"])) + indicator = item.indicator + assert indicator.severity == ToolSeverity.CRITICAL + assert indicator.badge == "2 down" and indicator.attention + assert (item.pill.icon_name, item.pill.text) == ("error", "BEC") + assert item.badge_chip.text() == "2 down" + assert item.badge_reveal.shown + + item.status_box.update_service_status(*_all_services()) + assert item.indicator.badge is None + qtbot.waitUntil(lambda: not item.badge_reveal.shown) + + +def test_pill_shows_the_restart(item): + item.status_box.update_service_status(*_all_services()) + item.model.set_restart(RestartState.RUNNING, "Restarting BEC server · 2/5") + assert item.indicator.summary == "Restarting BEC server · 2/5" + assert item.indicator.active + assert (item.pill.icon_name, item.pill.spinning) == ("sync", True) + item.model.set_restart( + RestartState.FAILED, "Restart not finished: Scan server did not come back" + ) + assert item.indicator.severity == ToolSeverity.CRITICAL + assert (item.pill.icon_name, item.pill.spinning) == ("error", False) + item.model.set_restart(RestartState.DONE, "BEC server restarted") + assert item.indicator.summary == "BEC server restarted" + assert item.pill.icon_name == "check_circle" + item.model.set_restart(RestartState.NONE) + assert item.indicator.summary == "All core services running" + assert item.pill.text == "BEC" + + +def test_pill_shows_idle_services_as_a_warning(item): + from bec_lib.messages import BECStatus + + item.status_box.update_service_status(*_all_services(core_status=BECStatus.IDLE)) + assert item.indicator.severity == ToolSeverity.WARNING + assert item.pill.icon_name == "warning" + + +def test_indicator_changed_only_on_change(item, qtbot): + item.status_box.update_service_status(*_all_services()) + emitted = [] + item.indicator_changed.connect(emitted.append) + item.status_box.update_service_status(*_all_services()) + assert emitted == [] + item.status_box.update_service_status(*_all_services(skip=["SciHub"])) + assert len(emitted) == 1 + + +def test_small_pill_and_large_size_saved_per_user(item, qtbot, mocked_client, settings_path): + item.status_box.update_service_status(*_all_services()) + assert item.pill.sizeHint().width() < PILL_WIDTHS["compact"][0] / 2 + item.set_width_mode("wide") # no width modes for the icon pill + assert item.width_mode == "compact" + item.set_large(True) + again = create_widget( + qtbot, + ServerStatusItem, + client=mocked_client, + settings=lambda: QSettings(settings_path, QSettings.Format.IniFormat), + ) + assert again.large and again.pill.height() == 34 + settings = QSettings(settings_path, QSettings.Format.IniFormat) + assert settings.value("server_status/large") in (True, "true") + + +def test_restart_dialog_keeps_the_card_open(item, qtbot): + """The restart confirmation is a modal of the card; the controller keeps the card for it.""" + item.status_box.update_service_status(*_all_services()) + with mock.patch( + "bec_widgets.widgets.services.bec_status_box.bec_status_box.QMessageBox.warning", + return_value=mock.MagicMock(), + ) as dialog: + item.status_box.view.header.restart_button.click() + dialog.assert_called_once() + assert dialog.call_args.args[0] is item.status_box + + +def test_cleanup_stops_the_status_box(item, qtbot): + poller = item.poller + with mock.patch.object(poller, "_get_service_status"): + item.show() + qtbot.waitExposed(item) + assert poller.polling + item.close() + assert not poller.polling + + +def test_server_indicator_without_widget(): + model = mock.MagicMock() + model.services_down = 0 + model.headline = "Device server: error" + model.detail = "4/5 core services up" + model.severity = ToolSeverity.CRITICAL + model.restart_state = RestartState.NONE + indicator = server_indicator(model) + assert indicator.summary == "Device server: error" + assert indicator.badge is None + assert indicator.severity == ToolSeverity.CRITICAL + + +def test_polls_only_while_shown(item, qtbot): + poller = item.poller + assert poller is item.status_box.bec_service_status + assert not item.isVisible() + assert not poller.polling + with mock.patch.object(poller, "_get_service_status") as read: + item.show() + qtbot.waitExposed(item) + assert poller.polling + assert poller._service_update_timer.interval() == 3000 + read.assert_called_once() # a fresh read right away, not after the first interval + item.hide() + assert not poller.polling + + +def test_pills_of_two_windows_share_one_poll(qtbot, mocked_client, tmp_path): + def pill(name): + return create_widget( + qtbot, + ServerStatusItem, + client=mocked_client, + settings=lambda: QSettings(str(tmp_path / f"{name}.ini"), QSettings.Format.IniFormat), + ) + + first, second = pill("first"), pill("second") + poller = first.poller + assert second.poller is poller + with mock.patch.object(poller, "_get_service_status") as read: + first.show() + second.show() + qtbot.waitExposed(second) + read.assert_called_once() # one poll for both windows + first.hide() + assert poller.polling # the other window still shows its pill + second.hide() + assert not poller.polling + first.show() + qtbot.waitExposed(first) + assert poller.polling and read.call_count == 2 # resumes with a fresh read + first.close() + assert not poller.polling + + +def test_server_pill_opens_the_status_box_in_the_dock_area( + qtbot, mocked_client, monkeypatch, tmp_path +): + from bec_widgets.applications.main_app import BECMainApp + + monkeypatch.setenv("BECWIDGETS_PROFILE_DIR", str(tmp_path)) + app = create_widget(qtbot, BECMainApp, client=mocked_client) + dock_area = app.dock_area.dock_area + item = app._server_status_item + item._prepare_card() + assert not item.card.hint.isHidden() + + def docked(): + return [w for w in dock_area.widget_list() if isinstance(w, BECStatusBox)] + + before = len(docked()) + qtbot.mouseDClick(item.pill, Qt.MouseButton.LeftButton) + assert len(docked()) == before + 1 + # the docked box is its own widget, not the one in the card + assert item.status_box not in docked() + qtbot.mouseDClick(item.pill, Qt.MouseButton.LeftButton) + assert len(docked()) == before + 1