"""Required input receipts remain factual through completion and legacy retry.""" 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 REQUIRED = ( ("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 sections(status="submitted"): return [ {"key": key, "label": "不得显示的来源姓名", "count": index % 2, "availability": "empty" if index % 2 == 0 else "present", "status": status} for index, (key, _) in enumerate(REQUIRED) ] @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 _worker: None), )) instance = module.AiConsultDialog(object()) monkeypatch.setattr(instance, "_load_workspace", lambda _: None) instance.open_for(diagnosis_id=501, patient_id=1501) instance._ask("合成资料核对") 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) @pytest.mark.parametrize("terminal", [ {}, {"items": [], "attachment_count": 0, "required_sections": []}, {"items": [{"kind": "image", "label": "图片附件1", "status": "omitted"}], "attachment_count": 0, "required_sections": sections("prepared")}, {"source_summary": {"required_sections": sections("prepared")}}, {"transfer_manifest_final": False, "required_sections": sections("failed")}, ]) def test_done_metadata_never_resets_observed_submission_or_loses_tail(dialog, terminal): emit(dialog, { "event": "progress", "phase": "attachments", "status": "submitted", "attachment_count": 1, "attachment_transfer": "remote_url_references", "items": [{"kind": "image", "label": "图片附件1", "status": "submitted"}], "required_sections": sections(), "source_summary": {"diagnosis_count": 2}, }) emit(dialog, {"event": "delta", "text": "合成正文"}) emit(dialog, {"event": "delta", "text": "未刷新尾段"}) emit(dialog, {"event": "done", **terminal}) text = dialog._stream_bubble.transfer_status.text() assert "图片附件1(图片):引用已提交" in text assert "本请求附件通道:1 项" in text assert "基本信息:无(已提交)" in text assert "日常整个页面:已提交" in text assert "诊单 2 条" in text assert "不得显示" not in text assert dialog._stream_bubble._raw_payload == "合成正文未刷新尾段" assert dialog._stream_completed and dialog.send_button.isEnabled() assert not dialog._stream_timeout_timer.isActive() assert dialog._stream_meta["source_summary"]["required_sections"] == sections() def test_final_manifest_can_correct_files_without_downgrading_submitted_text(dialog): emit(dialog, { "event": "progress", "phase": "attachments", "status": "submitted", "items": [{"kind": "document", "label": "文档附件1", "status": "submitted"}], "attachment_count": 1, "required_sections": sections(), }) emit(dialog, { "event": "done", "answer": "合成正文", "transfer_manifest_final": True, "items": [{"kind": "document", "label": "文档附件1", "status": "omitted"}], "attachment_count": 0, "required_sections": sections(), }) text = dialog._stream_bubble.transfer_status.text() assert "文档附件1(文档):未提交" in text assert "生命体征:已提交" in text assert "本请求附件通道:0 项" in text @pytest.mark.parametrize("nested", [False, True]) def test_all_required_columns_show_prepared_empty_and_submitted_truthfully(dialog, nested): for status, expected in [ ("prepared", "无(已整理,待提交)"), ("submitting", "无(提交中)"), ("submitted", "无(已提交)"), ("failed", "无(提交失败)"), ("omitted", "无(未提交)"), ]: manifest = sections(status) field = {"source_summary": {"required_sections": manifest}} if nested else { "required_sections": manifest, } emit(dialog, {"event": "progress", "phase": "attachments", "status": status, **field}) text = dialog._stream_bubble.transfer_status.text() assert f"基本信息:{expected}" in text assert all(f"{label}:" in text for _, label in REQUIRED) assert "不得显示的来源姓名" not in text if status != "submitted": assert "无(已提交)" not in text emit(dialog, {"event": "done", "answer": "合成正文"}) def test_legacy_retry_reports_omitted_files_and_keeps_text_submission(dialog): original = [{"kind": "document", "label": "文档附件1", "status": "submitted"}] emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", "items": original, "attachment_count": 1, "required_sections": sections()}) emit(dialog, {"event": "progress", "phase": "attachments", "status": "failed", "items": [{**original[0], "status": "failed"}], "required_sections": sections("failed")}) assert "文档附件1(文档):提交失败" in dialog._stream_bubble.transfer_status.text() emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", "items": [{**original[0], "status": "omitted"}], "attachment_count": 0, "required_sections": sections()}) text = dialog._stream_bubble.transfer_status.text() assert "资料正文已提交;本次附件未提交" in text assert "文档附件1(文档):未提交" in text assert "生命体征:已提交" in text emit(dialog, {"event": "done", "answer": "合成正文", "items": original, "attachment_count": 1, "required_sections": sections("prepared")}) text = dialog._stream_bubble.transfer_status.text() assert "文档附件1(文档):未提交" in text assert "生命体征:已提交" in text def test_legacy_service_does_not_invent_empty_or_submitted_columns(dialog): emit(dialog, {"event": "start"}) emit(dialog, {"event": "done", "answer": "合成正文"}) text = dialog._stream_bubble.transfer_status.text() assert "当前服务器未回传资料栏目清单,无法核对逐项提交状态。" in text assert "状态未回报" not in text and "资料栏目提交清单:" not in text assert "无(已提交)" not in text assert ":已提交" not in text @pytest.mark.parametrize("items,count", [ ([{"kind": "video", "label": "视频附件1", "status": "submitted"}], 0), ([{"kind": "VIDEO", "label": "不得显示的录制文件", "status": "failed"}, {"kind": "image", "label": "图片附件1", "status": "submitted"}], 1), ([{"label": "视频附件2", "status": "omitted"}, {"kind": "document", "label": "文档附件1", "status": "omitted"}], 0), ]) def test_video_attachments_never_appear_in_transfer_items_or_count(items, count): text = module._transfer_description({"items": items, "attachment_count": 7}, "合成状态") assert "视频附件" not in text and "不得显示" not in text assert f"本请求附件通道:{count} 项" in text assert "资料栏目清单:服务器尚未回传。" in text def test_missing_required_section_is_unreported_instead_of_invented_empty(): text = module._transfer_description({"required_sections": [ {"key": "basic_info", "availability": "empty", "status": "submitted"}, {"key": "untrusted", "label": "不得显示的姓名", "status": "submitted"}, ]}, "合成状态") assert "基本信息:无(已提交)" in text assert "日常整个页面:状态未回报" in text assert "不得显示" not in text def test_empty_top_level_manifest_uses_valid_nested_receipt(dialog): emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", "required_sections": [], "source_summary": {"required_sections": sections()}}) emit(dialog, {"event": "done", "answer": "合成正文"}) text = dialog._stream_bubble.transfer_status.text() assert "基本信息:无(已提交)" in text and "日常整个页面:已提交" in text assert "状态未回报" not in text @pytest.mark.parametrize("initial", [[], sections("prepared")]) def test_attachment_progress_does_not_block_first_actual_column_receipt(dialog, initial): emit(dialog, {"event": "start", "required_sections": initial}) emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", "items": [{"kind": "image", "label": "图片附件1", "status": "omitted"}], "attachment_count": 0}) emit(dialog, {"event": "done", "answer": "合成正文", "required_sections": sections()}) text = dialog._stream_bubble.transfer_status.text() assert "基本信息:无(已提交)" in text and "日常整个页面:已提交" in text assert "图片附件1(图片):未提交" in text assert "状态未回报" not in text def test_actual_file_upload_progress_is_distinct_from_model_submission(dialog): items = [{"kind": "image", "label": "图片附件1", "status": "uploaded"}, {"kind": "document", "label": "文档附件1", "status": "uploading"}] emit(dialog, {"event": "progress", "phase": "attachments", "status": "uploading", "upload_index": 2, "upload_total": 2, "items": items, "attachment_transfer": "uploaded_files", "required_sections": sections("prepared")}) text = dialog._stream_bubble.transfer_status.text() assert "正在上传附件(2/2)" in text assert "图片附件1(图片):已上传,待提交" in text assert "文档附件1(文档):上传中" in text assert "生命体征:已整理,待提交" in text emit(dialog, {"event": "done", "answer": "合成正文", "transfer_manifest_final": True, "items": [{**item, "status": "submitted"} for item in items], "attachment_transfer": "uploaded_files", "required_sections": sections()}) assert "图片附件1(图片):已上传并提交" in dialog._stream_bubble.transfer_status.text() def submitted_images(): return [ {"kind": "image", "label": f"图片附件{index}", "status": "submitted"} for index in (1, 2) ] def submit_images(dialog): emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", "items": submitted_images(), "attachment_count": 2, "required_sections": sections()}) def fail(dialog, data): dialog._stream_failed(dialog._generation, dialog._stream_generation, ApiBusinessError( "合成必需资料提交失败", data=data, )) def test_failed_progress_without_items_does_not_keep_successful_file_receipts(dialog): submit_images(dialog) emit(dialog, {"event": "progress", "phase": "attachments", "status": "failed", "required_sections": sections("failed")}) text = dialog._stream_bubble.transfer_status.text() assert "基本信息:无(提交失败)" in text assert "图片附件1(图片):提交失败" in text assert "图片附件2(图片):提交失败" in text assert "引用已提交" not in text fail(dialog, {"code": "REQUIRED_FILES_REJECTED"}) dialog._stream_finished(dialog._generation, dialog._stream_generation, dialog._stream_worker) assert "引用已提交" not in dialog._stream_bubble.transfer_status.text() assert not dialog._asking and not dialog._stream_completed assert dialog.send_button.isEnabled() and dialog._stream_ended_at is not None assert dialog._stream_meta["status"] == "failed" and dialog._stream_worker is None def test_failed_terminal_manifest_corrects_all_observed_receipts_and_keeps_tail(dialog): submit_images(dialog) emit(dialog, {"event": "delta", "text": "合成已有正文"}) emit(dialog, {"event": "delta", "text": "未刷新尾段"}) failed_items = [{**item, "status": "failed"} for item in submitted_images()] fail(dialog, {"code": "REQUIRED_FILES_REJECTED", "transfer_manifest_final": True, "items": failed_items, "required_sections": sections("failed"), "attachment_count": 2, "source_summary": {"diagnosis_count": 3}}) text = dialog._stream_bubble.transfer_status.text() assert "图片附件1(图片):提交失败" in text and "引用已提交" not in text assert "基本信息:无(提交失败)" in text and "诊单 3 条" in text assert dialog._stream_meta["source_summary"]["required_sections"] == sections("failed") assert dialog._stream_bubble._raw_payload.startswith("合成已有正文未刷新尾段") assert "合成必需资料提交失败" in dialog._stream_bubble._raw_payload assert not dialog._stream_completed and not dialog._stream_timeout_timer.isActive() emit(dialog, {"event": "done", "answer": "不得覆盖失败", "required_sections": sections()}) assert "不得覆盖失败" not in dialog._stream_bubble._raw_payload assert "引用已提交" not in dialog._stream_bubble.transfer_status.text() @pytest.mark.parametrize("code", ["REQUIRED_FILES_REJECTED", "REQUIRED_FILES_UNSUPPORTED", "REQUIRED_FILES_INVALID"]) @pytest.mark.parametrize("manifest", [{}, {"items": [], "required_sections": []}]) def test_legacy_required_file_error_without_manifest_fails_known_receipts_only(dialog, code, manifest): submit_images(dialog) dialog._stream_meta["items"].append( {"kind": "document", "label": "文档附件1", "status": "omitted"}, ) fail(dialog, {"code": code, **manifest}) text = dialog._stream_bubble.transfer_status.text() assert "图片附件1(图片):提交失败" in text and "引用已提交" not in text assert "文档附件1(文档):未提交" in text assert "基本信息:无(提交失败)" in text def test_error_manifest_without_final_marker_can_correct_failed_items(dialog): submit_images(dialog) fail(dialog, {"items": [{**item, "status": "failed"} for item in submitted_images()], "source_summary": {"required_sections": sections("failed")}}) text = dialog._stream_bubble.transfer_status.text() assert "图片附件1(图片):提交失败" in text and "引用已提交" not in text assert "基本信息:无(提交失败)" in text def test_failure_receipt_preserves_explicit_per_item_results(dialog): submit_images(dialog) emit(dialog, {"event": "progress", "phase": "attachments", "status": "failed", "required_sections": sections("failed"), "items": [{**submitted_images()[0], "status": "failed"}, submitted_images()[1]]}) text = dialog._stream_bubble.transfer_status.text() assert "图片附件1(图片):提交失败" in text assert "图片附件2(图片):引用已提交" in text def test_authoritative_failure_with_empty_manifest_can_replace_previous_items(dialog): submit_images(dialog) fail(dialog, {"code": "REQUIRED_FILES_INVALID", "transfer_manifest_final": True, "items": [], "attachment_count": 0, "required_sections": sections("failed")}) text = dialog._stream_bubble.transfer_status.text() assert "图片附件" not in text and "本请求附件通道:0 项" in text assert "基本信息:无(提交失败)" in text @pytest.mark.parametrize("data", [None, {"code": "UPSTREAM_STREAM_INTERRUPTED"}, {"source_summary": {"required_sections": sections("prepared")}, "items": [], "attachment_count": 0}]) def test_generation_failure_keeps_actual_submitted_receipts(dialog, data): submit_images(dialog) fail(dialog, data) text = dialog._stream_bubble.transfer_status.text() assert "图片附件1(图片):引用已提交" in text assert "基本信息:无(已提交)" in text assert "本请求附件通道:2 项" in text assert not dialog._stream_completed and not dialog._asking def test_failure_with_no_manifest_does_not_invent_sources_or_file_items(dialog): fail(dialog, {"code": "REQUIRED_FILES_REJECTED"}) text = dialog._stream_bubble.transfer_status.text() assert "资料栏目清单:服务器尚未回传。" in text assert "图片附件" not in text and "无(提交失败)" not in text def missing_image(): return {"kind": "image", "label": "图片附件1", "status": "skipped", "reason": "not_found"} def test_missing_file_stays_skipped_through_bulk_upload_submission_and_done(dialog): available = {"kind": "document", "label": "文档附件1", "status": "uploading"} emit(dialog, {"event": "progress", "phase": "attachments", "status": "uploading", "items": [missing_image(), available], "attachment_count": 2, "submitted_attachment_count": 0, "skipped_attachment_count": 1, "attachment_transfer": "uploaded_files", "required_sections": sections("prepared")}) assert "图片附件1(图片):文件不存在,已跳过" in dialog._stream_bubble.transfer_status.text() assert "文档附件1(文档):上传中" in dialog._stream_bubble.transfer_status.text() # Older bulk status transitions may still apply a uniform status to sources. bulk_items = [{**missing_image(), "status": "submitted"}, {**available, "status": "submitted"}] emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", "items": bulk_items, "attachment_count": 2, "submitted_attachment_count": 1, "skipped_attachment_count": 1, "required_sections": sections()}) emit(dialog, {"event": "done", "answer": "合成可用资料回复", "transfer_manifest_final": True, "items": bulk_items, "attachment_count": 2, "submitted_attachment_count": 1, "skipped_attachment_count": 1, "required_sections": sections()}) text = dialog._stream_bubble.transfer_status.text() assert "图片附件1(图片):文件不存在,已跳过" in text assert "文档附件1(文档):已上传并提交" in text assert "本请求附件通道:1 项" in text assert all(f"{label}:" in text for _, label in REQUIRED) assert "提交失败" not in text and "状态未回报" not in text assert dialog._stream_meta["items"][0] == missing_image() assert dialog._stream_meta["attachment_count"] == 2 assert dialog._stream_meta["required_sections"] == sections() assert dialog._stream_bubble._raw_payload == "合成可用资料回复" assert dialog._stream_completed and dialog.send_button.isEnabled() def test_all_missing_files_skip_upload_and_still_complete_text_reply(dialog): items = [missing_image(), {"kind": "document", "label": "文档附件1", "status": "skipped", "reason": "not_found"}] emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", "items": items, "attachment_count": 2, "submitted_attachment_count": 0, "skipped_attachment_count": 2, "required_sections": sections()}) text = dialog._stream_bubble.transfer_status.text() assert "资料正文已提交;不存在的附件已跳过,等待 AI 正文" in text assert "本次附件未提交" not in text and "附件引用已提交" not in text assert "本请求附件通道:0 项" in text emit(dialog, {"event": "delta", "text": "合成正文"}) emit(dialog, {"event": "done", "items": [], "attachment_count": 0, "submitted_attachment_count": 2, "skipped_attachment_count": 0, "required_sections": sections("prepared")}) text = dialog._stream_bubble.transfer_status.text() assert text.startswith("本次回复已完成。") assert text.count("文件不存在,已跳过") == 2 assert "本请求附件通道:0 项" in text assert "提交失败" not in text assert dialog._stream_meta["items"] == items assert dialog._stream_meta["attachment_count"] == 2 assert dialog._stream_meta["submitted_attachment_count"] == 0 assert dialog._stream_meta["skipped_attachment_count"] == 2 assert dialog._stream_meta["required_sections"] == sections() assert dialog._stream_bubble._raw_payload == "合成正文" assert dialog._stream_completed and dialog.send_button.isEnabled() @pytest.mark.parametrize("manifest", [None, {}, {"items": [], "required_sections": []}]) def test_terminal_submission_failure_never_converts_missing_file_to_failed(dialog, manifest): items = [missing_image(), {"kind": "document", "label": "文档附件1", "status": "submitted"}] emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", "items": items, "attachment_count": 2, "submitted_attachment_count": 1, "skipped_attachment_count": 1, "required_sections": sections()}) receipt = {"code": "REQUIRED_FILES_REJECTED"} if manifest is None: receipt.update({"transfer_manifest_final": True, "items": [{**item, "status": "failed"} for item in items], "attachment_count": 2, "submitted_attachment_count": 0, "skipped_attachment_count": 1, "required_sections": sections("failed")}) else: receipt.update(manifest) fail(dialog, receipt) text = dialog._stream_bubble.transfer_status.text() assert "图片附件1(图片):文件不存在,已跳过" in text assert "文档附件1(文档):提交失败" in text assert "基本信息:无(提交失败)" in text assert dialog._stream_meta["items"][0] == missing_image() assert not dialog._stream_completed and dialog.send_button.isEnabled() def test_missing_file_in_error_receipt_is_not_hidden_by_prior_preparation(dialog): emit(dialog, {"event": "progress", "phase": "attachments", "status": "uploading", "items": [{**missing_image(), "status": "uploading"}], "attachment_count": 1, "submitted_attachment_count": 1, "skipped_attachment_count": 0, "required_sections": sections("prepared")}) fail(dialog, {"code": "UPSTREAM_STREAM_INTERRUPTED", "items": [missing_image()], "attachment_count": 1, "submitted_attachment_count": 0, "skipped_attachment_count": 1, "required_sections": sections()}) text = dialog._stream_bubble.transfer_status.text() assert "图片附件1(图片):文件不存在,已跳过" in text assert "本请求附件通道:0 项" in text assert "生命体征:已提交" in text assert dialog._stream_meta["submitted_attachment_count"] == 0 assert dialog._stream_meta["skipped_attachment_count"] == 1 @pytest.mark.parametrize("submitted_count", [None, True, -1, "0", 1.5]) def test_skipped_file_count_fallback_excludes_missing_files(submitted_count): text = module._transfer_description({ "items": [missing_image(), {"kind": "document", "label": "文档附件1", "status": "submitted"}], "attachment_count": 2, "submitted_attachment_count": submitted_count, }, "合成状态") assert "本请求附件通道:1 项" in text