feat(ops): unify redacted diagnostic results
这个提交存在于:
父节点
b07d983951
当前提交
46ac0a717d
共有 6 个文件被更改,包括 543 次插入 和 130 次删除
290
diagnostic_envelope.py
普通文件
290
diagnostic_envelope.py
普通文件
|
|
@ -0,0 +1,290 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Public, persistable diagnostic result DTOs.
|
||||||
|
|
||||||
|
This module deliberately has no AstrBot or plugin imports. Diagnostic results
|
||||||
|
cross the page API and the on-disk troubleshooting history, so untrusted error
|
||||||
|
text must never define the public payload.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
|
||||||
|
DIAGNOSTIC_ENVELOPE_VERSION = "private_companion.diagnostic.v1"
|
||||||
|
DIAGNOSTIC_PUBLIC_FIELDS = (
|
||||||
|
"diagnostic_version",
|
||||||
|
"test_id",
|
||||||
|
"duration_ms",
|
||||||
|
"phase",
|
||||||
|
"error_category",
|
||||||
|
"retryable",
|
||||||
|
"next_step",
|
||||||
|
)
|
||||||
|
|
||||||
|
_VALID_IDENTIFIER = re.compile(r"^[a-z0-9][a-z0-9_-]{0,79}$")
|
||||||
|
_VALID_TEST_ID = re.compile(r"^diag_[a-z0-9_]{1,40}_(?:[a-f0-9]{12,32}|legacy)$")
|
||||||
|
_VALID_PHASES = frozenset({"completed", "failed", "scheduled", "running"})
|
||||||
|
_VALID_STEP_STATUSES = frozenset({"ok", "error", "warn", "info", "pending"})
|
||||||
|
_ISSUED_TEST_KINDS = frozenset({
|
||||||
|
"provider",
|
||||||
|
"image_api_endpoint",
|
||||||
|
"image_generation",
|
||||||
|
"image_generation_text2img",
|
||||||
|
"image_generation_selfie",
|
||||||
|
"tts_generation",
|
||||||
|
"screen_peek",
|
||||||
|
"qzone_integration",
|
||||||
|
"proactive_message",
|
||||||
|
"model_diagnostics",
|
||||||
|
"skill_similarity",
|
||||||
|
})
|
||||||
|
_PUBLIC_TITLES = {
|
||||||
|
"provider": "Provider diagnostic",
|
||||||
|
"image_api_endpoint": "Image API endpoint diagnostic",
|
||||||
|
"image_generation": "Image generation diagnostic",
|
||||||
|
"image_generation_text2img": "Text-to-image diagnostic",
|
||||||
|
"image_generation_selfie": "Reference image diagnostic",
|
||||||
|
"tts_generation": "TTS generation diagnostic",
|
||||||
|
"screen_peek": "Screen observation diagnostic",
|
||||||
|
"qzone_integration": "QZone diagnostic",
|
||||||
|
"proactive_message": "Proactive message diagnostic",
|
||||||
|
"model_diagnostics": "Model data diagnostic",
|
||||||
|
"skill_similarity": "Skill similarity diagnostic",
|
||||||
|
"check": "Diagnostic test",
|
||||||
|
}
|
||||||
|
_PUBLIC_ERROR_LABELS = {
|
||||||
|
"configuration": "Configuration is incomplete or incompatible.",
|
||||||
|
"authorization": "Authentication or permission was not accepted.",
|
||||||
|
"timeout": "The diagnostic call timed out.",
|
||||||
|
"unavailable": "The required service is unavailable.",
|
||||||
|
"validation": "The diagnostic target or parameters are invalid.",
|
||||||
|
"provider": "The provider did not return a usable result.",
|
||||||
|
"unknown": "The diagnostic did not complete.",
|
||||||
|
"none": "",
|
||||||
|
}
|
||||||
|
_NEXT_STEPS = {
|
||||||
|
"configuration": "Check the required model or service configuration, then test again.",
|
||||||
|
"authorization": "Check the account authorization or credential configuration, then test again.",
|
||||||
|
"timeout": "Check service load and network state, then retry the diagnostic.",
|
||||||
|
"unavailable": "Confirm the related plugin, service, or provider is running, then test again.",
|
||||||
|
"validation": "Refresh the operations page and check the selected test target.",
|
||||||
|
"provider": "Check provider status and model configuration; use a fallback provider if needed.",
|
||||||
|
"unknown": "Use the test id to inspect plugin logs, then retry after confirming configuration.",
|
||||||
|
"none": "No action is needed.",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def diagnostic_test_id(test_kind: Any, *, token: str | None = None) -> str:
|
||||||
|
"""Create an opaque id with no user, endpoint, path, or prompt input."""
|
||||||
|
normalized = str(test_kind or "").strip().lower()
|
||||||
|
normalized = normalized if normalized in _ISSUED_TEST_KINDS else "check"
|
||||||
|
suffix = str(token or secrets.token_hex(6)).lower()
|
||||||
|
if not re.fullmatch(r"[a-f0-9]{12,32}", suffix):
|
||||||
|
suffix = secrets.token_hex(6)
|
||||||
|
return f"diag_{normalized}_{suffix}"
|
||||||
|
|
||||||
|
|
||||||
|
def classify_diagnostic_error(value: Any) -> str:
|
||||||
|
text = str(value or "").lower()
|
||||||
|
if not text:
|
||||||
|
return "unknown"
|
||||||
|
if any(token in text for token in ("timeout", "timed out", "超时", "等待其他", "排队")):
|
||||||
|
return "timeout"
|
||||||
|
if any(token in text for token in ("401", "403", "authorization", "unauthorized", "forbidden", "认证", "权限", "api key", "密钥")):
|
||||||
|
return "authorization"
|
||||||
|
if any(token in text for token in ("未知排障", "unknown test", "参数", "无效", "invalid", "校验")):
|
||||||
|
return "validation"
|
||||||
|
if any(token in text for token in ("missing", "configuration", "未配置", "缺少", "配置", "not configured")):
|
||||||
|
return "configuration"
|
||||||
|
if any(token in text for token in ("不可用", "未检测到", "未安装", "not available", "connection refused", "服务未启动")):
|
||||||
|
return "unavailable"
|
||||||
|
if any(token in text for token in ("provider", "模型", "tts", "调用失败", "generation", "rate limit", "429")):
|
||||||
|
return "provider"
|
||||||
|
return "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
def _as_int(value: Any, default: int = 0, *, ceiling: int = 86_400_000) -> int:
|
||||||
|
try:
|
||||||
|
parsed = int(float(value))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return default
|
||||||
|
return min(max(0, parsed), ceiling)
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_identifier(value: Any, limit: int = 80) -> str:
|
||||||
|
text = str(value or "").strip().lower()
|
||||||
|
if not _VALID_IDENTIFIER.fullmatch(text):
|
||||||
|
return ""
|
||||||
|
return text[:limit]
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_label(value: Any, limit: int = 100) -> str:
|
||||||
|
text = " ".join(str(value or "").replace("\r", " ").replace("\n", " ").split())
|
||||||
|
if not text:
|
||||||
|
return ""
|
||||||
|
if "traceback" in text.lower() or "authorization:" in text.lower() or "cookie:" in text.lower():
|
||||||
|
return "Internal detail is hidden."
|
||||||
|
text = re.sub(r"(?i)(bearer\s+)[^\s,;]+", r"\1[hidden]", text)
|
||||||
|
text = re.sub(r"(?i)(api[_ -]?key|token|secret|password)\s*[=:]\s*[^\s,;]+", r"\1=[hidden]", text)
|
||||||
|
return text[:limit]
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_url(value: Any) -> str:
|
||||||
|
raw = str(value or "").strip()
|
||||||
|
if not raw:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
parsed = urlparse(raw)
|
||||||
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||||
|
return ""
|
||||||
|
port = f":{parsed.port}" if parsed.port else ""
|
||||||
|
return _safe_label(f"{parsed.scheme}://{parsed.hostname}{port}{parsed.path or ''}", 180)
|
||||||
|
except ValueError:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_steps(value: Any) -> list[dict[str, str]]:
|
||||||
|
if not isinstance(value, list):
|
||||||
|
return []
|
||||||
|
items: list[dict[str, str]] = []
|
||||||
|
for raw in value[:12]:
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
continue
|
||||||
|
status = _safe_identifier(raw.get("status"), 16)
|
||||||
|
if status not in _VALID_STEP_STATUSES:
|
||||||
|
status = "info"
|
||||||
|
name = _safe_label(raw.get("name"), 40) or "Diagnostic step"
|
||||||
|
detail = {
|
||||||
|
"ok": "This stage completed.",
|
||||||
|
"error": "This stage did not pass; see the next step below.",
|
||||||
|
"warn": "This stage needs attention.",
|
||||||
|
"pending": "This stage is still waiting.",
|
||||||
|
"info": "This stage was recorded.",
|
||||||
|
}[status]
|
||||||
|
items.append({"name": name, "status": status, "detail": detail})
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_test_id(value: Any, test_type: str) -> str:
|
||||||
|
candidate = str(value or "").strip().lower()
|
||||||
|
if _VALID_TEST_ID.fullmatch(candidate):
|
||||||
|
return candidate
|
||||||
|
return f"diag_{test_type or 'check'}_legacy"
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_test_kind(value: Any) -> str:
|
||||||
|
candidate = _safe_identifier(value, 40)
|
||||||
|
return candidate if candidate in _ISSUED_TEST_KINDS else "check"
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_diagnostic_result(
|
||||||
|
result: dict[str, Any] | None,
|
||||||
|
*,
|
||||||
|
test_type: Any = "",
|
||||||
|
duration_ms: Any = 0,
|
||||||
|
test_id: Any = "",
|
||||||
|
contract_version: Any = DIAGNOSTIC_ENVELOPE_VERSION,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Project an internal result into the public, default-redacted DTO."""
|
||||||
|
source = dict(result) if isinstance(result, dict) else {}
|
||||||
|
kind = _safe_test_kind(test_type or source.get("type"))
|
||||||
|
ok = bool(source.get("ok"))
|
||||||
|
pending = bool(source.get("pending")) and not ok
|
||||||
|
raw_error = source.get("error") or source.get("detail")
|
||||||
|
category = "none" if (ok or pending) else classify_diagnostic_error(raw_error)
|
||||||
|
phase = "completed" if ok else ("scheduled" if pending else "failed")
|
||||||
|
supplied_phase = _safe_identifier(source.get("phase"), 20)
|
||||||
|
if supplied_phase in _VALID_PHASES and ((supplied_phase == "running" and pending) or supplied_phase == phase):
|
||||||
|
phase = supplied_phase
|
||||||
|
retryable = category in {"timeout", "unavailable"}
|
||||||
|
if category == "provider":
|
||||||
|
retryable = any(token in str(raw_error or "").lower() for token in ("429", "rate limit", "临时", "network", "connection"))
|
||||||
|
supplied_id = test_id or source.get("test_id")
|
||||||
|
public_id = _safe_test_id(supplied_id, kind)
|
||||||
|
if not supplied_id:
|
||||||
|
public_id = f"diag_{kind}_legacy"
|
||||||
|
duration = _as_int(duration_ms) or _as_int(source.get("duration_ms")) or _as_int(source.get("elapsed_ms"))
|
||||||
|
title = _PUBLIC_TITLES[kind]
|
||||||
|
detail = "The test completed." if ok else ("The test is scheduled or running." if pending else _PUBLIC_ERROR_LABELS[category])
|
||||||
|
|
||||||
|
return {
|
||||||
|
"diagnostic_version": _safe_label(contract_version, 60) or DIAGNOSTIC_ENVELOPE_VERSION,
|
||||||
|
"test_id": public_id,
|
||||||
|
"duration_ms": duration,
|
||||||
|
"phase": phase,
|
||||||
|
"error_category": category,
|
||||||
|
"retryable": retryable,
|
||||||
|
"next_step": _NEXT_STEPS[category],
|
||||||
|
"type": kind,
|
||||||
|
"test_key": _safe_identifier(source.get("test_key"), 80),
|
||||||
|
"ok": ok,
|
||||||
|
"pending": pending,
|
||||||
|
"outcome_type": _safe_identifier(source.get("outcome_type"), 40),
|
||||||
|
"title": title,
|
||||||
|
"backend": _safe_label(source.get("backend"), 80),
|
||||||
|
"image_model": _safe_label(source.get("image_model"), 80),
|
||||||
|
"image_size": _safe_label(source.get("image_size"), 40),
|
||||||
|
"endpoint_index": _as_int(source.get("endpoint_index"), -1, ceiling=10_000),
|
||||||
|
"endpoint_name": _safe_label(source.get("endpoint_name"), 80),
|
||||||
|
"endpoint_platform": _safe_label(source.get("endpoint_platform"), 60),
|
||||||
|
"endpoint_url": _safe_url(source.get("endpoint_url")),
|
||||||
|
"endpoint_status": _safe_identifier(source.get("endpoint_status"), 20),
|
||||||
|
"endpoint_timeout_seconds": _as_int(source.get("endpoint_timeout_seconds")),
|
||||||
|
"queue_wait_ms": _as_int(source.get("queue_wait_ms")),
|
||||||
|
"workflow_kind": _safe_identifier(source.get("workflow_kind"), 20),
|
||||||
|
"used_reference": bool(source.get("used_reference")),
|
||||||
|
"reference_id": _safe_identifier(source.get("reference_id"), 60),
|
||||||
|
"reference_kind": _safe_identifier(source.get("reference_kind"), 40),
|
||||||
|
"reference_roles": [_safe_identifier(item, 40) for item in (source.get("reference_roles") if isinstance(source.get("reference_roles"), list) else [])[:8] if _safe_identifier(item, 40)],
|
||||||
|
"wardrobe_mode": _safe_identifier(source.get("wardrobe_mode"), 40),
|
||||||
|
"wardrobe_category": _safe_identifier(source.get("wardrobe_category"), 40),
|
||||||
|
"outfit_locked": bool(source.get("outfit_locked")),
|
||||||
|
"daily_outfit_removed": bool(source.get("daily_outfit_removed")),
|
||||||
|
"final_presets": [_safe_identifier(item, 60) for item in (source.get("final_presets") if isinstance(source.get("final_presets"), list) else [])[:6] if _safe_identifier(item, 60)],
|
||||||
|
"prompt_hash": _safe_identifier(source.get("prompt_hash"), 80),
|
||||||
|
"provider": _safe_label(source.get("provider"), 100),
|
||||||
|
"file_size": _as_int(source.get("file_size")),
|
||||||
|
"detail": detail,
|
||||||
|
"error": "" if (ok or pending) else _PUBLIC_ERROR_LABELS[category],
|
||||||
|
"timeout_seconds": _as_int(source.get("timeout_seconds")),
|
||||||
|
"test_timeout_seconds": _as_int(source.get("test_timeout_seconds")),
|
||||||
|
"estimated_timeout_seconds": _as_int(source.get("estimated_timeout_seconds")),
|
||||||
|
"timeout_budget": _safe_label(source.get("timeout_budget"), 120),
|
||||||
|
"backend_preference": _safe_identifier(source.get("backend_preference"), 30),
|
||||||
|
"external_timeout_seconds": _as_int(source.get("external_timeout_seconds")),
|
||||||
|
"backup_external_timeout_seconds": _as_int(source.get("backup_external_timeout_seconds")),
|
||||||
|
"comfyui_wait_seconds": _as_int(source.get("comfyui_wait_seconds")),
|
||||||
|
"backup_external": bool(source.get("backup_external")),
|
||||||
|
"external_queue_lock": bool(source.get("external_queue_lock")),
|
||||||
|
"tool_call_timeout_seconds": _as_int(source.get("tool_call_timeout_seconds")),
|
||||||
|
"context_chars": _as_int(source.get("context_chars")),
|
||||||
|
"action": _safe_identifier(source.get("action"), 60),
|
||||||
|
"reason": _safe_identifier(source.get("reason"), 40),
|
||||||
|
"extra_count": _as_int(source.get("extra_count")),
|
||||||
|
"local_count": _as_int(source.get("local_count")),
|
||||||
|
"model_count": _as_int(source.get("model_count")),
|
||||||
|
"suggestion_count": _as_int(source.get("suggestion_count")),
|
||||||
|
"steps": _safe_steps(source.get("steps")),
|
||||||
|
"elapsed_ms": duration,
|
||||||
|
"ran_at": float(source.get("ran_at") or 0) if str(source.get("ran_at") or "").replace(".", "", 1).isdigit() else 0.0,
|
||||||
|
"ran_at_text": _safe_label(source.get("ran_at_text"), 40),
|
||||||
|
# Compatibility keys are deliberately blank: they can carry paths,
|
||||||
|
# prompts, samples, or conversation text in historical result shapes.
|
||||||
|
"path": "",
|
||||||
|
"prompt_path": "",
|
||||||
|
"reference_image": "",
|
||||||
|
"umo": "",
|
||||||
|
"prompt": "",
|
||||||
|
"text": "",
|
||||||
|
"sample": "",
|
||||||
|
"text_preview": "",
|
||||||
|
"original_text_preview": "",
|
||||||
|
"final_text_preview": "",
|
||||||
|
"diagnostic_detail": "",
|
||||||
|
"warnings": [],
|
||||||
|
"suggestions": [],
|
||||||
|
"sections": [],
|
||||||
|
}
|
||||||
|
|
@ -104,6 +104,7 @@ from .dreaming import (
|
||||||
weighted_unique_fragment_sample,
|
weighted_unique_fragment_sample,
|
||||||
)
|
)
|
||||||
from .helpers import _date_key, _now_ts, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key
|
from .helpers import _date_key, _now_ts, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key
|
||||||
|
from .diagnostic_envelope import DIAGNOSTIC_ENVELOPE_VERSION, DIAGNOSTIC_PUBLIC_FIELDS
|
||||||
from .planning import (
|
from .planning import (
|
||||||
build_daily_plan_prompt,
|
build_daily_plan_prompt,
|
||||||
build_detail_enhancement_prompt,
|
build_detail_enhancement_prompt,
|
||||||
|
|
@ -242,6 +243,15 @@ _PLATFORM_DISPLAY_NAMES = {
|
||||||
class IntegrationStatusMixin:
|
class IntegrationStatusMixin:
|
||||||
"""外部插件状态、世界观适配与运行环境描述"""
|
"""外部插件状态、世界观适配与运行环境描述"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _diagnostic_operations_contract() -> dict[str, Any]:
|
||||||
|
"""Return only the versioned public DTO contract used by operations."""
|
||||||
|
return {
|
||||||
|
"version": DIAGNOSTIC_ENVELOPE_VERSION,
|
||||||
|
"fields": list(DIAGNOSTIC_PUBLIC_FIELDS),
|
||||||
|
"history_projection": True,
|
||||||
|
}
|
||||||
|
|
||||||
def _register_page_api_if_available(self) -> None:
|
def _register_page_api_if_available(self) -> None:
|
||||||
if not hasattr(self.context, "register_web_api"):
|
if not hasattr(self.context, "register_web_api"):
|
||||||
logger.debug("[PrivateCompanion] 当前 AstrBot 版本未提供 register_web_api,跳过插件拓展页面 API 注册")
|
logger.debug("[PrivateCompanion] 当前 AstrBot 版本未提供 register_web_api,跳过插件拓展页面 API 注册")
|
||||||
|
|
|
||||||
174
page_api.py
174
page_api.py
|
|
@ -27,6 +27,7 @@ from quart import request, send_file
|
||||||
|
|
||||||
from .constants import DEFAULT_DAILY_PLAN_ITEMS, PAGE_FONT_NAMES, PAGE_THEME_NAMES, _REASON_TEXT
|
from .constants import DEFAULT_DAILY_PLAN_ITEMS, PAGE_FONT_NAMES, PAGE_THEME_NAMES, _REASON_TEXT
|
||||||
from .config_migration import _ensure_config_parent_dir
|
from .config_migration import _ensure_config_parent_dir
|
||||||
|
from .diagnostic_envelope import DIAGNOSTIC_ENVELOPE_VERSION, diagnostic_test_id, normalize_diagnostic_result
|
||||||
from .helpers import _flat_get, _normalize_timezone_name, _path_text, _redact_outbound_secrets, _safe_int, _set_into_config, _set_today_key_timezone, _strip_internal_message_blocks, _text_looks_garbled, _text_similarity, _today_key
|
from .helpers import _flat_get, _normalize_timezone_name, _path_text, _redact_outbound_secrets, _safe_int, _set_into_config, _set_today_key_timezone, _strip_internal_message_blocks, _text_looks_garbled, _text_similarity, _today_key
|
||||||
from .page_api_qzone import PrivateCompanionPageApiQzoneMixin
|
from .page_api_qzone import PrivateCompanionPageApiQzoneMixin
|
||||||
from .page_api_users_groups import PrivateCompanionPageApiUsersGroupsMixin
|
from .page_api_users_groups import PrivateCompanionPageApiUsersGroupsMixin
|
||||||
|
|
@ -2368,10 +2369,17 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
||||||
"title": self._troubleshooting_test_title(test_type),
|
"title": self._troubleshooting_test_title(test_type),
|
||||||
"error": str(exc),
|
"error": str(exc),
|
||||||
}
|
}
|
||||||
|
elapsed_ms = self._int(result.get("elapsed_ms")) or int((time.time() - start) * 1000)
|
||||||
result["type"] = test_type
|
result["type"] = test_type
|
||||||
result["elapsed_ms"] = self._int(result.get("elapsed_ms")) or int((time.time() - start) * 1000)
|
result["elapsed_ms"] = elapsed_ms
|
||||||
result["ran_at"] = time.time()
|
result["ran_at"] = time.time()
|
||||||
result["ran_at_text"] = self.plugin._format_timestamp_elapsed(result["ran_at"])
|
result["ran_at_text"] = self.plugin._format_timestamp_elapsed(result["ran_at"])
|
||||||
|
result = self._diagnostic_envelope(
|
||||||
|
result,
|
||||||
|
test_type=test_type,
|
||||||
|
duration_ms=elapsed_ms,
|
||||||
|
test_id=diagnostic_test_id(test_type),
|
||||||
|
)
|
||||||
await self._remember_troubleshooting_test_result(result_key, result)
|
await self._remember_troubleshooting_test_result(result_key, result)
|
||||||
return self._ok(result)
|
return self._ok(result)
|
||||||
|
|
||||||
|
|
@ -2570,10 +2578,17 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
||||||
safe_error = self._redact_image_api_test_text(exc, endpoint, 220)
|
safe_error = self._redact_image_api_test_text(exc, endpoint, 220)
|
||||||
logger.warning("[PrivateCompanionPage] 生图 API 单独测试失败: %s", safe_error)
|
logger.warning("[PrivateCompanionPage] 生图 API 单独测试失败: %s", safe_error)
|
||||||
result = {"ok": False, "title": "在线图片 API 单独测试", "error": safe_error}
|
result = {"ok": False, "title": "在线图片 API 单独测试", "error": safe_error}
|
||||||
|
elapsed_ms = self._int(result.get("elapsed_ms")) or int((time.time() - started) * 1000)
|
||||||
result["type"] = "image_api_endpoint"
|
result["type"] = "image_api_endpoint"
|
||||||
result["elapsed_ms"] = self._int(result.get("elapsed_ms")) or int((time.time() - started) * 1000)
|
result["elapsed_ms"] = elapsed_ms
|
||||||
result["ran_at"] = time.time()
|
result["ran_at"] = time.time()
|
||||||
result["ran_at_text"] = self.plugin._format_timestamp_elapsed(result["ran_at"])
|
result["ran_at_text"] = self.plugin._format_timestamp_elapsed(result["ran_at"])
|
||||||
|
result = self._diagnostic_envelope(
|
||||||
|
result,
|
||||||
|
test_type="image_api_endpoint",
|
||||||
|
duration_ms=elapsed_ms,
|
||||||
|
test_id=diagnostic_test_id("image_api_endpoint"),
|
||||||
|
)
|
||||||
result_key = self._single_line(result.get("test_key"), 80) or "image_api_endpoint"
|
result_key = self._single_line(result.get("test_key"), 80) or "image_api_endpoint"
|
||||||
await self._remember_troubleshooting_test_result(result_key, result)
|
await self._remember_troubleshooting_test_result(result_key, result)
|
||||||
return self._ok(result)
|
return self._ok(result)
|
||||||
|
|
@ -4659,112 +4674,33 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
||||||
)
|
)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
def _diagnostic_envelope(
|
||||||
|
self,
|
||||||
|
result: dict[str, Any] | None,
|
||||||
|
*,
|
||||||
|
test_type: str = "",
|
||||||
|
duration_ms: int = 0,
|
||||||
|
test_id: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
contract_version = DIAGNOSTIC_ENVELOPE_VERSION
|
||||||
|
getter = getattr(self.plugin, "_diagnostic_operations_contract", None)
|
||||||
|
if callable(getter):
|
||||||
|
try:
|
||||||
|
contract = getter()
|
||||||
|
if isinstance(contract, dict):
|
||||||
|
contract_version = self._single_line(contract.get("version"), 60) or contract_version
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return normalize_diagnostic_result(
|
||||||
|
result,
|
||||||
|
test_type=test_type,
|
||||||
|
duration_ms=duration_ms,
|
||||||
|
test_id=test_id,
|
||||||
|
contract_version=contract_version,
|
||||||
|
)
|
||||||
|
|
||||||
def _sanitize_troubleshooting_test_result(self, result: dict[str, Any]) -> dict[str, Any]:
|
def _sanitize_troubleshooting_test_result(self, result: dict[str, Any]) -> dict[str, Any]:
|
||||||
return {
|
return self._diagnostic_envelope(result)
|
||||||
"type": self._single_line(result.get("type"), 40),
|
|
||||||
"test_key": self._single_line(result.get("test_key"), 80),
|
|
||||||
"ok": bool(result.get("ok")),
|
|
||||||
"pending": bool(result.get("pending")),
|
|
||||||
"outcome_type": self._single_line(result.get("outcome_type"), 40),
|
|
||||||
"title": self._single_line(result.get("title"), 60),
|
|
||||||
"backend": self._single_line(result.get("backend"), 80),
|
|
||||||
"image_model": self._single_line(result.get("image_model"), 80),
|
|
||||||
"image_size": self._single_line(result.get("image_size"), 40),
|
|
||||||
"endpoint_index": self._int(result.get("endpoint_index"), -1),
|
|
||||||
"endpoint_name": self._single_line(result.get("endpoint_name"), 80),
|
|
||||||
"endpoint_platform": self._single_line(result.get("endpoint_platform"), 60),
|
|
||||||
"endpoint_url": self._single_line(result.get("endpoint_url"), 180),
|
|
||||||
"endpoint_status": self._single_line(result.get("endpoint_status"), 20),
|
|
||||||
"endpoint_timeout_seconds": self._int(result.get("endpoint_timeout_seconds")),
|
|
||||||
"queue_wait_ms": self._int(result.get("queue_wait_ms")),
|
|
||||||
"workflow_kind": self._single_line(result.get("workflow_kind"), 20),
|
|
||||||
"reference_image": self._single_line(result.get("reference_image"), 1000),
|
|
||||||
"used_reference": bool(result.get("used_reference")),
|
|
||||||
"reference_id": self._single_line(result.get("reference_id"), 60),
|
|
||||||
"reference_kind": self._single_line(result.get("reference_kind"), 40),
|
|
||||||
"reference_roles": [
|
|
||||||
self._single_line(value, 40)
|
|
||||||
for value in (result.get("reference_roles") if isinstance(result.get("reference_roles"), list) else [])
|
|
||||||
if self._single_line(value, 40)
|
|
||||||
][:8],
|
|
||||||
"wardrobe_mode": self._single_line(result.get("wardrobe_mode"), 40),
|
|
||||||
"wardrobe_category": self._single_line(result.get("wardrobe_category"), 40),
|
|
||||||
"outfit_locked": bool(result.get("outfit_locked")),
|
|
||||||
"daily_outfit_removed": bool(result.get("daily_outfit_removed")),
|
|
||||||
"final_presets": [
|
|
||||||
self._single_line(value, 60)
|
|
||||||
for value in (result.get("final_presets") if isinstance(result.get("final_presets"), list) else [])
|
|
||||||
if self._single_line(value, 60)
|
|
||||||
][:6],
|
|
||||||
"prompt_hash": self._single_line(result.get("prompt_hash"), 80),
|
|
||||||
"prompt_path": self._single_line(result.get("prompt_path"), 1000),
|
|
||||||
"provider": self._single_line(result.get("provider"), 100),
|
|
||||||
"umo": self._single_line(result.get("umo"), 180),
|
|
||||||
"path": self._single_line(result.get("path"), 1000),
|
|
||||||
"file_size": self._int(result.get("file_size")),
|
|
||||||
"detail": self._single_line(result.get("detail"), 220),
|
|
||||||
"error": self._single_line(result.get("error"), 220),
|
|
||||||
"diagnostic_detail": self._single_line(result.get("diagnostic_detail"), 2400),
|
|
||||||
"prompt": self._single_line(result.get("prompt"), 500),
|
|
||||||
"timeout_seconds": self._int(result.get("timeout_seconds")),
|
|
||||||
"test_timeout_seconds": self._int(result.get("test_timeout_seconds")),
|
|
||||||
"estimated_timeout_seconds": self._int(result.get("estimated_timeout_seconds")),
|
|
||||||
"timeout_budget": self._single_line(result.get("timeout_budget"), 220),
|
|
||||||
"backend_preference": self._single_line(result.get("backend_preference"), 30),
|
|
||||||
"external_timeout_seconds": self._int(result.get("external_timeout_seconds")),
|
|
||||||
"backup_external_timeout_seconds": self._int(result.get("backup_external_timeout_seconds")),
|
|
||||||
"comfyui_wait_seconds": self._int(result.get("comfyui_wait_seconds")),
|
|
||||||
"backup_external": bool(result.get("backup_external")),
|
|
||||||
"external_queue_lock": bool(result.get("external_queue_lock")),
|
|
||||||
"tool_call_timeout_seconds": self._int(result.get("tool_call_timeout_seconds")),
|
|
||||||
"warnings": [
|
|
||||||
self._single_line(item, 220)
|
|
||||||
for item in (result.get("warnings") if isinstance(result.get("warnings"), list) else [])[:8]
|
|
||||||
if self._single_line(item, 220)
|
|
||||||
],
|
|
||||||
"text_preview": self._single_line(result.get("text_preview"), 220),
|
|
||||||
"original_text_preview": self._single_line(result.get("original_text_preview"), 220),
|
|
||||||
"final_text_preview": self._single_line(result.get("final_text_preview"), 220),
|
|
||||||
"context_chars": self._int(result.get("context_chars")),
|
|
||||||
"action": self._single_line(result.get("action"), 60),
|
|
||||||
"reason": self._single_line(result.get("reason"), 40),
|
|
||||||
"extra_count": self._int(result.get("extra_count")),
|
|
||||||
"local_count": self._int(result.get("local_count")),
|
|
||||||
"model_count": self._int(result.get("model_count")),
|
|
||||||
"suggestion_count": self._int(result.get("suggestion_count")),
|
|
||||||
"suggestions": [
|
|
||||||
self._single_line(item, 220)
|
|
||||||
for item in (result.get("suggestions") if isinstance(result.get("suggestions"), list) else [])[:12]
|
|
||||||
if self._single_line(item, 220)
|
|
||||||
],
|
|
||||||
"sections": [
|
|
||||||
{
|
|
||||||
"key": self._single_line(section.get("key"), 40),
|
|
||||||
"title": self._single_line(section.get("title"), 60),
|
|
||||||
"local_count": self._int(section.get("local_count")),
|
|
||||||
"model_count": self._int(section.get("model_count")),
|
|
||||||
"suggestions": [
|
|
||||||
self._single_line(item, 220)
|
|
||||||
for item in (section.get("suggestions") if isinstance(section.get("suggestions"), list) else [])[:8]
|
|
||||||
if self._single_line(item, 220)
|
|
||||||
],
|
|
||||||
}
|
|
||||||
for section in (result.get("sections") if isinstance(result.get("sections"), list) else [])[:6]
|
|
||||||
if isinstance(section, dict)
|
|
||||||
],
|
|
||||||
"steps": [
|
|
||||||
{
|
|
||||||
"name": self._single_line(step.get("name"), 40),
|
|
||||||
"status": self._single_line(step.get("status"), 16),
|
|
||||||
"detail": self._single_line(step.get("detail"), 180),
|
|
||||||
}
|
|
||||||
for step in (result.get("steps") if isinstance(result.get("steps"), list) else [])[:12]
|
|
||||||
if isinstance(step, dict)
|
|
||||||
],
|
|
||||||
"elapsed_ms": self._int(result.get("elapsed_ms")),
|
|
||||||
"ran_at": self._float(result.get("ran_at")),
|
|
||||||
"ran_at_text": self._single_line(result.get("ran_at_text"), 40),
|
|
||||||
}
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _troubleshooting_test_title(test_type: str) -> str:
|
def _troubleshooting_test_title(test_type: str) -> str:
|
||||||
|
|
@ -9715,6 +9651,16 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
||||||
payload = await request.get_json(silent=True) or {}
|
payload = await request.get_json(silent=True) or {}
|
||||||
key = str(payload.get("key", "")).strip()
|
key = str(payload.get("key", "")).strip()
|
||||||
provider_id = self._single_line(payload.get("provider_id"), 160)
|
provider_id = self._single_line(payload.get("provider_id"), 160)
|
||||||
|
started = time.time()
|
||||||
|
if key and key not in self._allowed_provider_keys():
|
||||||
|
return self._ok(
|
||||||
|
self._diagnostic_envelope(
|
||||||
|
{"ok": False, "key": key, "title": "Provider diagnostic", "error": "invalid provider test target"},
|
||||||
|
test_type="provider",
|
||||||
|
duration_ms=int((time.time() - started) * 1000),
|
||||||
|
test_id=diagnostic_test_id("provider"),
|
||||||
|
)
|
||||||
|
)
|
||||||
if key and key not in self._allowed_provider_keys():
|
if key and key not in self._allowed_provider_keys():
|
||||||
return self._error("不允许测试该 Provider 配置项")
|
return self._error("不允许测试该 Provider 配置项")
|
||||||
timeout_raw = payload.get("timeout_seconds")
|
timeout_raw = payload.get("timeout_seconds")
|
||||||
|
|
@ -9734,23 +9680,33 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
||||||
elapsed_ms = int((time.time() - start) * 1000)
|
elapsed_ms = int((time.time() - start) * 1000)
|
||||||
ok = bool(text)
|
ok = bool(text)
|
||||||
return self._ok(
|
return self._ok(
|
||||||
|
self._diagnostic_envelope(
|
||||||
{
|
{
|
||||||
"ok": ok,
|
"ok": ok,
|
||||||
"key": key,
|
"key": key,
|
||||||
"provider_id": provider_id,
|
"provider_id": provider_id,
|
||||||
"elapsed_ms": elapsed_ms,
|
"elapsed_ms": elapsed_ms,
|
||||||
"sample": self._single_line(text, 80),
|
"sample": self._single_line(text, 80),
|
||||||
}
|
},
|
||||||
|
test_type="provider",
|
||||||
|
duration_ms=elapsed_ms,
|
||||||
|
test_id=diagnostic_test_id("provider"),
|
||||||
|
)
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
return self._ok(
|
return self._ok(
|
||||||
|
self._diagnostic_envelope(
|
||||||
{
|
{
|
||||||
"ok": False,
|
"ok": False,
|
||||||
"key": key,
|
"key": key,
|
||||||
"provider_id": provider_id,
|
"provider_id": provider_id,
|
||||||
"elapsed_ms": int((time.time() - start) * 1000),
|
"elapsed_ms": int((time.time() - start) * 1000),
|
||||||
"error": str(exc),
|
"error": str(exc),
|
||||||
}
|
},
|
||||||
|
test_type="provider",
|
||||||
|
duration_ms=int((time.time() - start) * 1000),
|
||||||
|
test_id=diagnostic_test_id("provider"),
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
def _user_summary(self, user_id: str, user: dict[str, Any]) -> dict[str, Any]:
|
def _user_summary(self, user_id: str, user: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
|
|
||||||
|
|
@ -7951,9 +7951,9 @@ async function testSetupGuideProvider(key, control = null) {
|
||||||
[key]: {
|
[key]: {
|
||||||
status: ok ? "ok" : "fail",
|
status: ok ? "ok" : "fail",
|
||||||
provider_id: providerId,
|
provider_id: providerId,
|
||||||
elapsed_ms: result?.elapsed_ms || 0,
|
elapsed_ms: result?.duration_ms || result?.elapsed_ms || 0,
|
||||||
sample: result?.sample || "",
|
sample: "",
|
||||||
error: result?.error || (ok ? "" : "未返回有效结果"),
|
error: result?.error || result?.next_step || (ok ? "" : "未返回有效结果"),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
updateSetupGuideStatusViews();
|
updateSetupGuideStatusViews();
|
||||||
|
|
@ -9833,13 +9833,17 @@ function troubleshootingChainTestMarkup(results, recentPhotoGenerations = [], sc
|
||||||
result.timeout_seconds ? `等待上限 ${result.timeout_seconds}s` : "",
|
result.timeout_seconds ? `等待上限 ${result.timeout_seconds}s` : "",
|
||||||
result.timeout_budget ? `预算 ${result.timeout_budget}` : "",
|
result.timeout_budget ? `预算 ${result.timeout_budget}` : "",
|
||||||
result.context_chars ? `摘要 ${result.context_chars} 字` : "",
|
result.context_chars ? `摘要 ${result.context_chars} 字` : "",
|
||||||
result.elapsed_ms ? `${result.elapsed_ms}ms` : "",
|
(result.duration_ms || result.elapsed_ms) ? `${result.duration_ms || result.elapsed_ms}ms` : "",
|
||||||
|
result.phase ? `阶段 ${result.phase}` : "",
|
||||||
|
result.error_category && result.error_category !== "none" ? `分类 ${result.error_category}` : "",
|
||||||
|
result.test_id ? `测试 ${result.test_id}` : "",
|
||||||
result.file_size ? `${formatBytes(result.file_size)}` : "",
|
result.file_size ? `${formatBytes(result.file_size)}` : "",
|
||||||
result.ran_at_text || "",
|
result.ran_at_text || "",
|
||||||
].filter(Boolean).join(" · ");
|
].filter(Boolean).join(" · ");
|
||||||
const stepsMarkup = troubleshootingChainStepsMarkup(result.steps);
|
const stepsMarkup = troubleshootingChainStepsMarkup(result.steps);
|
||||||
const previewMarkup = troubleshootingChainPreviewMarkup(test.type, result);
|
const previewMarkup = troubleshootingChainPreviewMarkup(test.type, result);
|
||||||
const diagnosticMarkup = proactiveDiagnosticDetailsMarkup(result.diagnostic_detail);
|
const diagnosticMarkup = proactiveDiagnosticDetailsMarkup(result.diagnostic_detail);
|
||||||
|
const envelopeMarkup = troubleshootingDiagnosticEnvelopeMarkup(result);
|
||||||
const detailText = troubleshootingChainDetailText(test, result, hasResult);
|
const detailText = troubleshootingChainDetailText(test, result, hasResult);
|
||||||
return `
|
return `
|
||||||
<section class="troubleshooting-chain-test ${escapeHtml(status)}">
|
<section class="troubleshooting-chain-test ${escapeHtml(status)}">
|
||||||
|
|
@ -9847,10 +9851,9 @@ function troubleshootingChainTestMarkup(results, recentPhotoGenerations = [], sc
|
||||||
<b>${escapeHtml(test.title)}</b>
|
<b>${escapeHtml(test.title)}</b>
|
||||||
<p>${escapeHtml(detailText)}</p>
|
<p>${escapeHtml(detailText)}</p>
|
||||||
${meta ? `<small>${escapeHtml(meta)}</small>` : ""}
|
${meta ? `<small>${escapeHtml(meta)}</small>` : ""}
|
||||||
${result.path ? `<small class="path">${escapeHtml(result.path)}</small>` : ""}
|
|
||||||
${result.prompt_path ? `<small class="path">完整调试文件:${escapeHtml(result.prompt_path)}</small>` : ""}
|
|
||||||
${previewMarkup}
|
${previewMarkup}
|
||||||
${diagnosticMarkup}
|
${diagnosticMarkup}
|
||||||
|
${envelopeMarkup}
|
||||||
${stepsMarkup}
|
${stepsMarkup}
|
||||||
</div>
|
</div>
|
||||||
<button type="button" data-troubleshooting-test="${escapeHtml(test.type)}" ${test.workflowKind ? `data-troubleshooting-workflow-kind="${escapeHtml(test.workflowKind)}"` : ""}>${escapeHtml(test.button)}</button>
|
<button type="button" data-troubleshooting-test="${escapeHtml(test.type)}" ${test.workflowKind ? `data-troubleshooting-workflow-kind="${escapeHtml(test.workflowKind)}"` : ""}>${escapeHtml(test.button)}</button>
|
||||||
|
|
@ -9885,6 +9888,9 @@ function troubleshootingTtsRuntimeMarkup(tts = {}) {
|
||||||
|
|
||||||
function troubleshootingChainDetailText(test, result, hasResult) {
|
function troubleshootingChainDetailText(test, result, hasResult) {
|
||||||
if (!hasResult) return test.text;
|
if (!hasResult) return test.text;
|
||||||
|
if (result.error_category && result.error_category !== "none") {
|
||||||
|
return `${troubleshootingDiagnosticCategoryLabel(result.error_category)}${result.next_step ? `:${result.next_step}` : ""}`;
|
||||||
|
}
|
||||||
if (result.error) return result.error;
|
if (result.error) return result.error;
|
||||||
if ((test.type === "skill_similarity" || test.type === "model_diagnostics") && result.ok) {
|
if ((test.type === "skill_similarity" || test.type === "model_diagnostics") && result.ok) {
|
||||||
const localCount = Number(result.local_count || 0);
|
const localCount = Number(result.local_count || 0);
|
||||||
|
|
@ -9894,6 +9900,37 @@ function troubleshootingChainDetailText(test, result, hasResult) {
|
||||||
return result.detail || test.text;
|
return result.detail || test.text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function troubleshootingDiagnosticCategoryLabel(category) {
|
||||||
|
return {
|
||||||
|
configuration: "配置需要调整",
|
||||||
|
authorization: "认证或权限未通过",
|
||||||
|
timeout: "诊断调用超时",
|
||||||
|
unavailable: "依赖服务当前不可用",
|
||||||
|
validation: "测试目标或参数无效",
|
||||||
|
provider: "Provider 未返回可用结果",
|
||||||
|
unknown: "诊断未完成",
|
||||||
|
}[category] || "诊断未完成";
|
||||||
|
}
|
||||||
|
|
||||||
|
function troubleshootingDiagnosticEnvelopeMarkup(result = {}) {
|
||||||
|
if (!result.test_id) return "";
|
||||||
|
const duration = Number(result.duration_ms || result.elapsed_ms || 0);
|
||||||
|
const retry = result.retryable ? "可重试" : "请先按建议处理";
|
||||||
|
const category = result.error_category && result.error_category !== "none"
|
||||||
|
? troubleshootingDiagnosticCategoryLabel(result.error_category)
|
||||||
|
: "未发现诊断错误";
|
||||||
|
return `
|
||||||
|
<details class="chain-test-steps diagnostic-envelope">
|
||||||
|
<summary>查看安全诊断详情</summary>
|
||||||
|
<div class="chain-test-step info"><b>测试标识</b><span>${escapeHtml(result.test_id)}</span></div>
|
||||||
|
<div class="chain-test-step info"><b>执行阶段</b><span>${escapeHtml(result.phase || "unknown")}</span></div>
|
||||||
|
<div class="chain-test-step info"><b>错误分类</b><span>${escapeHtml(category)}</span></div>
|
||||||
|
<div class="chain-test-step info"><b>耗时 / 重试</b><span>${escapeHtml(`${duration}ms · ${retry}`)}</span></div>
|
||||||
|
${result.next_step ? `<div class="chain-test-step info"><b>下一步</b><span>${escapeHtml(result.next_step)}</span></div>` : ""}
|
||||||
|
</details>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
function troubleshootingChainStepsMarkup(stepsRaw) {
|
function troubleshootingChainStepsMarkup(stepsRaw) {
|
||||||
const steps = Array.isArray(stepsRaw) ? stepsRaw : [];
|
const steps = Array.isArray(stepsRaw) ? stepsRaw : [];
|
||||||
if (!steps.length) return "";
|
if (!steps.length) return "";
|
||||||
|
|
|
||||||
|
|
@ -250,10 +250,9 @@ window.PrivateCompanionProviderTree = (() => {
|
||||||
const timeoutSeconds = currentProviderTimeoutValues(context)[key] || null;
|
const timeoutSeconds = currentProviderTimeoutValues(context)[key] || null;
|
||||||
const result = await postJson("/provider/test", { key, provider_id: providerId, timeout_seconds: timeoutSeconds });
|
const result = await postJson("/provider/test", { key, provider_id: providerId, timeout_seconds: timeoutSeconds });
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
const suffix = result.sample ? ` · ${result.sample}` : "";
|
setProviderStatus(context, key, `正常 ${result.duration_ms || result.elapsed_ms || 0}ms`, "ok");
|
||||||
setProviderStatus(context, key, `正常 ${result.elapsed_ms}ms${suffix}`, "ok");
|
|
||||||
} else {
|
} else {
|
||||||
setProviderStatus(context, key, result.error || "未返回内容", "warn");
|
setProviderStatus(context, key, result.next_step || result.error || "未返回内容", "warn");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setProviderStatus(context, key, error.message, "warn");
|
setProviderStatus(context, key, error.message, "warn");
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,121 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ast
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
MODULE_PATH = ROOT / "diagnostic_envelope.py"
|
||||||
|
|
||||||
|
|
||||||
|
def _module():
|
||||||
|
spec = importlib.util.spec_from_file_location("q4_diagnostic_envelope", MODULE_PATH)
|
||||||
|
assert spec and spec.loader
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
def test_q4_envelope_adds_public_fields_and_keeps_legacy_compatibility() -> None:
|
||||||
|
api = _module()
|
||||||
|
result = api.normalize_diagnostic_result(
|
||||||
|
{"ok": True, "type": "tts_generation", "elapsed_ms": 42, "title": "TTS test", "sample": "normal"},
|
||||||
|
test_id="diag_tts_generation_012345abcdef",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["diagnostic_version"] == api.DIAGNOSTIC_ENVELOPE_VERSION
|
||||||
|
assert result["test_id"] == "diag_tts_generation_012345abcdef"
|
||||||
|
assert result["duration_ms"] == result["elapsed_ms"] == 42
|
||||||
|
assert result["phase"] == "completed"
|
||||||
|
assert result["error_category"] == "none"
|
||||||
|
assert result["retryable"] is False
|
||||||
|
assert result["next_step"]
|
||||||
|
assert result["ok"] is True
|
||||||
|
assert result["sample"] == ""
|
||||||
|
assert result["path"] == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_q4_envelope_removes_secrets_paths_and_conversation_content() -> None:
|
||||||
|
api = _module()
|
||||||
|
secret = "q4-secret-token"
|
||||||
|
raw = {
|
||||||
|
"ok": False,
|
||||||
|
"type": "image_api_endpoint",
|
||||||
|
"title": "a private title should not leave the diagnostic boundary",
|
||||||
|
"error": f"Traceback Authorization: Bearer {secret} at C:\\Users\\tester\\photo.png",
|
||||||
|
"endpoint_url": f"https://images.example.test/v1/generate?api_key={secret}",
|
||||||
|
"path": "C:\\Users\\tester\\photo.png",
|
||||||
|
"prompt_path": "/var/lib/astrbot/private/prompt.json",
|
||||||
|
"reference_image": "/var/lib/astrbot/private/reference.jpg",
|
||||||
|
"prompt": "chat secret should not leave the diagnostic boundary",
|
||||||
|
"text_preview": "a private screen/chat excerpt",
|
||||||
|
"original_text_preview": "another private chat excerpt",
|
||||||
|
"final_text_preview": "one more private chat excerpt",
|
||||||
|
"sample": "model response should not be echoed",
|
||||||
|
"steps": [{"name": "Provider call", "status": "error", "detail": secret}],
|
||||||
|
}
|
||||||
|
result = api.normalize_diagnostic_result(raw, test_id="diag_image_api_endpoint_012345abcdef")
|
||||||
|
rendered = json.dumps(result, ensure_ascii=False)
|
||||||
|
|
||||||
|
assert secret not in rendered
|
||||||
|
assert "C:\\Users" not in rendered
|
||||||
|
assert "/var/lib/astrbot" not in rendered
|
||||||
|
assert "private screen/chat" not in rendered
|
||||||
|
assert "private title" not in rendered
|
||||||
|
assert result["endpoint_url"] == "https://images.example.test/v1/generate"
|
||||||
|
assert result["error_category"] == "authorization"
|
||||||
|
assert result["error"] == "Authentication or permission was not accepted."
|
||||||
|
assert result["steps"] == [{"name": "Provider call", "status": "error", "detail": "This stage did not pass; see the next step below."}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_q4_error_categories_retryability_and_safe_ids() -> None:
|
||||||
|
api = _module()
|
||||||
|
cases = {
|
||||||
|
"missing model configuration": ("configuration", False),
|
||||||
|
"401 unauthorized": ("authorization", False),
|
||||||
|
"request timed out": ("timeout", True),
|
||||||
|
"service not available": ("unavailable", True),
|
||||||
|
"invalid test parameter": ("validation", False),
|
||||||
|
"provider rate limit 429": ("provider", True),
|
||||||
|
}
|
||||||
|
for message, expected in cases.items():
|
||||||
|
result = api.normalize_diagnostic_result({"ok": False, "type": "provider", "error": message})
|
||||||
|
assert (result["error_category"], result["retryable"]) == expected
|
||||||
|
assert result["next_step"]
|
||||||
|
|
||||||
|
test_id = api.diagnostic_test_id("provider / C:\\private / user 10001", token="012345abcdef")
|
||||||
|
assert re.fullmatch(r"diag_[a-z0-9_]+_[a-f0-9]{12}", test_id)
|
||||||
|
assert "10001" not in test_id
|
||||||
|
assert "private" not in test_id
|
||||||
|
|
||||||
|
|
||||||
|
def test_q4_legacy_history_is_projected_without_sensitive_fields() -> None:
|
||||||
|
api = _module()
|
||||||
|
result = api.normalize_diagnostic_result(
|
||||||
|
{"ok": False, "type": "tts_generation", "elapsed_ms": 9, "umo": "aiocqhttp:FriendMessage:10001"}
|
||||||
|
)
|
||||||
|
assert result["test_id"] == "diag_tts_generation_legacy"
|
||||||
|
assert result["umo"] == ""
|
||||||
|
assert result["elapsed_ms"] == result["duration_ms"] == 9
|
||||||
|
|
||||||
|
|
||||||
|
def test_q4_page_api_and_operations_contract_use_the_same_envelope() -> None:
|
||||||
|
page_api = (ROOT / "page_api.py").read_text(encoding="utf-8")
|
||||||
|
integration_status = (ROOT / "integration_status.py").read_text(encoding="utf-8")
|
||||||
|
app_js = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8")
|
||||||
|
provider_panel = (ROOT / "pages" / "陪伴面板" / "js" / "panels" / "provider-tree.js").read_text(encoding="utf-8")
|
||||||
|
tree = ast.parse(page_api)
|
||||||
|
methods = {node.name: ast.unparse(node) for node in ast.walk(tree) if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}
|
||||||
|
|
||||||
|
for name in ("run_troubleshooting_test", "test_image_api_endpoint", "test_provider"):
|
||||||
|
assert "_diagnostic_envelope" in methods[name]
|
||||||
|
assert "diagnostic_test_id" in methods[name]
|
||||||
|
assert "def _sanitize_troubleshooting_test_result" in page_api
|
||||||
|
assert "return self._diagnostic_envelope(result)" in page_api
|
||||||
|
assert "def _diagnostic_operations_contract" in integration_status
|
||||||
|
assert "DIAGNOSTIC_ENVELOPE_VERSION" in integration_status
|
||||||
|
assert "function troubleshootingDiagnosticEnvelopeMarkup" in app_js
|
||||||
|
assert "result.next_step || result.error" in provider_panel
|
||||||
正在加载…
添加表格
在新工单中引用