This commit is contained in:
Your Name
2026-10-23 13:57:11 +08:00
parent ff98014fa2
commit e86ee4ae66
28 changed files with 3310 additions and 66 deletions
+1 -1
View File
@@ -7,5 +7,5 @@ __version__ = "1.4.9"
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
DEBUG_MODE = False
DEBUG_MODE = True
ONLINE_API_BASE_URL = "https://admin.zhenyangtang.com.cn"
@@ -3514,7 +3514,7 @@ def _merge_stream_meta(meta: dict[str, Any], payload: Mapping[str, Any]) -> None
live_fields = (
"items", "attachment_count", "submitted_attachment_count", "skipped_attachment_count",
"attachment_transfer", "required_sections",
"attachment_transfer", "required_sections", "attachment_mode", "attachment_batch_count", "rejected_attachment_count",
)
event = str(payload.get("event") or "").lower()
terminal = event in {"done", "error"}
@@ -3574,7 +3574,7 @@ def _merge_stream_meta(meta: dict[str, Any], payload: Mapping[str, Any]) -> None
entries = update.get(key)
if isinstance(entries, list) and any(
isinstance(item, Mapping) and item.get("status") in {
"submitted", "failed", "omitted", "skipped",
"submitted", "failed", "omitted", "skipped", "rejected",
}
and (key == "items" or str(item.get("key")) in dict(_REQUIRED_TRANSFER_SECTIONS))
for item in entries
@@ -3583,7 +3583,7 @@ def _merge_stream_meta(meta: dict[str, Any], payload: Mapping[str, Any]) -> None
if "items" in error_receipt_fields:
error_receipt_fields.update((
"attachment_count", "submitted_attachment_count", "skipped_attachment_count",
"attachment_transfer",
"attachment_transfer", "attachment_mode", "attachment_batch_count", "rejected_attachment_count",
))
if terminal and observed and payload.get("transfer_manifest_final") is not True:
for key in live_fields:
@@ -3657,6 +3657,11 @@ def _transfer_description(meta: Mapping[str, Any], state: str) -> str:
lines.append("复用已整理的证据摘要。")
elif meta.get("source_form") == "full_context":
lines.append("本次正文:来源上下文。")
if meta.get("attachment_mode") == "batch_evidence":
batch_count = meta.get("attachment_batch_count")
if type(batch_count) is int and batch_count > 0:
lines.append(f"附件处理:同一模型已进行 {batch_count} 批提交尝试。")
lines.append("最终回答依据完整正文与分批提取证据;最终单次请求未重传全部原始附件。")
items = meta.get("items")
visible_items: list[Mapping[str, Any]] = []
if isinstance(items, list):
@@ -3664,7 +3669,7 @@ def _transfer_description(meta: Mapping[str, Any], state: str) -> str:
statuses = {
"prepared": "等待上传", "uploading": "上传中", "uploaded": "已上传,待提交",
"submitting": "提交中", "submitted": "引用已提交", "omitted": "未提交", "failed": "提交失败",
"skipped": "已跳过",
"skipped": "已跳过", "rejected": "上游拒收,未读取",
}
if meta.get("attachment_transfer") == "uploaded_files":
statuses["submitted"] = "已上传并提交"
@@ -3679,6 +3684,25 @@ def _transfer_description(meta: Mapping[str, Any], state: str) -> str:
status = statuses.get(str(item.get("status")), "等待提交")
if item.get("status") == "skipped" and item.get("reason") == "not_found":
status = "文件不存在,已跳过"
if item.get("status") == "rejected":
reason = {"file_count": "数量限制", "file_type": "格式不支持", "file_size": "大小限制",
"file_access": "附件不可读取"}.get(str(item.get("reason")))
if reason:
status = f"上游拒收,未读取({reason})"
if item.get("status") == "submitted" and item.get("kind") == "image":
text_status = {
"processed": "附带本地识别文字,供模型核对",
"unreadable": "未取得可用识别文字,保留原图分析",
"unavailable": "本地文字识别未完成,保留原图分析",
"withheld": "本地识别文字超出本轮容量,未附加;保留原图分析",
}.get(str(item.get("text_check_status")))
if text_status:
status = f"{status};{text_status}"
if item.get("status") == "submitted" and item.get("evidence_status") in {"unreadable", "unverified"}:
if item.get("evidence_reason") == "context_budget":
status = f"{status};本轮综合容量不足,未可靠纳入结论"
else:
status = f"{status};逐项观察未核实,已向模型说明资料缺口"
lines.append(f"{label}({kind}):{status}")
submitted_count = meta.get("submitted_attachment_count")
valid_submitted_count = type(submitted_count) is int and submitted_count >= 0
@@ -3688,9 +3712,10 @@ def _transfer_description(meta: Mapping[str, Any], state: str) -> str:
for item in items
)
if has_video or (not valid_submitted_count and any(
item.get("status") == "skipped" for item in visible_items
item.get("status") in {"omitted", "skipped", "rejected", "failed"}
for item in visible_items
)):
count = sum(item.get("status") not in {"omitted", "skipped"} for item in visible_items)
count = sum(item.get("status") not in {"omitted", "skipped", "rejected", "failed"} for item in visible_items)
if type(count) is int and count >= 0:
lines.append(f"本请求附件通道:{count} 项;模型实际读取进度不可获取。")
return "\n".join(lines)
@@ -6233,6 +6258,7 @@ class AiConsultDialog(QDialog):
time_text="系统",
)
return True
self._cancel_stream(replaced=self._asking)
status = self._append_bubble(
"ai",
"正在核对当前诊单与患者归属,并读取患者全部纵向资料生成处方草稿。",
@@ -6358,6 +6384,10 @@ class AiConsultDialog(QDialog):
if str(payload.get("task") or "") != "prescription_generate":
status.set_payload("AI返回的不是处方草稿,已停止开方。")
return
if _required_transfer_sections(payload) or isinstance(payload.get("items"), list):
receipt: dict[str, Any] = {}
_merge_stream_meta(receipt, {**payload, "event": "done"})
status.set_transfer_status(_transfer_description(receipt, "处方草稿资料处理已完成。"))
draft = _as_mapping(payload.get("prescription_draft"))
herbs = draft.get("herbs")
if (
@@ -6529,6 +6559,13 @@ class AiConsultDialog(QDialog):
if generation != self._generation:
return
message = friendly_error(error)
error_data = getattr(error, "data", None)
if isinstance(error_data, Mapping) and (
_required_transfer_sections(error_data) or isinstance(error_data.get("items"), list)
):
receipt: dict[str, Any] = {}
_merge_stream_meta(receipt, {**error_data, "event": "error"})
status.set_transfer_status(_transfer_description(receipt, "本次请求失败,资料或回复未完成。"))
status.set_payload(f"{prefix}:{message}")
status.set_time_text("系统")
show_toast(self, message, "danger", 4200)
@@ -6746,6 +6783,13 @@ class AiConsultDialog(QDialog):
state = "资料正文已整理,正在准备提交…"
if payload.get("status") == "failed":
state = "资料提交失败。"
if (
self._stream_meta.get("attachment_mode") == "batch_evidence"
and payload.get("transfer_manifest_final") is not True
and any(item.get("status") != "submitted" for item in _required_transfer_sections(self._stream_meta) or []
if isinstance(item, Mapping))
):
state = "正在分批提交附件并提取资料,完整病历尚未提交综合分析…"
if phase == "cancelled":
state = _cancel_description(self._stream_meta)
self._update_transfer_status(state)
@@ -0,0 +1,276 @@
"""Synthetic Qt regressions for batch receipts and isolated prescription results."""
from __future__ import annotations
import os
from copy import deepcopy
from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel, QPushButton
from doctor_workstation.core import PermissionSet
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),
))
repository = SimpleNamespace(
create_prescription=lambda *_: pytest.fail("test must never create a prescription"),
generate_ai_prescription=lambda *_: pytest.fail("test must never invoke an upstream"),
cancel_diagnosis_ai=lambda *_: {"cancel_requested": True},
)
instance = module.AiConsultDialog(repository, PermissionSet([
"tcm.diagnosis/aiAssistant", "tcm.diagnosis/chufang",
"tcm.diagnosis/aiGeneratePrescription",
]))
monkeypatch.setattr(instance, "_load_workspace", lambda _: None)
monkeypatch.setattr(module, "show_toast", lambda *_: None)
instance.open_for(diagnosis_id=501, patient_id=1501)
instance.resize(1280, 820)
instance.show()
application.processEvents()
yield instance
for timer in instance.findChildren(QTimer):
timer.stop()
instance.close()
instance.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def sections(status):
return [{"key": key, "status": status, "availability": "present"}
for key, _ in module._REQUIRED_TRANSFER_SECTIONS]
def receipt(status="submitted", nested=False):
data = {
"items": [
{"kind": "image", "label": "图片附件1", "status": status},
{"kind": "image", "label": "图片附件2", "status": "rejected", "reason": "file_type"},
],
"attachment_count": 2, "submitted_attachment_count": int(status == "submitted"),
"rejected_attachment_count": 1, "attachment_transfer": "uploaded_files",
"attachment_mode": "batch_evidence", "attachment_batch_count": 3,
"transfer_manifest_final": True,
}
manifest = sections("submitted" if status == "submitted" else "failed")
if nested:
data["source_summary"] = {"required_sections": manifest}
else:
data["required_sections"] = manifest
return data
def emit(dialog, payload):
dialog._stream_event(dialog._generation, dialog._stream_generation, payload)
def assert_collapsed(bubble):
assert bubble.transfer_status.isHidden() and not bubble.transfer_toggle.isChecked()
assert "展开详情" in bubble.transfer_toggle.text()
assert bubble._inner.itemAt(0).widget() is bubble.transfer_receipt
assert len(bubble.findChildren(QLabel, "AiConsultTransferStatus")) == 1
QTest.mouseClick(bubble.transfer_toggle, Qt.MouseButton.LeftButton)
assert bubble.transfer_status.isVisible()
QTest.mouseClick(bubble.transfer_toggle, Qt.MouseButton.LeftButton)
assert bubble.transfer_status.isHidden()
@pytest.mark.parametrize("nested", [False, True])
@pytest.mark.parametrize("outcome", ["success", "error"])
def test_prescription_receipt_is_local_collapsed_and_cannot_mutate_active_question(
dialog, monkeypatch, nested, outcome,
):
dialog._ask("独立的当前合成问答")
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted",
"items": [{"kind": "document", "label": "文档附件9", "status": "submitted"}],
"attachment_count": 1, "submitted_attachment_count": 1,
"required_sections": sections("submitted")})
current_bubble, current_worker = dialog._stream_bubble, dialog._stream_worker
current_meta = deepcopy(dialog._stream_meta)
current_text = current_bubble.transfer_status.text()
status = dialog._append_bubble("ai", "合成处方等待状态")
editor_calls = []
monkeypatch.setattr(dialog, "_open_prescription_editor_from_chat",
lambda *args: editor_calls.append(args))
payload = receipt("submitted" if outcome == "success" else "failed", nested)
original = deepcopy(payload)
if outcome == "success":
result = {**payload, "diagnosis_id": 501, "task": "prescription_generate",
"prescription_draft": {"clinical_diagnosis": "合成诊断",
"herbs": [{"name": "合成药材", "dosage": 1}]}}
dialog._ai_prescription_ready(dialog._generation, 501, status, {}, result)
assert len(editor_calls) == 1
assert "AI 已生成处方草稿" in status._raw_payload
assert "处方草稿资料处理已完成。" in status.transfer_status.text()
else:
payload["code"] = "REQUIRED_FILES_REJECTED"
original = deepcopy(payload)
dialog._prescription_action_error(dialog._generation, status, ApiBusinessError(
"合成附件拒绝", data=payload,
), prefix="AI处方草稿生成失败")
assert editor_calls == []
assert status._raw_payload == "AI处方草稿生成失败:合成附件拒绝"
assert "本次请求失败,资料或回复未完成。" in status.transfer_status.text()
text = status.transfer_status.text()
assert "附件处理:同一模型已进行 3 批提交尝试。" in text
assert "图片附件2(图片):上游拒收,未读取(格式不支持)" in text
assert "文档附件9" not in text
assert f"本请求附件通道:{int(outcome == 'success')} 项" in text
assert payload == original
assert dialog._stream_meta == current_meta
assert dialog._stream_worker is current_worker and dialog._stream_bubble is current_bubble
assert current_bubble.transfer_status.text() == current_text
assert dialog._asking and not dialog._stream_completed
assert_collapsed(status)
@pytest.mark.parametrize("outcome", ["success", "error"])
def test_prescription_without_manifest_cannot_borrow_active_question_receipt(dialog, monkeypatch, outcome):
dialog._ask("独立的合成问答")
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", **receipt()})
current_meta = deepcopy(dialog._stream_meta)
status = dialog._append_bubble("ai", "合成处方等待状态")
monkeypatch.setattr(dialog, "_open_prescription_editor_from_chat", lambda *_: None)
if outcome == "success":
dialog._ai_prescription_ready(dialog._generation, 501, status, {}, {
"diagnosis_id": 501, "task": "prescription_generate",
"prescription_draft": {"clinical_diagnosis": "合成诊断",
"herbs": [{"name": "合成药材", "dosage": 1}]},
})
else:
dialog._prescription_action_error(dialog._generation, status, ApiBusinessError(
"合成无清单错误", data={"code": "REQUIRED_FILES_REJECTED"},
), prefix="合成失败")
assert not status.findChildren(QLabel, "AiConsultTransferStatus")
assert dialog._stream_meta == current_meta
def test_prescription_button_cancels_old_stream_before_beginning_owned_action(dialog, monkeypatch, application):
begin = []
monkeypatch.setattr(dialog, "_begin_prescription_action", lambda *args: begin.append(args))
dialog._ask("旧的合成问答")
old_worker, old_bubble = dialog._stream_worker, dialog._stream_bubble
old_generation, old_stream = dialog._generation, dialog._stream_generation
emit(dialog, {"event": "delta", "text": "旧问答已收到正文"})
next(button for button in dialog.findChildren(QPushButton)
if button.text() == "AI 生成处方").click()
assert old_worker.is_cancelled()
assert dialog._stream_generation > old_stream
assert dialog._stream_worker is None and not dialog._asking
assert dialog._stream_meta == {}
assert "旧问答已收到正文" in old_bubble._raw_payload
assert "上游是否停止尚未确认" in old_bubble.transfer_status.text()
application.processEvents()
assert len(begin) == 1
generation, status = begin[0]
assert generation == dialog._generation and status is not old_bubble
expected = status._raw_payload
dialog._stream_event(old_generation, old_stream, {"event": "done", "answer": "不应外显的旧结果"})
dialog._stream_failed(old_generation, old_stream, RuntimeError("不应外显的旧错误"))
dialog._stream_finished(old_generation, old_stream, old_worker)
assert status._raw_payload == expected and dialog._stream_worker is None
@pytest.mark.parametrize("nested", [False, True])
@pytest.mark.parametrize(("phase", "status"), [
("attachments", "uploading"), ("attachments", "submitted"), ("upstream", "waiting"),
])
def test_batch_progress_never_presents_prepared_full_text_as_already_submitted(dialog, nested, phase, status):
dialog._ask("合成批处理问答")
payload = receipt(nested=nested)
payload["transfer_manifest_final"] = False
payload["attachment_batch_count"] = 2
if nested:
payload["source_summary"]["required_sections"] = sections("prepared")
else:
payload["required_sections"] = sections("prepared")
emit(dialog, {"event": "progress", "phase": phase, "status": status, **payload})
bubble = dialog._stream_bubble
text = bubble.transfer_status.text()
assert text.splitlines()[0] == "正在分批提交附件并提取资料,完整病历尚未提交综合分析…"
assert bubble._raw_payload == text.splitlines()[0]
assert "基本信息:已整理,待提交" in text
assert "基本信息:已提交" not in text
assert "资料正文已提交" not in text and "资料已提交,正在等待 AI 正文" not in text
assert dialog._stream_meta["attachment_mode"] == "batch_evidence"
assert dialog._stream_meta["attachment_batch_count"] == 2
assert dialog._asking and not dialog._stream_completed
assert_collapsed(bubble)
# Once the complete body is submitted, normal synthesis waiting is accurate.
emit(dialog, {"event": "progress", "phase": "upstream", "status": "waiting",
"required_sections": sections("submitted")})
assert "基本信息:已提交" in bubble.transfer_status.text()
assert "完整病历尚未提交" not in bubble.transfer_status.text()
@pytest.mark.parametrize(("reason", "expected"), [
("file_count", "(数量限制)"), ("file_type", "(格式不支持)"),
("file_size", "(大小限制)"), ("file_access", "(附件不可读取)"),
("private test filename https://example.test/hidden.png?secret=synthetic", ""),
("<b>synthetic-private-error</b>", ""),
])
def test_rejected_receipt_uses_only_safe_reason_codes_and_stays_collapsed(dialog, reason, expected):
dialog._ask("合成拒绝回执")
payload = receipt()
payload["items"][1].update({"reason": reason, "label": "synthetic-private-filename.png"})
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", **payload})
bubble = dialog._stream_bubble
text = bubble.transfer_status.text()
assert f"图片附件2(图片):上游拒收,未读取{expected}" in text
assert "synthetic-private" not in text and "https://" not in text
assert bubble.transfer_status.textFormat() == Qt.TextFormat.PlainText
assert "本请求附件通道:1 项" in text
assert_collapsed(bubble)
@pytest.mark.parametrize("with_skipped", [False, True])
@pytest.mark.parametrize("reported", [None, True, -1, "1"])
def test_rejected_and_failed_files_never_inflate_fallback_submitted_count(dialog, with_skipped, reported):
items = [
{"kind": "image", "label": "图片附件1", "status": "submitted"},
{"kind": "image", "label": "图片附件2", "status": "rejected", "reason": "file_type"},
{"kind": "image", "label": "图片附件3", "status": "failed"},
]
if with_skipped:
items.append({"kind": "image", "label": "图片附件4", "status": "skipped", "reason": "not_found"})
dialog._ask("合成计数回执")
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted",
"items": items, "attachment_count": len(items), "submitted_attachment_count": reported})
assert "本请求附件通道:1 项" in dialog._stream_bubble.transfer_status.text()
def test_nonfinal_error_manifest_keeps_batch_rejections_and_explicit_outcome_counts(dialog):
dialog._ask("合成错误回执纠正")
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted",
"items": [{"kind": "image", "label": "图片附件1", "status": "submitted"}],
"attachment_count": 1, "submitted_attachment_count": 1})
failed = receipt("failed")
failed.pop("transfer_manifest_final")
dialog._stream_failed(dialog._generation, dialog._stream_generation, ApiBusinessError(
"合成批处理失败", data={"code": "REQUIRED_FILES_REJECTED", **failed},
))
text = dialog._stream_bubble.transfer_status.text()
assert "图片附件1(图片):提交失败" in text
assert "图片附件2(图片):上游拒收,未读取(格式不支持)" in text
assert "本请求附件通道:0 项" in text
assert dialog._stream_meta["rejected_attachment_count"] == 1
assert dialog._stream_meta["attachment_mode"] == "batch_evidence"
assert dialog._stream_meta["attachment_batch_count"] == 3
assert not dialog._asking and not dialog._stream_completed
assert_collapsed(dialog._stream_bubble)
+44
View File
@@ -0,0 +1,44 @@
"""Keep transport, local text recognition and model observation distinct."""
import pytest
from doctor_workstation.ui.dialogs.ai_consult import _transfer_description
@pytest.mark.parametrize("status, expected", [
("processed", "附带本地识别文字,供模型核对"),
("unreadable", "未取得可用识别文字,保留原图分析"),
("unavailable", "本地文字识别未完成,保留原图分析"),
("withheld", "本地识别文字超出本轮容量,未附加;保留原图分析"),
])
def test_image_text_status_does_not_claim_model_reading(status, expected):
text = _transfer_description({
"items": [{"kind": "image", "label": "图片附件1", "status": "submitted",
"text_check_status": status, "raw_text": "PRIVATE_OCR_TEXT"}],
"attachment_transfer": "uploaded_files", "submitted_attachment_count": 1,
}, "done")
assert expected in text
assert "已上传并提交" in text
assert "模型实际读取进度不可获取" in text
assert "PRIVATE_OCR_TEXT" not in text
def test_missing_source_observation_is_visible_even_after_successful_upload():
text = _transfer_description({
"items": [{"kind": "image", "status": "submitted", "evidence_status": "unverified"}],
"attachment_mode": "batch_evidence", "submitted_attachment_count": 1,
}, "done")
assert "逐项观察未核实" in text
assert "已向模型说明资料缺口" in text
assert "最终单次请求未重传全部原始附件" in text
def test_extracted_source_not_synthesized_is_not_presented_as_complete_analysis():
text = _transfer_description({
"items": [{"kind": "image", "status": "submitted", "evidence_status": "unverified",
"evidence_reason": "context_budget"}],
"attachment_mode": "batch_evidence", "submitted_attachment_count": 1,
"attachment_transfer": "uploaded_files",
}, "done")
assert "本轮综合容量不足,未可靠纳入结论" in text
assert "已上传并提交" in text
@@ -0,0 +1,95 @@
"""Large synthetic manifests stay complete and collapsed across terminal states."""
from __future__ import annotations
import os
from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel
from doctor_workstation.core import PermissionSet
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(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(instance, "_load_workspace", lambda _: None)
instance.open_for(diagnosis_id=501, patient_id=1501)
instance.resize(1280, 820)
instance.show()
yield instance
for timer in instance.findChildren(QTimer):
timer.stop()
instance.close()
instance.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def sections(status):
return [{"key": key, "status": status, "availability": "present"}
for key, _ in module._REQUIRED_TRANSFER_SECTIONS]
@pytest.mark.parametrize("count", [10, 11, 20, 40])
@pytest.mark.parametrize("terminal", ["done", "error"])
def test_large_batch_receipt_keeps_every_source_separate_and_collapsed(dialog, count, terminal):
dialog._ask("合成大量附件核对")
generation, stream = dialog._generation, dialog._stream_generation
bubble = dialog._stream_bubble
items = [{"kind": "image", "label": f"图片附件{index}", "status": "prepared"}
for index in range(1, count + 1)]
prepared = {"event": "progress", "phase": "attachments", "status": "uploading",
"attachment_mode": "batch_evidence", "attachment_batch_count": (count + 9) // 10,
"attachment_count": count, "submitted_attachment_count": 0,
"attachment_transfer": "uploaded_files", "required_sections": sections("prepared"),
"items": items}
dialog._stream_event(generation, stream, prepared)
assert bubble.transfer_status.isHidden() and not bubble.transfer_toggle.isChecked()
assert "完整病历尚未提交综合分析" in bubble.transfer_status.text()
if terminal == "done":
final_items = [{**item, "status": "submitted"} for item in items]
final_items[-1].update({"status": "rejected", "reason": "file_size"})
manifest = {**prepared, "items": final_items, "submitted_attachment_count": count - 1,
"rejected_attachment_count": 1, "required_sections": sections("submitted"),
"transfer_manifest_final": True}
dialog._stream_event(generation, stream, {**manifest, "event": "done", "answer": "合成最终正文"})
assert bubble._raw_payload == "合成最终正文" and dialog._stream_completed
assert f"图片附件{count}(图片):上游拒收,未读取(大小限制)" in bubble.transfer_status.text()
else:
final_items = [{**item, "status": "submitted" if index < count // 2 else "prepared"}
for index, item in enumerate(items)]
manifest = {**prepared, "items": final_items, "submitted_attachment_count": count // 2,
"transfer_manifest_final": True, "code": "UPSTREAM_UNAVAILABLE"}
manifest.pop("event")
dialog._stream_failed(generation, stream, ApiBusinessError("合成连接故障", data=manifest))
assert not dialog._stream_completed and "合成连接故障" in bubble._raw_payload
assert f"图片附件{count}(图片):等待上传" in bubble.transfer_status.text()
assert "基本信息:已整理,待提交" in bubble.transfer_status.text()
assert bubble.transfer_status.isHidden() and not bubble.transfer_toggle.isChecked()
assert bubble._inner.itemAt(0).widget() is bubble.transfer_receipt
assert len(bubble.findChildren(QLabel, "AiConsultTransferStatus")) == 1
assert len(dialog._stream_meta["items"]) == count
for index in range(1, count + 1):
assert f"图片附件{index}(图片):" in bubble.transfer_status.text()
assert "资料栏目提交清单" not in bubble._raw_payload
assert not dialog._asking and dialog.send_button.isEnabled()
QTest.mouseClick(bubble.transfer_toggle, Qt.MouseButton.LeftButton)
assert bubble.transfer_status.isVisible()
QTest.mouseClick(bubble.transfer_toggle, Qt.MouseButton.LeftButton)
assert bubble.transfer_status.isHidden()
@@ -0,0 +1,339 @@
"""Synthetic quick-action contract checks; no credentials, records or live network.
Use actual Qt click signals, QRunnable workers, repository and SSE parsing. Every
HTTP request terminates in MockTransport at the reserved example.test host.
"""
from __future__ import annotations
import asyncio
import json
import os
from threading import Event
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, QPushButton
from doctor_workstation.core import PermissionSet
from doctor_workstation.services import ApiClient, RemoteDoctorRepository
from doctor_workstation.ui.dialogs import ai_consult as module
# These are explicit observed contract values, rather than expectations computed
# with diagnosis_ai_task itself. Semantic routing issues are documented separately.
ENTRIES = (
("tool", "分析病历", "请根据当前病历给出辨证与病情摘要。", "tcm_pattern"),
("tool", "血糖趋势", "请评估该患者的血糖控制情况与趋势。", "custom"),
("tool", "用药评估", "请评估当前用药是否合理并给出调整建议。", "medication_review"),
("tool", "并发症风险", "请评估并发症风险并给出随访建议。", "complication_risk"),
("tool", "生成问诊小结", "请生成本次问诊小结,便于写入病历。", "custom"),
("tool", "健康建议", "请给出饮食、运动与生活方式建议。", "custom"),
("chip", "总结当前病情", "请根据当前病历总结患者病情、证候与风险。", "tcm_pattern"),
("chip", "给出用药建议", "请评估当前用药是否合理,并给出调整建议。", "medication_review"),
("menu", "建议检查项目", "请根据现病史给出下一步检查与检验建议。", "exam_review"),
("menu", "并发症风险评估", "请评估并发症风险并给出随访要点。", "complication_risk"),
("menu", "生成问诊问题", "请生成接下来应向患者确认的关键问诊问题。", "custom"),
)
SECTION_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 manifest(status: str) -> dict:
return {
"attachment_count": 7,
"submitted_attachment_count": 7 if status == "submitted" else 0,
"attachment_transfer": "uploaded_files",
"items": [{"kind": "image", "label": f"图片附件{index}", "status": status}
for index in range(1, 8)],
"required_sections": [{"key": key, "availability": "present", "status": status}
for key in SECTION_KEYS],
}
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 = 3.0) -> None:
deadline = monotonic() + timeout
while not predicate() and monotonic() < deadline:
QTest.qWait(5)
assert predicate(), "synthetic client did not reach the expected state"
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def client_dialog(application, monkeypatch):
resources = []
def create(handler, grants=None):
client = ApiClient("https://example.test", transport=httpx.MockTransport(handler))
dialog = module.AiConsultDialog(
RemoteDoctorRepository(client),
PermissionSet(grants or ["tcm.diagnosis/aiAssistant"]),
)
# Workspace loading is intentionally excluded: this test never fetches a
# patient record, image URL, filesystem attachment or saved credential.
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
dialog.open_for(diagnosis_id=501, patient_id=1501)
dialog.show()
application.processEvents()
resources.append((client, dialog))
return dialog
yield create
for client, dialog in resources:
dialog.close()
assert QThreadPool.globalInstance().waitForDone(3000)
for timer in dialog.findChildren(QTimer):
timer.stop()
client.close()
dialog.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def click(dialog, entry: tuple[str, str, str, str]) -> None:
kind, label, _, _ = entry
if kind == "tool":
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)
elif kind == "chip":
next(button for button in dialog.findChildren(QPushButton)
if button.text() == label).click()
else:
more = next(button for button in dialog.findChildren(QPushButton)
if button.text() == "更多")
next(action for action in more.menu().actions() if action.text() == label).trigger()
@pytest.mark.parametrize("entry", ENTRIES, ids=[f"{kind}-{label}" for kind, label, _, _ in ENTRIES])
@pytest.mark.parametrize("outcome", ["submitted", "rejected"])
def test_every_quick_action_reaches_exact_api_and_owns_its_seven_image_receipt(
client_dialog, entry, outcome,
):
requests = []
def handler(request):
assert request.url.host == "example.test"
requests.append(request)
assert request.url.path == "/adminapi/tcm.diagnosis/aiAssistantStream"
events = sse("start", {"model_label": "合成模型"})
events += sse("progress", {"phase": "attachments", "status": "submitted",
**manifest("submitted")})
if outcome == "submitted":
events += sse("delta", {"text": "七张合成图片的测试回复"})
events += sse("done", {"transfer_manifest_final": True, **manifest("submitted")})
else:
events += sse("error", {"code": "REQUIRED_FILES_REJECTED",
"message": "合成模型拒绝七张附件",
"transfer_manifest_final": True, **manifest("failed")})
# An invalid late success must never overwrite an error terminal.
events += sse("done", {"answer": "不应显示的迟到成功", **manifest("submitted")})
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=events)
dialog = client_dialog(handler)
dialog._patient_ai_context = "不应进入请求的本地旧预览"
click(dialog, entry)
bubble = dialog._stream_bubble
assert bubble is not None
wait_until(lambda: bool(requests) and dialog._stream_worker is None and not dialog._asking)
assert len(requests) == 1 # Includes default max_retries=2: POST must not retry.
body = json.loads(requests[0].content)
assert requests[0].method == "POST"
assert set(body) == {"id", "prompt", "task", "request_id"}
assert body["id"] == 501 and body["prompt"] == entry[2] and body["task"] == entry[3]
assert len(body["request_id"]) == 36
assert "本地旧预览" not in requests[0].content.decode()
expected = "已上传并提交" if outcome == "submitted" else "提交失败"
receipt = bubble.transfer_status.text()
for index in range(1, 8):
assert f"图片附件{index}(图片):{expected}" in receipt
assert dialog._stream_completed is (outcome == "submitted")
assert dialog.send_button.isEnabled()
assert not dialog._stream_timeout_timer.isActive()
assert not dialog._delivery_timer.isActive()
assert not dialog._stream_elapsed_timer.isActive()
assert "不应显示的迟到成功" not in bubble._raw_payload
if outcome == "rejected":
assert dialog._stream_meta["code"] == "REQUIRED_FILES_REJECTED"
assert "已上传并提交" not in receipt
assert "合成模型拒绝七张附件" in bubble._raw_payload
def test_all_tools_recover_after_rejection_without_receipt_or_request_identity_leak(client_dialog):
requests, old = [], []
def handler(request):
requests.append(request)
body = json.loads(request.content)
assert request.url.path == "/adminapi/tcm.diagnosis/aiAssistantStream"
# Alternate terminal failures and successes on the same dialog and host.
if len(requests) % 2:
events = sse("progress", {"phase": "attachments", "status": "submitted",
**manifest("submitted")})
events += sse("error", {"code": "REQUIRED_FILES_REJECTED",
"message": "合成拒绝", **manifest("failed")})
else:
events = sse("progress", {"phase": "attachments", "status": "submitted",
**manifest("submitted")})
events += sse("done", {"answer": f"当前合成回复{body['request_id']}"})
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=events)
dialog = client_dialog(handler)
for index, entry in enumerate(ENTRIES):
click(dialog, entry)
bubble, worker = dialog._stream_bubble, dialog._stream_worker
generation, stream_generation = dialog._generation, dialog._stream_generation
assert bubble is not None and worker is not None
wait_until(lambda count=index + 1: len(requests) == count and dialog._stream_worker is None)
current_body, receipt = bubble._raw_payload, bubble.transfer_status.text()
for old_generation, old_stream_generation, old_worker in old:
dialog._stream_event(old_generation, old_stream_generation,
{"event": "done", "answer": "旧请求迟到正文", **manifest("failed")})
dialog._stream_failed(old_generation, old_stream_generation, RuntimeError("旧请求迟到错误"))
dialog._stream_finished(old_generation, old_stream_generation, old_worker)
assert bubble._raw_payload == current_body and bubble.transfer_status.text() == receipt
assert dialog._stream_completed is (index % 2 == 1)
assert not dialog._asking and dialog.send_button.isEnabled()
old.append((generation, stream_generation, worker))
ids = [json.loads(request.content)["request_id"] for request in requests]
assert len(ids) == len(set(ids)) == len(ENTRIES)
assert [json.loads(request.content)["task"] for request in requests] == [entry[3] for entry in ENTRIES]
def test_prescription_chip_uses_owned_blocking_request_and_never_writes_after_rejection(
client_dialog, monkeypatch,
):
requests = []
def immediate(function, *args, on_success=None, on_error=None, on_finished=None, **kwargs):
try:
result = function(*args, **kwargs)
except Exception as error:
if on_error:
on_error(error)
else:
if on_success:
on_success(result)
finally:
if on_finished:
on_finished()
return object()
monkeypatch.setattr(module, "run_async", immediate)
def handler(request):
assert request.url.host == "example.test"
requests.append(request)
if request.url.path == "/adminapi/tcm.diagnosis/readonlyDetail":
assert request.method == "GET" and request.url.params["id"] == "501"
return httpx.Response(200, json={"code": 1, "data": {
"diagnosis": {"id": 501, "patient_id": 1501},
}})
assert request.url.path == "/adminapi/tcm.diagnosis/aiAssistant"
return httpx.Response(200, json={
"code": 0, "msg": "合成模型拒绝七张附件", "data": {
"code": "REQUIRED_FILES_REJECTED", "transfer_manifest_final": True,
**manifest("failed"),
},
})
dialog = client_dialog(handler, [
"tcm.diagnosis/aiAssistant", "tcm.diagnosis/chufang",
"tcm.diagnosis/aiGeneratePrescription",
])
next(button for button in dialog.findChildren(QPushButton)
if button.text() == "AI 生成处方").click()
wait_until(lambda: len(requests) == 2)
assert len(requests) == 2 # No fallback, retry or create-prescription write.
body = json.loads(requests[1].content)
assert body == {
"id": 501, "task": "prescription_generate",
"prompt": "请依据患者全部纵向资料生成一份可复核的中医处方草稿。",
}
bubbles = dialog.findChildren(module._ChatBubble)
assert any("AI处方草稿生成失败:合成模型拒绝七张附件" in bubble._raw_payload
for bubble in bubbles)
assert dialog._stream_worker is None and not dialog._asking
def test_live_quick_switches_cancel_exact_old_request_and_reject_duplicate_clicks(client_dialog):
streams, cancels, closed = [], [], []
release = Event()
class PausedStream(httpx.AsyncByteStream):
def __init__(self, request_id):
self.request_id = request_id
async def __aiter__(self):
yield sse("progress", {"phase": "attachments", "status": "submitted",
**manifest("submitted")}).encode()
while not release.is_set():
await asyncio.sleep(0.01)
yield sse("delta", {"text": f"最终合成回复{self.request_id}"}).encode()
yield sse("done", {}).encode()
async def aclose(self):
closed.append(self.request_id)
def handler(request):
assert request.url.host == "example.test"
body = json.loads(request.content)
if request.url.path == "/adminapi/tcm.diagnosis/cancelAiAssistant":
cancels.append(body)
return httpx.Response(200, json={"code": 1, "data": {
"cancel_requested": True, "upstream_stop_confirmed": False,
}})
assert request.url.path == "/adminapi/tcm.diagnosis/aiAssistantStream"
streams.append(body)
return httpx.Response(200, headers={"content-type": "text/event-stream"},
stream=PausedStream(body["request_id"]))
dialog = client_dialog(handler)
prior_bubble, prior_worker = None, None
try:
for index, entry in enumerate(ENTRIES):
click(dialog, entry)
bubble, worker = dialog._stream_bubble, dialog._stream_worker
assert bubble is not None and worker is not None
assert bubble is not prior_bubble and worker is not prior_worker
assert dialog._stream_meta == {} # Never inherits the preceding seven images.
wait_until(lambda count=index + 1: len(streams) == count and len(dialog._stream_meta.get("items", [])) == 7)
assert streams[-1]["prompt"] == entry[2] and streams[-1]["task"] == entry[3]
assert all(item["status"] == "submitted" for item in dialog._stream_meta["items"])
click(dialog, entry)
QTest.qWait(15)
assert len(streams) == index + 1 and dialog._stream_worker is worker
if prior_worker is not None:
assert prior_worker.is_cancelled()
assert "上游是否停止尚未确认" in prior_bubble.transfer_status.text()
assert "最终合成回复" not in prior_bubble._raw_payload
prior_bubble, prior_worker = bubble, worker
wait_until(lambda: len(cancels) == len(ENTRIES) - 1)
expected = [{"id": 501, "request_id": item["request_id"]} for item in streams[:-1]]
assert {json.dumps(item, sort_keys=True) for item in cancels} == {
json.dumps(item, sort_keys=True) for item in expected
}
assert len({item["request_id"] for item in streams}) == len(ENTRIES)
release.set()
wait_until(lambda: dialog._stream_worker is None and dialog._stream_completed)
assert prior_bubble._raw_payload == f"最终合成回复{streams[-1]['request_id']}"
wait_until(lambda: len(closed) == len(ENTRIES))
assert sorted(closed) == sorted(item["request_id"] for item in streams)
finally:
release.set()