This commit is contained in:
gr
2026-10-27 16:33:30 +08:00
423 changed files with 72666 additions and 5389 deletions
+2 -2
View File
@@ -3,9 +3,9 @@
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
# Single source of truth for runtime, package, installer, and executable versions.
__version__ = "1.4.9"
__version__ = "1.5.0"
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
DEBUG_MODE = True
DEBUG_MODE = False
ONLINE_API_BASE_URL = "https://admin.zhenyangtang.com.cn"
@@ -6,7 +6,7 @@ import hashlib
import json
import struct
import zlib
from collections.abc import Mapping, Sequence
from collections.abc import Callable, Mapping, Sequence
from copy import deepcopy
from datetime import date, datetime, timedelta
from os import PathLike
@@ -2771,10 +2771,14 @@ class DemoDoctorRepository:
*,
call_record_id: int | None = None,
mime_type: str = "audio/webm",
on_progress: Callable[[int, int], None] | None = None,
) -> dict[str, Any]:
"""Upload then attach a demo local-audio file using the production sequence."""
source_path = Path(path)
size = source_path.stat().st_size if source_path.is_file() else 0
if on_progress is not None:
on_progress(0, size)
is_audio = source_path.suffix.lower() in {
".ogg",
".opus",
@@ -2811,6 +2815,8 @@ class DemoDoctorRepository:
record["local_audio_status_text"] = "已保存"
else:
self.attach_local_call_recording(diagnosis_id, file_url, call_record_id=target_id)
if on_progress is not None:
on_progress(size, size)
return {
"diagnosis_id": diagnosis_id,
"call_record_id": target_id,
@@ -683,6 +683,7 @@ class DoctorRepository(Protocol):
*,
call_record_id: int | None = None,
mime_type: str = "audio/webm",
on_progress: Callable[[int, int], None] | None = None,
) -> dict[str, Any]:
"""Upload a locally captured call recording to a real call record."""
@@ -2512,8 +2513,13 @@ class RemoteDoctorRepository:
*,
call_record_id: int | None = None,
mime_type: str = "audio/webm",
on_progress: Callable[[int, int], None] | None = None,
) -> dict[str, Any]:
"""Chunk-upload one local audio recording and attach it atomically."""
"""Chunk-upload one local audio recording and attach it atomically.
``on_progress(sent_bytes, total_bytes)`` runs on the calling thread after
every confirmed chunk; its failures never interrupt the upload.
"""
if diagnosis_id <= 0:
raise ValueError("diagnosis_id must be positive")
@@ -2533,6 +2539,13 @@ class RemoteDoctorRepository:
clean_mime = str(mime_type or "audio/webm").strip()[:120] or "audio/webm"
final_result: Mapping[str, Any] | None = None
bound_call_record_id = call_record_id
def report(sent: int) -> None:
if on_progress is not None:
with suppress(Exception):
on_progress(min(sent, file_size), file_size)
report(0)
with recording_path.open("rb") as stream:
for chunk_index in range(chunk_total):
content = stream.read(chunk_size)
@@ -2567,6 +2580,7 @@ class RemoteDoctorRepository:
raise ApiProtocolError(
"uploadCallRecording returned a different call_record_id"
)
report((chunk_index + 1) * chunk_size)
if final_result is None or not bool(final_result.get("completed")):
raise ApiProtocolError("uploadCallRecording did not complete the local audio upload")
@@ -2990,6 +3004,9 @@ def _diagnosis_ai_request(diagnosis_id: int, prompt: str, task: str) -> tuple[st
raise ValueError("prompt must not exceed 500 characters")
clean_task = task.strip().lower() or "custom"
if clean_task not in {
"case_analysis",
"glucose_trend",
"lifestyle_advice",
"summary",
"tcm_pattern",
"prescription_review",
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,121 @@
"""从 AI 回复中摘出药名(中药 / 西药),供用药速览与正文高亮使用。
只用显式词表匹配,不按“…汤/…片”等后缀猜测,宁可漏标也不把普通词误标成药。
匹配按长词优先,所以「六味地黄丸」不会被拆成「地黄」。
"""
from __future__ import annotations
import re
from typing import NamedTuple
TCM = "tcm"
WESTERN = "western"
# 中药绿、西药蓝;与侧栏状态卡的完成/进行中色一致。
DRUG_COLORS = {
TCM: ("#1F7A4D", "#EAF7F0", "#BFE6D0"),
WESTERN: ("#3347B8", "#EEF1FA", "#C9D1F3"),
}
DRUG_STYLES = {
kind: f"color: {fg}; background-color: {bg}; font-weight: 700;"
for kind, (fg, bg, _border) in DRUG_COLORS.items()
}
# 常用中药饮片(两字及以上,避免单字误配)。
_TCM_HERBS = """
黄芪 党参 人参 西洋参 太子参 红参 白术 苍术 茯苓 茯神 土茯苓 猪苓 泽泻 薏苡仁 甘草 炙甘草
当归 川芎 白芍 赤芍 熟地黄 生地黄 熟地 生地 地黄 山茱萸 山萸肉 牡丹皮 丹皮 丹参 三七 红花 桃仁
黄连 黄芩 黄柏 栀子 知母 石膏 天花粉 葛根 麦冬 天冬 玉竹 黄精 石斛 沙参 北沙参 南沙参 百合
五味子 枸杞子 女贞子 墨旱莲 菟丝子 桑椹 覆盆子 金樱子 芡实 怀山药 鸡内金 神曲 麦芽 山楂
陈皮 青皮 枳实 枳壳 厚朴 半夏 法半夏 姜半夏 竹茹 干姜 炮姜 桂枝 肉桂 附子 制附子
柴胡 升麻 防风 荆芥 羌活 独活 秦艽 威灵仙 桑枝 桑叶 菊花 薄荷 蝉蜕 牛蒡子 连翘 金银花 蒲公英
板蓝根 大青叶 鱼腥草 败酱草 白花蛇舌草 夏枯草 决明子 车前子 车前草 木通 通草 滑石 萹蓄 瞿麦
茵陈 金钱草 虎杖 大黄 芒硝 火麻仁 郁李仁 杏仁 苦杏仁 桔梗 紫菀 款冬花 百部 川贝母 浙贝母 贝母
瓜蒌 全瓜蒌 薤白 远志 酸枣仁 柏子仁 夜交藤 首乌藤 合欢皮 龙骨 牡蛎 珍珠母 磁石 天麻 钩藤 石决明
地龙 全蝎 蜈蚣 僵蚕 水蛭 土鳖虫 鸡血藤 牛膝 怀牛膝 川牛膝 杜仲 续断 桑寄生 狗脊 骨碎补 补骨脂
淫羊藿 仙茅 巴戟天 肉苁蓉 锁阳 益智仁 乌药 小茴香 吴茱萸 木香 香附 郁金 延胡索 川楝子 佛手
砂仁 白豆蔻 豆蔻 草豆蔻 藿香 佩兰 苍耳子 辛夷 白芷 细辛 麻黄 紫苏 苏叶 紫苏叶 苏子 紫苏子
乌梅 五倍子 诃子 浮小麦 麻黄根 山茱萸肉 何首乌 制何首乌 阿胶 鹿角胶 龟甲 鳖甲 玄参 牛黄 冰片
麝香 苏合香 石菖蒲 益母草 泽兰 王不留行 莪术 三棱 乳香 没药 五灵脂 蒲黄 茜草 白茅根 侧柏叶
仙鹤草 艾叶 地榆 槐花 小蓟 大蓟 白及 荷叶 绞股蓝 桑白皮 地骨皮 青蒿 银柴胡 胡黄连 白薇
苦参 白鲜皮 地肤子 蛇床子 黄药子 海藻 昆布 荔枝核 橘核 鬼箭羽 翻白草 玉米须 冬瓜皮 赤小豆
""".split()
# 常用方剂与中成药(含糖尿病常用)。
_TCM_FORMULAS = """
六味地黄丸 知柏地黄丸 杞菊地黄丸 麦味地黄丸 金匮肾气丸 济生肾气丸 桂附地黄丸 左归丸 右归丸
玉泉丸 消渴丸 参芪降糖颗粒 津力达颗粒 天芪降糖胶囊 渴乐宁胶囊 金芪降糖片 降糖舒胶囊 糖脉康颗粒
芪蛭降糖胶囊 木丹颗粒 通心络胶囊 复方丹参滴丸 银杏叶片 血塞通 血栓通 丹参酮 脑心通胶囊
补中益气丸 补中益气汤 归脾丸 归脾汤 逍遥丸 逍遥散 加味逍遥丸 丹栀逍遥散 柴胡疏肝散 四逆散
四君子汤 六君子汤 香砂六君子汤 参苓白术散 理中丸 附子理中丸 四物汤 八珍汤 十全大补汤 当归补血汤
生脉饮 生脉散 玉女煎 白虎加人参汤 白虎汤 葛根芩连汤 黄连解毒汤 半夏泻心汤 大柴胡汤 小柴胡汤
血府逐瘀汤 补阳还五汤 桃红四物汤 二陈汤 温胆汤 黄连温胆汤 天麻钩藤饮 镇肝熄风汤 酸枣仁汤
天王补心丹 一贯煎 增液汤 沙参麦冬汤 益胃汤 竹叶石膏汤 五苓散 猪苓汤 真武汤 实脾饮 防己黄芪汤
玉屏风散 桂枝汤 麻黄汤 银翘散 桑菊饮 藿香正气散 藿香正气水 保和丸 平胃散 二妙丸 三妙丸 四妙丸
当归四逆汤 黄芪桂枝五物汤 独活寄生汤 身痛逐瘀汤 大补阴丸 二至丸 交泰丸 安宫牛黄丸 浓缩水丸
""".split()
# 西药(以内分泌、心血管、常见合并用药为主)。
_WESTERN = """
二甲双胍 盐酸二甲双胍 格列美脲 格列齐特 格列吡嗪 格列本脲 格列喹酮 瑞格列奈 那格列奈 阿卡波糖
伏格列波糖 米格列醇 吡格列酮 罗格列酮 西格列汀 沙格列汀 维格列汀 利格列汀 阿格列汀 达格列净
恩格列净 卡格列净 艾托格列净 利拉鲁肽 司美格鲁肽 度拉糖肽 艾塞那肽 利司那肽 贝那鲁肽 替尔泊肽
胰岛素 门冬胰岛素 赖脯胰岛素 谷赖胰岛素 甘精胰岛素 地特胰岛素 德谷胰岛素 精蛋白锌胰岛素
重组人胰岛素 生物合成人胰岛素 预混胰岛素 硝苯地平 氨氯地平 左旋氨氯地平 非洛地平 尼群地平
贝尼地平 厄贝沙坦 缬沙坦 氯沙坦 替米沙坦 坎地沙坦 奥美沙坦 沙库巴曲缬沙坦 依那普利 贝那普利
培哚普利 卡托普利 福辛普利 美托洛尔 比索洛尔 卡维地洛 阿替洛尔 氢氯噻嗪 吲达帕胺 呋塞米
螺内酯 托拉塞米 阿托伐他汀 瑞舒伐他汀 辛伐他汀 普伐他汀 匹伐他汀 依折麦布 非诺贝特 苯扎贝特
阿司匹林 氯吡格雷 替格瑞洛 华法林 利伐沙班 达比加群 硫酸氢氯吡格雷 甲钴胺 依帕司他 硫辛酸
α-硫辛酸 胰激肽原酶 羟苯磺酸钙 前列地尔 贝前列素钠 别嘌醇 非布司他 苯溴马隆 碳酸氢钠
左甲状腺素 甲巯咪唑 丙硫氧嘧啶 奥美拉唑 泮托拉唑 雷贝拉唑 埃索美拉唑 雷尼替丁 法莫替丁
多潘立酮 莫沙必利 二甲硅油 乳果糖 阿莫西林 头孢呋辛 左氧氟沙星 莫西沙星 阿奇霉素 布洛芬
对乙酰氨基酚 塞来昔布 加巴喷丁 普瑞巴林 碳酸钙 骨化三醇 维生素D 维生素B12 叶酸 硝酸甘油
单硝酸异山梨酯 曲美他嗪 地高辛 胺碘酮 坦索罗辛 非那雄胺 西地那非 他达拉非
""".split()
# 西药常带剂型后缀;一起摘出,展示时保留原文写法。
_WESTERN_FORM = r"(?:缓释片|控释片|肠溶片|分散片|片|缓释胶囊|肠溶胶囊|胶囊|注射液|注射剂|笔|颗粒)?"
class DrugMention(NamedTuple):
start: int
end: int
# 去掉剂型后缀的药名,用于速览去重;高亮范围仍覆盖原文中的完整写法。
name: str
kind: str
def _alternation(names: list[str]) -> str:
return "|".join(re.escape(name) for name in sorted(set(names), key=len, reverse=True))
# 单一正则、长词优先:中成药 > 西药 > 饮片,保证一个位置只被归入一类。
_DRUG_RE = re.compile(
rf"(?P<tcm_formula>{_alternation(_TCM_FORMULAS)})"
rf"|(?P<western>(?P<western_base>{_alternation(_WESTERN)}){_WESTERN_FORM})"
rf"|(?P<herb>{_alternation(_TCM_HERBS)})"
)
def find_drug_mentions(text: str) -> list[DrugMention]:
"""返回正文中每一处药名的位置与类别(不重叠、按出现顺序)。"""
mentions: list[DrugMention] = []
for match in _DRUG_RE.finditer(str(text or "")):
if match.group("western"):
mentions.append(DrugMention(match.start(), match.end(), match.group("western_base"), WESTERN))
else:
mentions.append(DrugMention(match.start(), match.end(), match.group(), TCM))
return mentions
def summarize_drugs(text: str) -> dict[str, list[str]]:
"""按类别去重汇总药名,保留首次出现的顺序。"""
summary: dict[str, list[str]] = {TCM: [], WESTERN: []}
for mention in find_drug_mentions(text):
names = summary[mention.kind]
if mention.name not in names:
names.append(mention.name)
return summary
@@ -15,6 +15,8 @@ from contextvars import ContextVar
from dataclasses import dataclass
from html import escape
from .ai_consult_drug_names import DRUG_STYLES, find_drug_mentions
from .ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
@@ -393,18 +395,23 @@ def metric_text_html(text: str, *, metric_label: str = "") -> str:
if metric_label and _MISSING_PLACEHOLDER_RE.fullmatch(text):
spans.append((0, len(text), UNKNOWN_COLOR))
# 药名高亮:中药绿、西药蓝,浅底加粗,让医生在正文里一眼看到用药。
styled = [(start, end, f"color: {color}; font-weight: 600;") for start, end, color in spans]
styled.extend(
(mention.start, mention.end, DRUG_STYLES[mention.kind])
for mention in find_drug_mentions(text)
)
# Prefer a full reading over a contained unitless value, then consume each
# original character once. Generated markup is never scanned by a regex.
spans.sort(key=lambda span: (span[0], -(span[1] - span[0])))
styled.sort(key=lambda span: (span[0], -(span[1] - span[0])))
pieces = ['<span style="white-space: pre-wrap;">']
position = 0
for start, end, color in spans:
for start, end, style in styled:
if start < position:
continue
pieces.append(escape(text[position:start]))
pieces.append(
f'<span style="color: {color}; font-weight: 600;">{escape(text[start:end])}</span>'
)
pieces.append(f'<span style="{style}">{escape(text[start:end])}</span>')
position = end
pieces.append(escape(text[position:]))
pieces.append("</span>")
@@ -2,13 +2,26 @@
from __future__ import annotations
import mimetypes
import re
import sqlite3
from collections.abc import Mapping, Sequence
from contextlib import suppress
from pathlib import Path
from typing import Any
from PySide6.QtCore import QDate, QDateTime, QEvent, QPoint, QRect, Qt, QTimer, QUrl, Signal
from PySide6.QtCore import (
QDate,
QDateTime,
QEvent,
QObject,
QPoint,
QRect,
Qt,
QTimer,
QUrl,
Signal,
)
from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import (
QAbstractItemView,
@@ -22,6 +35,7 @@ from PySide6.QtWidgets import (
QLabel,
QMessageBox,
QPlainTextEdit,
QProgressBar,
QPushButton,
QScrollArea,
QSizePolicy,
@@ -83,6 +97,13 @@ from .issued_prescription_ai import can_open_issued_ai, present_issued_prescript
from .local_audio_queue import LocalAudioQueueDialog
from .prescription_ai import can_open_diagnosis_ai_report, present_diagnosis_ai_report
class _UploadProgressRelay(QObject):
"""把后台线程中的分片上传进度转回界面线程(信号跨线程自动排队)。"""
# 用 object 传字节数:Qt 的 int 是 32 位,超过 2 GB 的视频会溢出。
progressed = Signal(object, object)
_PHONE_PERMISSION = "tcm.diagnosis/phonePlain"
_PATIENT_ORDERS_PERMISSION = "tcm.diagnosis/patientOrders"
_ORDER_DETAIL_PERMISSION = "tcm.prescriptionOrder/detail"
@@ -145,7 +166,6 @@ _DIAGNOSIS_FIELDS = (
("脂肪肝程度", "fatty_liver_degree", "脂肪肝程度"),
("舌象", "tongue", "舌质、舌苔等观察"),
("舌苔", "tongue_coating", "舌苔记录"),
("脉象", "pulse", "脉象记录"),
("临床诊断", "clinical_diagnosis", "填写临床诊断"),
("治则", "treatment_principle", "治疗原则"),
("处方", "prescription", "处方摘要"),
@@ -1513,9 +1533,38 @@ class DiagnosisDialog(QDialog):
)
toolbar.addWidget(self.video_upload_button)
layout.addLayout(toolbar)
layout.addWidget(self._build_video_upload_progress())
layout.addWidget(self._new_table("video", "DiagnosisVideoTable"), 1)
return page
def _build_video_upload_progress(self) -> QFrame:
"""上传本地回放时的进度条:按分片实时更新,医生能看到上传在进行、进行到哪。"""
frame = QFrame()
frame.setObjectName("DiagnosisVideoUploadProgress")
frame.setStyleSheet(
"QFrame#DiagnosisVideoUploadProgress { background-color: #EEF1FA;"
" border: 1px solid #C9D1F3; border-radius: 8px; }"
"QFrame#DiagnosisVideoUploadProgress QLabel { color: #3347B8; background: transparent;"
" font-size: 13px; font-weight: 500; }"
"QFrame#DiagnosisVideoUploadProgress QProgressBar { background-color: #FFFFFF;"
" border: 0; border-radius: 4px; min-height: 8px; max-height: 8px; }"
"QFrame#DiagnosisVideoUploadProgress QProgressBar::chunk { background-color: #4F63D9;"
" border-radius: 4px; }"
)
row = QVBoxLayout(frame)
row.setContentsMargins(12, 8, 12, 10)
row.setSpacing(6)
self.video_upload_status = QLabel()
self.video_upload_status.setWordWrap(True)
row.addWidget(self.video_upload_status)
self.video_upload_bar = QProgressBar()
self.video_upload_bar.setRange(0, 1000)
self.video_upload_bar.setTextVisible(False)
row.addWidget(self.video_upload_bar)
frame.hide()
self.video_upload_frame = frame
return frame
def _build_orders_tab(self) -> QWidget:
page = QWidget()
page.setObjectName("DiagnosisTabOrders")
@@ -3279,8 +3328,6 @@ class DiagnosisDialog(QDialog):
),
"tongue": first_value(diagnosis, "tongue", "tongue_coating"),
"tongue_image": first_value(diagnosis, "tongue_image"),
"pulse": first_value(diagnosis, "pulse"),
"pulse_condition": first_value(diagnosis, "pulse_condition"),
"clinical_diagnosis": build_prescription_clinical_diagnosis(diagnosis, case_record),
"doctor_name": first_value(
appointment, "doctor_name", default=first_value(diagnosis, "doctor_name")
@@ -3326,6 +3373,15 @@ class DiagnosisDialog(QDialog):
)
if not path:
return
# 明确按视频上报类型;默认的 audio/webm 会让 .webm 视频被服务端当成本机录音。
mime_type = mimetypes.guess_type(path)[0] or ""
if not mime_type.startswith("video/"):
mime_type = "video/mp4"
file_name = Path(path).name
relay = _UploadProgressRelay(self)
relay.progressed.connect(lambda sent, total: self._video_upload_progressed(file_name, sent, total))
self._video_upload_relay = relay
self._video_upload_progressed(file_name, 0, 0)
self._run_media_mutation(
lambda: invoke(
self.repository,
@@ -3333,13 +3389,47 @@ class DiagnosisDialog(QDialog):
path=path,
diagnosis_id=self._diagnosis_id,
call_record_id=call_record_id,
mime_type=mime_type,
on_progress=relay.progressed.emit,
),
"视频回放已追加到指定通话记录。"
if call_record_id is not None
else "视频回放已上传并创建通话记录。",
"video",
on_finished=lambda: self._video_upload_finished(relay),
)
def _video_upload_progressed(self, file_name: str, sent: int, total: int) -> None:
self.video_upload_frame.show()
self.video_upload_button.setEnabled(False)
if total <= 0:
self.video_upload_bar.setRange(0, 0) # 未拿到大小前显示滚动条
self.video_upload_status.setText(f"正在准备上传「{file_name}」…")
self.video_upload_button.setText("上传中…")
return
self.video_upload_bar.setRange(0, 1000)
ratio = min(1.0, max(0.0, sent / total))
self.video_upload_bar.setValue(int(ratio * 1000))
percent = int(ratio * 100)
mb = 1024 * 1024
if sent >= total:
text = f"「{file_name}」已上传完成({total / mb:.1f} MB),正在生成通话记录…"
else:
text = f"正在上传「{file_name}」 {percent}%({sent / mb:.1f} / {total / mb:.1f} MB),请勿关闭窗口"
self.video_upload_status.setText(text)
self.video_upload_button.setText(f"上传中 {percent}%")
self._show_message(text, "info")
def _video_upload_finished(self, relay: QObject) -> None:
if getattr(self, "_video_upload_relay", None) is not relay:
return
self._video_upload_relay = None
self.video_upload_frame.hide()
self.video_upload_bar.setRange(0, 1000)
self.video_upload_bar.setValue(0)
self.video_upload_button.setText("上传本地回放")
self.video_upload_button.setEnabled(True)
def _open_local_audio_queue(self) -> None:
if self._diagnosis_id <= 0 or not self._can_video_upload:
self._show_message("当前账号无本机录音上传权限或接口不可用。", "warning")
@@ -3439,7 +3529,14 @@ class DiagnosisDialog(QDialog):
"chat",
)
def _run_media_mutation(self, operation: Any, success_text: str, reload_key: str) -> None:
def _run_media_mutation(
self,
operation: Any,
success_text: str,
reload_key: str,
*,
on_finished: Any = None,
) -> None:
self._media_generation += 1
generation = self._media_generation
diagnosis_id = self._diagnosis_id
@@ -3450,6 +3547,7 @@ class DiagnosisDialog(QDialog):
success_text, reload_key, diagnosis_id, generation
),
on_error=lambda error: self._mutation_error(error, diagnosis_id, generation, "media"),
on_finished=on_finished,
)
def _media_mutation_success(
@@ -28,6 +28,7 @@ from PySide6.QtCore import (
QDate,
QEvent,
QIODevice,
QModelIndex,
QMarginsF,
QObject,
QPoint,
@@ -51,6 +52,8 @@ from PySide6.QtGui import (
QPainter,
QPdfWriter,
QPen,
QStandardItem,
QStandardItemModel,
QTextDocument,
)
from PySide6.QtPrintSupport import QPrintDialog, QPrinter
@@ -61,6 +64,7 @@ from PySide6.QtWidgets import (
QCalendarWidget,
QCheckBox,
QComboBox,
QCompleter,
QDialog,
QDialogButtonBox,
QDoubleSpinBox,
@@ -81,6 +85,9 @@ from PySide6.QtWidgets import (
QSizePolicy,
QSpinBox,
QSplitter,
QStyle,
QStyledItemDelegate,
QStyleOptionViewItem,
QTableWidget,
QTableWidgetItem,
QTabWidget,
@@ -323,7 +330,8 @@ QFrame#PrescriptionDrawerSurface QDoubleSpinBox {
border: 1px solid #EDEDEE;
border-radius: 7px;
padding: 0 11px;
selection-background-color: #EEF1FA; font-size: 14px;
selection-background-color: #C9D1F3;
selection-color: #1A1C1F; font-size: 14px;
}
QFrame#PrescriptionDrawerSurface QComboBox {
min-height: 32px;
@@ -333,7 +341,17 @@ QFrame#PrescriptionDrawerSurface QComboBox {
border-radius: 7px;
padding-left: 11px;
padding-right: 28px;
selection-background-color: #EEF1FA; font-size: 14px;
selection-background-color: #C9D1F3;
selection-color: #1A1C1F; font-size: 14px;
}
QFrame#PrescriptionHerbTableRow QComboBox,
QFrame#PrescriptionHerbTableRow QDoubleSpinBox {
border: 1px solid #D2D2D3;
font-weight: 500;
}
QFrame#PrescriptionHerbTableRow QComboBox:focus,
QFrame#PrescriptionHerbTableRow QDoubleSpinBox:focus {
border: 1px solid #4F63D9;
}
QFrame#PrescriptionDrawerSurface QLineEdit[prescriptionControl="true"],
QFrame#PrescriptionDrawerSurface QComboBox[prescriptionControl="true"],
@@ -901,6 +919,23 @@ def _float(value: Any, default: float = 0.0) -> float:
return default
# 处方表单里的数字框、下拉框不响应鼠标滚轮:滚轮只滚动页面,
# 避免医生滚动表单时把鼠标停在输入框上而误改剂量、药材或剂数。
class NoWheelSpinBox(QSpinBox):
def wheelEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
event.ignore()
class NoWheelDoubleSpinBox(QDoubleSpinBox):
def wheelEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
event.ignore()
class NoWheelComboBox(QComboBox):
def wheelEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
event.ignore()
def _bool(value: Any) -> bool:
if isinstance(value, str):
return value.strip().lower() not in {"", "0", "false", "no", "off"}
@@ -1412,6 +1447,47 @@ class MultiSelectComboBox(QComboBox):
self.lineEdit().setText("、".join(self.values()))
_MEDICINE_NAME_ROLE = Qt.ItemDataRole.UserRole + 1
_MEDICINE_ID_ROLE = Qt.ItemDataRole.UserRole + 2
_MEDICINE_META_ROLE = Qt.ItemDataRole.UserRole + 3
class _MedicineSuggestionDelegate(QStyledItemDelegate):
"""药材候选行:左侧药名,右侧灰色「调配中心 · 单位 · ID」,与管理端下拉一致。"""
def sizeHint(self, option: QStyleOptionViewItem, index: QModelIndex) -> QSize: # noqa: N802
return QSize(super().sizeHint(option, index).width(), 36)
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None:
opt = QStyleOptionViewItem(option)
self.initStyleOption(opt, index)
opt.text = ""
widget = opt.widget
(widget.style() if widget is not None else QApplication.style()).drawControl(
QStyle.ControlElement.CE_ItemViewItem, opt, painter, widget
)
rect = option.rect.adjusted(14, 0, -14, 0)
name = str(index.data(Qt.ItemDataRole.DisplayRole) or "")
meta = str(index.data(_MEDICINE_META_ROLE) or "")
enabled = bool(index.flags() & Qt.ItemFlag.ItemIsEnabled)
metrics = option.fontMetrics
align = Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft
painter.save()
if meta:
name_width = int(rect.width() * 0.42)
painter.setPen(QColor("#1A1C1F"))
painter.drawText(rect.adjusted(0, 0, name_width - rect.width(), 0), align,
metrics.elidedText(name, Qt.TextElideMode.ElideRight, name_width - 12))
painter.setPen(QColor("#8A8B8D"))
meta_rect = rect.adjusted(name_width, 0, 0, 0)
painter.drawText(meta_rect, align,
metrics.elidedText(meta, Qt.TextElideMode.ElideRight, meta_rect.width()))
else:
painter.setPen(QColor("#1A1C1F" if enabled else "#8A8B8D"))
painter.drawText(rect, align, metrics.elidedText(name, Qt.TextElideMode.ElideRight, rect.width()))
painter.restore()
class RemoteMedicineComboBox(QComboBox):
"""Editable remote medicine selector retaining both id and canonical name."""
@@ -1433,6 +1509,10 @@ class RemoteMedicineComboBox(QComboBox):
# but no medicine id. New/changed text must still be selected from the
# remote master-data list rather than submitted as arbitrary input.
self._legacy_name = str(name or "").strip() if self._selected_id is None else ""
# 最近一次有效选择(药材库 id + 规范名);手输文字无法匹配药材库时恢复为它。
self._selected_name = str(name or "").strip() if self._selected_id is not None else ""
self._last_valid: tuple[int | None, str] = (self._selected_id, str(name or "").strip())
self._settle_pending = False
self.setEditable(True)
self.setInsertPolicy(QComboBox.InsertPolicy.NoInsert)
self.setMaxVisibleItems(14)
@@ -1440,6 +1520,23 @@ class RemoteMedicineComboBox(QComboBox):
self.lineEdit().setPlaceholderText("搜索药材名称或拼音首字母")
self.lineEdit().textEdited.connect(self._queue_search)
self.currentIndexChanged.connect(self._selection_changed)
# 与管理端 MedicineNameSelect 一致:点击或输入即弹出药材库匹配列表,
# 只能从列表中选;列表不抢输入焦点,可边输入边看结果。
self._suggestions = QStandardItemModel(self)
self._completer = QCompleter(self._suggestions, self)
self._completer.setCompletionMode(QCompleter.CompletionMode.UnfilteredPopupCompletion)
self._completer.setCompletionRole(_MEDICINE_NAME_ROLE)
self._completer.setMaxVisibleItems(14)
self._completer.activated[QModelIndex].connect(self._suggestion_activated)
popup = self._completer.popup()
popup.setItemDelegate(_MedicineSuggestionDelegate(popup))
popup.setStyleSheet(
"QListView { background-color: #FFFFFF; border: 1px solid #E4E7ED; border-radius: 6px;"
" padding: 4px 0; font-size: 14px; outline: 0; }"
"QListView::item:selected, QListView::item:hover { background-color: #F5F7FA; }"
)
self.lineEdit().setCompleter(self._completer)
self.lineEdit().installEventFilter(self)
self._timer = QTimer(self)
self._timer.setSingleShot(True)
self._timer.setInterval(250)
@@ -1451,9 +1548,9 @@ class RemoteMedicineComboBox(QComboBox):
@property
def medicine_id(self) -> int | None:
data = self.currentData()
value = _int(data, 0)
return value or self._selected_id
# 只认从药材库选中的 id;不能回退到旧下拉项的 data,否则改过文字的行
# 仍会带着原药材 id 通过校验,相当于允许直接输入药名。
return self._selected_id
@property
def medicine_name(self) -> str:
@@ -1462,12 +1559,16 @@ class RemoteMedicineComboBox(QComboBox):
@property
def has_valid_selection(self) -> bool:
name = self.medicine_name
return bool(self.medicine_id) or bool(self._legacy_name and name == self._legacy_name)
if self._selected_id is not None:
return not self._selected_name or name == self._selected_name
return bool(self._legacy_name and name == self._legacy_name)
def set_value(self, medicine_id: Any, name: Any) -> None:
self._selected_id = _int(medicine_id, 0) or None
canonical_name = str(name or "").strip()
self._legacy_name = canonical_name if self._selected_id is None else ""
self._selected_name = canonical_name if self._selected_id is not None else ""
self._last_valid = (self._selected_id, canonical_name)
self.blockSignals(True)
self.clear()
if canonical_name:
@@ -1478,20 +1579,117 @@ class RemoteMedicineComboBox(QComboBox):
def showPopup(self) -> None:
if self.count() <= 1:
self._queue_search(self.currentText())
# 只是打开列表浏览,不清除已选药材。
self._timer.stop()
self._search()
self._search(browse=self.has_valid_selection or not self.medicine_name)
super().showPopup()
def _queue_search(self, _text: str) -> None:
self._selected_id = None
self._selected_name = ""
self._legacy_name = ""
self._timer.start()
def _search(self) -> None:
query = self.currentText().strip()
def wheelEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
# 滚轮不切换药材,只滚动页面。
event.ignore()
def eventFilter(self, watched: Any, event: Any) -> bool: # noqa: N802 - Qt virtual
# 鼠标点一下输入框就列出药材库,和管理端下拉一样可以直接挑;
# 不看焦点原因,已获得焦点时再点一次也能打开。
if (
watched is self.lineEdit()
and event.type() == QEvent.Type.MouseButtonPress
and self.isEnabled()
and not self._completer.popup().isVisible()
):
self._timer.stop()
self._search(browse=self.has_valid_selection or not self.medicine_name)
return super().eventFilter(watched, event)
def focusOutEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
super().focusOutEvent(event)
# 打开下拉列表也会让输入框失焦,此时还在挑选,不做校正。
if (
event.reason() == Qt.FocusReason.PopupFocusReason
or self.view().isVisible()
or self._completer.popup().isVisible()
):
return
self._settle_typed_text()
def _suggestion_activated(self, index: QModelIndex) -> None:
medicine_id = _int(index.data(_MEDICINE_ID_ROLE), 0)
name = str(index.data(_MEDICINE_NAME_ROLE) or "").strip()
if not medicine_id or not name:
return
for row in range(self.count()):
data = self.itemData(row)
if isinstance(data, Mapping) and _int(data.get("id"), 0) == medicine_id:
self.setCurrentIndex(row)
self._selection_changed(row)
return
self.set_value(medicine_id, name)
def _show_suggestions(self, rows: list[tuple[int, str, str]], note: str = "") -> None:
self._suggestions.clear()
for medicine_id, name, meta in rows:
item = QStandardItem(name)
item.setData(name, _MEDICINE_NAME_ROLE)
item.setData(medicine_id, _MEDICINE_ID_ROLE)
item.setData(meta, _MEDICINE_META_ROLE)
item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable)
self._suggestions.appendRow(item)
if note:
# 提示行不可选,只告诉医生当前状态(搜索中 / 无匹配)。
item = QStandardItem(note)
item.setData(self.medicine_name, _MEDICINE_NAME_ROLE)
item.setFlags(Qt.ItemFlag.NoItemFlags)
self._suggestions.appendRow(item)
if self.lineEdit().hasFocus() and self.isEnabled():
self._completer.complete()
def _settle_typed_text(self) -> None:
"""离开输入框时,手输文字必须落到药材库中的一味药,否则恢复原值。"""
if self.has_valid_selection:
return
text = self.medicine_name
if text and self._select_exact(text):
return
if not text:
self._restore_last_valid()
return
# 搜索结果可能还没回来:立即按当前文字查一次,结果到达后再定。
self._settle_pending = True
self._timer.stop()
self._search()
def _select_exact(self, text: str) -> bool:
key = "".join(text.split()).casefold()
for row in range(self.count()):
data = self.itemData(row)
if isinstance(data, Mapping) and "".join(str(data.get("name") or "").split()).casefold() == key:
self.setCurrentIndex(row)
self._selection_changed(row)
return True
return False
def _restore_last_valid(self) -> None:
medicine_id, name = self._last_valid
if medicine_id is not None or name:
self.set_value(medicine_id, name)
return
self.blockSignals(True)
self.setEditText("")
self.blockSignals(False)
def _search(self, browse: bool = False) -> None:
# browse:点开下拉时按空关键字列出药材库,与管理端打开下拉的行为一致。
query = "" if browse else self.currentText().strip()
self._generation += 1
generation = self._generation
if self.lineEdit().hasFocus() and self._suggestions.rowCount() == 0:
self._show_suggestions([], "正在搜索药材库…")
run_async(
lambda: _repository_action(
self.repository,
@@ -1510,6 +1708,7 @@ class RemoteMedicineComboBox(QComboBox):
return
rows = page_items(result)
current_text = self.currentText().strip()
suggestions: list[tuple[int, str, str]] = []
self.blockSignals(True)
self.clear()
for row in rows:
@@ -1524,11 +1723,23 @@ class RemoteMedicineComboBox(QComboBox):
if meta:
label = f"{name} {meta}"
self.addItem(label, {"id": medicine_id, "name": name})
suggestions.append((medicine_id, name, meta))
self.setEditText(current_text or query)
self.blockSignals(False)
self._show_suggestions(
suggestions,
"" if suggestions else f"药材库中没有与「{query}」匹配的药材,请换个名称或拼音首字母",
)
if self._settle_pending and not self.hasFocus():
self._settle_pending = False
if not self._select_exact(query):
self._restore_last_valid()
def _search_error(self, error: Exception, generation: int) -> None:
if generation == self._generation:
if self._settle_pending and not self.hasFocus():
self._settle_pending = False
self._restore_last_valid()
self.search_failed.emit(friendly_error(error))
def _selection_changed(self, index: int) -> None:
@@ -1538,9 +1749,9 @@ class RemoteMedicineComboBox(QComboBox):
name = str(data.get("name") or "").strip()
if name:
self._legacy_name = ""
self._selected_name = name
self._last_valid = (self._selected_id, name)
self.setEditText(name)
else:
self._selected_id = _int(data, 0) or self._selected_id
class HerbRowWidget(QFrame):
@@ -1575,7 +1786,7 @@ class HerbRowWidget(QFrame):
if source_locked is None
else bool(source_locked)
)
self.formula_combo = QComboBox(self)
self.formula_combo = NoWheelComboBox(self)
self.formula_combo.addItem("主方", "主方")
self.formula_combo.addItem("辅方", "辅方")
_set_combo_data(
@@ -1591,7 +1802,7 @@ class HerbRowWidget(QFrame):
parent=self,
)
self.medicine.setEnabled(not locked)
self.dosage = QDoubleSpinBox(self)
self.dosage = NoWheelDoubleSpinBox(self)
self.dosage.setRange(0, 1e100)
self.dosage.setDecimals(1)
self.dosage.setSingleStep(0.5)
@@ -2173,7 +2384,7 @@ class PrescriptionTemplateDialog(QDialog):
self.name_edit.setMaxLength(100)
self.name_edit.setPlaceholderText("请输入处方名称")
form.addRow("处方名称", self.name_edit)
self.formula_combo = QComboBox()
self.formula_combo = NoWheelComboBox()
self.formula_combo.addItem("主方", "主方")
self.formula_combo.addItem("辅方", "辅方")
_set_combo_data(
@@ -2293,7 +2504,7 @@ class TemplateImportDialog(QDialog):
self.name_edit.setPlaceholderText("请输入处方名称搜索")
self.name_edit.returnPressed.connect(self.search)
filters.addWidget(self.name_edit, 1)
self.formula_combo = QComboBox()
self.formula_combo = NoWheelComboBox()
self.formula_combo.addItem("全部", "")
self.formula_combo.addItem("主方", "主方")
self.formula_combo.addItem("辅方", "辅方")
@@ -2304,7 +2515,7 @@ class TemplateImportDialog(QDialog):
root.addLayout(filters)
mode_layout = QHBoxLayout()
mode_layout.addWidget(QLabel("导入方式"))
self.mode_combo = QComboBox()
self.mode_combo = NoWheelComboBox()
self.mode_combo.addItem("覆盖现有药材", "replace")
self.mode_combo.addItem("追加到末尾", "append")
mode_layout.addWidget(self.mode_combo)
@@ -2511,7 +2722,7 @@ class PasteHerbsDialog(QDialog):
root.addWidget(self.text_edit, 1)
mode_row = QHBoxLayout()
mode_row.addWidget(QLabel("导入方式"))
self.mode_combo = QComboBox()
self.mode_combo = NoWheelComboBox()
self.mode_combo.addItem("覆盖现有药材", "replace")
self.mode_combo.addItem("追加到末尾", "append")
mode_row.addWidget(self.mode_combo)
@@ -2735,8 +2946,8 @@ class PrescriptionEditorDialog(QDialog):
self.revive_banner = MessageBanner()
self.body_layout.addWidget(self.revive_banner)
self._responsive_grids: list[tuple[QGridLayout, int, list[tuple[QWidget, int]]]] = []
self._form_columns = 3
self._responsive_grids: list[tuple[QGridLayout, int, list[tuple[QWidget, int]]]] = []
self._form_columns = 3
self.patient_section = self._build_patient_section()
self.diagnosis_section = self._build_diagnosis_section()
self.herbs_section = self._build_herbs_section()
@@ -2978,7 +3189,7 @@ class PrescriptionEditorDialog(QDialog):
gender_layout.addWidget(self.gender_female)
gender_layout.addStretch(1)
self.gender = gender_host
self.age = QSpinBox()
self.age = NoWheelSpinBox()
self.age.setRange(0, 150)
self.visit_no = QLineEdit()
self.visit_no.setPlaceholderText("自动生成或手动输入")
@@ -3130,7 +3341,7 @@ class PrescriptionEditorDialog(QDialog):
for value in self.PRESCRIPTION_TYPES:
self.prescription_type.addItem(value, value)
self.prescription_type.currentIndexChanged.connect(self._type_changed)
self.dose_count = QSpinBox()
self.dose_count = NoWheelSpinBox()
self.dose_count.setRange(1, 2_147_483_647)
self.dose_unit = SelectComboBox()
self.dose_unit.addItems(["剂", "丸", "袋", "盒", "瓶", "膏", "贴"])
@@ -3153,9 +3364,9 @@ class PrescriptionEditorDialog(QDialog):
self.dosage_bag_count = LabeledIntCombo(range(1, 6), "袋")
self.need_decoction = BoolRadioRow("代煎", "不代煎")
self.bags_per_dose = LabeledIntCombo(range(1, 10), "包")
self.times_per_day = QSpinBox()
self.times_per_day = NoWheelSpinBox()
self.times_per_day.setRange(1, 6)
self.usage_days = QSpinBox()
self.usage_days = NoWheelSpinBox()
self.usage_days.setRange(1, 365)
self._main_dosage_field = self._field("用量", self.dosage_amount)
self._main_dosage_unit_field = self._field("用量单位", self.dosage_unit)
@@ -3188,9 +3399,9 @@ class PrescriptionEditorDialog(QDialog):
self.aux_dosage_bag_count = LabeledIntCombo(range(1, 6), "袋")
self.aux_need_decoction = BoolRadioRow("代煎", "不代煎")
self.aux_bags_per_dose = LabeledIntCombo(range(1, 10), "包")
self.aux_times_per_day = QSpinBox()
self.aux_times_per_day = NoWheelSpinBox()
self.aux_times_per_day.setRange(1, 6)
self.aux_usage_days = QSpinBox()
self.aux_usage_days = NoWheelSpinBox()
self.aux_usage_days.setRange(1, 365)
self.aux_prescription_name = QLineEdit()
self._aux_dosage_field = self._field("用量", self.aux_dosage_amount)
@@ -3964,7 +4175,7 @@ class PatchPatientDialog(QDialog):
self.patient_name = QLineEdit(str(first_value(prescription, "patient_name", default="")))
self.patient_name.setMaxLength(50)
form.addRow("患者姓名 *", self.patient_name)
self.gender = QComboBox()
self.gender = NoWheelComboBox()
self.gender.addItem("男", 1)
self.gender.addItem("女", 0)
_set_combo_data(self.gender, first_value(prescription, "gender", default=1))
@@ -5311,7 +5522,7 @@ class PrescriptionOrderDialog(QDialog):
def _build_recipient_tab(self) -> QWidget:
tab, form = self._form_tab()
self.diagnosis_id = QSpinBox()
self.diagnosis_id = NoWheelSpinBox()
self.diagnosis_id.setRange(0, 2_000_000_000)
self.diagnosis_id.valueChanged.connect(self._diagnosis_changed)
form.addRow("诊单 ID *", self.diagnosis_id)
@@ -5333,14 +5544,14 @@ class PrescriptionOrderDialog(QDialog):
def _build_service_tab(self) -> QWidget:
tab, form = self._form_tab()
self.ship_mode = QComboBox()
self.ship_mode = NoWheelComboBox()
self.ship_mode.addItem("甘草药房", "gancao")
self.ship_mode.addItem("洛阳药房", "direct")
self.ship_mode.setEnabled(self.can_select_ship_mode)
form.addRow("发货类型", self.ship_mode)
self.is_follow_up = QCheckBox("复诊订单")
form.addRow("是否复诊", self.is_follow_up)
self.medication_days = QSpinBox()
self.medication_days = NoWheelSpinBox()
self.medication_days.setRange(0, 365)
self.medication_days.setSpecialValueText("未填写")
form.addRow("服用天数", self.medication_days)
@@ -5365,7 +5576,7 @@ class PrescriptionOrderDialog(QDialog):
def _build_amount_tab(self) -> QWidget:
tab, form = self._form_tab()
self.fee_type = QComboBox()
self.fee_type = NoWheelComboBox()
self.fee_type.addItem("药品费用", 3)
self.fee_type.addItem("挂号费", 1)
self.fee_type.addItem("问诊费", 2)
@@ -5373,12 +5584,12 @@ class PrescriptionOrderDialog(QDialog):
self.fee_type.addItem("尾款", 5)
self.fee_type.addItem("其他", 6)
form.addRow("费用类别 *", self.fee_type)
self.amount = QDoubleSpinBox()
self.amount = NoWheelDoubleSpinBox()
self.amount.setRange(0, 10_000_000)
self.amount.setDecimals(2)
self.amount.setPrefix("¥ ")
form.addRow("订单金额 *", self.amount)
self.internal_cost = QDoubleSpinBox(tab)
self.internal_cost = NoWheelDoubleSpinBox(tab)
self.internal_cost.setRange(0, 10_000_000)
self.internal_cost.setDecimals(2)
self.internal_cost.setPrefix("¥ ")
@@ -119,10 +119,28 @@ def preferred_ai_model(content: str = "", *, entry: str = "diagnosis") -> str:
return "qwen" if entry in {"prescription", "diagnosis"} else "openai"
DIAGNOSIS_TASK_TITLES = {
"case_analysis": "病历分析",
"glucose_trend": "血糖趋势",
"medication_review": "用药评估",
"complication_risk": "并发症风险",
"summary": "问诊小结",
"lifestyle_advice": "健康建议",
}
def diagnosis_ai_task(prompt: str) -> str:
"""Map a user-facing question to the server assistant's stable task key."""
text = prompt.strip().lower()
if any(marker in text for marker in ("分析病历", "分析当前病历", "当前病历给出辨证与病情摘要")):
return "case_analysis"
if any(marker in text for marker in ("血糖控制", "血糖趋势", "血糖记录", "glucose")):
return "glucose_trend"
if any(marker in text for marker in ("问诊小结", "问诊摘要")):
return "summary"
if any(marker in text for marker in ("健康建议", "生活方式建议", "lifestyle")):
return "lifestyle_advice"
if any(marker in text for marker in ("并发症", "complication")):
return "complication_risk"
if any(marker in text for marker in ("指南", "共识", "guideline")):
@@ -133,10 +151,19 @@ def diagnosis_ai_task(prompt: str) -> str:
return "prescription_review"
if any(marker in text for marker in ("用药", "药物", "中药", "medication")):
return "medication_review"
if any(marker in text for marker in ("辨证", "证候", "舌象", "脉象", "tcm")):
has_tcm_intent = any(marker in text for marker in ("中医", "辨证", "证候", "舌象", "脉象", "tcm"))
wants_full_report = (
any(marker in text for marker in ("完整", "full", "complete"))
and any(marker in text for marker in ("报告", "report"))
)
if has_tcm_intent and ("tcm_pattern" in text or wants_full_report):
return "tcm_pattern"
# A summary may mention evidence such as 证候 without requesting a full
# TCM report. Specific clinical tasks above still take precedence.
if any(marker in text for marker in ("总结", "概括", "摘要", "summary")):
return "summary"
if has_tcm_intent:
return "tcm_pattern"
if any(marker in text for marker in ("风险", "预后", "急症", "risk")):
return "complication_risk"
return "custom"
@@ -0,0 +1,446 @@
"""Approved SSE bursts paint progressively without extending request lifetime.
Real offscreen Qt, finite workers and MockTransport only; all data is synthetic.
"""
from __future__ import annotations
import json
import os
from time import monotonic, perf_counter
from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import httpx
import pytest
from PySide6.QtCore import QEvent, QObject, Qt, QThreadPool, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel
from shiboken6 import isValid
from doctor_workstation.core import PermissionSet
from doctor_workstation.services import ApiClient, RemoteDoctorRepository
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseReportCard
SOURCE_KEYS = (
"basic_info", "vital_signs", "chief_complaint", "present_illness", "past_history",
"other_history", "diagnosis_info", "doctor_image_notes", "doctor_file_notes",
"daily_tracking", "prescriptions", "video_consultation_text", "chat",
)
TOOLS = (
("分析病历", "case_analysis", "病历分析", "口渴记录提示需结合现有血糖资料分析,缺少病程不能确立证型。"),
("血糖趋势", "glucose_trend", "血糖趋势", "一条血糖只能说明当次情况,不能据此认定连续升降趋势。"),
("用药评估", "medication_review", "用药评估", "二甲双胍的既有记录可用于核对治疗,剂量未记不能据此加量。"),
("并发症风险", "complication_risk", "并发症风险", "糖尿病史提示筛查价值;未记录筛查不能直接认定已患或排除并发症。"),
("生成问诊小结", "summary", "问诊小结", "本次口渴,既往有糖尿病及二甲双胍记录,病程与剂量仍需确认。"),
("健康建议", "lifestyle_advice", "健康建议", "可规律分配饮食并记录血糖,活动量需结合现有体能逐步安排。"),
)
def receipt():
return {"transfer_manifest_final": True, "attachment_count": 0, "items": [],
"required_sections": [{"key": key, "availability": "absent", "status": "submitted"}
for key in SOURCE_KEYS]}
def report():
original = [{"record_date": "2026-01-01", "role": "患者", "content": f"第 {i} 类合成来源原文 🩺"}
for i in range(13)]
text = "## 合成判断\n\n" + "已有信息可支持有限分析;缺少日期不能认定控制正常。" * 320
text += "\n\n## 原始记录\n\n```json\n" + json.dumps(original, ensure_ascii=False)
return text + "\n```\n\n**唯一完整结尾** 🩺"
def wait_until(predicate, seconds=5):
deadline = monotonic() + seconds
while not predicate() and monotonic() < deadline:
QTest.qWait(5)
assert predicate(), "finite presentation/transport wait expired"
def event(dialog, kind, **values):
dialog._stream_event(dialog._generation, dialog._stream_generation, {"event": kind, **values})
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def dialogs(application, monkeypatch):
resources = []
def create(handler=None):
if handler is None:
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(
globalInstance=lambda: SimpleNamespace(start=lambda _: None),
))
repository, client = object(), None
else:
client = ApiClient("https://example.test", transport=httpx.MockTransport(handler))
repository = RemoteDoctorRepository(client)
dialog = module.AiConsultDialog(repository, PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
dialog.open_for(diagnosis_id=501, patient_id=1501)
dialog.show()
application.processEvents()
resources.append((dialog, client))
return dialog
yield create
for dialog, client in resources:
dialog.close()
for timer in dialog.findChildren(QTimer):
timer.stop()
if client is not None:
client.close()
dialog.deleteLater()
assert QThreadPool.globalInstance().waitForDone(3000)
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def test_validated_burst_done_and_transport_finished_leave_many_real_intermediate_frames(dialogs):
answer = report()
calls = []
def handler(request):
assert request.url.host == "example.test"
calls.append(request)
body = "".join(f"event: {kind}\ndata: {json.dumps(value, ensure_ascii=False)}\n\n"
for kind, value in [
("start", {"model_label": "原配置千问", "model_key": "qwen"}),
("progress", {"phase": "attachments", "status": "submitted", **receipt()}),
("delta", {"text": answer}), ("done", receipt()),
])
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
dialog = dialogs(handler)
dialog._ask("生成合成病历分析", task="case_analysis")
bubble = dialog._stream_bubble
class PaintProbe(QObject):
def __init__(self):
super().__init__(bubble.body)
self.sizes = []
def eventFilter(self, watched, paint_event): # noqa: N802 - Qt API
if paint_event.type() == QEvent.Type.Paint:
size = len(bubble.body.toPlainText())
if not self.sizes or self.sizes[-1] != size:
self.sizes.append(size)
return False
paint_probe = PaintProbe()
bubble.body.viewport().installEventFilter(paint_probe)
wait_until(lambda: not dialog._asking and dialog._stream_worker is None)
assert dialog.send_button.isEnabled() and dialog._stream_completed
assert bubble._presentation_timer.isActive()
assert 0 < len(bubble.body.toPlainText()) < len(answer) // 3
assert bubble._raw_payload == answer == dialog._stream_text
assert bubble._clinical_panel is None
assert "本次回复已完成" in bubble.transfer_status.text()
frames, gaps = [], []
previous = perf_counter()
def sample():
nonlocal previous
now = perf_counter()
gaps.append((now - previous) * 1000)
previous = now
size = len(bubble.body.toPlainText())
if not frames or size != frames[-1]:
frames.append(size)
heartbeat = QTimer()
heartbeat.setInterval(5)
heartbeat.timeout.connect(sample)
heartbeat.start()
try:
wait_until(lambda: not bubble._presentation_timer.isActive() and not bubble._report_render_pending)
finally:
heartbeat.stop()
assert len(frames) >= 15
assert len(paint_probe.sizes) >= 10
assert max(gaps) < 200 # Host-local event-loop guard, not a native-display/model SLA.
assert len(calls) == 1
assert json.loads(calls[0].content)["task"] == "case_analysis"
assert "model" not in json.loads(calls[0].content)
assert bubble._raw_payload == answer
oracle = module._RichMessage("ai")
oracle.document().setDefaultFont(bubble.body.document().defaultFont())
oracle.set_payload(answer)
module._highlight_document_metrics(oracle.document())
assert bubble.body.toPlainText() == oracle.toPlainText()
actual_html, expected_html = bubble.body.toHtml(), oracle.toHtml()
mismatch = next((i for i, (a, b) in enumerate(zip(actual_html, expected_html, strict=False)) if a != b), 0)
assert actual_html == expected_html, (mismatch, actual_html[mismatch:mismatch + 120], expected_html[mismatch:mismatch + 120])
oracle.deleteLater()
assert [row["key"] for row in bubble._provenance["required_sections"]] == list(SOURCE_KEYS)
assert "原配置千问" in bubble.stamp.text()
# Fenced original-source JSON keeps the existing full Markdown renderer.
assert bubble._clinical_panel is None
rendered = bubble.body.toPlainText()
for i in range(13):
assert f"第 {i} 类合成来源原文" in rendered
@pytest.mark.parametrize("tool", TOOLS, ids=[tool[1] for tool in TOOLS])
@pytest.mark.parametrize("legacy", [False, True])
def test_six_actual_tool_answers_keep_source_fields_after_presentation(dialogs, tool, legacy):
label, task, title, analysis = tool
sources = "\n".join(
f"- 合成来源 {i} 原文:" + json.dumps({"record_date": "2026-01-01", "note": f"原文唯一 {i}"}, ensure_ascii=False)
for i in range(13)
)
answer = f"## {title}判断\n- {analysis}\n- {task}_ACTUAL_MODEL_ANSWER\n\n## 全部原文\n{sources}"
requests = []
def handler(request):
assert request.url.host == "example.test"
requests.append(request)
if request.url.path.endswith("/aiAssistantStream"):
if legacy:
return httpx.Response(404, json={"msg": "合成旧服务"})
body = "".join(f"event: {kind}\ndata: {json.dumps(value, ensure_ascii=False)}\n\n"
for kind, value in [("delta", {"text": answer}), ("done", receipt())])
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
assert legacy and request.url.path.endswith("/aiAssistant")
return httpx.Response(200, json={"code": 1, "data": {"answer": answer, **receipt()}})
dialog = dialogs(handler)
card = next(card for card in dialog.findChildren(module._ClickCard, "AiConsultToolCard")
if any(child.text() == label for child in card.findChildren(QLabel)))
target = next(child for child in card.findChildren(QLabel) if child.text() == label)
QTest.mouseClick(target, Qt.MouseButton.LeftButton)
bubble = dialog._stream_bubble
wait_until(lambda: dialog._stream_worker is None and not dialog._asking)
assert bubble._raw_payload == answer and dialog.send_button.isEnabled()
wait_until(lambda: not bubble._presentation_timer.isActive() and not bubble._report_render_pending)
assert bubble._raw_payload == answer
assert len(requests) == (2 if legacy else 1)
for request in requests:
body = json.loads(request.content)
assert body["task"] == task and "model_key" not in body and "model" not in body
assert isinstance(bubble._clinical_panel, module._StructuredReportPanel)
panel = bubble._clinical_panel
assert panel.findChild(QLabel, "AiConsultClinicalTitle").text() == f"AI · {title}"
text = "\n".join(view.toPlainText() for view in panel.findChildren(module.QTextBrowser))
assert analysis in text and f"{task}_ACTUAL_MODEL_ANSWER" in text
assert "记录日期:2026-01-01" in text and "&quot;" not in text
for i in range(13):
assert f"原文唯一 {i}" in text
assert [row["key"] for row in bubble._provenance["required_sections"]] == list(SOURCE_KEYS)
@pytest.mark.parametrize("length", [1, 8, 24, 72, 513])
@pytest.mark.parametrize("answer_only", [False, True])
def test_tiny_and_done_answer_races_finish_once_with_exact_text(dialogs, length, answer_only):
dialog = dialogs()
dialog._ask("合成问诊", task="summary")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
answer = ("合成文字🩺\n" * 100)[:length]
finished = []
bubble.stream_presentation_finished.connect(lambda: finished.append(True))
if not answer_only:
event(dialog, "delta", text=answer)
event(dialog, "done", answer=answer, **receipt())
assert not dialog._asking and dialog.send_button.isEnabled()
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
assert dialog._stream_worker is None
event(dialog, "done", answer="伪造迟到成功")
wait_until(lambda: not bubble._presentation_timer.isActive())
assert finished == [True]
assert bubble._raw_payload == answer
oracle = module._RichMessage("ai")
oracle.document().setDefaultFont(bubble.body.document().defaultFont())
oracle.set_payload(answer)
assert bubble.body.toHtml() == oracle.toHtml()
oracle.deleteLater()
def test_completed_old_bubble_keeps_own_animation_after_new_request(dialogs):
dialog = dialogs()
dialog._ask("旧问题", task="case_analysis")
old, worker = dialog._stream_bubble, dialog._stream_worker
answer = report()
event(dialog, "delta", text=answer)
event(dialog, "done")
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
assert dialog._stream_worker is None and old._presentation_timer.isActive()
old_frames = []
old.stream_frame_presented.connect(lambda: old_frames.append(True))
dialog._ask("新问题", task="summary")
new = dialog._stream_bubble
event(dialog, "delta", text="新请求的唯一答案")
event(dialog, "done")
wait_until(lambda: not old._presentation_timer.isActive() and not old._report_render_pending)
assert old_frames and old._raw_payload == answer
assert new._raw_payload == "新请求的唯一答案"
assert new.body.toPlainText() == "新请求的唯一答案"
assert "旧问题" not in new.body.toPlainText()
assert dialog._stream_text == "新请求的唯一答案"
assert new._task_title == "问诊小结" and old._task_title == "病历分析"
@pytest.mark.parametrize("exit_path", ["close", "patient", "replace", "cancel"])
def test_exit_stops_correct_bubble_and_no_late_timer_can_change_next_request(dialogs, exit_path):
dialog = dialogs()
dialog._ask("旧问题", task="case_analysis")
old, worker = dialog._stream_bubble, dialog._stream_worker
old_generation = (dialog._generation, dialog._stream_generation)
answer = report()
event(dialog, "delta", text=answer)
assert old._presentation_timer.isActive()
if exit_path == "close":
dialog.close()
elif exit_path == "patient":
dialog.open_for(diagnosis_id=502, patient_id=1502)
dialog._ask("新患者问题")
elif exit_path == "replace":
dialog._ask("替代问题", replace_active=True)
else:
dialog._cancel_stream(reason="合成超时")
assert not old._presentation_timer.isActive()
assert old._clinical_panel is None
assert old._raw_payload == answer
current = dialog._stream_bubble
expected = current._raw_payload if current is not None else None
dialog._stream_event(*old_generation, {"event": "done", "answer": "迟到伪造成功"})
dialog._stream_finished(*old_generation, worker)
QTest.qWait(80)
assert old._raw_payload == answer
assert not isValid(old._presentation_timer) or not old._presentation_timer.isActive()
if current is not None:
assert current._raw_payload == expected
if exit_path in {"replace", "cancel"}:
assert "唯一完整结尾" in old.body.toPlainText()
assert "取消" in old.transfer_status.text()
def test_error_preserves_all_approved_partial_and_never_formats_success(dialogs):
dialog = dialogs()
dialog._ask("合成判断", task="case_analysis")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
answer = report()
event(dialog, "delta", text=answer)
assert len(bubble.body.toPlainText()) < len(answer)
failure = RuntimeError("AI正文与病历的已知、阴性或未记录状态不一致")
dialog._stream_failed(dialog._generation, dialog._stream_generation, failure)
assert not bubble._presentation_timer.isActive()
assert answer in bubble._raw_payload
assert "生成中断:AI正文与病历" in bubble._raw_payload
assert "唯一完整结尾" in bubble.body.toPlainText()
assert not dialog._stream_completed and bubble._clinical_panel is None
event(dialog, "done", answer="迟到伪造成功")
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
QTest.qWait(80)
assert bubble._clinical_panel is None and not bubble._presentation_timer.isActive()
assert "迟到伪造成功" not in bubble._raw_payload
assert dialog._stream_worker is None and dialog.send_button.isEnabled()
def test_cancelled_progress_is_terminal_even_if_a_late_done_follows(dialogs):
dialog = dialogs()
dialog._ask("合成判断", task="case_analysis")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
answer = report()
event(dialog, "delta", text=answer)
event(dialog, "progress", phase="cancelled")
assert not dialog._asking and not bubble._presentation_timer.isActive()
assert "取消" in bubble.transfer_status.text()
event(dialog, "delta", text="迟到伪造正文")
event(dialog, "done", answer="迟到伪造成功")
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
QTest.qWait(80)
assert bubble._raw_payload == answer and bubble._clinical_panel is None
assert dialog._stream_worker is None and not dialog._stream_completed
def test_eof_releases_transport_and_keeps_approved_partial_without_success_panel(dialogs):
dialog = dialogs()
dialog._ask("合成问诊", task="case_analysis")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
answer = report()
event(dialog, "delta", text=answer)
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
assert dialog._stream_worker is None and not dialog._asking and dialog.send_button.isEnabled()
assert bubble._presentation_timer.isActive()
assert "未收到回复完成确认" in bubble.transfer_status.text()
assert not dialog._stream_completed and bubble._clinical_panel is None
wait_until(lambda: not bubble._presentation_timer.isActive())
assert bubble._raw_payload == answer and "唯一完整结尾" in bubble.body.toPlainText()
assert bubble._clinical_panel is None and not bubble._report_render_pending
@pytest.mark.parametrize("owner_change", ["none", "patient_id", "diagnosis_id", "_chart_patient_id"])
def test_done_freezes_record_snapshot_before_playback_and_rechecks_owner(dialogs, owner_change):
dialog = dialogs()
dialog._workspace_sections = {"tracking": {"value": {"diagnosis_id": 501, "blood_records": [
{"diagnosis_id": 501, "patient_id": 1501, "record_date": "2026-01-01", "fasting_blood_sugar": 6.2},
]}}}
dialog._ask("血糖资料", task="glucose_trend")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
answer = ("## 血糖记录\n- 已有空腹血糖 6.2 mmol/L,单条记录不能确定趋势。\n\n## 来源复核\n- "
+ "合成来源日期与数值逐项保留。" * 500)
event(dialog, "delta", text=answer)
event(dialog, "done")
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
assert bubble._presentation_timer.isActive() and bubble._report_render_pending
dialog._workspace_sections["tracking"]["value"]["blood_records"][0]["fasting_blood_sugar"] = 99
if owner_change == "none":
dialog._ask("新的问题")
else:
setattr(dialog, owner_change, 9999)
wait_until(lambda: not bubble._presentation_timer.isActive() and not bubble._report_render_pending)
assert bubble._raw_payload == answer
if owner_change == "none":
assert bubble._clinical_panel is not None
chart = bubble.findChild(GlucoseReportCard)
assert chart is not None and chart.chart.data.readings[0].fasting == 6.2
else:
assert bubble._clinical_panel is None and bubble.findChild(GlucoseReportCard) is None
@pytest.mark.parametrize("terminal", ["close", "patient"])
def test_session_exit_also_stops_previously_completed_bubble_animation(dialogs, terminal):
dialog = dialogs()
dialog._ask("已完成旧问题", task="case_analysis")
old, worker = dialog._stream_bubble, dialog._stream_worker
event(dialog, "delta", text=report())
event(dialog, "done")
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
dialog._ask("当前问题")
assert old._presentation_timer.isActive()
if terminal == "close":
dialog.close()
else:
dialog.open_for(diagnosis_id=502, patient_id=1502)
assert not old._presentation_timer.isActive()
QTest.qWait(80)
assert old._clinical_panel is None
def test_first_frame_and_every_playback_slice_are_bounded(dialogs, monkeypatch):
dialog = dialogs()
dialog._ask("合成大段正文")
bubble = dialog._stream_bubble
chunks = []
original = bubble.body.append_stream_text
def append(text):
chunks.append(len(text))
original(text)
monkeypatch.setattr(bubble.body, "append_stream_text", append)
started = perf_counter()
event(dialog, "delta", text=report())
assert (perf_counter() - started) * 1000 < 80
assert len(chunks) == 1 and chunks[0] <= 24
event(dialog, "done")
assert len(chunks) == 1 and not dialog._asking
QTest.qWait(130)
assert len(chunks) >= 3 and max(chunks) <= 256
assert bubble._presentation_timer.isActive()
+1 -1
View File
@@ -38,7 +38,7 @@ def test_progress_lists_actual_materials_without_claiming_model_reading(applicat
bubble = dialog._stream_bubble
dialog._stream_event(generation, stream_generation, {"event": "start"})
assert "资料已整理" not in bubble._raw_payload
assert "整理" in bubble.transfer_status.text()
assert module.AI_STREAM_WAITING_TEXT in bubble.transfer_status.text()
dialog._stream_event(generation, stream_generation, {
"event": "progress", "phase": "preparing",
"source_summary": {"diagnosis_count": 2, "doctor_note_count": 3, "patient_name": "敏感姓名"},
@@ -0,0 +1,624 @@
"""Strict approved-grapheme playback in real Qt; every datum is synthetic.
Controlled timeout signals bound long-input tests. A separate test observes
physical single-shot timers and actual viewport paints, without model/network IO.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
from time import monotonic, perf_counter
from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QCoreApplication, QEvent, QObject, Qt, QThreadPool, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QScrollArea
from shiboken6 import isValid
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseReportCard
class OfflineWorker(module._AiStreamWorker):
def cancel(self):
self._cancelled.set()
return self.take_events()
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def bubbles(application):
resources = []
def create():
host = QScrollArea()
host.resize(760, 480)
host.setWidgetResizable(True)
bubble = module._ChatBubble(role="ai", text="正在等待合成测试正文")
host.setWidget(bubble)
host.show()
application.processEvents()
resources.append((host, bubble))
return bubble
yield create
for host, bubble in resources:
bubble.stop_stream_presentation()
assert not bubble._presentation_timer.isActive()
host.close()
host.deleteLater()
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
@pytest.fixture
def dialogs(application, monkeypatch):
resources = []
monkeypatch.setattr(module, "_AiStreamWorker", OfflineWorker)
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(
globalInstance=lambda: SimpleNamespace(start=lambda _: None)))
def create():
dialog = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
dialog.open_for(diagnosis_id=501, patient_id=1501)
dialog.show()
application.processEvents()
resources.append(dialog)
return dialog
yield create
for dialog in resources:
dialog.close()
assert not any(timer.isActive() for timer in dialog.findChildren(QTimer))
dialog.deleteLater()
assert QThreadPool.globalInstance().waitForDone(1000)
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def event(dialog, kind, **values):
dialog._stream_event(dialog._generation, dialog._stream_generation, {"event": kind, **values})
def tick(bubble):
"""Deliver exactly one real Qt timeout signal, without a wall-clock wait."""
bubble._presentation_timer.stop()
bubble._presentation_timer.timeout.emit()
def drain(bubble, limit=1000):
steps = 0
while bubble._presentation_timer.isActive() and steps < limit:
tick(bubble)
steps += 1
assert not bubble._presentation_timer.isActive(), "controlled playback exceeded finite bound"
return steps
def wait_until(predicate, seconds=2):
deadline = monotonic() + seconds
while not predicate() and monotonic() < deadline:
QTest.qWait(5)
assert predicate(), "finite Qt wait expired"
def report():
return ("## 合成血糖记录\n- 空腹血糖 6.2 mmol/L,仅一条记录不能说明长期趋势。\n"
+ "合成来源原文应保持完整,未记录的项目不能认定正常。" * 4
+ "\n\n## 合成复核计划\n- 请结合日期和现有信息复核,不据此增加用药。\n- 合成完整结尾。")
@pytest.mark.parametrize("length", [1, 2, 24, 25, 2001, 11000])
def test_first_prefix_is_one_character_and_never_accelerates_for_backlog(bubbles, length):
bubble = bubbles()
answer = "甲" * length
frames = []
bubble.stream_frame_presented.connect(lambda: frames.append(bubble.body.toPlainText()))
bubble.queue_approved_stream_text(answer)
assert frames == ["甲"]
assert bubble._raw_payload == answer
assert bubble._presentation_timer.interval() == 24
assert bubble._presentation_timer.isSingleShot()
assert bubble._presentation_timer.timerType() == Qt.TimerType.PreciseTimer
for index in range(1, min(length, 100)):
tick(bubble)
assert frames[-1] == answer[:index + 1]
assert len(frames) == min(length, 100)
def test_later_idle_burst_backlog_and_done_each_wait_for_their_own_tick(bubbles):
bubble = bubbles()
frames = []
bubble.stream_frame_presented.connect(lambda: frames.append(bubble.body.toPlainText()))
bubble.queue_approved_stream_text("首")
assert frames == ["首"] and not bubble._presentation_timer.isActive()
answer = "首" + "后来逐字。" * 400
bubble.queue_approved_stream_text(answer[:200])
assert frames == ["首"]
tick(bubble)
assert frames[-1] == answer[:2]
bubble.queue_approved_stream_text(answer)
assert len(frames) == 2
finished = []
bubble.complete_stream_presentation(lambda: finished.append(True))
assert len(frames) == 2 and not finished
for index in range(2, 202):
tick(bubble)
assert frames[-1] == answer[:index + 1]
assert not finished and bubble._raw_payload == answer
@pytest.mark.parametrize("remaining", [1, 2, 23, 24, 25])
def test_done_has_no_same_turn_remaining_text_shortcut(bubbles, remaining):
bubble = bubbles()
answer = "甲" + "乙" * remaining
bubble.queue_approved_stream_text(answer)
finished = []
bubble.complete_stream_presentation(lambda: finished.append(bubble.body.toPlainText()))
assert bubble.body.toPlainText() == "甲" and not finished
for index in range(remaining):
tick(bubble)
assert bubble.body.toPlainText() == answer[:index + 2]
assert bool(finished) == (index == remaining - 1)
assert finished == [answer]
tick(bubble)
assert finished == [answer]
def test_whole_unicode_graphemes_are_visible_exact_prefixes(bubbles):
bubble = bubbles()
characters = ["医", "🩺", "e\u0301", "👩\u200d⚕️", "🇨🇳", "क्\u200dष", "\r\n", "尾"]
answer = "".join(characters)
frames = []
bubble.stream_frame_presented.connect(lambda: frames.append(bubble.body.toPlainText()))
bubble.queue_approved_stream_text(answer)
finished = []
bubble.complete_stream_presentation(lambda: finished.append(True))
assert len(frames) == 1
for _ in characters[1:]:
tick(bubble)
expected = ["".join(characters[:index + 1]).replace("\r\n", "\n")
for index in range(len(characters))]
assert frames == expected
assert bubble._raw_payload == answer
assert bubble._presentation_offset == len(answer)
assert finished == [True]
@pytest.mark.parametrize("prefix", ["", "医", "👨\u200d👩\u200d👧", "👩\u200d⚕️"])
@pytest.mark.parametrize("count", [1, 2, 3, 4, 5, 6, 7])
def test_regional_indicator_pairs_start_at_each_contiguous_run(bubbles, prefix, count):
bubble = bubbles()
regional = "🇨🇳🇺🇸🇯🇵🇬"[:count]
groups = ([prefix] if prefix else []) + [regional[i:i + 2] for i in range(0, count, 2)] + ["终"]
answer = "".join(groups)
seen = []
bubble.stream_frame_presented.connect(lambda: seen.append(bubble.body.toPlainText()))
bubble.queue_approved_stream_text(answer)
finished = []
bubble.complete_stream_presentation(lambda: finished.append(True))
assert seen == groups[:1]
for index in range(1, len(groups)):
tick(bubble)
assert seen[-1] == "".join(groups[:index + 1])
assert bool(finished) == (index == len(groups) - 1)
assert len(seen) == len(groups)
assert bubble._raw_payload == answer and finished == [True]
@pytest.mark.parametrize("groups", [
["👨\u200d👩\u200d👧", "🇨🇳", "中", "🇺🇸", "🇯", "终"],
["🇨", "中", "🇺🇸", "🇯🇵", "终"],
["👨\u200d👩\u200d👧", "🇨🇳\u0301", "终"],
["👨\u200d👩\u200d👧", "🇨🇳", "🇺\u0301", "终"],
])
def test_regional_run_normalization_retains_surrounding_graphemes(bubbles, groups):
bubble = bubbles()
answer = "".join(groups)
bubble.queue_approved_stream_text(answer)
assert bubble.body.toPlainText() == groups[0]
for index in range(1, len(groups)):
tick(bubble)
assert bubble.body.toPlainText() == "".join(groups[:index + 1])
assert not bubble._presentation_timer.isActive()
assert bubble._raw_payload == answer
@pytest.mark.parametrize("prefix", ["", "甲", "甲乙"])
def test_split_crlf_holds_trailing_cr_and_reveals_one_normalized_newline(bubbles, prefix):
bubble = bubbles()
initial = prefix + "\r"
bubble.queue_approved_stream_text(initial)
drain(bubble)
before = bubble.body.toPlainText()
assert bubble._presentation_offset == len(prefix)
assert bubble._raw_payload == initial
answer = initial + "\n终"
bubble.queue_approved_stream_text(answer)
finished = []
bubble.complete_stream_presentation(lambda: finished.append(True))
assert bubble.body.toPlainText() == before and not finished
tick(bubble)
assert bubble.body.toPlainText() == prefix + "\n"
assert bubble._presentation_offset == len(initial) + 1 and not finished
tick(bubble)
assert bubble.body.toPlainText() == prefix + "\n终"
assert bubble._raw_payload == answer and finished == [True]
@pytest.mark.parametrize("prefix", ["", "甲", "甲乙丙丁"])
def test_true_terminal_cr_finishes_on_its_own_tick_even_with_backlog(bubbles, prefix):
bubble = bubbles()
answer = prefix + "\r"
bubble.queue_approved_stream_text(answer)
before = bubble.body.toPlainText()
finished = []
bubble.complete_stream_presentation(lambda: finished.append(bubble.body.toPlainText()))
assert bubble.body.toPlainText() == before and not finished
drain(bubble)
assert bubble.body.toPlainText() == prefix + "\n"
assert finished == [prefix + "\n"]
assert bubble._raw_payload == answer and bubble._presentation_offset == len(answer)
def test_held_cr_before_non_lf_is_not_dropped_or_joined_to_next_character(bubbles):
bubble = bubbles()
bubble.queue_approved_stream_text("甲\r")
assert bubble.body.toPlainText() == "甲"
bubble.queue_approved_stream_text("甲\r乙")
assert bubble.body.toPlainText() == "甲"
tick(bubble)
assert bubble.body.toPlainText() == "甲\n"
tick(bubble)
assert bubble.body.toPlainText() == "甲\n乙"
assert bubble._raw_payload == "甲\r乙"
@pytest.mark.parametrize("initial_count", [1, 3, 5])
def test_later_regional_indicator_extends_odd_run_after_family_on_later_tick(bubbles, initial_count):
bubble = bubbles()
family = "👨\u200d👩\u200d👧"
regional = "🇨🇳🇺🇸🇯🇵"
initial = family + regional[:initial_count]
bubble.queue_approved_stream_text(initial)
drain(bubble)
assert bubble.body.toPlainText() == initial
answer = family + regional[:initial_count + 1] + "终"
bubble.queue_approved_stream_text(answer)
assert bubble.body.toPlainText() == initial
tick(bubble)
assert bubble.body.toPlainText() == answer[:-1]
tick(bubble)
assert bubble.body.toPlainText() == answer
assert bubble._raw_payload == answer
@pytest.mark.parametrize("initial,joined", [
("e", "e\u0301"),
("👩", "👩\u200d⚕️"),
("🇨", "🇨🇳"),
("\ud83d", "\ud83d\udc69"),
])
def test_future_chunk_may_extend_visible_cluster_without_losing_raw_text(bubbles, initial, joined):
bubble = bubbles()
bubble.queue_approved_stream_text(initial)
before = bubble.body.toPlainText()
answer = joined + "终"
bubble.queue_approved_stream_text(answer)
assert bubble.body.toPlainText() == before
assert bubble._raw_payload == answer
tick(bubble)
canonical = joined.encode("utf-16", "surrogatepass").decode("utf-16")
assert bubble.body.toPlainText() == canonical
assert bubble._presentation_offset == len(joined)
tick(bubble)
assert bubble.body.toPlainText() == canonical + "终"
assert bubble._raw_payload == answer
def test_markdown_formats_during_character_playback_without_reparsing_whole_reply(bubbles, monkeypatch):
bubble = bubbles()
answer = '## 标题\n\n**重点** <b>字</b> [链接](https://example.test)\n{"原文":"🩺"}'
calls = []
original = bubble.body.set_payload
def set_payload(text):
calls.append(text)
original(text)
monkeypatch.setattr(bubble.body, "set_payload", set_payload)
bubble.queue_approved_stream_text(answer)
for index in range(1, len(answer)):
assert bubble._presentation_offset == index
if index >= len("## 标题"):
assert bubble.body.document().begin().blockFormat().headingLevel() == 2
assert "##" not in bubble.body.toPlainText()
if index >= answer.index(" <b>"):
assert bubble.body.document().find("重点").charFormat().fontWeight() >= 700
assert "**" not in bubble.body.toPlainText()
if index < answer.index("🩺") + 1:
assert "🩺" not in bubble.body.toPlainText()
tick(bubble)
assert calls == [""] # The mode switch clears the old waiting message once.
assert bubble._raw_payload == answer
assert "https://example.test" not in bubble.body.toPlainText()
bubble.complete_stream_presentation(bubble.finish_stream_text)
assert calls == ["", answer] and bubble._raw_payload == answer
oracle = module._RichMessage("ai")
oracle.set_payload(answer)
assert bubble.body.toPlainText() == oracle.toPlainText()
oracle.deleteLater()
def test_sse_markdown_is_formatted_while_request_is_still_generating(dialogs):
dialog = dialogs()
dialog._ask("合成血糖趋势", task="glucose_trend")
bubble = dialog._stream_bubble
prefix = "### 血糖趋势评估\n\n**可比较的血糖记录**"
answer = prefix + "\n\n- 空腹血糖:8.2 mmol/L。\n- 尚未轮到的最后一项。"
event(dialog, "delta", text=answer)
while bubble._presentation_offset < len(prefix):
tick(bubble)
assert dialog._asking and not dialog._stream_completed
assert not bubble._presentation_terminal and bubble._presentation_timer.isActive()
assert bubble.body.document().begin().blockFormat().headingLevel() == 3
assert bubble.body.document().find("可比较的血糖记录").charFormat().fontWeight() >= 700
assert "8.2" not in bubble.body.toPlainText()
assert "尚未轮到" not in bubble.body.toPlainText()
assert bubble._raw_payload == dialog._stream_text == answer
def test_segmentation_is_cached_on_approved_input_not_rebuilt_each_frame(bubbles, monkeypatch):
bubble = bubbles()
original = module._stream_grapheme_ends
calls = []
def segment(text):
calls.append(len(text))
return original(text)
monkeypatch.setattr(module, "_stream_grapheme_ends", segment)
bubble.queue_approved_stream_text("甲" * 2200)
for _ in range(100):
tick(bubble)
assert calls == [2200]
bubble.queue_approved_stream_text("甲" * 2300)
tick(bubble)
assert calls == [2200, 2300]
def test_physical_single_shot_timer_has_one_character_per_frame_and_no_catchup(bubbles, application):
bubble = bubbles()
answer = "物理计时器每次只显示一个字且不会追赶积压。"
frames, times, paints = [], [], []
class PaintProbe(QObject):
def eventFilter(self, watched, paint_event): # noqa: N802 - Qt API
if paint_event.type() == QEvent.Type.Paint:
text = bubble.body.toPlainText()
if not paints or paints[-1] != text:
paints.append(text)
return False
probe = PaintProbe(bubble.body)
bubble.body.viewport().installEventFilter(probe)
bubble.stream_frame_presented.connect(lambda: (frames.append(bubble.body.toPlainText()),
times.append(perf_counter())))
started = perf_counter()
bubble.queue_approved_stream_text(answer)
bubble.complete_stream_presentation(lambda: None)
assert frames == [answer[:1]]
QTest.qSleep(120) # Block dispatch: missed wall-clock ticks must not become a batch.
application.processEvents()
assert frames == [answer[:1], answer[:2]]
wait_until(lambda: not bubble._presentation_timer.isActive(), seconds=3)
elapsed = perf_counter() - started
assert frames == [answer[:index] for index in range(1, len(answer) + 1)]
assert len(paints) >= 5
assert elapsed >= 0.120 + (len(answer) - 2) * 0.023
measurement = {
"synthetic": True, "graphemes": len(answer), "interval_ms": 24,
"first_immediate": True, "event_loop_block_ms": 120,
"physical_frames": len(frames), "distinct_viewport_paints": len(paints),
"elapsed_seconds": elapsed, "characters_per_second_including_block": len(answer) / elapsed,
"frame_gaps_ms": [(b - a) * 1000 for a, b in zip(times, times[1:], strict=False)],
"model_request_count": 0,
}
if destination := os.environ.get("R40_CHARACTER_MEASUREMENT"):
Path(destination).write_text(json.dumps(measurement, indent=2), encoding="utf-8")
@pytest.mark.parametrize("answer_only", [False, True])
def test_done_releases_request_and_input_before_final_character_and_ignores_late_done(dialogs, answer_only):
dialog = dialogs()
dialog._ask("合成问题", task="summary")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
answer = "本次合成回复共有多个字。"
if not answer_only:
event(dialog, "delta", text=answer)
event(dialog, "done", answer=answer)
assert not dialog._asking and dialog.send_button.isEnabled() and dialog._stream_completed
assert bubble.body.toPlainText() == answer[:1]
assert bubble._raw_payload == dialog._stream_text == answer
assert bubble._presentation_timer.isActive() and bubble._report_render_pending
assert "正在逐字显示" in dialog.side_request_status.text()
assert "正在逐字显示" in bubble.transfer_status.text()
assert "完整显示" not in dialog.side_request_status.text()
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
assert dialog._stream_worker is None
event(dialog, "done", answer="迟到未校验正文")
assert drain(bubble) == len(answer) - 1
wait_until(lambda: not bubble._report_render_pending)
assert bubble.body.toPlainText() == answer and bubble._raw_payload == answer
assert "已完整显示" in dialog.side_request_status.text()
assert "已完整显示" in bubble.transfer_status.text()
def test_completed_old_bubble_finishes_own_characters_after_successor_starts(dialogs):
dialog = dialogs()
dialog._ask("旧合成问题", task="summary")
old, worker = dialog._stream_bubble, dialog._stream_worker
answer = "旧请求自己逐字显示完整结尾。"
event(dialog, "delta", text=answer)
event(dialog, "done")
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
dialog._ask("新合成问题", task="medication_review")
new = dialog._stream_bubble
event(dialog, "delta", text="新请求")
current_status = dialog.side_request_status.text()
assert old._presentation_timer.isActive() and new._presentation_timer.isActive()
tick(old)
assert old.body.toPlainText() == answer[:2] and new.body.toPlainText() == "新"
assert drain(old) == len(answer) - 2
wait_until(lambda: not old._report_render_pending)
assert old._raw_payload == answer and new._raw_payload == dialog._stream_text == "新请求"
assert "已完整显示" in old.transfer_status.text()
assert dialog.side_request_status.text() == current_status
assert "已完整显示" not in dialog.side_request_status.text()
assert old._task_title == "问诊小结" and new._task_title == "用药评估"
@pytest.mark.parametrize("owner_change", ["none", "patient_id", "diagnosis_id", "_chart_patient_id"])
def test_last_character_precedes_report_conversion_and_frozen_owner_check(dialogs, owner_change):
dialog = dialogs()
dialog._workspace_sections = {"tracking": {"value": {"diagnosis_id": 501, "blood_records": [
{"diagnosis_id": 501, "patient_id": 1501, "record_date": "2026-01-01",
"fasting_blood_sugar": 6.2},
]}}}
dialog._ask("合成血糖资料", task="glucose_trend")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
answer = report()
event(dialog, "delta", text=answer)
event(dialog, "done")
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
dialog._workspace_sections["tracking"]["value"]["blood_records"][0]["fasting_blood_sugar"] = 99
if owner_change == "none":
dialog._ask("新合成问题")
else:
setattr(dialog, owner_change, 9999)
for _ in range(len(answer) - 2):
tick(bubble)
assert bubble._presentation_offset == len(answer) - 1
oracle = module._RichMessage("ai")
oracle.set_payload(answer[:-1])
# Markdown control characters are no longer visible during playback.
assert bubble.body.toPlainText().split() == oracle.toPlainText().split()
oracle.deleteLater()
assert bubble._clinical_panel is None and bubble._report_render_pending
tick(bubble)
wait_until(lambda: not bubble._report_render_pending)
assert bubble._raw_payload == answer
if owner_change == "none":
assert isinstance(bubble._clinical_panel, module._StructuredReportPanel)
chart = bubble.findChild(GlucoseReportCard)
assert chart is not None and chart.chart.data.readings[0].fasting == 6.2
else:
assert bubble._clinical_panel is None and bubble.findChild(GlucoseReportCard) is None
@pytest.mark.parametrize("exit_path", ["close", "patient", "replace", "cancel"])
def test_exit_stops_timers_and_no_late_callback_changes_new_owner(dialogs, exit_path):
dialog = dialogs()
dialog._ask("旧合成请求", task="case_analysis")
old, worker = dialog._stream_bubble, dialog._stream_worker
owner = (dialog._generation, dialog._stream_generation)
answer = "已通过校验的合成正文完整尾部。" * 3
event(dialog, "delta", text=answer)
if exit_path == "close":
dialog.close()
elif exit_path == "patient":
dialog.open_for(diagnosis_id=502, patient_id=1502)
dialog._ask("新患者合成请求")
elif exit_path == "replace":
dialog._ask("替代合成请求", replace_active=True)
else:
dialog._cancel_stream(reason="合成停止")
assert not old._presentation_timer.isActive()
before = old.body.toPlainText()
tick(old) # A stale queued callback must not restart this stopped bubble.
assert old.body.toPlainText() == before
dialog._stream_event(*owner, {"event": "done", "answer": "迟到未校验成功"})
dialog._stream_finished(*owner, worker)
assert old._raw_payload == answer and old._clinical_panel is None
assert not old._presentation_timer.isActive()
if exit_path in {"replace", "cancel"}:
assert old.body.toPlainText() == answer
assert "取消" in old.transfer_status.text()
@pytest.mark.parametrize("terminal", ["error", "eof"])
def test_failure_and_eof_keep_strict_approved_partial_without_success_conversion(dialogs, terminal):
dialog = dialogs()
dialog._ask("合成失败测试", task="case_analysis")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
answer = "## 已通过校验的合成段落\n" + "原文仍需逐字显示。" * 8
event(dialog, "delta", text=answer)
before = bubble.body.toPlainText()
failure = "AI正文与病历的已知、阴性或未记录状态不一致,本次报告未通过校验。"
if terminal == "error":
dialog._stream_failed(dialog._generation, dialog._stream_generation, RuntimeError(failure))
assert bubble._stream_failure_label.isVisible()
assert failure in bubble._stream_failure_label.text()
assert bubble._stream_failure_label.textFormat() == Qt.TextFormat.PlainText
assert failure in dialog.side_request_status.text()
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
assert bubble.body.toPlainText() == before
assert not dialog._asking and dialog._stream_worker is None and dialog.send_button.isEnabled()
assert not dialog._stream_completed and bubble._clinical_panel is None
assert bubble._raw_payload == dialog._stream_text == answer
event(dialog, "done", answer="迟到未校验成功")
assert drain(bubble) == len(answer) - 1
assert bubble._raw_payload == answer and bubble._clinical_panel is None
assert not bubble._report_render_pending
assert "已完整显示" not in bubble.transfer_status.text()
assert "已完整显示" not in dialog.side_request_status.text()
assert "已通过校验的合成段落" in bubble.body.toPlainText()
assert "迟到未校验成功" not in bubble.body.toPlainText()
assert failure not in bubble._raw_payload
if terminal == "eof":
assert "未收到回复完成确认" in bubble.transfer_status.text()
def test_error_without_approved_text_remains_prominent_after_worker_finished(dialogs):
dialog = dialogs()
dialog._ask("合成无正文失败")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
failure = "合成错误:正文校验未通过。"
dialog._stream_failed(dialog._generation, dialog._stream_generation, RuntimeError(failure))
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
assert bubble._stream_failure_label.isVisible() and failure in bubble._stream_failure_label.text()
assert bubble.body.isHidden() and not bubble._presentation_timer.isActive()
assert not dialog._stream_completed and not dialog._stream_text
assert bubble._raw_payload == ""
assert bubble._clinical_panel is None
@pytest.mark.parametrize("exit_path", ["close", "patient"])
def test_session_exit_also_stops_older_done_playback(dialogs, exit_path):
dialog = dialogs()
dialog._ask("旧合成请求")
old, worker = dialog._stream_bubble, dialog._stream_worker
event(dialog, "delta", text="旧请求的文字仍在逐字呈现。" * 4)
event(dialog, "done")
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
dialog._ask("当前合成请求")
assert old._presentation_timer.isActive()
if exit_path == "close":
dialog.close()
else:
dialog.open_for(diagnosis_id=502, patient_id=1502)
assert not old._presentation_timer.isActive()
tick(old)
assert old._clinical_panel is None and not old._presentation_timer.isActive()
assert isValid(old)
+29
View File
@@ -0,0 +1,29 @@
from __future__ import annotations
from doctor_workstation.ui.dialogs.ai_consult_drug_names import (
TCM,
WESTERN,
find_drug_mentions,
summarize_drugs,
)
def test_formula_wins_over_contained_herb() -> None:
mentions = find_drug_mentions("可参考六味地黄丸加减")
assert [(m.name, m.kind) for m in mentions] == [("六味地黄丸", TCM)]
def test_western_dosage_form_is_highlighted_but_deduplicated_by_base_name() -> None:
text = "在用二甲双胍胶囊,二甲双胍早晚各1片,加用阿卡波糖"
mentions = find_drug_mentions(text)
assert text[mentions[0].start:mentions[0].end] == "二甲双胍胶囊"
assert summarize_drugs(text) == {TCM: [], WESTERN: ["二甲双胍", "阿卡波糖"]}
def test_herbs_and_western_drugs_are_split_by_kind() -> None:
summary = summarize_drugs("黄芪、丹参益气活血;格列美脲注意低血糖;黄芪可加量")
assert summary == {TCM: ["黄芪", "丹参"], WESTERN: ["格列美脲"]}
def test_plain_text_and_diet_words_are_not_drugs() -> None:
assert summarize_drugs("建议多吃山药、大枣,少吃甜食,规律运动") == {TCM: [], WESTERN: []}
+11 -1
View File
@@ -118,7 +118,6 @@ def test_current_readings_after_targets_do_not_keep_reference_color() -> None:
"诊单ID:123456;patient_id=1501;流水ABC123456;电话13800138000",
"2026-08-18,2026/08/19,08:30,第1章,1. 检查,2. 处理",
"病程3年,持续2周,随访7天,每次30分钟",
"二甲双胍500mg,每日2次;胰岛素10U;阿司匹林100 mg",
"剂量0.2mg/kg、浓度5mg/mL,外用2%利多卡因",
"统计显示80%的患者改善20%,目标完成率90%,报销比例50%",
"BMI2026-08-18;eGFR2026/08/19;heart_rate2026-08-18",
@@ -131,6 +130,17 @@ def test_unrelated_numbers_and_drug_doses_remain_unemphasized(text: str) -> None
assert "color:" not in rendered
def test_drug_names_are_highlighted_but_their_doses_stay_plain() -> None:
text = "二甲双胍500mg,每日2次;胰岛素10U;阿司匹林100 mg;黄芪30g"
rendered = metric_text_html(text)
for name in ("二甲双胍", "胰岛素", "阿司匹林"):
assert f'background-color: #EEF1FA; font-weight: 700;">{name}</span>' in rendered
assert 'background-color: #EAF7F0; font-weight: 700;">黄芪</span>' in rendered
for dose in ("500mg", "10U", "100 mg", "30g"):
assert f'font-weight: 600;">{dose}' not in rendered
assert f'font-weight: 700;">{dose}' not in rendered
def test_explicit_statuses_are_emphasized_without_classifying_the_numbers() -> None:
document = _document("血糖6.0 mmol/L未达标;血压140/90mmHg正常;血糖偏高;检查异常")
assert _color(document, "6.0 mmol/L") == "#BD4B58"
@@ -0,0 +1,65 @@
"""Current no-pulse workflow; old records and old acceptance fixtures stay intact."""
from __future__ import annotations
import os
from copy import deepcopy
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, QTimer
from PySide6.QtWidgets import QApplication
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.diagnosis import _DIAGNOSIS_FIELDS
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
def test_current_prompts_and_suggestions_do_not_request_pulse():
prompts = [prompt for _, prompt in module.QUICK_PROMPTS]
prompts += [prompt for _, _, prompt in module.TOOL_ITEMS]
for text in [*prompts, *module.SUGGESTIONS]:
assert "舌脉" not in text
assert "脉象" not in text
assert len(module.TOOL_ITEMS) == 6
assert len(module.SUGGESTIONS) == 5
def test_context_uses_tongue_without_repurposing_historical_pulse():
detail = {"diagnosis": {"tongue": "舌淡红", "pulse": "历史脉细", "pulse_condition": "旧字段"}}
original = deepcopy(detail)
text, labels = module.build_patient_ai_context(detail=detail)
assert labels == ["舌象"]
assert "舌淡红" in text
assert "脉" not in text
assert detail == original
def test_pulse_only_does_not_create_current_context_or_collection_field():
assert module.build_patient_ai_context(detail={"diagnosis": {"pulse": "旧脉象"}}) == ("", [])
assert "pulse" not in {key for _, key, _ in _DIAGNOSIS_FIELDS}
def test_new_prescription_seed_has_no_active_pulse_fields(application, monkeypatch):
dialog = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
detail = {"diagnosis": {"id": 501, "patient_id": 1501, "tongue": "舌淡红", "pulse": "历史脉细"}}
original = deepcopy(detail)
try:
dialog.open_for(diagnosis_id=501, patient_id=1501)
seed = dialog._prescription_seed(detail)
assert "pulse" not in seed and "pulse_condition" not in seed
assert seed["tongue"] == "舌淡红"
assert detail == original
finally:
for timer in dialog.findChildren(QTimer):
timer.stop()
dialog.close()
dialog.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
@@ -0,0 +1,177 @@
"""Paint the actual measured source text, including long unbroken record values."""
from __future__ import annotations
import json
import os
from html import escape
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, Qt, QTimer
from PySide6.QtGui import QTextCursor, QTextDocument
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel, QTextBrowser
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.theme import apply_theme
@pytest.fixture(scope="module")
def application():
app = QApplication.instance() or QApplication([])
apply_theme(app)
return app
@pytest.mark.parametrize("rich", [True, False])
def test_long_unbroken_tail_uses_actual_paint_document_and_exact_selection(application, rich):
text = "record_date" * 100 + "TAIL_SENTINEL"
label = module._FittedText(module._reading_html(text) if rich else text, rich=rich)
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
try:
label.show()
for width in (528, 240, 760, 528):
label.resize(width, label.height())
QTest.qWait(5)
label._fit()
view = label._text_view
document = view.document()
assert document is label._measure_document
assert document.toPlainText() == text
layout = document.firstBlock().layout()
assert layout.lineCount() > 5
assert all(layout.lineAt(n).naturalTextWidth() <= view.viewport().width()
for n in range(layout.lineCount()))
cursor = QTextCursor(document)
cursor.movePosition(QTextCursor.MoveOperation.End)
view.setTextCursor(cursor)
assert view.cursorRect().bottom() < view.viewport().height()
assert view.verticalScrollBar().maximum() == 0
image = view.viewport().grab().toImage()
# The final line actually paints at its document position, rather
# than a separate QLabel painter centering one clipped long token.
rect = view.cursorRect()
assert any(image.pixelColor(x, y).alpha() > 0
and image.pixelColor(x, y).red() < 180
for y in range(max(0, rect.top()), min(image.height(), rect.bottom() + 1))
for x in range(image.width()))
label.setSelection(len(text) - len("TAIL_SENTINEL"), len("TAIL_SENTINEL"))
assert label.hasSelectedText() and label.selectedText() == "TAIL_SENTINEL"
finally:
label.close()
label.deleteLater()
@pytest.mark.parametrize("layers", [0, 1, 2])
def test_source_fields_are_readable_without_rewriting_original_reply(application, layers):
record = {"record_date": 1775577600, "record_time": "07:30", "fasting_blood_sugar": 6.2,
"unknown_key": "保留未知字段", "zero": 0, "flag": False, "missing": None,
"nested": {"note": "<script>保留字面文本</script>;血糖 <7.0 mmol/L"}}
raw = json.dumps(record, ensure_ascii=False, separators=(",", ":"))
for _ in range(layers):
raw = escape(raw)
original = raw
rendered = QTextDocument()
rendered.setHtml(module._reading_html(raw))
plain = rendered.toPlainText()
assert "记录日期:2026-04-08" in plain
assert "记录时间:07:30" in plain
assert "6.2" in plain and "unknown_key:保留未知字段" in plain
assert "zero:0" in plain and "flag:否" in plain and "missing:未记录" in plain
assert "<script>保留字面文本</script>" in plain and "血糖 <7.0 mmol/L" in plain
assert "&quot;" not in plain
assert raw == original
@pytest.mark.parametrize("raw", [
'{"record_date":1775577600,"record_date":1775664000,"note":"原文不删"}',
'{"record_date":1775577600,"note":"未闭合尾部',
'{"record_date":1775577600,"number":NaN}',
])
def test_unsupported_source_stays_literal_and_complete(application, raw):
rendered = QTextDocument()
rendered.setHtml(module._reading_html(escape(raw)))
assert rendered.toPlainText() == raw
def test_source_continuation_keeps_date_role_and_one_owning_bullet():
record = escape('{"record_date":1775577600,"note":"原记录终点"}')
raw = ("## 一、原始资料\n- 2026-04-08 · 日常记录原文(非本次建议):\\[\n"
+ record + "\n\\]\n\n## 二、待核对\n- " + "只核对已采集资料,不添加患者事实。" * 5)
original = raw
_, sections, _ = module.parse_structured_report(raw)
assert len(sections[0].items) == 1
assert "日常记录原文(非本次建议)" in sections[0].items[0]
shown = module._report_display_text(sections[0].items[0])
assert "2026-04-08" in shown and "原记录终点" in shown
assert r"\[" not in shown and r"\]" not in shown
assert raw == original
assert "<7.0" in module._plain_markdown("血糖 <7.0,餐后 >10 mmol/L")
def test_pretty_source_is_grouped_before_markdown_changes_keys_or_values():
record = {"record_date": 1775577600, "unknown__key": "字面 **内容** 与 __标记__",
"nested": {"text": "<script>原字面值</script>"}}
raw = ("## 一、原始资料\n- 2026-04-08 · 日常记录原文:\\[\n"
+ json.dumps(record, ensure_ascii=False, indent=2)
+ "\n\\]\n## 二、复核\n- " + "保留资料,不添加患者事实。" * 5)
original = raw
_, sections, _ = module.parse_structured_report(raw)
assert len(sections[0].items) == 1
shown = QTextDocument()
shown.setHtml(module._reading_html(sections[0].items[0]))
assert "unknown__key:字面 **内容** 与 __标记__" in shown.toPlainText()
assert "<script>原字面值</script>" in shown.toPlainText()
assert raw == original
@pytest.mark.parametrize("repeat", [1, 100])
def test_pretty_negative_array_entries_keep_signs_and_do_not_become_bullets(repeat):
values = ",\n".join([" -1", " -0.25", " -3.5e-06"] * repeat)
body = '{\n "record_date":1775577600,\n "values":[\n' + values + '\n ],\n "tail":"NEGATIVE_ARRAY_TAIL"\n}'
raw = ("## 一、资料\n- 日常记录原文:\\[\n" + body
+ "\n\\]\n- 独立下一项\n## 二、核对\n- " + "保留原数据和日期,不编造。" * 5)
_, sections, _ = module.parse_structured_report(raw)
assert len(sections[0].items) == 2
shown = module._report_display_text(sections[0].items[0])
assert "-1、-0.25、-3.5e-06" in shown
assert shown.count("-3.5e-06") == repeat
assert "NEGATIVE_ARRAY_TAIL" in shown
assert sections[0].items[1] == "独立下一项"
def test_sidebar_tools_do_not_duplicate_on_report_resize_and_scroll(application, monkeypatch):
dialog = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
try:
dialog.open_for(diagnosis_id=501, patient_id=1501)
original = "## 一、核对资料\n- " + "完整记录,不编造缺项。" * 100 + "\n## 二、核对结尾\n- 独有结尾"
bubble = dialog._append_bubble("ai", original)
assert bubble.finalize_clinical_analysis()
dialog.show()
for width, height in ((1280, 820), (1635, 3708), (1080, 680), (1440, 900), (1280, 820)):
dialog.resize(width, height)
QTest.qWait(30)
tools = dialog.findChildren(module._ClickCard, "AiConsultToolCard")
suggestions = dialog.findChildren(module._ClickCard, "AiConsultSuggestRow")
assert len(tools) == 6 and len(suggestions) == 5
for card, (_, text, _) in zip(tools, module.TOOL_ITEMS):
labels = card.findChildren(QLabel)
assert sum(label.text() == text for label in labels) == 1
assert len([label for label in labels if not label.pixmap().isNull()]) == 1
for value in (0, dialog.chat_scroll.verticalScrollBar().maximum()):
dialog.chat_scroll.verticalScrollBar().setValue(value)
application.processEvents()
assert bubble._raw_payload == original
assert dialog.findChild(module.QWidget, "AiConsultSideCanvas") is not None
assert dialog.findChild(module.QWidget, "AiConsultSideViewport") is not None
assert bubble.findChildren(QTextBrowser, "AiConsultFittedViewport")
finally:
for timer in dialog.findChildren(QTimer):
timer.stop()
dialog.close()
dialog.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
+69
View File
@@ -129,6 +129,75 @@ def test_ai_consult_dialog_matches_workspace_chrome(
dialog.close()
@pytest.mark.parametrize("value", [None, "", " ", "—", 0, False, "0", "false", " FALSE "])
def test_family_history_default_flags_do_not_become_negative(value: Any) -> None:
assert ai_consult_module._family_text({"family_history": value}) == ""
@pytest.mark.parametrize("value", [1, True, "1", "true", " TRUE "])
def test_family_history_positive_flags_stay_positive(value: Any) -> None:
assert ai_consult_module._family_text({"family_history": value}) == "有"
@pytest.mark.parametrize(
"record", ["无", "否认", "否认家族史", "父亲有糖尿病", "未记录", "不详"]
)
@pytest.mark.parametrize("key", ["family_history", "family_history_text", "family_history_desc"])
def test_family_history_authored_records_keep_their_original_state(key: str, record: str) -> None:
assert ai_consult_module._family_text({key: record}) == record
@pytest.mark.parametrize(
("sources", "expected"),
[
(({"family_history": 0}, {"family_history_text": "否认家族史"}), "否认家族史"),
(({"family_history": 1}, {"family_history_desc": "尚未询问"}), "尚未询问"),
(({"family_history_text": "—", "family_history_desc": "父亲有糖尿病"},), "父亲有糖尿病"),
(({"family_history_text": False, "family_history_desc": "否认"},), "否认"),
(({"family_history_text": " 未记录 "}, {"family_history_text": ""}), "未记录"),
(({"family_history_text": "无"}, {"family_history_desc": None}), "无"),
(({"family_history": False}, {"family_history": "父亲有糖尿病"}), "父亲有糖尿病"),
(({"family_history": "否认"}, {"family_history": 0}), "否认"),
],
)
def test_family_history_prefers_authored_text_and_skips_empty_flags(
sources: tuple[dict[str, Any], ...], expected: str
) -> None:
assert ai_consult_module._family_text(*sources) == expected
@pytest.mark.parametrize("source", ["diagnosis", "patient", "appointment", "payload"])
@pytest.mark.parametrize(
("history", "expected"),
[
({"family_history": 0}, "未记录"),
({"family_history": False, "family_history_text": "否认家族史"}, "否认家族史"),
({"family_history": 1, "family_history_desc": "未记录"}, "未记录"),
],
)
def test_header_family_history_card_preserves_recorded_state_from_each_source(
application: QApplication, source: str, history: dict[str, Any], expected: str
) -> None:
dialog = AiConsultDialog(
DemoDoctorRepository(), PermissionSet(["tcm.diagnosis/aiAssistant"])
)
payload: dict[str, Any] = {"diagnosis": {"id": 501}}
if source == "payload":
payload.update(history)
else:
payload.setdefault(source, {}).update(history)
try:
dialog._apply_header(payload)
cards = [dialog.key_grid.itemAt(index).widget() for index in range(dialog.key_grid.count())]
family_card = next(
card for card in cards
if card.findChild(QLabel, "AiConsultKeyLabel").text() == "家族史"
)
assert family_card.findChild(QLabel, "AiConsultKeyValue").text() == expected
finally:
dialog.close()
def test_header_and_chat_filter_move_to_right_pane_and_filter_message_roles(
application: QApplication,
) -> None:
+191
View File
@@ -0,0 +1,191 @@
"""Preparation substages describe observed work without echoing source text."""
from __future__ import annotations
import os
from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, QTimer
from PySide6.QtWidgets import QApplication
from doctor_workstation.core.errors import ApiBusinessError
from doctor_workstation.ui.dialogs import ai_consult as module
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def dialog(application, monkeypatch):
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(
globalInstance=lambda: SimpleNamespace(start=lambda _: None),
))
instance = module.AiConsultDialog(object())
monkeypatch.setattr(instance, "_load_workspace", lambda _: None)
instance.open_for(diagnosis_id=501, patient_id=1501)
yield instance
for timer in instance.findChildren(QTimer):
timer.stop()
instance.close()
instance.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def emit(dialog, payload):
dialog._stream_event(dialog._generation, dialog._stream_generation, payload)
def test_queued_request_at_52_seconds_does_not_claim_preparation(dialog, monkeypatch):
now = [100.0]
monkeypatch.setattr(module, "monotonic", lambda: now[0])
dialog._ask("合成完整资料核对")
worker, bubble = dialog._stream_worker, dialog._stream_bubble
assert worker.prompt == "合成完整资料核对" and worker.diagnosis_id == 501
assert worker.run_started_at is None
now[0] = 152.0
dialog._stream_elapsed_timer.timeout.emit()
assert bubble._raw_payload == "正在连接 AI 服务,等待资料处理进度…"
assert "52 秒" in bubble.stamp.text()
assert "正在整理" not in bubble.body.toPlainText()
assert dialog._asking and dialog._stream_timeout_timer.isActive()
emit(dialog, {"event": "start", "message": "禁止显示的患者临床信息"})
assert bubble._raw_payload == module.AI_STREAM_WAITING_TEXT
assert module.AI_STREAM_WAITING_TEXT in bubble.transfer_status.text()
emit(dialog, {"event": "progress", "phase": "preparing"})
assert bubble._raw_payload == module.AI_STREAM_PREPARING_TEXT
@pytest.mark.parametrize("status,expected", [
("aggregating", "正在汇总本次授权范围内的患者资料…"),
("aggregated", "患者资料已汇总,正在检查提交内容…"),
("ready", "资料正文已整理,正在准备提交…"),
(None, module.AI_STREAM_PREPARING_TEXT),
("禁止显示的患者临床信息", module.AI_STREAM_PREPARING_TEXT),
(["禁止显示的患者临床信息"], module.AI_STREAM_PREPARING_TEXT),
])
def test_known_preparation_states_use_safe_local_copy(dialog, status, expected):
dialog._ask("合成资料核对")
emit(dialog, {
"event": "progress", "phase": "preparing", "status": status,
"message": "禁止显示的患者临床信息 https://example.test/private.pdf",
})
bubble = dialog._stream_bubble
assert bubble._raw_payload == expected
assert bubble.transfer_status.text().splitlines()[0] == expected
assert "禁止显示" not in bubble.body.toPlainText() + bubble.transfer_status.text()
assert "example.test" not in bubble.body.toPlainText() + bubble.transfer_status.text()
assert "资料已提交" not in bubble._raw_payload
assert dialog._asking and not dialog._stream_completed
@pytest.mark.parametrize("completed,total", [(0, 3), (1, 3), (3, 3)])
def test_compacting_counts_same_model_history_work_and_keeps_all_13_receipts(
dialog, completed, total,
):
dialog._ask("合成完整病历核对")
manifest = [
{"key": key, "label": "禁止显示的患者临床信息", "status": "prepared"}
for key, _ in module._REQUIRED_TRANSFER_SECTIONS
]
emit(dialog, {
"event": "progress", "phase": "preparing", "status": "aggregated",
"required_sections": manifest, "source_summary": {"diagnosis_count": 23},
})
emit(dialog, {
"event": "progress", "phase": "preparing", "status": "compacting",
"completed": completed, "total": total, "message": "禁止显示的患者临床信息",
})
bubble = dialog._stream_bubble
assert "当前 AI 模型整理历史资料" in bubble._raw_payload
assert f"已完成 {completed}/{total}" in bubble._raw_payload
assert "完整病历尚未提交综合分析" in bubble._raw_payload
receipt = bubble.transfer_status.text()
assert all(f"{label}:已整理,待提交" in receipt
for _, label in module._REQUIRED_TRANSFER_SECTIONS)
assert len(manifest) == 13
assert dialog._stream_meta["required_sections"] == manifest
assert "诊单 23 条" in receipt and "禁止显示" not in receipt
assert "资料正文已提交" not in receipt
assert dialog._asking and dialog._stream_first_delta_at is None
@pytest.mark.parametrize("completed,total", [
(None, 3), (0, None), (-1, 3), (4, 3), (0, 0), (-1, -2),
(True, 3), (1, False), (1.0, 3), (1, 3.0), ("1", 3), (1, "3"),
(float("nan"), 3), (1, float("inf")),
({"private": "禁止显示的患者临床信息"}, 3),
(1, ["禁止显示的患者临床信息"]),
])
def test_invalid_compacting_counts_are_not_rendered(dialog, completed, total):
dialog._ask("合成资料核对")
emit(dialog, {
"event": "progress", "phase": "preparing", "status": "compacting",
"completed": completed, "total": total, "message": "禁止显示的患者临床信息",
})
bubble = dialog._stream_bubble
assert bubble._raw_payload == (
"正在由当前 AI 模型整理历史资料,完整病历尚未提交综合分析…"
)
assert "已完成" not in bubble.transfer_status.text()
assert "禁止显示" not in bubble.body.toPlainText() + bubble.transfer_status.text()
def test_late_preparation_progress_never_replaces_received_answer(dialog):
dialog._ask("合成资料核对")
emit(dialog, {"event": "delta", "text": "合成正文"})
for status in ("aggregating", "aggregated", "compacting", "ready"):
emit(dialog, {
"event": "progress", "phase": "preparing", "status": status,
"completed": 1, "total": 2, "message": "禁止显示的患者临床信息",
})
assert dialog._stream_bubble._raw_payload == "合成正文"
emit(dialog, {"event": "delta", "text": "未刷新尾段"})
emit(dialog, {"event": "done"})
assert dialog._stream_bubble._raw_payload == "合成正文未刷新尾段"
assert dialog.send_button.isEnabled() and not dialog._asking
@pytest.mark.parametrize("ending", ["done", "error", "eof", "timeout", "cancelled"])
def test_compacting_exits_on_terminal_path_and_ignores_late_preparation(dialog, ending):
dialog._ask("合成资料核对")
emit(dialog, {
"event": "progress", "phase": "preparing", "status": "compacting",
"completed": 1, "total": 2,
})
generation, stream = dialog._generation, dialog._stream_generation
worker, bubble = dialog._stream_worker, dialog._stream_bubble
if ending == "done":
emit(dialog, {"event": "done", "answer": "合成最终正文"})
assert bubble._raw_payload == "合成最终正文"
elif ending == "error":
dialog._stream_failed(generation, stream, RuntimeError("合成失败"))
assert "本次请求失败" in bubble.transfer_status.text()
elif ending == "eof":
dialog._stream_finished(generation, stream, worker)
assert bubble._raw_payload == module.AI_STREAM_SILENT_TEXT
elif ending == "timeout":
dialog._stream_timed_out()
assert module.AI_STREAM_TIMEOUT_TEXT in bubble.transfer_status.text()
assert worker.is_cancelled()
else:
emit(dialog, {"event": "progress", "phase": "cancelled", "cancel_requested": True})
dialog._stream_failed(generation, stream, ApiBusinessError(
"已取消", code=409, data={"code": "AI_ASSISTANT_CANCELLED"},
))
assert "取消" in bubble.transfer_status.text()
assert not dialog._asking and dialog.send_button.isEnabled()
assert not dialog._stream_timeout_timer.isActive()
assert not dialog._stream_elapsed_timer.isActive()
before = bubble._raw_payload, bubble.transfer_status.text(), bubble.stamp.text()
dialog._stream_event(generation, stream, {
"event": "progress", "phase": "preparing", "status": "compacting",
"completed": 2, "total": 2,
})
assert (bubble._raw_payload, bubble.transfer_status.text(), bubble.stamp.text()) == before
@@ -29,12 +29,12 @@ from doctor_workstation.ui.dialogs import ai_consult as module
ENTRIES = (
("tool", "分析病历", "请根据当前病历给出辨证与病情摘要。", "tcm_pattern"),
("tool", "血糖趋势", "请评估该患者的血糖控制情况与趋势。", "custom"),
("tool", "用药评估", "请评估当前用药是否合理并给出调整建议。", "medication_review"),
("tool", "用药评估", "请核对四诊及舌脉,按八纲、气血津液与脏腑辨证,归纳证名、治法,以中药为主评估药证、合用、用法及禁忌;西药只简要核对相互作用与必要监测。", "medication_review"),
("tool", "并发症风险", "请评估并发症风险并给出随访建议。", "complication_risk"),
("tool", "生成问诊小结", "请生成本次问诊小结,便于写入病历。", "custom"),
("tool", "健康建议", "请给出饮食、运动与生活方式建议。", "custom"),
("chip", "总结当前病情", "请根据当前病历总结患者病情、证候与风险。", "tcm_pattern"),
("chip", "给出用药建议", "请评估当前用药是否合理,并给出调整建议。", "medication_review"),
("chip", "总结当前病情", "请根据当前病历总结患者病情、证候与风险。", "summary"),
("chip", "给出用药建议", "请先核对四诊及舌脉,再按八纲、气血津液与脏腑归纳证名、治法,重点给出中药用药提醒与方药复核建议;西药只保留必要的安全核对。", "medication_review"),
("menu", "建议检查项目", "请根据现病史给出下一步检查与检验建议。", "exam_review"),
("menu", "并发症风险评估", "请评估并发症风险并给出随访要点。", "complication_risk"),
("menu", "生成问诊问题", "请生成接下来应向患者确认的关键问诊问题。", "custom"),
@@ -0,0 +1,262 @@
"""Six task actions reach the real repository and preserve mocked model answers.
Finite offscreen Qt tests only. HTTP terminates in MockTransport; all clinical
text and transfer metadata below are synthetic, including incomplete sources.
"""
from __future__ import annotations
import json
import os
from time import monotonic
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import httpx
import pytest
from PySide6.QtCore import QEvent, Qt, QThreadPool, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel, QTextBrowser
from doctor_workstation.core import PermissionSet
from doctor_workstation.services import ApiClient, RemoteDoctorRepository
from doctor_workstation.services.repository import _diagnosis_ai_request
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.prescription_ai import diagnosis_ai_task
# Explicit acceptance values; neither tasks nor answer content are derived from
# the implementation's classifier or tool-task mapping.
TOOLS = (
("分析病历", "case_analysis", "病历分析", "已有口渴记录,结合血糖异常可分析津液受损的可能;不能据此直接确立证型。"),
("血糖趋势", "glucose_trend", "血糖趋势", "已有一条空腹血糖 8.2 mmol/L;单点不能确定升降趋势,应结合日期与连续监测解释。"),
("用药评估", "medication_review", "用药评估", "已记录二甲双胍,但剂量与肾功能缺失;可提示胃肠不适监测,不能据此增加剂量。"),
("并发症风险", "complication_risk", "并发症风险", "糖尿病病史提示需关注眼、肾和足部风险;未记录相应筛查不能推定已患或排除并发症。"),
("生成问诊小结", "summary", "问诊小结", "本次主诉口渴,既往有糖尿病;已记录二甲双胍及一条空腹血糖,病程与检查日期待明确。"),
("健康建议", "lifestyle_advice", "健康建议", "可先规律分配主食并记录饮食与血糖;运动宜从适量步行开始,出现低血糖症状时应停止活动。"),
)
SOURCE_KEYS = (
"basic_info", "vital_signs", "chief_complaint", "present_illness", "past_history",
"other_history", "diagnosis_info", "doctor_image_notes", "doctor_file_notes",
"daily_tracking", "prescriptions", "video_consultation_text", "chat",
)
def source_receipt() -> dict:
return {
"transfer_manifest_final": True,
"attachment_count": 0,
"submitted_attachment_count": 0,
"items": [],
"required_sections": [
{"key": key, "availability": "present" if key in {
"chief_complaint", "past_history", "prescriptions", "daily_tracking",
} else "absent", "status": "submitted"}
for key in SOURCE_KEYS
],
}
def answer_for(tool) -> str:
_label, task, title, analysis = tool
return (
f"当前{title}依据已记录的部分资料完成。\n\n"
f"## {title}判断\n- {analysis}\n- 专属结果标记:{task}_ACTUAL_MODEL_ANSWER。\n\n"
f"## {title}后续建议\n- 根据以上已有信息执行相应随访,不将缺项改写为正常。"
"\n- 缺失资料仅影响相应结论,不取代上述分析。"
)
def sse(kind: str, data: dict) -> str:
return f"event: {kind}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
def wait_until(predicate, timeout: float = 4.0) -> None:
deadline = monotonic() + timeout
while not predicate() and monotonic() < deadline:
QTest.qWait(5)
assert predicate(), "finite mocked request did not finish"
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def dialog_factory(application, monkeypatch):
resources = []
def create(handler):
client = ApiClient("https://example.test", transport=httpx.MockTransport(handler))
dialog = module.AiConsultDialog(
RemoteDoctorRepository(client), PermissionSet(["tcm.diagnosis/aiAssistant"]),
)
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
dialog.open_for(diagnosis_id=501, patient_id=1501)
dialog._detail = {"diagnosis": {"id": 501, "patient_id": 1501}}
# The intentionally absent case and errored local previews cannot block
# inference, synthesize a result, or become a stale request context.
dialog._workspace_sections = {"diagnosis": {"value": None, "error": "合成本地资料未加载"}}
dialog._patient_ai_context = "不能发往服务的本地旧预览"
dialog.show()
application.processEvents()
resources.append((dialog, client))
return dialog
yield create
for dialog, client in resources:
assert QThreadPool.globalInstance().waitForDone(4000)
dialog.close()
for timer in dialog.findChildren(QTimer):
timer.stop()
client.close()
dialog.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def click_tool(dialog, label: str) -> None:
cards = dialog.findChildren(module._ClickCard, "AiConsultToolCard")
target = next(child for card in cards for child in card.findChildren(QLabel)
if child.text() == label)
QTest.mouseClick(target, Qt.MouseButton.LeftButton)
def readable_answer(bubble) -> str:
if bubble._clinical_panel is None:
return bubble.body.toPlainText()
return "\n".join(view.toPlainText()
for view in bubble._clinical_panel.findChildren(QTextBrowser))
@pytest.mark.parametrize("tool", TOOLS, ids=[tool[1] for tool in TOOLS])
@pytest.mark.parametrize("route", ["stream", "legacy404"])
def test_incomplete_case_click_dispatches_distinct_task_and_shows_actual_task_answer(
dialog_factory, tool, route,
):
requests = []
answer = answer_for(tool)
label, task, title, analysis = tool
def handler(request):
assert request.url.host == "example.test"
requests.append(request)
if request.url.path.endswith("/aiAssistantStream"):
if route == "legacy404":
return httpx.Response(404, json={"msg": "合成旧部署无流式路由"})
events = sse("start", {"model_key": "qwen", "model_label": "原配置千问"})
events += sse("progress", {"phase": "attachments", "status": "submitted", **source_receipt()})
events += sse("delta", {"text": answer[:35]})
events += sse("delta", {"text": answer[35:]})
events += sse("done", {"model_key": "qwen", "model_label": "原配置千问", **source_receipt()})
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=events)
assert route == "legacy404" and request.url.path.endswith("/aiAssistant")
return httpx.Response(200, json={"code": 1, "data": {
"answer": answer, "model_key": "qwen", "model_label": "原配置千问", **source_receipt(),
}})
dialog = dialog_factory(handler)
click_tool(dialog, label)
bubble = dialog._stream_bubble
assert bubble is not None
wait_until(lambda: dialog._stream_worker is None and not dialog._asking)
assert len(requests) == (1 if route == "stream" else 2)
expected_prompt = next(prompt for _, name, prompt in module.TOOL_ITEMS if name == label)
for request in requests:
assert request.method == "POST"
body = json.loads(request.content)
assert set(body) == ({"id", "prompt", "task", "request_id"}
if request.url.path.endswith("/aiAssistantStream")
else {"id", "prompt", "task"})
assert body["task"] == task and body["id"] == 501
assert body["prompt"] == expected_prompt
assert "本地旧预览" not in request.content.decode()
assert "model" not in body and "model_key" not in body # Server model selection remains authoritative.
assert bubble._raw_payload == answer
assert isinstance(bubble._clinical_panel, module._StructuredReportPanel)
assert bubble._clinical_panel.findChild(QLabel, "AiConsultClinicalTitle").text() == f"AI · {title}"
visible = readable_answer(bubble)
assert analysis in visible and f"{task}_ACTUAL_MODEL_ANSWER" in visible
assert [section.title for section in bubble._clinical_panel.sections] == [
f"{title}判断", f"{title}后续建议",
]
assert len(dialog._stream_meta["required_sections"]) == 13
assert [item["key"] for item in dialog._stream_meta["required_sections"]] == list(SOURCE_KEYS)
assert dialog._stream_meta["model_key"] == "qwen" and "原配置千问" in bubble.stamp.text()
assert dialog._stream_completed and dialog.send_button.isEnabled()
assert not any(timer.isActive() for timer in (
dialog._delivery_timer, dialog._stream_timeout_timer, dialog._stream_elapsed_timer,
))
@pytest.mark.parametrize("tool", TOOLS, ids=[tool[1] for tool in TOOLS])
def test_each_tool_failed_model_request_is_honest_and_does_not_show_fake_success(dialog_factory, tool):
requests = []
label, task, title, _analysis = tool
def handler(request):
assert request.url.host == "example.test"
requests.append(request)
events = sse("start", {"model_key": "qwen", "model_label": "原配置千问"})
events += sse("error", {"code": "SYNTHETIC_MODEL_FAILURE", "message": f"{title}合成模型失败"})
events += sse("done", {"answer": f"{task}_FAKE_LATE_SUCCESS"})
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=events)
dialog = dialog_factory(handler)
click_tool(dialog, label)
bubble = dialog._stream_bubble
wait_until(lambda: dialog._stream_worker is None and not dialog._asking)
assert len(requests) == 1 and json.loads(requests[0].content)["task"] == task
assert f"{title}合成模型失败" in bubble._raw_payload
assert "FAKE_LATE_SUCCESS" not in bubble._raw_payload
assert "ACTUAL_MODEL_ANSWER" not in bubble._raw_payload
assert bubble._role_name.text() == f"AI · {title}"
assert bubble._clinical_panel is None and not dialog._stream_completed
assert dialog._stream_meta["code"] == "SYNTHETIC_MODEL_FAILURE"
assert dialog.send_button.isEnabled()
@pytest.mark.parametrize("tool", TOOLS, ids=[tool[1] for tool in TOOLS])
def test_task_classifier_and_real_repository_allowlist_keep_six_explicit_tasks(tool):
label, expected_task, _title, _analysis = tool
prompt = next(prompt for _, name, prompt in module.TOOL_ITEMS if name == label)
assert diagnosis_ai_task(prompt) == expected_task
assert _diagnosis_ai_request(501, prompt, expected_task) == (prompt, expected_task)
assert len(prompt) <= 500
assert "舌脉" not in prompt and "脉象" not in prompt
def test_unsupported_task_still_rejected():
with pytest.raises(ValueError, match="task is not supported"):
_diagnosis_ai_request(501, "合成提问", "not_a_supported_task")
@pytest.mark.parametrize("tool", TOOLS, ids=[tool[1] for tool in TOOLS])
def test_tool_answers_keep_all_points_and_extra_sections_in_old_clinical_heading_shape(application, tool):
_label, task, title, _analysis = tool
headings = ("证候分析", "信息缺口", "建议下一步", "风险提示", f"{title}专属补充")
points = [f"{heading}要点{index}:" + "这段完整推理与建议需要保留原意和全部内容。" * 6
+ f"{task}_{ordinal}_{index}_TAIL"
for ordinal, heading in enumerate(headings) for index in range(5)]
reply = "已按当前任务完成分析。\n\n" + "\n\n".join(
f"## {heading}\n" + "\n".join(f"- {point}" for point in points[index * 5:(index + 1) * 5])
for index, heading in enumerate(headings)
)
bubble = module._ChatBubble(role="ai", text=reply)
try:
bubble.set_analysis_task(task)
assert bubble.finalize_clinical_analysis()
assert isinstance(bubble._clinical_panel, module._StructuredReportPanel)
assert bubble._raw_payload == reply
assert [section.title for section in bubble._clinical_panel.sections] == list(headings)
assert sum(len(section.items) for section in bubble._clinical_panel.sections) == 25
visible = readable_answer(bubble)
for point in points:
assert any(point in section.items for section in bubble._clinical_panel.sections)
lead, body = point.split(":", 1)
assert lead in visible and body in visible
assert "当前更倾向" not in visible
finally:
bubble.close()
bubble.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
@@ -0,0 +1,58 @@
"""A later approved paragraph stays progressive after the earlier one catches up."""
from __future__ import annotations
import os
from time import monotonic
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QCoreApplication, QEvent
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QScrollArea
from doctor_workstation.ui.dialogs.ai_consult import _ChatBubble
def wait_until(predicate, timeout=5):
end = monotonic() + timeout
while not predicate() and monotonic() < end:
QTest.qWait(5)
assert predicate()
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.mark.parametrize("first_length,later_length", [(11000, 214), (7500, 120)])
def test_new_burst_has_multiple_document_updates_after_idle(application, first_length, later_length):
host = QScrollArea()
host.resize(720, 480)
host.setWidgetResizable(True)
bubble = _ChatBubble(role="ai", text="waiting")
host.setWidget(bubble)
host.show()
application.processEvents()
first = "A" * first_length
later = "\n\nLATER_PARAGRAPH_START_" + "B" * (later_length - 34) + "_LATER_END"
assert len(later) == later_length and len(first + later) < 12000
try:
bubble.queue_approved_stream_text(first)
wait_until(lambda: not bubble._presentation_timer.isActive())
updates = []
bubble.stream_frame_presented.connect(lambda: updates.append(bubble.body.toPlainText()))
bubble.queue_approved_stream_text(first + later)
wait_until(lambda: not bubble._presentation_timer.isActive())
assert len(updates) >= 2
assert not updates[0].endswith("_LATER_END")
assert updates[-1].endswith("_LATER_END")
assert bubble._raw_payload == first + later
finally:
bubble.stop_stream_presentation()
assert not bubble._presentation_timer.isActive()
host.close()
host.deleteLater()
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
@@ -0,0 +1,68 @@
"""The pinned cancellation state follows only its own late control result."""
from __future__ import annotations
import pytest
import test_ai_sidebar_request_state_r39 as shared
application = shared.application
workspace = shared.workspace
@pytest.mark.parametrize(("result", "expected"), [
({"upstream_terminal_confirmed": True, "upstream_terminal_status": "stopped"}, "上游工作流已停止"),
({"upstream_terminal_confirmed": True, "upstream_terminal_status": "succeeded"}, "上游工作流已结束(已完成)"),
({"upstream_terminal_confirmed": True, "upstream_terminal_status": "failed"}, "上游工作流已结束(失败)"),
({"upstream_stop_confirmed": True}, "工作流是否结束尚未确认"),
])
def test_late_cancel_result_keeps_task_time_identity_and_matches_own_receipt(workspace, result, expected):
dialog, _, deferred = workspace
deferred.complete(0)
dialog._ask("合成取消问题", task="summary")
worker, bubble = dialog._stream_worker, dialog._stream_bubble
generation, diagnosis = dialog._generation, dialog.diagnosis_id
dialog._stream_started_at -= 42
dialog._cancel_stream(reason="合成停止原因")
header = dialog.side_request_status.text().split("\n", 1)[0]
assert "问诊小结" in header and "42 秒" in header
properties = {key: dialog.side_request_status.property(key) for key in ("task", "diagnosisId", "requestId")}
dialog._stream_cancel_result(generation, diagnosis, bubble, worker, {**result, "transport_closed": True})
assert expected in bubble.transfer_status.text() and expected in dialog.side_request_status.text()
assert dialog.side_request_status.text().split("\n", 1)[0] == header
assert "合成停止原因" in dialog.side_request_status.text()
assert properties == {key: dialog.side_request_status.property(key) for key in properties}
assert not dialog._asking and not dialog._stream_completed and dialog._stream_worker is None
assert not dialog._stream_started_at and not dialog._stream_task
def test_older_cancel_confirmation_updates_old_receipt_without_replacing_new_status(workspace):
dialog, _, deferred = workspace
deferred.complete(0)
dialog._ask("旧合成问题", task="summary")
generation, diagnosis = dialog._generation, dialog.diagnosis_id
worker, bubble = dialog._stream_worker, dialog._stream_bubble
dialog._ask("新合成问题", replace_active=True, task="medication_review")
status, request_id = dialog.side_request_status.text(), dialog._sidebar_request_id
dialog._stream_cancel_result(generation, diagnosis, bubble, worker, {
"upstream_terminal_confirmed": True, "upstream_terminal_status": "stopped"})
assert "上游工作流已停止" in bubble.transfer_status.text()
assert dialog.side_request_status.text() == status
assert dialog.side_request_status.property("requestId") == request_id != worker.request_id
assert dialog.side_request_status.property("task") == "medication_review"
assert dialog._asking and not dialog._stream_completed
@pytest.mark.parametrize("boundary", ["patient", "close"])
def test_cancel_callback_cannot_cross_patient_or_closed_session(workspace, boundary):
dialog, _, deferred = workspace
deferred.complete(0)
dialog._ask("旧患者合成问题", task="summary")
generation, diagnosis = dialog._generation, dialog.diagnosis_id
worker, bubble = dialog._stream_worker, dialog._stream_bubble
if boundary == "patient":
dialog.open_for(diagnosis_id=502, patient_id=1502)
else:
dialog.close()
status = dialog.side_request_status.text()
dialog._stream_cancel_result(generation, diagnosis, bubble, worker, {
"upstream_terminal_confirmed": True, "upstream_terminal_status": "stopped"})
assert dialog.side_request_status.text() == status
@@ -0,0 +1,248 @@
"""Saved patient reports remain distinct from the current request in real Qt."""
from __future__ import annotations
import os
from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QCoreApplication, QEvent, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
class Deferred:
def __init__(self):
self.pending = []
def __call__(self, function, *args, on_success=None, **_kwargs):
self.pending.append((function, args, on_success))
def complete(self, index):
function, args, success = self.pending[index]
success(function(*args))
class Repository:
def __init__(self):
self.foreign_owner = False
self.report_text = {
1501: "甲患者保存报告开头。\n" + "甲患者完整历史依据。\n" * 60 + "4. 免责声明:甲患者历史报告结尾。",
1502: "乙患者保存报告开头。\n" + "乙患者完整历史依据。\n" * 60 + "乙患者历史报告结尾。",
}
def get_diagnosis_detail(self, diagnosis_id, **_kwargs):
return {"diagnosis": {"id": diagnosis_id, "patient_id": diagnosis_id + 1000,
"patient_name": "甲患者" if diagnosis_id == 501 else "乙患者"}}
def list_patient_ai_reports(self, patient_id):
return {"patient_id": 9999 if self.foreign_owner else patient_id,
"reports": [{"patient_id": patient_id, "model_label": "离线测试模型",
"created_at": "2026-10-20 08:00:00",
"report": {"diagnosis_advice": self.report_text[patient_id],
"treatment_advice": "保存的用药复核依据。"}}]}
def list_im_chat_messages(self, *_args, **_kwargs):
return []
class OfflineWorker(module._AiStreamWorker):
def cancel(self):
# Exercise UI cancellation and ownership without starting control HTTP
# threads; worker transport cancellation has its own regression suite.
self._cancelled.set()
return self.take_events()
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def workspace(application, monkeypatch):
deferred = Deferred()
monkeypatch.setattr(module, "run_async", deferred)
monkeypatch.setattr(module, "_AiStreamWorker", OfflineWorker)
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(
globalInstance=lambda: SimpleNamespace(start=lambda _: None)))
repository = Repository()
dialog = module.AiConsultDialog(repository, PermissionSet(["tcm.diagnosis/aiAssistant"]))
dialog.open_for(diagnosis_id=501, patient_id=1501)
dialog.show()
application.processEvents()
yield dialog, repository, deferred
bubbles = dialog.findChildren(module._ChatBubble)
dialog.close()
assert dialog._session_closed
assert not any(timer.isActive() for timer in dialog.findChildren(QTimer))
assert not any(bubble._presentation_timer.isActive() for bubble in bubbles)
dialog.deleteLater()
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def insight_text(dialog):
return "\n".join(label.text() for label in dialog.side_scroll.findChildren(QLabel)
if label.objectName() == "AiConsultInsightText")
def emit(dialog, event):
dialog._stream_event(dialog._generation, dialog._stream_generation, event)
def test_long_saved_report_preserves_content_and_has_explicit_source(workspace, application):
dialog, repository, deferred = workspace
deferred.complete(0)
application.processEvents()
assert "历史" in dialog.insight_source.text()
assert "2026-10-20 08:00:00" in dialog.insight_source.text()
assert "离线测试模型" in dialog.insight_source.text()
report_bubble = next(bubble for bubble in dialog.findChildren(module._ChatBubble)
if "甲患者保存报告开头" in str(bubble._raw_payload))
assert report_bubble._provenance["diagnosis_advice"] == repository.report_text[1501]
assert "已保存报告(历史)" in report_bubble.stamp.text()
assert insight_text(dialog).count("甲患者完整历史依据") == 60
assert "甲患者历史报告结尾" in insight_text(dialog)
assert dialog.side_scroll.verticalScrollBar().maximum() > 0
assert len(dialog.findChildren(module._ClickCard, "AiConsultToolCard")) == 6
def test_current_request_is_visible_above_scrolled_history_and_keeps_task_owner(workspace, application):
dialog, _repository, deferred = workspace
deferred.complete(0)
application.processEvents()
bar = dialog.side_scroll.verticalScrollBar()
bar.setValue(bar.maximum())
dialog._ask("无模板合成问题", task="medication_review")
worker = dialog._stream_worker
dialog._stream_started_at -= 42
emit(dialog, {"event": "progress", "phase": "upstream"})
status = dialog.side_request_status
assert "用药评估" in status.text() and "已等待 42 秒" in status.text()
assert "等待 AI 正文" in status.text()
assert status.property("diagnosisId") == 501
assert status.property("requestId") == worker.request_id
assert status.property("task") == "medication_review"
assert not dialog.side_scroll.isAncestorOf(status)
assert status.isVisible() and status.visibleRegion().boundingRect().height() > 0
assert "甲患者历史报告结尾" in insight_text(dialog)
assert "甲患者保存报告" not in dialog._stream_bubble._raw_payload
assert not dialog._stream_text
def test_late_saved_report_during_wait_does_not_become_current_reply(workspace, application):
dialog, _repository, deferred = workspace
dialog._ask("合成实时问题", task="summary")
worker = dialog._stream_worker
emit(dialog, {"event": "progress", "phase": "upstream"})
expected_status = dialog.side_request_status.text()
deferred.complete(0)
application.processEvents()
assert dialog.side_request_status.text() == expected_status
assert dialog.side_request_status.property("requestId") == worker.request_id
assert dialog._stream_bubble._raw_payload == "资料已提交,正在等待 AI 正文…"
assert not dialog._stream_text and not dialog._stream_completed
assert "历史" in dialog.insight_source.text()
def test_request_status_tracks_submission_wait_and_first_body_without_substitution(workspace):
dialog, _repository, deferred = workspace
deferred.complete(0)
saved_source = dialog.insight_source.text()
dialog._ask("合成无模板问题", task="complication_risk")
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted",
"attachment_count": 0})
assert "资料正文已提交,等待 AI 正文" in dialog.side_request_status.text()
emit(dialog, {"event": "progress", "phase": "upstream"})
assert "等待 AI 正文" in dialog.side_request_status.text()
emit(dialog, {"event": "delta", "text": "模型批准的原始片段🩺"})
assert "已收到 AI 正文,正在生成" in dialog.side_request_status.text()
assert "已用时" in dialog.side_request_status.text()
assert "已等待" not in dialog.side_request_status.text()
assert dialog._stream_text == "模型批准的原始片段🩺"
assert dialog.insight_source.text() == saved_source
assert dialog._asking and not dialog._stream_completed
def test_patient_switch_resets_scroll_and_late_old_owner_cannot_change_sidebar(workspace, application):
dialog, _repository, deferred = workspace
deferred.complete(0)
application.processEvents()
bar = dialog.side_scroll.verticalScrollBar()
bar.setValue(bar.maximum())
assert bar.value() > 0
dialog._ask("甲患者旧问题", task="case_analysis")
old_generation, old_stream = dialog._generation, dialog._stream_generation
dialog.open_for(diagnosis_id=502, patient_id=1502)
assert bar.value() == 0
assert dialog.side_request_status.text() == "本次尚未发起 AI 请求。"
assert dialog.side_request_status.property("requestId") == ""
deferred.complete(0) # A duplicated late callback still belongs to patient A.
dialog._stream_event(old_generation, old_stream, {"event": "delta", "text": "甲患者迟到正文"})
assert "甲患者" not in insight_text(dialog)
deferred.complete(1)
application.processEvents()
assert bar.value() == 0
assert "乙患者历史报告结尾" in insight_text(dialog)
assert "甲患者" not in insight_text(dialog)
assert dialog.side_request_status.property("diagnosisId") == 502
def test_report_with_wrong_owner_is_rejected_before_display(workspace, application):
dialog, repository, deferred = workspace
repository.foreign_owner = True
deferred.complete(0)
application.processEvents()
assert "甲患者保存报告开头" not in insight_text(dialog)
assert "加载失败" in dialog.insight_source.text()
@pytest.mark.parametrize("ending", ["done", "error", "eof", "cancel"])
def test_terminal_request_status_is_truthful_and_preserves_history(workspace, application, ending):
dialog, _repository, deferred = workspace
deferred.complete(0)
dialog._ask("合成终态问题", task="glucose_trend")
worker = dialog._stream_worker
generation, stream = dialog._generation, dialog._stream_generation
emit(dialog, {"event": "delta", "text": "本次收到的真实片段。"})
if ending == "done":
emit(dialog, {"event": "done"})
expected = "本次回复已完成"
elif ending == "error":
dialog._stream_failed(generation, stream, RuntimeError("离线合成错误"))
expected = "本次请求失败"
elif ending == "eof":
dialog._stream_finished(generation, stream, worker)
expected = "未收到回复完成确认"
else:
dialog._cancel_stream(reason="离线合成取消")
expected = "已停止本次等待"
QTest.qWait(40)
assert expected in dialog.side_request_status.text()
assert "血糖趋势" in dialog.side_request_status.text()
assert "甲患者历史报告结尾" in insight_text(dialog)
assert not dialog._asking
assert not dialog._stream_elapsed_timer.isActive()
assert not dialog._delivery_timer.isActive()
assert not dialog._stream_timeout_timer.isActive()
def test_replacement_request_rejects_previous_status_and_text(workspace):
dialog, _repository, deferred = workspace
deferred.complete(0)
dialog._ask("合成旧请求", task="case_analysis")
generation, stream = dialog._generation, dialog._stream_generation
old_id = dialog._stream_worker.request_id
dialog._ask("合成新请求", replace_active=True, task="lifestyle_advice")
expected = dialog.side_request_status.text()
dialog._stream_event(generation, stream, {"event": "progress", "phase": "upstream"})
dialog._stream_event(generation, stream, {"event": "done", "answer": "过期答案"})
assert dialog.side_request_status.text() == expected
assert "健康建议" in expected
assert dialog.side_request_status.property("requestId") != old_id
assert not dialog._stream_text
+220
View File
@@ -0,0 +1,220 @@
"""Live Markdown uses the approved character queue, with synthetic content only."""
from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QCoreApplication, QEvent
from PySide6.QtGui import QTextBlockUserData, QTextCursor
from PySide6.QtWidgets import QApplication
from doctor_workstation.ui.dialogs import ai_consult as module
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def bubble(application):
widget = module._ChatBubble(role="ai", text=module.AI_STREAM_WAITING_TEXT)
yield widget
widget.stop_stream_presentation()
widget.deleteLater()
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
def tick(bubble):
bubble._presentation_timer.stop()
bubble._presentation_timer.timeout.emit()
def drain(bubble):
for _ in range(12000):
if not bubble._presentation_timer.isActive():
return
tick(bubble)
pytest.fail("synthetic character queue exceeded finite bound")
@pytest.mark.parametrize("chunk_size", [1, 7, 10000])
def test_heading_bold_and_list_render_before_terminal(bubble, chunk_size):
answer = ("### 血糖趋势评估\n\n**1. 可比较的血糖记录**\n\n"
"* **空腹血糖**:10左右 mmol/L。来源:[vital_signs]、[present_illness]。\n"
"* **餐后血糖**:未记录。来源:[vital_signs]。")
for end in range(chunk_size, len(answer) + chunk_size, chunk_size):
accepted = answer[:end]
bubble.queue_approved_stream_text(accepted)
assert bubble._raw_payload == accepted
drain(bubble)
assert not bubble._presentation_terminal
assert bubble.body.document().begin().blockFormat().headingLevel() == 3
assert bubble.body.document().find("可比较的血糖记录").charFormat().fontWeight() >= 700
fasting = bubble.body.document().find("空腹血糖")
assert fasting.charFormat().fontWeight() >= 700
assert fasting.block().textList() is not None
view = bubble.body.toPlainText()
assert all(marker not in view for marker in ("###", "**", "* "))
assert "10左右 mmol/L" in view and "[vital_signs]" in view
assert "餐后血糖:未记录" in view
assert bubble._raw_payload == answer
bubble.complete_stream_presentation(bubble.finish_stream_text)
oracle = module._RichMessage("ai")
oracle.set_payload(answer)
assert bubble.body.toHtml() == oracle.toHtml()
oracle.deleteLater()
def test_later_markdown_formats_shown_prefix_without_revealing_backlog(bubble):
initial = "普通合成正文"
bubble.queue_approved_stream_text(initial)
drain(bubble)
answer = initial + "\n\n### 新小节\n\n**新重点** 尚未轮到的尾部"
bubble.queue_approved_stream_text(answer)
assert bubble.body.toPlainText() == initial
tick(bubble)
assert bubble._presentation_offset == len(initial) + 1
assert "新小节" not in bubble.body.toPlainText()
assert "尚未轮到" not in bubble.body.toPlainText()
drain(bubble)
assert bubble.body.document().find("新小节").blockFormat().headingLevel() == 3
assert bubble.body.document().find("新重点").charFormat().fontWeight() >= 700
assert "尚未轮到的尾部" in bubble.body.toPlainText()
assert bubble._raw_payload == answer
def test_long_tail_keeps_format_and_parses_later_inline_syntax(bubble):
source = "**已有重点** " + "甲" * 2200
bubble.queue_approved_stream_text(source)
drain(bubble)
assert bubble.body._stream_tail_plain
assert "**" not in bubble.body.toPlainText()
assert bubble.body.document().find("已有重点").charFormat().fontWeight() >= 700
answer = source + " **后来重点** 唯一结尾"
bubble.queue_approved_stream_text(answer)
drain(bubble)
assert "**" not in bubble.body.toPlainText()
assert bubble.body.document().find("后来重点").charFormat().fontWeight() >= 700
assert bubble.body.document().find("唯一结尾").charFormat().fontWeight() < 700
assert bubble.body.toPlainText().count("甲") == 2200
assert bubble.body.toPlainText().endswith("唯一结尾")
assert bubble._raw_payload == answer
@pytest.mark.parametrize("opening, closing", [("**", "**"), ("`", "`"), ("[", "](https://example.test)"), ("_", "_")])
def test_long_tail_reclassifies_delimiters_before_ordinary_letters(bubble, opening, closing):
source = opening + "x" * 2050 + closing
bubble.queue_approved_stream_text(source)
drain(bubble)
answer = source + "TAIL"
bubble.queue_approved_stream_text(answer)
drain(bubble)
oracle = module._RichMessage("ai")
oracle.set_payload(answer)
assert bubble.body.toPlainText() == oracle.toPlainText()
actual = bubble.body.document().find("TAIL").charFormat()
expected = oracle.document().find("TAIL").charFormat()
assert actual.fontWeight() == expected.fontWeight()
assert actual.fontItalic() == expected.fontItalic()
assert actual.fontFamilies() == expected.fontFamilies()
assert actual.isAnchor() == expected.isAnchor()
assert bubble._raw_payload == answer
oracle.deleteLater()
def test_plain_character_in_long_list_only_formats_its_changed_block(application, monkeypatch):
browser = module._RichMessage("ai")
browser.append_stream_text("- synthetic item\n" * 2000 + "- last item")
visited = []
original = module.apply_reading_rhythm
def apply(view, *, role, start_position=0):
block = view.document().findBlock(start_position)
while block.isValid():
visited.append(block.blockNumber())
block = block.next()
original(view, role=role, start_position=start_position)
monkeypatch.setattr(module, "apply_reading_rhythm", apply)
browser.append_stream_text("x")
assert len(visited) == 1
assert visited[0] >= 2000
assert browser.toPlainText().endswith("last itemx")
browser.deleteLater()
@pytest.mark.parametrize("answer", [
"[name][id]\n\n[id]: https://example.test",
"<https://example.test>",
"---",
r"a\*b",
])
def test_other_markdown_syntax_is_recognized_before_terminal(bubble, answer):
bubble.queue_approved_stream_text(answer)
drain(bubble)
oracle = module._RichMessage("ai")
oracle.set_payload(answer)
assert bubble.body.toPlainText() == oracle.toPlainText()
assert not bubble._presentation_terminal
if "example.test" in answer:
label = "name" if answer.startswith("[") else "https://example.test"
assert bubble.body.document().find(label).charFormat().anchorHref() == "https://example.test"
assert bubble._raw_payload == answer
oracle.deleteLater()
def test_character_updates_keep_stable_blocks_and_selection(bubble, monkeypatch):
prefix = "### 已有标题\n\n已有正文。\n\n"
bubble.queue_approved_stream_text(prefix)
drain(bubble)
block = bubble.body.document().begin()
marker = QTextBlockUserData()
block.setUserData(marker)
cursor = bubble.body.textCursor()
cursor.setPosition(0)
cursor.setPosition(4, QTextCursor.MoveMode.KeepAnchor)
bubble.body.setTextCursor(cursor)
selected = bubble.body.textCursor().selectedText()
monkeypatch.setattr(bubble.body, "set_payload", lambda _: pytest.fail("whole reply reparse"))
answer = prefix + "**新增重点** 完整尾部"
bubble.queue_approved_stream_text(answer)
drain(bubble)
assert bubble.body.document().begin().userData() is marker
assert bubble.body.textCursor().selectedText() == selected
assert bubble.body.document().find("新增重点").charFormat().fontWeight() >= 700
assert bubble._raw_payload == answer
@pytest.mark.parametrize("answer", [
"### 合成🩺标题\r\n\r\n**e\u0301👩\u200d⚕️🇨🇳**\r\n\r\n尾部",
"```text\n### 原始标记 **原文**\n- 原文条目\n```\n\n**完整末尾**",
r"\# 原文 \*原文\*,血糖 <7.0 mmol/L,数值 -1。",
"| 日期 | 数值 |\n| --- | --- |\n| 合成日 | 8.2 |\n\n**表格尾部**",
])
def test_unicode_code_and_literal_content_survive_live_formatting(bubble, answer):
bubble.queue_approved_stream_text(answer)
drain(bubble)
oracle = module._RichMessage("ai")
oracle.set_payload(answer)
assert bubble.body.toPlainText().split() == oracle.toPlainText().split()
assert bubble._raw_payload == answer
bubble.complete_stream_presentation(bubble.finish_stream_text)
assert bubble.body.toHtml() == oracle.toHtml()
oracle.deleteLater()
@pytest.mark.parametrize("answer", [
'<h2>合成标题</h2><p>完整末尾</p>',
'{"summary":"合成完整末尾","value":8.2}',
])
def test_complete_html_and_json_keep_terminal_auto_detection(bubble, answer):
bubble.queue_approved_stream_text(answer)
drain(bubble)
assert bubble._raw_payload == answer
bubble.complete_stream_presentation(bubble.finish_stream_text)
assert "完整末尾" in bubble.body.toPlainText()
assert "<h2>" not in bubble.body.toPlainText()
assert '{"summary"' not in bubble.body.toPlainText()
+140
View File
@@ -0,0 +1,140 @@
"""Summary intent and the released shortcut use the summary API task.
Offscreen workstation widgets and the real repository are exercised with
synthetic answers. Every HTTP request ends in MockTransport at example.test.
"""
from __future__ import annotations
import json
import os
from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import httpx
import pytest
from PySide6.QtCore import QEvent, Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QPushButton
from doctor_workstation.core import PermissionSet
from doctor_workstation.services import ApiClient, RemoteDoctorRepository
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.prescription_ai import diagnosis_ai_task
class _SyncMockTransport(httpx.BaseTransport):
"""Use the finite sync parser without Windows event-loop socket setup."""
def __init__(self, handler):
self.mock = httpx.MockTransport(handler)
def handle_request(self, request):
return self.mock.handle_request(request)
@pytest.mark.parametrize(("prompt", "expected"), [
("请根据当前病历总结患者病情、证候与风险。", "summary"),
("请概括患者现有证候和舌象。", "summary"),
("请给出当前辨证思路的摘要。", "summary"),
("请用一句话 summary 当前证候。", "summary"),
("请总结当前病情及风险。", "summary"),
("请生成完整中医辨证报告,并在末尾总结。", "tcm_pattern"),
("请生成完整的中医报告并附病情摘要。", "tcm_pattern"),
("请生成 full TCM report,附 summary。", "tcm_pattern"),
("task=tcm_pattern;总结当前病情。", "tcm_pattern"),
("请辨证并给出证候、治法。", "tcm_pattern"),
("tcm", "tcm_pattern"),
("请总结血糖趋势及可能证候。", "glucose_trend"),
("请总结用药风险及证候。", "medication_review"),
("请总结并发症风险及证候。", "complication_risk"),
("请摘要处方配伍及证候。", "prescription_review"),
("请总结检查结果及证候。", "exam_review"),
("请分析当前病历并总结辨证思路。", "case_analysis"),
])
def test_mixed_summary_and_tcm_intent_preserves_specific_tasks(prompt, expected):
assert diagnosis_ai_task(prompt) == expected
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.mark.parametrize("route", ["stream", "legacy404"])
@pytest.mark.parametrize("entry", ["shortcut", "free_text", "explicit_tcm"])
def test_summary_workstation_dispatch_reaches_real_repository(
application, monkeypatch, route, entry,
):
requests = []
expected_task = "tcm_pattern" if entry == "explicit_tcm" else "summary"
expected_prompt = "请根据当前病历总结患者病情、证候与风险。"
answer = "## 本次病情小结\n合成主诉为口渴,已记录证候待复核。\n\n## 后续事项\n合成病程日期待明确。"
workers = []
# Dispatch uses the real worker, run deterministically after the click so
# routing coverage does not depend on offscreen Qt thread scheduling.
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(
globalInstance=lambda: SimpleNamespace(start=workers.append),
))
def handler(request):
assert request.url.host == "example.test"
requests.append(request)
if request.url.path.endswith("/aiAssistantStream"):
if route == "legacy404":
return httpx.Response(404, json={"msg": "合成旧部署"})
events = (
f"event: delta\ndata: {json.dumps({'text': answer}, ensure_ascii=False)}\n\n"
"event: done\ndata: {}\n\n"
)
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=events)
assert route == "legacy404" and request.url.path.endswith("/aiAssistant")
return httpx.Response(200, json={"code": 1, "data": {"answer": answer}})
client = ApiClient("https://example.test", transport=_SyncMockTransport(handler))
dialog = module.AiConsultDialog(
RemoteDoctorRepository(client), PermissionSet(["tcm.diagnosis/aiAssistant"]),
)
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
dialog.open_for(diagnosis_id=501, patient_id=1501)
dialog.show()
application.processEvents()
try:
if entry == "shortcut":
# A stable shortcut task must survive a classifier change. This
# would still fail if only the free-text classifier were repaired.
monkeypatch.setattr(module, "diagnosis_ai_task", lambda _: "tcm_pattern")
target = next(button for button in dialog.findChildren(QPushButton)
if button.text() == "总结当前病情")
QTest.mouseClick(target, Qt.MouseButton.LeftButton)
elif entry == "explicit_tcm":
dialog._ask(expected_prompt, task="tcm_pattern")
else:
dialog.input.setText(expected_prompt)
QTest.mouseClick(dialog.send_button, Qt.MouseButton.LeftButton)
bubble = dialog._stream_bubble
assert bubble is not None
assert len(workers) == 1
workers[0].run()
application.processEvents()
assert dialog._stream_worker is None and not dialog._asking
assert len(requests) == (1 if route == "stream" else 2)
for request in requests:
body = json.loads(request.content)
assert body["id"] == 501
assert body["prompt"] == expected_prompt
assert body["task"] == expected_task
assert "model" not in body and "model_key" not in body
assert dialog._stream_task == expected_task
assert dialog._stream_completed and bubble._raw_payload == answer
if expected_task == "summary":
assert bubble._role_name.text() == "AI · 问诊小结"
assert dialog.send_button.isEnabled()
finally:
dialog.close()
for timer in dialog.findChildren(QTimer):
timer.stop()
client.close()
dialog.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
+7 -9
View File
@@ -1401,13 +1401,14 @@ def test_reception_ai_card_is_compact_preview_without_nested_scroll(
assert page.ai_summary_label.fullText() == _ai_narrative_text(
payload["diagnosis_advice"]
)
assert page.ai_treatment_label.fullText() == _ai_narrative_text(
assert page.ai_treatment_label.text() == _ai_narrative_text(
payload["treatment_advice"]
)
assert page.ai_summary_label.text().count("\n") + 1 == 3
assert page.ai_treatment_label.text().count("\n") + 1 == 2
assert page.ai_summary_label.text().endswith("…")
assert page.ai_treatment_label.text().endswith("…")
# The approved card previews diagnosis only; treatment stays complete in the
# cached report opened by the expand action, rather than a second preview.
assert not page.ai_treatment_label.isVisible()
chips = [
label
@@ -1421,12 +1422,9 @@ def test_reception_ai_card_is_compact_preview_without_nested_scroll(
]
assert len(chips) == 3
assert [label.text() for label in overflow] == ["+3 项"]
assert max(label.x() + label.width() for label in [*chips, *overflow]) <= (
page.ai_risk_chip_host.width()
)
assert max(label.y() + label.height() for label in [*chips, *overflow]) <= (
page.ai_risk_chip_host.height()
)
# Qt does not lay out explicitly hidden risk sections. Their retained data
# is still checked above, without asserting geometry for invisible widgets.
assert not page.ai_risk_chip_host.isVisible()
assert page.ai_risk_label.text().count("、") == 5
page.close()