This commit is contained in:
Your Name
2026-10-23 10:17:09 +08:00
parent 1cbe8bfe54
commit e974d3cfa5
15 changed files with 1501 additions and 71 deletions
@@ -0,0 +1,219 @@
<?php
declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
use app\adminapi\logic\tcm\PatientAiReportLogic;
use app\adminapi\service\AiRequiredSource;
use app\common\service\NihaixiaClinicalSkill;
function requiredSourceExpect(bool $ok, string $message): void
{
if (!$ok) throw new RuntimeException($message);
}
/** In-memory database peer: exercises the production loader without any connection. */
final class RequiredSourceDb
{
public static array $tables = [];
public static array $queries = [];
public static function name(string $table): RequiredSourceQuery
{
return new RequiredSourceQuery($table);
}
}
final class RequiredSourceQuery
{
private array $and = [];
private array $or = [];
private array $orders = [];
private array $result = [];
public function __construct(private string $table) {}
public function whereIn(string $field, array $values): self
{
RequiredSourceDb::$queries[] = [$this->table, 'whereIn', $field, $values];
$this->and[] = static fn (array $row): bool => in_array($row[$field] ?? null, $values);
return $this;
}
public function where($field, $value = null): self
{
if (is_callable($field)) {
$group = new self($this->table);
$field($group);
$this->and[] = static fn (array $row): bool => $group->matches($row);
} else {
$this->and[] = static fn (array $row): bool => ($row[$field] ?? null) == $value;
}
return $this;
}
public function whereOr(string $field, $value): self
{
$this->or[] = static fn (array $row): bool => ($row[$field] ?? null) == $value;
return $this;
}
public function whereNull(string $field): self
{
$this->and[] = static fn (array $row): bool => ($row[$field] ?? null) === null;
return $this;
}
public function order(string $field, string $direction): self
{
$this->orders[] = [$field, $direction];
return $this;
}
public function field(array $fields): self { return $this; }
public function getTableFields(): array { return ['id', 'patient_id', 'diagnosis_id']; }
public function limit(...$args): self { throw new RuntimeException('Mandatory sources cannot paginate'); }
public function select(): self
{
$this->result = array_values(array_filter(RequiredSourceDb::$tables[$this->table] ?? [],
fn (array $row): bool => $this->matches($row)));
usort($this->result, function (array $a, array $b): int {
foreach ($this->orders as [$field, $direction]) {
$cmp = ($a[$field] ?? null) <=> ($b[$field] ?? null);
if ($cmp !== 0) return $direction === 'desc' ? -$cmp : $cmp;
}
return 0;
});
return $this;
}
public function toArray(): array { return $this->result; }
public function matches(array $row): bool
{
$and = true;
foreach ($this->and as $check) $and = $and && $check($row);
if ($and) return true;
foreach ($this->or as $check) if ($check($row)) return true;
return false;
}
}
requiredSourceExpect(class_alias(RequiredSourceDb::class, 'think\\facade\\Db'), 'isolated DB peer is installed');
$reflection = new ReflectionClass(PatientAiReportLogic::class);
$build = $reflection->getMethod('buildSourceSnapshotFromRows');
$load = $reflection->getMethod('buildSourceSnapshot');
$sanitize = $reflection->getMethod('sanitizeSnapshotForUpstream');
$filesMethod = $reflection->getMethod('collectUpstreamFiles');
$now = time();
$longNote = str_repeat('保留全部文件备注内容。', 15000) . '备注终点标记';
$diagnoses = [[
'id' => 101, 'patient_id' => 88, 'patient_name' => '合成测试身份',
'phone' => '13812345678', 'id_card' => '11010519491231002X', 'gender' => 0, 'age' => 52,
'diagnosis_date' => 1700000000, 'height' => 165, 'weight' => 60,
'systolic_pressure' => 128, 'diastolic_pressure' => 82,
'chief_complaint' => '主诉完整标记', 'present_illness' => '现病史完整标记',
'past_history' => 'custom_history', 'appetite' => ['dry', 'bitter'],
'trauma_history' => 0, 'allergy_history' => 1, 'family_history' => 0,
'clinical_diagnosis' => '诊断完整标记', 'remark' => '诊断补充标记',
'current_medications' => '在用药物完整标记', 'create_source' => 'manual', 'show_card' => 0,
]];
$blood = [];
for ($index = 1; $index <= 240; ++$index) {
$blood[] = ['id' => $index, 'diagnosis_id' => 101, 'patient_id' => 88,
'record_date' => 1700000000 + $index * 86400, 'record_time' => '08:00',
'record_time_estimated' => 1, 'record_time_period' => '早晨', 'record_time_text' => '晨起约八点',
'followup_audio_task_id' => 11, 'fasting_blood_sugar' => '7.1',
'postprandial_blood_sugar' => '8.2', 'other_blood_sugar' => '6.5',
'systolic_pressure' => 123, 'diastolic_pressure' => 78,
'western_medicine' => "西药完整标记{$index}", 'insulin' => "胰岛素完整标记{$index}"];
}
$calls = [
['id' => 11, 'diagnosis_id' => 101, 'call_type' => 2, 'status' => 2, 'start_time' => $now - 3600,
'end_time' => $now - 3000, 'transcription_session_id' => 'bound-session',
'recording_urls' => ['https://assets.test/history.mp4'], 'transcript_text' => '既往视频回退文字'],
['id' => 12, 'diagnosis_id' => 101, 'call_type' => 2, 'status' => 1, 'transcript_text' => '当前直播不得提交'],
['id' => 13, 'diagnosis_id' => 101, 'call_type' => 1, 'status' => 2, 'transcript_text' => '语音通话不得提交'],
['id' => 14, 'diagnosis_id' => 101, 'call_type' => 2, 'status' => 3, 'transcript_text' => '未接通不得提交'],
['id' => 15, 'diagnosis_id' => 101, 'call_type' => 2, 'status' => 2, 'start_time' => $now + 1000, 'transcript_text' => '未来不得提交'],
['id' => 16, 'diagnosis_id' => 101, 'call_type' => 2, 'status' => 2, 'delete_time' => 1, 'transcript_text' => '已删不得提交'],
['id' => 17, 'diagnosis_id' => 999, 'call_type' => 2, 'status' => 2, 'transcript_text' => '越权不得提交'],
];
RequiredSourceDb::$tables = [
'dict_data' => [['type_value' => 'past_history', 'value' => 'custom_history', 'name' => '自定义既往史完整标记'],
['type_value' => 'appetite', 'value' => 'dry', 'name' => '口干'],
['type_value' => 'appetite', 'value' => 'bitter', 'name' => '口苦']],
'doctor_note' => [['id' => 1, 'diagnosis_id' => 101, 'note_date' => '2020-01-01', 'content' => $longNote,
'tongue_images' => ['https://assets.test/note1.jpg', 'https://assets.test/ignored.mp4'],
'report_files' => ['https://assets.test/note1.pdf', ['url' => 'https://assets.test/opaque', 'mime_type' => 'video/mp4']]],
['id' => 2, 'diagnosis_id' => 101, 'content' => '纯文字医生备注完整标记'],
['id' => 3, 'diagnosis_id' => 999, 'content' => '越权备注不得提交']],
'tracking_note' => [['id' => 3, 'diagnosis_id' => 101, 'content' => '跟踪备注完整标记']],
'tcm_blood_record' => $blood,
'patient_diet_record' => [['id' => 1, 'diagnosis_id' => 101, 'patient_id' => 88, 'record_time' => '12:00',
'breakfast' => '旧早餐完整标记', 'lunch_foods' => '午餐完整标记', 'dinner_foods' => '晚餐完整标记']],
'patient_exercise_record' => [['id' => 1, 'diagnosis_id' => 101, 'patient_id' => 88, 'record_time' => '17:00',
'exercise_type' => '运动完整标记', 'duration' => 35, 'intensity' => 2, 'note' => '运动备注完整标记']],
'tcm_diagnosis_todo' => [['id' => 1, 'diagnosis_id' => 101, 'patient_id' => 88, 'content' => '日常待办完整标记', 'status' => 0],
['id' => 2, 'diagnosis_id' => 999, 'patient_id' => 99, 'content' => '越权待办不得提交']],
'tcm_prescription' => [['id' => 1, 'diagnosis_id' => 101, 'patient_id' => 88, 'prescription_name' => '既往处方完整标记',
'herbs' => [['name' => '测试药味', 'dosage' => 1]], 'audit_status' => 1, 'void_status' => 0]],
'tcm_im_chat_message' => [['id' => 1, 'diagnosis_id' => 101, 'patient_id' => 88,
'from_account' => 'patient_88', 'to_account' => 'doctor_7', 'msg_type' => 'composite',
'text' => json_encode([['msg_type' => 'text', 'text' => '复合聊天完整标记'],
['msg_type' => 'image', 'image_url' => 'https://assets.test/chat.jpg'],
['msg_type' => 'file', 'file_url' => 'https://assets.test/chat.pdf'],
['msg_type' => 'video', 'file_url' => 'https://assets.test/download/opaque-part']], JSON_UNESCAPED_UNICODE)],
['id' => 2, 'diagnosis_id' => 101, 'patient_id' => 88, 'from_account' => 'patient_99',
'to_account' => 'doctor_7', 'text' => '错绑聊天不得提交'],
['id' => 3, 'diagnosis_id' => 101, 'patient_id' => 88, 'from_account' => 'patient_88',
'to_account' => 'doctor_7', 'msg_type' => 'video', 'file_url' => 'https://assets.test/download/opaque-im', 'text' => '视频附带说明完整标记'],
['id' => 4, 'diagnosis_id' => 101, 'patient_id' => 88, 'from_account' => 'patient_88',
'to_account' => 'doctor_7', 'msg_type' => 'file', 'file_name' => 'clip.MP4', 'file_url' => 'https://assets.test/download/opaque-file']],
'wechat_chat_record' => [['id' => 1, 'diagnosis_id' => 101, 'patient_id' => 88, 'content' => '企微聊天完整标记'],
['id' => 2, 'diagnosis_id' => 101, 'patient_id' => 88, 'msg_type' => 'video', 'media_url' => 'https://assets.test/download/opaque-wechat']],
'tcm_call_record' => $calls,
'tcm_call_transcript_segment' => [
['id' => 1, 'call_record_id' => 11, 'transcription_session_id' => 'bound-session', 'speaker_role' => 'doctor', 'timestamp_ms' => 1000, 'text' => '历史视频医生完整标记'],
['id' => 2, 'call_record_id' => 11, 'transcription_session_id' => 'bound-session', 'speaker_role' => 'patient', 'timestamp_ms' => 2000, 'text' => '历史视频患者完整标记'],
['id' => 3, 'call_record_id' => 12, 'speaker_role' => 'patient', 'text' => '直播片段不得提交'],
['id' => 4, 'call_record_id' => 17, 'speaker_role' => 'patient', 'text' => '越权片段不得提交'],
['id' => 5, 'call_record_id' => 11, 'transcription_session_id' => 'stale-session', 'text' => '旧会话片段不得提交']],
];
$snapshot = $load->invoke(null, 88, $diagnoses);
$manifest = $snapshot['source_summary']['required_sections'];
requiredSourceExpect(array_column($manifest, 'key') === array_keys(AiRequiredSource::LABELS), 'every required section appears in fixed order');
foreach ($manifest as $section) requiredSourceExpect($section['availability'] === 'present', $section['key'] . ' has its actual records');
requiredSourceExpect($snapshot['diagnoses'][0]['past_history_text'] === '自定义既往史完整标记', 'dictionary labels are loaded without dropping source codes');
requiredSourceExpect($snapshot['diagnoses'][0]['trauma_history_text'] === '无', 'documented negative history is explicitly labelled');
requiredSourceExpect(count($snapshot['daily_records']['blood_glucose_pressure']) === 240, 'all old and same-day daily rows are retained without UI window or pagination');
requiredSourceExpect(count($snapshot['video_calls']) === 1 && $snapshot['source_summary']['transcript_segment_count'] === 2,
'only authorized ended past video and its segments are included');
$safe = $sanitize->invoke(null, AiRequiredSource::submission($snapshot));
$json = json_encode($safe, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
foreach (['主诉完整标记', '现病史完整标记', '自定义既往史完整标记', '诊断完整标记', '诊断补充标记',
'在用药物完整标记', '备注终点标记', '纯文字医生备注完整标记', '跟踪备注完整标记', '日常待办完整标记',
'西药完整标记1', '西药完整标记240', '胰岛素完整标记240', '晨起约八点', '旧早餐完整标记', '午餐完整标记',
'晚餐完整标记', '运动完整标记', '运动备注完整标记', '既往处方完整标记', '复合聊天完整标记', '企微聊天完整标记',
'历史视频医生完整标记', '历史视频患者完整标记', '视频附带说明完整标记'] as $marker) {
requiredSourceExpect(str_contains($json, $marker), $marker . ' survives complete model projection');
}
foreach (['当前直播不得提交', '直播片段不得提交', '语音通话不得提交', '未接通不得提交', '未来不得提交',
'已删不得提交', '越权不得提交', '越权备注不得提交', '越权待办不得提交', '越权片段不得提交', '旧会话片段不得提交', '错绑聊天不得提交',
'13812345678', '11010519491231002X', '合成测试身份', 'assets.test'] as $forbidden) {
requiredSourceExpect(!str_contains($json, $forbidden), $forbidden . ' is not exposed to the model');
}
$files = $filesMethod->invoke(null, $snapshot);
requiredSourceExpect(count($files) === 4 && array_column($files, 'type') === ['image', 'document', 'image', 'document'],
'doctor notes and nested composite chat both contribute actual non-video files');
$empty = $sanitize->invoke(null, AiRequiredSource::submission($build->invoke(null, [])));
foreach ($empty['required_content'] as $section) requiredSourceExpect($section['value'] === '无', $section['key'] . ' is explicitly submitted as 无 when absent');
requiredSourceExpect(count($empty['required_content']) === 13, 'empty input never omits a required category');
$sparse = $build->invoke(null, ['diagnoses' => [['id' => 101, 'clinical_diagnosis' => '有诊断但无附件',
'tongue_images' => [], 'report_files' => [], 'family_history' => '无']]]);
$safeSparse = $sanitize->invoke(null, AiRequiredSource::submission($sparse));
$diagnosisSection = array_values(array_filter($safeSparse['required_content'], static fn (array $section): bool => $section['key'] === 'diagnosis_info'))[0];
requiredSourceExpect($diagnosisSection['value'][0]['tongue_images']['attachment_count'] === 0
&& $diagnosisSection['value'][0]['report_files']['attachment_count'] === 0, 'empty attachment markers never invent one file');
$historySection = array_values(array_filter($safeSparse['required_content'], static fn (array $section): bool => $section['key'] === 'other_history'))[0];
requiredSourceExpect($historySection['value'][0]['family_history'] === '无', 'explicit negative history remains a source fact');
foreach ([['unknown_attachment_key' => 'opaque'], 'javascript:synthetic-invalid'] as $invalidFile) {
$rejected = false;
try { $filesMethod->invoke(null, ['doctor_notes' => [['report_files' => [$invalidFile]]]]); }
catch (RuntimeException $error) { $rejected = true; }
requiredSourceExpect($rejected, 'an invalid required source fails instead of disappearing silently');
}
requiredSourceExpect(NihaixiaClinicalSkill::knowledgeSourceForPromptVersion('patient-longitudinal-report-required-sources-v5') !== null,
'new persisted patient report version retains clinical knowledge provenance');
echo "Required AI source loader / full clinical projection / empty markers / history-only video / no binary video: OK\n";
@@ -42,7 +42,8 @@ namespace {
$options = ['should_abort' => static fn (): bool => $GLOBALS['lifecycleCancelled'],
'on_authorized' => static function (array $metadata): bool {
$GLOBALS['lifecycle'][] = 'start';
lifecycleExpect($metadata === ['diagnosis_id' => 11, 'task' => 'summary', 'model_key' => 'qwen'], 'early start exposes only authorized identity and model key');
lifecycleExpect($metadata === ['diagnosis_id' => 11, 'task' => 'summary', 'model_key' => 'qwen', 'required_sections' => []],
'early start exposes authorized identity and no unaggregated section claims');
return true;
},
'on_progress' => static function (array $event): void { $GLOBALS['lifecycle'][] = $event; }];
@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace think\facade {
class Cache {
public static array $entries = [];
public static function get(string $key) { return self::$entries[$key] ?? null; }
public static function set(string $key, $value, int $ttl): void { self::$entries[$key] = $value; }
}
class Log { public static function warning(string $message, array $context = []): void {} }
}
namespace app\adminapi\service {
function config(string $key): array { return ['context_compaction_cache_ttl' => 300]; }
}
namespace app\adminapi\logic\firstvisit {
class MyPatientLogic {
public static function canAccessDiagnosis($id, $adminId, $adminInfo): bool { ++$GLOBALS['requiredScopeChecks']; return true; }
}
}
namespace app\adminapi\logic\tcm {
function config(string $key): array { return ['timeout' => 5, 'models' => ['qwen' => ['name' => 'synthetic', 'label' => '合成模型']]]; }
class DiagnosisLogic {
public static function detail($params, $adminInfo): array { return ['id' => $params['id'], 'patient_id' => 99, 'gender' => '女', 'age' => 42]; }
}
class PatientAiReportLogic {
public static function contextForAuthorizedDiagnosis($diagnosis, $adminId, $adminInfo): array {
++$GLOBALS['requiredAggregates'];
return ['snapshot' => ['required_sections' => $GLOBALS['requiredRawSections'],
'synthetic_history' => str_repeat('合成无真实患者资料。', 9000) . $GLOBALS['requiredRevision']],
'source_summary' => ['required_sections' => $GLOBALS['requiredMetadata'], 'snapshot_complete' => true],
'source_diagnosis_ids' => [11, 12], 'files' => array_fill(0, 8,
['type' => 'document', 'url' => 'https://synthetic.invalid/required.pdf'])];
}
public static function compactSourceForPrompt(string $profile, string $source, array $options): array {
++$GLOBALS['requiredCompactions'];
foreach ($GLOBALS['requiredMetadata'] as $section) {
\contextRequiredExpect(str_contains($source, $section['label']), 'every required section enters the complete evidence extraction source');
}
if ($GLOBALS['requiredCancelInCompaction']) $GLOBALS['requiredContextCancelled'] = true;
return ['text' => '逐片合成证据摘要。', 'chunk_count' => 4, 'reduction_rounds' => 1,
'source_bytes' => strlen($source), 'compacted' => true];
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use app\adminapi\logic\tcm\DiagnosisAiLogic;
use think\facade\Cache;
function contextRequiredExpect(bool $ok, string $message): void { if (!$ok) throw new RuntimeException($message); }
$requiredMetadata = []; $requiredRawSections = [];
foreach (['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' => '聊天'] as $key => $label) {
$empty = in_array($key, ['other_history', 'chat'], true);
$requiredMetadata[] = ['key' => $key, 'label' => $label, 'count' => $empty ? 0 : 1,
'availability' => $empty ? 'empty' : 'present', 'status' => 'prepared'];
$requiredRawSections[$key] = ['label' => $label, 'content' => $empty ? '无' : '合成记录'];
}
$requiredScopeChecks = 0; $requiredAggregates = 0; $requiredCompactions = 0; $requiredRevision = 'revision-1';
$requiredContextCancelled = false; $requiredCancelInCompaction = false;
$prepare = static function (): array|null {
$events = []; $started = null;
$result = DiagnosisAiLogic::prepareAssistant(11, 'summary', '', 7, ['root' => 1], null,
['should_abort' => static fn (): bool => $GLOBALS['requiredContextCancelled'],
'on_authorized' => static function (array $metadata) use (&$started): bool { $started = $metadata; return true; },
'on_progress' => static function (array $event) use (&$events): void { $events[] = $event; }]);
if ($result !== null) {
contextRequiredExpect($started['required_sections'] === [], 'start makes no section availability claims before aggregation');
contextRequiredExpect(count($events[1]['required_sections']) === 13 && count(end($events)['required_sections']) === 13,
'aggregation and prepared progress carry every mandatory section');
}
return $result;
};
$prepared = $prepare();
contextRequiredExpect(is_array($prepared) && $prepared['source_form'] === 'evidence_summary' && !$prepared['evidence_cache_hit'], 'large source is fully covered by evidence extraction');
foreach ($requiredMetadata as $section) {
contextRequiredExpect(str_contains($prepared['query'], $section['label']) && str_contains($prepared['inputs']['herbs_json'], $section['label']),
'required column survives compaction in both model input channels');
}
contextRequiredExpect(str_contains($prepared['query'], '其他病史:无') && str_contains($prepared['query'], '聊天:无'), 'empty required sections remain explicit no-data body entries');
contextRequiredExpect(count($prepared['required_sections']) === 13 && $prepared['required_sections'][0]['status'] === 'prepared', 'preparation never reports submission');
$cached = $prepare();
contextRequiredExpect($cached['evidence_cache_hit'] && $requiredCompactions === 1 && $requiredScopeChecks === 2 && $requiredAggregates === 2,
'cache reuse follows fresh scope authorization and complete live aggregation');
contextRequiredExpect($cached['required_sections'] === $prepared['required_sections'] && str_contains($cached['query'], '聊天:无')
&& count($cached['files']) === 8 && count($prepared['files']) === 8, 'cache cannot remove required source manifest or attachments');
$requiredRevision = 'revision-2'; $requiredCancelInCompaction = true;
contextRequiredExpect($prepare() === null && DiagnosisAiLogic::getAssistantErrorCode() === 'AI_ASSISTANT_CANCELLED'
&& count(Cache::$entries) === 1, 'cancelled evidence extraction is not cached or promoted to ready');
echo "Diagnosis AI required source prepare / compaction / cache / explicit empty context: OK\n";
}
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace think\facade {
class Log { public static function warning(string $message): void {} }
}
namespace app\common\service {
function config(string $name): array { return $GLOBALS['loopbackRequiredConfig']; }
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use app\common\service\DifyChatService;
function loopbackRequiredExpect(bool $ok, string $message): void { if (!$ok) throw new RuntimeException($message); }
if (($argv[1] ?? '') === 'server') {
$listener = stream_socket_server('tcp://127.0.0.1:0', $error, $message);
if ($listener === false) exit(2);
echo json_encode(['address' => stream_socket_get_name($listener, false)]) . "\n";
flush();
$client = stream_socket_accept($listener, 5);
if ($client === false) { fclose($listener); exit(3); }
stream_set_timeout($client, 5);
$wire = '';
while (!str_contains($wire, "\r\n\r\n")) {
$chunk = fread($client, 8192);
if ($chunk === '' || $chunk === false) break;
$wire .= $chunk;
}
[$headers, $body] = array_pad(explode("\r\n\r\n", $wire, 2), 2, '');
preg_match('/\r\nContent-Length:\s*(\d+)/i', $headers, $length);
$expected = (int) ($length[1] ?? 0);
while (strlen($body) < $expected) {
$chunk = fread($client, $expected - strlen($body));
if ($chunk === '' || $chunk === false) break;
$body .= $chunk;
}
$payload = json_decode($body, true);
$stream = ($payload['response_mode'] ?? '') === 'streaming' || !empty($payload['stream']);
$status = ($argv[2] ?? '') === 'reject' ? 413 : 200;
$response = $status === 413 ? '{"code":"invalid_param"}'
: ($stream ? "data: {\"event\":\"message\",\"answer\":\"synthetic-answer\"}\n\ndata: {\"event\":\"message_end\"}\n\n" : '{"answer":"synthetic-answer"}');
fwrite($client, 'HTTP/1.1 ' . $status . " Synthetic\r\nContent-Type: " . ($stream ? 'text/event-stream' : 'application/json')
. "\r\nContent-Length: " . strlen($response) . "\r\nConnection: close\r\n\r\n" . $response);
fclose($client); fclose($listener);
echo json_encode(['payload' => $payload, 'body_bytes' => strlen($body), 'expected_body_bytes' => $expected], JSON_UNESCAPED_SLASHES) . "\n";
exit;
}
$files = [];
for ($index = 1; $index <= 8; ++$index) $files[] = ['type' => $index <= 4 ? 'image' : 'document',
'url' => 'https://synthetic.invalid/required-' . $index . ($index <= 4 ? '.png' : '.pdf')];
$files[] = ['type' => 'video', 'url' => 'https://synthetic.invalid/not-transmitted.mp4'];
$sections = [['key' => 'chat', 'label' => '聊天', 'count' => 0, 'availability' => 'empty', 'status' => 'prepared']];
foreach (['blocking', 'streaming', 'reject'] as $scenario) {
$process = proc_open([PHP_BINARY, __FILE__, 'server', $scenario],
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, null, ['bypass_shell' => true]);
loopbackRequiredExpect(is_resource($process), 'loopback peer starts');
$ready = json_decode((string) fgets($pipes[1]), true);
loopbackRequiredExpect(is_string($ready['address'] ?? null), 'loopback peer supplies ephemeral port');
$loopbackRequiredConfig = ['enable' => true, 'base_url' => 'http://' . $ready['address'] . '/v1/chat-messages',
'timeout' => 5, 'max_files' => 3, 'models' => ['qwen' => ['name' => 'synthetic', 'api_key' => 'loopback-fixture-only']]];
$options = ['required_files' => true, 'required_sections' => $sections, 'knowledge_mode' => 'evidence'];
$result = $scenario === 'streaming'
? DifyChatService::streamChat('qwen', [], '合成资料;聊天:无', 'synthetic-user', static fn (string $delta): bool => true, null, $files, $options)
: DifyChatService::chat('qwen', [], '合成资料;聊天:无', 'synthetic-user', $files, $options);
$captured = json_decode((string) fgets($pipes[1]), true);
fclose($pipes[0]); fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]); fclose($pipes[2]);
$exit = proc_close($process);
loopbackRequiredExpect($exit === 0 && $stderr === '', 'loopback peer exits cleanly');
loopbackRequiredExpect($captured['body_bytes'] === $captured['expected_body_bytes']
&& count($captured['payload']['files']) === 8, 'actual HTTP body carries all eight required attachments with complete Content-Length');
loopbackRequiredExpect(!str_contains(json_encode($captured['payload']), 'not-transmitted.mp4')
&& str_contains($captured['payload']['query'], '聊天:无'), 'actual HTTP wire contains explicit empty text and no video');
if ($scenario === 'reject') loopbackRequiredExpect(($result['error_code'] ?? '') === 'REQUIRED_FILES_REJECTED', 'real 413 terminates as required data failure');
else loopbackRequiredExpect(!empty($result['ok']) && $result['attachment_count'] === 8
&& $result['required_sections'][0]['status'] === 'submitted', 'actual successful HTTP delivery has final complete manifest');
}
echo "Dify required sources actual loopback HTTP blocking / streaming / hard-limit rejection: OK\n";
}
@@ -0,0 +1,149 @@
<?php
declare(strict_types=1);
namespace think\facade {
class Log { public static function warning(string $message): void {} }
}
namespace app\common\service {
require __DIR__ . '/fixtures/CancellableCurlMultiStub.php';
function config(string $name): array { return $GLOBALS['requiredConfig']; }
function curl_init(): \stdClass { return new \stdClass(); }
function curl_setopt_array(\stdClass $handle, array $options): bool {
$handle->options = $options;
$handle->payload = json_decode($options[CURLOPT_POSTFIELDS], true);
$handle->url = $options[CURLOPT_URL];
return true;
}
function curl_exec(\stdClass $handle): string|bool {
$payload = $handle->payload;
$stream = ($payload['response_mode'] ?? '') === 'streaming' || !empty($payload['stream']);
$GLOBALS['requiredRequests'][] = ['url' => $handle->url, 'payload' => $payload];
$scenario = $GLOBALS['requiredScenario'];
$handle->code = $scenario === 'reject' ? 413 : ($scenario === 'input_rejected' && !empty($payload['inputs']) ? 400
: ($scenario === 'fallback' && str_ends_with($handle->url, '/chat-messages') ? 404 : 200));
if (isset($handle->options[CURLOPT_HEADERFUNCTION])) {
($handle->options[CURLOPT_HEADERFUNCTION])($handle, 'HTTP/1.1 ' . $handle->code . " Synthetic\r\n");
}
if ($scenario === 'cancel') $GLOBALS['requiredCancelled'] = true;
$progress = $handle->options[defined('CURLOPT_XFERINFOFUNCTION') ? CURLOPT_XFERINFOFUNCTION : CURLOPT_PROGRESSFUNCTION] ?? null;
if (is_callable($progress) && $progress($handle, 0, 0, 100, 100)) return false;
if ($handle->code !== 200) return $stream ? true : '{}';
if (!$stream) return json_encode(['answer' => '合成回答']);
$write = $handle->options[CURLOPT_WRITEFUNCTION];
if (str_ends_with($handle->url, '/chat-messages')) {
$write($handle, 'data: ' . json_encode(['event' => 'message', 'answer' => '合成回答']) . "\n\n");
$write($handle, "data: {\"event\":\"message_end\"}\n\n");
} else {
$write($handle, 'data: ' . json_encode(['choices' => [['delta' => ['content' => '合成回答']]]]) . "\n\n");
$write($handle, "data: [DONE]\n\n");
}
return true;
}
function curl_errno(\stdClass $handle): int { return 0; }
function curl_getinfo(\stdClass $handle, int $option): int { return $handle->code; }
function curl_close(\stdClass $handle): void { ++$GLOBALS['requiredClosed']; }
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use app\common\service\DifyChatService;
use app\adminapi\logic\tcm\DiagnosisAiLogic;
use app\adminapi\service\AssistantSseTiming;
function requiredExpect(bool $ok, string $message): void { if (!$ok) throw new RuntimeException($message); }
$requiredConfig = ['enable' => true, 'base_url' => 'https://synthetic.invalid/v1/chat-messages', 'timeout' => 5,
'max_files' => 3, 'models' => ['qwen' => ['name' => 'synthetic', 'api_key' => 'fixture-only']]];
$reset = static function (string $scenario = 'success'): void {
$GLOBALS['requiredScenario'] = $scenario; $GLOBALS['requiredRequests'] = [];
$GLOBALS['requiredCancelled'] = false; $GLOBALS['requiredClosed'] = 0;
};
$sections = [];
foreach (['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'] as $key) {
$sections[] = ['key' => $key, 'label' => $key, 'count' => $key === 'chat' ? 0 : 1,
'availability' => $key === 'chat' ? 'empty' : 'present', 'status' => 'prepared'];
}
$files = [];
for ($id = 1; $id <= 8; ++$id) $files[] = ['type' => $id <= 4 ? 'image' : 'document',
'url' => 'https://synthetic.invalid/fixture-' . $id . ($id <= 4 ? '.png' : '.pdf')];
$options = ['required_files' => true, 'knowledge_mode' => 'evidence',
'required_sections' => $sections, 'source_summary' => ['required_sections' => $sections]];
foreach ([false, true] as $streaming) {
$reset(); $events = [];
$withProgress = $options + ['on_progress' => static function (array $event) use (&$events): void { $events[] = $event; }];
$withVideos = array_merge($files, [['type' => 'video', 'url' => 'https://synthetic.invalid/record.mp4'],
['type' => 'document', 'url' => 'https://synthetic.invalid/disguised.MOV'],
['type' => 'image', 'url' => 'https://synthetic.invalid/opaque', 'mime_type' => 'video/webm']]);
$result = $streaming
? DifyChatService::streamChat('qwen', [], '合成资料;聊天:无', 'synthetic-user', static fn (string $text): bool => true, null, $withVideos, $withProgress)
: DifyChatService::chat('qwen', [], '合成资料;聊天:无', 'synthetic-user', $withVideos, $withProgress);
requiredExpect(!empty($result['ok']) && count($requiredRequests) === 1, 'required request succeeds exactly once');
requiredExpect(count($requiredRequests[0]['payload']['files']) === 8 && $result['transmitted_file_count'] === 8,
'all eight images/documents reach serialized wire payload despite default max_files=3');
requiredExpect(array_column($requiredRequests[0]['payload']['files'], 'url') === array_column($files, 'url'), 'video references never enter payload');
requiredExpect($result['transfer_manifest_final'] === true && $result['attachment_count'] === 8
&& array_unique(array_column($result['items'], 'status')) === ['submitted'], 'final attachment manifest reflects actual complete payload');
requiredExpect(count($result['required_sections']) === 13
&& array_unique(array_column($result['required_sections'], 'status')) === ['submitted']
&& $result['required_sections'][12]['availability'] === 'empty', 'empty required text section is explicitly submitted, not omitted');
requiredExpect($events[0]['required_sections'][0]['status'] === 'submitting'
&& $events[1]['source_summary']['required_sections'][0]['status'] === 'submitted', 'progress moves actual source manifest from submitting to submitted');
$reset('reject');
$result = $streaming
? DifyChatService::streamChat('qwen', [], '合成资料', 'synthetic-user', static fn (string $text): bool => true, null, $files, $options)
: DifyChatService::chat('qwen', [], '合成资料', 'synthetic-user', $files, $options);
requiredExpect(($result['error_code'] ?? '') === 'REQUIRED_FILES_REJECTED' && count($requiredRequests) === 1
&& count($requiredRequests[0]['payload']['files']) === 8, 'hard provider limit fails explicitly without stripping files');
}
foreach ([['type' => 'unknown', 'url' => 'https://synthetic.invalid/file'], ['type' => 'image', 'url' => 'invalid'],
['type' => 'custom', 'url' => 'https://synthetic.invalid/file'], ['type' => 'image', 'url' => 'https://synthetic.invalid/a.png', 'transfer_method' => 'local_file']] as $invalid) {
$reset(); $result = DifyChatService::chat('qwen', [], '合成资料', 'synthetic-user', [$invalid], $options);
requiredExpect(($result['error_code'] ?? '') === 'REQUIRED_FILES_INVALID' && $requiredRequests === [], 'invalid/unknown mandatory files fail before network');
}
foreach ([false, true] as $streaming) {
$reset('input_rejected');
$result = $streaming
? DifyChatService::streamChat('qwen', ['synthetic_undeclared' => 'value'], '合成正文', 'synthetic-user', static fn (string $text): bool => true, null, $files, $options)
: DifyChatService::chat('qwen', ['synthetic_undeclared' => 'value'], '合成正文', 'synthetic-user', $files, $options);
requiredExpect(!empty($result['ok']) && count($requiredRequests) === 2
&& count($requiredRequests[0]['payload']['files']) === 8 && count($requiredRequests[1]['payload']['files']) === 8,
'undeclared Dify inputs retry preserves complete required files and query');
}
$reset();
$fallbackOptions = array_replace($options, ['required_sections' => []]);
$result = DifyChatService::chat('qwen', [], '合成正文', 'synthetic-user', [], $fallbackOptions);
requiredExpect(count($result['required_sections']) === 13 && $result['attachment_count'] === 0,
'source_summary manifest fallback keeps all text sections when attachment list is empty');
$requiredConfig['base_url'] = 'https://synthetic.invalid/v1/chat/completions';
$reset(); $result = DifyChatService::chat('qwen', [], '合成资料', 'synthetic-user', $files, $options);
requiredExpect(($result['error_code'] ?? '') === 'REQUIRED_FILES_UNSUPPORTED' && $requiredRequests === [], 'OpenAI documents fail before unsupported transmission');
$reset(); $result = DifyChatService::chat('qwen', [], '合成资料', 'synthetic-user', array_slice($files, 0, 4), $options);
requiredExpect(!empty($result['ok']) && count($requiredRequests[0]['payload']['messages'][0]['content']) === 5, 'all four OpenAI image_url parts are serialized');
$requiredConfig['base_url'] = 'https://synthetic.invalid/v1';
$reset('fallback'); $result = DifyChatService::chat('qwen', [], '合成资料', 'synthetic-user', $files, $options);
requiredExpect(($result['error_code'] ?? '') === 'REQUIRED_FILES_UNSUPPORTED' && count($requiredRequests) === 1, 'protocol fallback cannot fake document submission');
$requiredConfig['base_url'] = 'https://synthetic.invalid/v1/chat-messages';
$prepared = ['profile' => 'qwen', 'task' => 'summary', 'query' => '合成资料;聊天:无', 'user' => 'synthetic-user',
'files' => $files, 'required_sections' => $sections, 'source_summary' => ['required_sections' => $sections], 'upstream_timeout' => 5];
$run = static function () use ($prepared): array {
$deltas = []; $events = [];
$result = DiagnosisAiLogic::streamPreparedAssistant($prepared,
static function (string $delta) use (&$deltas): bool { $deltas[] = $delta; return true; },
static fn (): bool => $GLOBALS['requiredCancelled'], new AssistantSseTiming(),
['knowledge_mode' => 'evidence', 'on_progress' => static function (array $event) use (&$events): void { $events[] = $event; }]);
return compact('result', 'deltas', 'events');
};
$reset(); $test = $run();
requiredExpect($test['result']['transfer_manifest_final'] === true && $test['result']['attachment_count'] === 8
&& $test['result']['required_sections'][0]['status'] === 'submitted'
&& $test['result']['source_summary']['required_sections'][0]['status'] === 'submitted', 'assistant done preserves actual final manifest instead of prepared status');
$reset('reject'); $test = $run();
requiredExpect($test['result'] === null && DiagnosisAiLogic::getAssistantErrorCode() === 'REQUIRED_FILES_REJECTED'
&& count($requiredRequests) === 1 && $test['deltas'] === [], 'assistant mandatory rejection does not trigger blocking compatibility retry');
$reset('cancel'); $test = $run();
requiredExpect($test['result'] === null && DiagnosisAiLogic::getAssistantErrorCode() === 'AI_ASSISTANT_CANCELLED'
&& count($requiredRequests) === 1 && $requiredClosed === 1 && $test['deltas'] === [], 'cancellation still closes transport without late answer or retry');
echo "Dify required sources serialized payload / complete files / truthful manifests / cancellation: OK\n";
}