"""End-to-end verification of Clinical OS 4.0 Dual-Wing Companion & Split-Stage Engine.""" from __future__ import annotations import os os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") import pytest from PySide6.QtCore import QEvent, Qt, QTimer from PySide6.QtTest import QTest from PySide6.QtWidgets import QApplication, QDialog from doctor_workstation.core.permissions import PermissionSet from doctor_workstation.services.demo_repository import DEMO_PERMISSIONS, DemoDoctorRepository from doctor_workstation.ui.dialogs.appointment_complete import AppointmentCompleteDialog from doctor_workstation.ui.dialogs.prescription import PrescriptionEditorDialog from doctor_workstation.ui.shell_spatial import SpatialShellWindow from doctor_workstation.ui.theme import apply_theme from doctor_workstation.ui.visuals.ai_report_wing import ( ClinicalAiReportWingPanel, _extract_key_takeaways, _split_evidence_rows, ) def _settle(app: QApplication, rounds: int = 16) -> None: for _ in range(rounds): app.processEvents() QTest.qWait(8) @pytest.fixture(scope="module") def application() -> QApplication: app = QApplication.instance() or QApplication([]) apply_theme(app) return app def test_ai_report_wing_extracts_tcm_takeaways_and_evidence_rows() -> None: sample_advice = ( "四诊:望诊见舌质偏红,舌苔黄腻(部分区域可见剥落),舌体略胖大,边有齿痕\n" "闻诊未见异常记录\n" "问诊见口干口苦,手脚偶发麻木,近期视物模糊、重影,腰酸\n" "切诊脉象未采集\n" "八纲:里证(病在脏腑)、热证(苔黄、口干口苦)、虚实夹杂\n" "气血津液与脏腑定位:气阴两虚,湿热内蕴,病位主要在脾、肾、肝\n" "证名:消渴病,气阴两虚兼湿热证" ) takeaways = _extract_key_takeaways(sample_advice) assert len(takeaways) == 3 assert takeaways[0][0] == "辨证证名" assert "消渴病" in takeaways[0][1] assert takeaways[1][0] == "八纲属性" assert takeaways[2][0] == "病位病机" assert "脾、肾、肝" in takeaways[2][1] rows = _split_evidence_rows(sample_advice) badges = [r[0] for r in rows] assert "望诊" in badges assert "闻诊" in badges assert "问诊" in badges assert "切诊" in badges assert "辨证结论" in badges # Also verify inline OpenAI bracketed wall-of-text splits into distinct structured sections openai_wall = ( "【已知事实】56岁男性,身高186 cm、体重70 kg,初诊空腹血糖11.00 mmol/L。" "【合理推断】总体符合长期糖尿病伴血糖控制不稳定。" "【信息缺口】缺少糖尿病明确分型、HbA1c及眼底检查。" ) o_rows = _split_evidence_rows(openai_wall) o_badges = [r[0] for r in o_rows] assert o_badges == ["已知事实", "临床推断", "待补信息"] def test_spatial_wing_ai_report_left_right_dock_and_magnetic_sidecar( application: QApplication, ) -> None: repo = DemoDoctorRepository() session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) shell = SpatialShellWindow( repo, {"session": session, "user": session.user, "demo_mode": True}, PermissionSet(DEMO_PERMISSIONS), ) shell.resize(1520, 920) shell.show() _settle(application, 24) try: # 1. Open AI Report Companion Wing via bottom sheet button (replaces ugly modal dialog!) shell._open_active_patient_ai_report() _settle(application, 8) wm = shell.wing_manager assert wm.is_open assert wm.side == "right" assert wm.mode == "docked" assert shell.right_wing_dock.isVisible() assert not shell.left_wing_dock.isVisible() assert isinstance(wm.active_widget, ClinicalAiReportWingPanel) # Copy report uses clean inline feedback without giant center overlay wm.active_widget._copy_current_report() assert "已复制" in wm.active_widget.copy_btn.text() # 2. Switch wing to LEFT dock wm.set_side("left") _settle(application, 6) assert wm.side == "left" assert shell.left_wing_dock.isVisible() assert not shell.right_wing_dock.isVisible() # Switch back to RIGHT dock wm.set_side("right") _settle(application, 6) assert wm.side == "right" assert shell.right_wing_dock.isVisible() # 3. Detach to external Magnetic Companion Sidecar Window & prove ZERO overlap! wm.set_mode("sidecar") _settle(application, 8) assert wm.mode == "sidecar" assert wm._sidecar is not None and wm._sidecar.isVisible() assert not shell.right_wing_dock.isVisible() assert shell.geometry().right() < wm._sidecar.geometry().left() # 4. Re-dock back into main window & verify clean restoration wm.set_mode("docked") _settle(application, 6) assert wm.mode == "docked" assert shell.right_wing_dock.isVisible() assert not wm._sidecar.isVisible() wm.close_wing() _settle(application, 4) assert not wm.is_open finally: for page in shell.pages.values(): if hasattr(page, "poll_timer"): page.poll_timer.stop() shell.chat_notifications.stop() shell.close() shell.deleteLater() application.sendPostedEvents(None, QEvent.Type.DeferredDelete) application.processEvents() def test_qdialogs_and_exec_callers_mount_non_modally_in_spatial_wing( application: QApplication, ) -> None: repo = DemoDoctorRepository() session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) shell = SpatialShellWindow( repo, {"session": session, "user": session.user, "demo_mode": True}, PermissionSet(DEMO_PERMISSIONS), ) shell.resize(1520, 920) shell.show() _settle(application, 24) try: wm = shell.wing_manager # 1. Open DiagnosisDialog ('四诊病历') -> mounts full-bleed inside Right Wing! shell._open_active_patient_diagnosis() _settle(application, 12) assert wm.is_open assert wm.active_widget is shell._global_diagnosis_dialog assert shell._global_diagnosis_dialog.property("hostedInSpatialWing") is True assert shell.right_wing_dock.isVisible() # Close and reopen cached DiagnosisDialog -> must cleanly re-mount! wm.close_wing() _settle(application, 4) assert not wm.is_open shell._open_active_patient_diagnosis() _settle(application, 8) assert wm.is_open assert wm.active_widget is shell._global_diagnosis_dialog # 2. Open PrescriptionEditorDialog via synchronous `.exec()` and reject asynchronously! rx_dlg = PrescriptionEditorDialog( repo, {"diagnosis_id": 501, "patient_id": 301, "patient_name": "林晓岚"}, mode="add", current_user=session.user, permissions=PermissionSet(DEMO_PERMISSIONS), parent=shell, ) rx_errors: list[BaseException] = [] def _verify_and_close_rx() -> None: try: assert wm.is_open assert wm.active_widget is rx_dlg assert rx_dlg.property("hostedInSpatialWing") is True assert not rx_dlg.isModal() except BaseException as exc: # noqa: BLE001 rx_errors.append(exc) finally: rx_dlg.reject() QTimer.singleShot(40, _verify_and_close_rx) code = rx_dlg.exec() if rx_errors: raise rx_errors[0] assert code == int(QDialog.DialogCode.Rejected) assert not wm.is_open # 3. Test AppointmentCompleteDialog `.exec()` returning Accepted via Spatial Wing! comp_dlg = AppointmentCompleteDialog(can_note=True, parent=shell) QTimer.singleShot(30, comp_dlg.accept) res = comp_dlg.exec() assert res == int(QDialog.DialogCode.Accepted) finally: for page in shell.pages.values(): if hasattr(page, "poll_timer"): page.poll_timer.stop() shell.chat_notifications.stop() shell.close() shell.deleteLater() application.sendPostedEvents(None, QEvent.Type.DeferredDelete) application.processEvents() def test_125dpi_rapid_switching_zero_overlap_and_fast_open( application: QApplication, ) -> None: """Reproduce 1920x1080 @ 125% DPI (1536x864) rapid wing switching & verify zero overlap.""" import time from PySide6.QtWidgets import QScrollArea, QWidget repo = DemoDoctorRepository() session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) shell = SpatialShellWindow( repo, {"session": session, "user": session.user, "demo_mode": True}, PermissionSet(DEMO_PERMISSIONS), ) shell.resize(1536, 864) shell.show() _settle(application, 28) try: rec = shell.pages["reception"] wm = shell.wing_manager # Expand bottom sheet first, then open AI report wing -> bottom sheet must auto-collapse! shell.set_ai_bottom_sheet_expanded(True) assert shell.ai_bottom_sheet.is_expanded rec.open_ai_report_wing() _settle(application, 6) assert not shell.ai_bottom_sheet.is_expanded # Rapidly alternate between AI Report Wing and Edit Diagnosis 4 times for _ in range(2): t0 = time.perf_counter() rec._edit_diagnosis() dt_diag_ms = (time.perf_counter() - t0) * 1000.0 _settle(application, 6) visible_body_children = [ c for c in wm.card.body_host.findChildren(QWidget, options=Qt.FindChildOption.FindDirectChildrenOnly) if c.isVisible() and c is not wm.card.glide_veil ] assert len(visible_body_children) == 1 assert visible_body_children[0] is shell._global_diagnosis_dialog assert wm.card.header.title_label.text() == "编辑诊单" t1 = time.perf_counter() rec.open_ai_report_wing() dt_ai_ms = (time.perf_counter() - t1) * 1000.0 _settle(application, 6) visible_body_children = [ c for c in wm.card.body_host.findChildren(QWidget, options=Qt.FindChildOption.FindDirectChildrenOnly) if c.isVisible() and c is not wm.card.glide_veil ] assert len(visible_body_children) == 1 assert isinstance(visible_body_children[0], ClinicalAiReportWingPanel) assert dt_diag_ms < 180.0 assert dt_ai_ms < 120.0 # Open Edit Diagnosis at 1536x864 and verify cockpit columns & past_history do NOT clip/overlap rec._edit_diagnosis() _settle(application, 10) cockpit = rec.cockpit_view twin_right = cockpit.twin_stage.mapTo(cockpit, cockpit.twin_stage.rect().topRight()).x() plan_left = cockpit.plan_card.mapTo(cockpit, cockpit.plan_card.rect().topLeft()).x() assert twin_right <= plan_left, f"TwinStage ({twin_right}) overlapped PlanCard ({plan_left})!" diag = shell._global_diagnosis_dialog basic_scroll = diag.findChild(QScrollArea, "DiagnosisDrawerBody") assert basic_scroll is not None past_editor = diag._choice_fields["past_history"] assert past_editor.width() <= basic_scroll.viewport().width() # Verify clicking '原始详单 ↗' opens DiagnosisDialog in Wing WITHOUT leaving Cockpit view! wm.close_wing() _settle(application, 4) cockpit.open_chart_tab_requested.emit(0) _settle(application, 8) assert rec.view_mode_stack.currentWidget() is rec.cockpit_view assert wm.is_open and wm.active_widget is shell._global_diagnosis_dialog finally: for page in shell.pages.values(): if hasattr(page, "poll_timer"): page.poll_timer.stop() shell.chat_notifications.stop() shell.close() shell.deleteLater() application.sendPostedEvents(None, QEvent.Type.DeferredDelete) application.processEvents() def test_v4_3_calendar_density_patient_switch_sync_and_video_diagnosis_btn( application: QApplication, ) -> None: """Verify: (1) spacious 14d/7d calendar, (2) live Wing refresh on patient switch, (3) video 4-exam button.""" from PySide6.QtWidgets import QPushButton repo = DemoDoctorRepository() session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) shell = SpatialShellWindow( repo, {"session": session, "demo_mode": True}, session.permissions, ) shell.resize(1536, 864) shell.show() _settle(application, 22) try: rec = shell.pages["reception"] wm = shell.wing_manager journey_card = rec.cockpit_view.journey_card # 1. Full width: spacious 14-day rounded cards (every card >= 32px wide) _ = shell.grab() assert len(journey_card._day_rects) == 14 assert all(r.width() >= 32.0 for r, _ in journey_card._day_rects) # 2. Open Edit Diagnosis for first patient (林晓岚, diagnosis_id=501) rec._edit_diagnosis() _settle(application, 14) diag = shell._global_diagnosis_dialog assert wm.is_open and wm.active_widget is diag first_diag_id = diag._diagnosis_id assert first_diag_id > 0 # When Right Wing narrows stage at 1536x864, calendar adapts to 7 spacious cards! _ = shell.grab() assert len(journey_card._day_rects) == 7 assert all(r.width() >= 36.0 for r, _ in journey_card._day_rects) # Switch to the 2nd patient in queue while DiagnosisDialog stays open in Right Wing! assert len(rec._queue_records) >= 2 second_record = rec._queue_records[1] second_name = str( getattr(second_record, "patient_name", None) or (second_record.get("patient_name") if isinstance(second_record, dict) else "") or "" ) rec._select_record_from_cockpit(second_record) _settle(application, 18) assert diag._diagnosis_id != first_diag_id assert second_name and second_name in wm.card.header.context_badge.toolTip() name_widget = diag.edit_fields.get("name") or diag.display_fields.get("name") if name_widget is not None: rendered_name = ( name_widget.text() if hasattr(name_widget, "text") else name_widget.toPlainText() ) assert second_name in rendered_name # 3. Video/IM '四诊病历' QPushButton.clicked(bool=False) MUST NOT clobber diagnosis_id! wm.close_wing() _settle(application, 4) target_diag_id = diag._diagnosis_id callback = lambda *_args, current_id=target_diag_id: shell.open_diagnosis_by_id( # noqa: E731 current_id, modeless=True ) fake_hud_btn = QPushButton("四诊病历") fake_hud_btn.clicked.connect(lambda _checked=False: callback()) fake_hud_btn.click() _settle(application, 10) assert wm.is_open and wm.active_widget is diag assert diag._diagnosis_id == target_diag_id # Also verify open_diagnosis_by_id(False) safely falls back to active patient's diagnosis_id wm.close_wing() _settle(application, 4) recovered = shell.open_diagnosis_by_id(False, modeless=True) _settle(application, 8) assert recovered is diag assert diag._diagnosis_id == target_diag_id finally: for page in shell.pages.values(): if hasattr(page, "poll_timer"): page.poll_timer.stop() shell.chat_notifications.stop() shell.close() shell.deleteLater() application.sendPostedEvents(None, QEvent.Type.DeferredDelete) application.processEvents() def test_v4_4_locus_deep_links_and_real_dated_data_only( application: QApplication, ) -> None: """Verify: (1) sparse patient renders ONLY real dated values (zero empty '—' or 11 blank bars), (2) clicking each TwinStage card jumps straight to its matching tab & field in DiagnosisDialog.""" from doctor_workstation.ui.viewmodels.cockpit_vm import derive_cockpit_snapshot # 1. Sparse patient payload matching real-machine '王进花' screenshot sparse_vm = derive_cockpit_snapshot( appointment={ "id": 88, "diagnosis_id": 608, "patient_name": "王进花", "appointment_date": "2026-11-27", "appointment_time": "17:30:00", "diagnosis_type_text": "复诊", }, patient={"name": "王进花", "age": 67}, diagnosis={ "id": 608, "patient_name": "王进花", "diagnosis_date": 0, # Unset 0 timestamp must NEVER display '诊断日期 · 0' "chief_complaint": "姓名:王进花\n年龄:67\n患者空腹血糖:空腹18\n在用药物:没有吃药\n患病时长:一年多", }, ) assert sparse_vm.twin_sanjiao.scan_badge == "诊断日期 · 2026-11-27" assert len(sparse_vm.progression.bars) == 1 assert sparse_vm.progression.bars[0].value_text == "18" assert sparse_vm.progression.bars[0].label == "11-27" assert len(sparse_vm.diurnal.slots) == 0 assert len(sparse_vm.diurnal.vitals) >= 2 assert all(v.value != "—" and bool(v.date_label) for v in sparse_vm.diurnal.vitals) assert any("没有吃药" in v.value for v in sparse_vm.diurnal.vitals) assert any("一年多" in v.value for v in sparse_vm.diurnal.vitals) # 2. End-to-end Deep-Link Navigation across TwinStage cards & Glycemic cards repo = DemoDoctorRepository() session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) shell = SpatialShellWindow( repo, {"session": session, "demo_mode": True}, session.permissions, ) shell.resize(1536, 864) shell.show() _settle(application, 22) try: rec = shell.pages["reception"] cockpit = rec.cockpit_view # Click '下焦 · 腰肾二便与四肢' -> opens 'basic' tab & scrolls down to urine_condition cockpit.locus_selected.emit("kidney_limbs") _settle(application, 16) diag = shell._global_diagnosis_dialog assert shell.wing_manager.is_open and shell.wing_manager.active_widget is diag assert diag._current_tab_key() == "basic" assert diag._basic_scroll.verticalScrollBar().value() > 120 # Click '既往史与合并症' -> stays on 'basic' & scrolls down to past_history cockpit.locus_selected.emit("past_history") _settle(application, 10) assert diag._current_tab_key() == "basic" assert diag._basic_scroll.verticalScrollBar().value() > 180 # Click '医生备注与影像附件' -> switches directly to 'notes' tab cockpit.locus_selected.emit("notes_media") _settle(application, 8) assert diag._current_tab_key() == "notes" # Click '本诊单电子处方记录' -> switches directly to 'prescription' tab cockpit.locus_selected.emit("rx_summary") _settle(application, 8) assert diag._current_tab_key() == "prescription" # Click '空腹血糖监测' -> switches directly to 'daily' tab cockpit.progression_card.open_daily_requested.emit() _settle(application, 8) assert diag._current_tab_key() == "daily" finally: for page in shell.pages.values(): if hasattr(page, "poll_timer"): page.poll_timer.stop() shell.chat_notifications.stop() shell.close() shell.deleteLater() application.sendPostedEvents(None, QEvent.Type.DeferredDelete) application.processEvents()