diff --git a/page_api.py b/page_api.py index 6cdc421..d753960 100644 --- a/page_api.py +++ b/page_api.py @@ -131,6 +131,48 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio self.plugin = plugin self._schema_key_index_cache: dict[str, Any] | None = None + @staticmethod + def _relationship_intimacy_projection(value: int) -> dict[str, Any]: + """Return the admin-facing phase for the legacy companion baseline only.""" + score = max(-1200, min(1200, int(value))) + if score <= -801: + phase_key, phase_label = "deeply_distant", "极度疏离" + elif score <= -401: + phase_key, phase_label = "strongly_distant", "强烈疏离" + elif score < 0: + phase_key, phase_label = "distant", "疏离" + elif score <= 199: + phase_key, phase_label = "acquaintance", "初识" + elif score <= 599: + phase_key, phase_label = "familiar", "熟悉" + elif score <= 899: + phase_key, phase_label = "close", "亲近" + elif score < 1200: + phase_key, phase_label = "intimate", "亲密" + else: + phase_key, phase_label = "deeply_bonded", "深度联结" + return { + "value": score, + "band": phase_label, + "phase": {"key": phase_key, "label": phase_label}, + "min": -1200, + "max": 1200, + "trend": "unknown", + } + + @staticmethod + def _p4_page_status_projection() -> dict[str, Any]: + """Return a fixed page-safe P4 status without resolving any person.""" + return { + "schema_version": "chat.p4.page_status.v1", + "scope": "chat_event_only", + "reply_gate": "host_verified_event_only", + "warmth": "host_verified_event_only", + "confinement": "not_exposed_to_page", + "manual_review": "not_migrated", + "action_available": False, + } + def _relationship_panel( self, user_id: str, @@ -153,8 +195,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio else: reply_band = "low" - score = self._int(user.get("relationship_score")) - basis = "close" if score >= 55 else "familiar" if score >= 3 else "initial" + relationship_intimacy = self._relationship_intimacy_projection(self._int(user.get("relationship_score"))) memory_phase = {"status": "unavailable", "phase": "unknown", "momentum_band": "unknown"} getter = getattr(self.plugin, "_memory_companion_peek_relationship_phase", None) session_id = self._single_line(user.get("umo"), 200) @@ -177,8 +218,12 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio "pending_observation_count": max(0, self._int(worldbook_member.get("pending_observation_count"))) if isinstance(worldbook_member, dict) else 0, } return { - "relationship_basis": {"band": basis}, + "relationship_basis": { + "value": relationship_intimacy["value"], + "band": relationship_intimacy["phase"]["label"], + }, "relationship_stage": self._single_line(relationship_stage, 24) or "unclassified", + "relationship_intimacy": relationship_intimacy, "interaction": {"inbound_count": inbound, "reply_count": replies, "reply_band": reply_band}, "memory_phase": memory_phase, "network": network, @@ -283,6 +328,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio register = self.plugin.context.register_web_api routes = [ ("/overview", self.get_overview, ["GET"], "Private Companion Page overview"), + ("/ops/status", self.get_ops_status, ["GET"], "Private Companion Page safe P4 status"), ("/expression-library", self.get_expression_library, ["GET"], "Private Companion Page expression library"), ("/expression-library/update", self.update_expression_library, ["POST"], "Private Companion Page update expression library"), ("/users", self.list_users, ["GET"], "Private Companion Page users"), @@ -398,6 +444,10 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio for path, handler, methods, desc in routes: register(f"{PAGE_API_PREFIX}{path}", handler, methods, desc) + async def get_ops_status(self) -> dict[str, Any]: + """Expose only the page-safe P4 status; no identity or ledger lookup.""" + return self._ok({"p4_runtime": self._p4_page_status_projection()}) + async def get_overview(self) -> dict[str, Any]: start = time.perf_counter() try: @@ -9824,6 +9874,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio relationship_state = self._emotion_relationship_state_summary(rel_state) pending_emotion_judgement = self._emotion_pending_judgement_summary(user.get("pending_emotion_judgement")) last_emotion_judgement_error = self._single_line(user.get("last_emotion_judgement_error"), 160) + relationship_intimacy = self._relationship_intimacy_projection(self._int(user.get("relationship_score"))) return { "user_id": user_id_text, "display_name": display_name, @@ -9894,6 +9945,11 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio "reply_count": user.get("reply_count", 0), "proactive_sent_count": user.get("proactive_sent_count", 0), "relationship_score": user.get("relationship_score", 0), + "relationship_basis": { + "value": relationship_intimacy["value"], + "band": relationship_intimacy["phase"]["label"], + }, + "relationship_intimacy": relationship_intimacy, "relationship_stage": relationship_stage, "relationship_state": relationship_state, "pending_emotion_judgement": pending_emotion_judgement, diff --git a/page_api_users_groups.py b/page_api_users_groups.py index 6972190..baa6e3c 100644 --- a/page_api_users_groups.py +++ b/page_api_users_groups.py @@ -14,6 +14,21 @@ from .helpers import _safe_int class PrivateCompanionPageApiUsersGroupsMixin: + @staticmethod + def _relationship_score_input(value: Any) -> int: + """Parse the dedicated manual companion intimacy baseline field.""" + if isinstance(value, bool): + raise ValueError("relationship_score must be an integer") + if isinstance(value, int): + score = value + elif isinstance(value, str) and re.fullmatch(r"[+-]?\d+", value.strip()): + score = int(value.strip()) + else: + raise ValueError("relationship_score must be an integer") + if not -1200 <= score <= 1200: + raise ValueError("relationship_score must be between -1200 and 1200") + return score + async def list_users(self) -> dict[str, Any]: start = time.perf_counter() try: @@ -49,6 +64,7 @@ class PrivateCompanionPageApiUsersGroupsMixin: relationship_stage=str(detail.get("relationship_stage") or ""), worldbook_member=worldbook_member, ) + detail["p4_runtime"] = self._p4_page_status_projection() route_status_getter = getattr(self.plugin, "_private_delivery_route_status", None) delivery_route = route_status_getter(user_id, user) if callable(route_status_getter) else {} detail.update( @@ -81,6 +97,15 @@ class PrivateCompanionPageApiUsersGroupsMixin: user_id = str(payload.get("user_id", "")).strip() if not user_id: return self._error("缺少 user_id") + relationship_score = None + intimacy_keys = [key for key in ("companion_intimacy", "relationship_score") if key in payload] + if len(intimacy_keys) > 1: + return self._error("陪伴亲密度字段不能重复提交") + if intimacy_keys: + try: + relationship_score = self._relationship_score_input(payload.get(intimacy_keys[0])) + except ValueError as exc: + return self._error(str(exc)) try: action_message = "" async with self.plugin._data_lock: @@ -105,6 +130,8 @@ class PrivateCompanionPageApiUsersGroupsMixin: if role: user["relationship_role"] = role expression_voice_needs_refresh = role != previous_role + if relationship_score is not None: + user["relationship_score"] = relationship_score if "proactive_daily_limit" in payload: user["proactive_daily_limit"] = _safe_int(payload.get("proactive_daily_limit"), -1, -1, 30) for key in ( diff --git a/pages/陪伴面板/app.css b/pages/陪伴面板/app.css index fa580b2..5b0f9c7 100644 --- a/pages/陪伴面板/app.css +++ b/pages/陪伴面板/app.css @@ -2089,6 +2089,59 @@ input[type="search"] { grid-template-columns: repeat(4, minmax(0, 1fr)) auto; } +.companion-intimacy-card { + display: grid; + gap: 10px; + margin: 0 0 14px; + padding: 14px; + border: 1px solid rgba(49, 128, 111, 0.28); + border-radius: 8px; + background: #f7fbf8; + box-shadow: var(--shadow-soft); +} + +.companion-intimacy-head, +.companion-intimacy-meta { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.companion-intimacy-head h3 { + margin: 2px 0 0; +} + +.companion-intimacy-value { + color: var(--accent-strong); + font-size: 28px; + line-height: 1; +} + +.companion-intimacy-form { + grid-template-columns: minmax(180px, 260px) auto; + align-items: end; + margin: 0; +} + +.companion-intimacy-phase { + display: inline-flex; + align-items: baseline; + gap: 6px; + color: var(--text-muted); + font-size: 12px; +} + +.companion-intimacy-phase strong { + color: var(--accent-strong); + font-size: 15px; +} + +.companion-intimacy-note { + grid-column: 1 / -1; + font-size: 12px; +} + .stack-form { display: grid; gap: 10px; diff --git a/pages/陪伴面板/app.js b/pages/陪伴面板/app.js index 1996296..7f9e834 100644 --- a/pages/陪伴面板/app.js +++ b/pages/陪伴面板/app.js @@ -12313,7 +12313,7 @@ function renderUsers() { ? rows.map((user) => ` ${escapeHtml(user.display_name || user.nickname || user.user_id)} ${userPlatformBadge(user)}${Array.isArray(user.alias_user_ids) && user.alias_user_ids.length ? ` 已合并 ${escapeHtml(user.alias_user_ids.length)} 个身份` : ""}
${escapeHtml(user.user_id)} - ${escapeHtml(user.enabled ? "启用" : "停用")} ${escapeHtml(user.relationship_role_label || "次要用户")} ${escapeHtml(user.relationship_stage || "未分层")}
分数 ${escapeHtml(user.relationship_score)} + ${escapeHtml(user.enabled ? "启用" : "停用")} ${escapeHtml(user.relationship_role_label || "次要用户")} ${escapeHtml(user.relationship_stage || "未分层")}
陪伴亲密度 ${escapeHtml(user.relationship_intimacy?.value ?? 0)} · ${escapeHtml(user.relationship_intimacy?.phase?.label || user.relationship_intimacy?.band || "初识")} 入站 ${escapeHtml(user.inbound_count)} · 回复 ${escapeHtml(user.reply_count)}
记忆 ${escapeHtml(user.memory_items)} 条 今日 ${escapeHtml(user.sent_today)} · 总计 ${escapeHtml(user.proactive_sent_count)}
${escapeHtml(user.next_proactive)} ${escapeHtml(user.last_seen)}
上次主动 ${escapeHtml(user.last_sent)} @@ -12383,8 +12383,9 @@ async function renderUserDetail(forceFetch = false) { + ${renderCompanionIntimacyEditor(detail)}
- ${scoreGauge("关系分", detail.relationship_score || 0, -20, 40)} + ${scoreGauge("陪伴亲密度", detail.relationship_intimacy?.value ?? 0, -1200, 1200)} ${scoreGauge("今日主动", detail.sent_today || 0, 0, proactiveGaugeMax(detail.sent_today, detail.effective_daily_limit, detail.effective_daily_limit_unlimited, state.overview?.private?.max_daily_messages || 8))} ${miniStat("片段", detail.dialogue_episode_count || (detail.dialogue_episodes || []).length)} ${miniStat("未完话头", Array.isArray(detail.open_loops) ? activeOpenLoopItems(detail.open_loops).length : (detail.open_loop_count || 0))} @@ -12396,6 +12397,7 @@ async function renderUserDetail(forceFetch = false) { ${renderPrivateDeliveryRoute(detail)} ${renderPrivateBehaviorHabits(detail)} ${emotionGateBlock(detail)} + ${renderUserP4RuntimeStatus(detail.p4_runtime)} ${userWorldbookBlock(detail.worldbook_member)} ${detailBlock("最近对话", "", [["用户消息", detail.last_user_message || ""], ["陪伴回复", detail.last_companion_message || ""]])} ${renderOpenLoopBlock(detail)} @@ -12407,19 +12409,57 @@ async function renderUserDetail(forceFetch = false) { bindUserActions(detail); } +function renderCompanionIntimacyEditor(detail) { + const intimacy = detail?.relationship_intimacy && typeof detail.relationship_intimacy === "object" ? detail.relationship_intimacy : {}; + const min = Number.isInteger(Number(intimacy.min)) ? Number(intimacy.min) : -1200; + const max = Number.isInteger(Number(intimacy.max)) ? Number(intimacy.max) : 1200; + const rawValue = Number(intimacy.value); + const value = Number.isInteger(rawValue) ? Math.max(min, Math.min(max, rawValue)) : 0; + const phase = intimacy.phase && typeof intimacy.phase === "object" ? intimacy.phase : {}; + const phaseLabel = String(phase.label || intimacy.band || "初识"); + const trend = String(intimacy.trend || "unknown"); + const trendLabel = trend === "rising" ? "正在升温" : trend === "cooling" ? "正在降温" : "变化轨迹暂未记录"; + return `
+
COMPANION BASELINE

陪伴亲密度

${value}
+
当前亲密阶段${escapeHtml(phaseLabel)}范围 ${min} 到 ${max} · ${escapeHtml(trendLabel)}
+
+ + 仅调整陪伴关系基础;不影响 P4 好感、黑屋、审核或安全权限。 + +
+
`; +} + function renderRelationshipPanel(panel) { const data = panel && typeof panel === "object" ? panel : {}; - const basis = data.relationship_basis && typeof data.relationship_basis === "object" ? data.relationship_basis : {}; + const intimacy = data.relationship_intimacy && typeof data.relationship_intimacy === "object" ? data.relationship_intimacy : {}; const interaction = data.interaction && typeof data.interaction === "object" ? data.interaction : {}; const memory = data.memory_phase && typeof data.memory_phase === "object" ? data.memory_phase : {}; const network = data.network && typeof data.network === "object" ? data.network : {}; - return detailBlock("Relationship", "Read-only local projection", [ - ["Basis", basis.band || "initial"], - ["Stage", data.relationship_stage || "unclassified"], - ["Interaction", `${interaction.inbound_count || 0} inbound, ${interaction.reply_count || 0} replies (${interaction.reply_band || "unknown"})`], - ["Memory phase", `${memory.phase || "unknown"} (${memory.status || "unavailable"})`], - ["Worldbook", `${network.status || "not_registered"}, ${network.pending_observation_count || 0} pending`], - ["Reply temperature", data.reply_temperature?.status || "live_chat_only"], + const momentumLabels = { rising: "正在升温", cooling: "正在降温", steady: "保持稳定", unknown: "暂不可确认" }; + return detailBlock("关系面板", "好感、当前状态和上下文会在真实聊天中合成为本轮最终回复温度。", [ + ["陪伴亲密度", `${Number.isInteger(Number(intimacy.value)) ? Number(intimacy.value) : 0} / ${Number.isInteger(Number(intimacy.min)) ? Number(intimacy.min) : -1200} 到 ${Number.isInteger(Number(intimacy.max)) ? Number(intimacy.max) : 1200}`], + ["当前亲密阶段", intimacy.phase?.label || intimacy.band || "初识"], + ["变化轨迹", intimacy.trend === "rising" ? "正在升温" : intimacy.trend === "cooling" ? "正在降温" : "暂未记录变化轨迹"], + ["陪伴阶段", data.relationship_stage || "未分层"], + ["互动回应", `${interaction.reply_band || "暂无样本"} · 入站 ${Number(interaction.inbound_count || 0)} / 回复 ${Number(interaction.reply_count || 0)}`], + ["记忆关系阶段", `${memory.phase || "暂不可用"} · ${momentumLabels[memory.momentum_band] || "暂不可确认"}`], + ["关系网", `${network.status || "未登记节点"} · 待观察 ${Number(network.pending_observation_count || 0)}`], + ["回复温度", data.reply_temperature?.status === "live_chat_only" ? "仅在真实聊天中合成" : (data.reply_temperature?.status || "仅在真实聊天中合成")], + ]); +} + +function renderUserP4RuntimeStatus(status) { + const p4 = status && typeof status === "object" ? status : {}; + const gateLabel = p4.reply_gate === "host_verified_event_only" ? "真实聊天事件内生效" : "暂不可确认"; + const warmthLabel = p4.warmth === "host_verified_event_only" ? "仅由已验证聊天事件决定" : "暂不可确认"; + const confinementLabel = p4.confinement === "not_exposed_to_page" ? "页面不读取个人黑屋状态" : "暂不可确认"; + const reviewLabel = p4.manual_review === "not_migrated" ? "候选生产尚未迁移,页面不能审核" : "暂不可确认"; + return detailBlock("P4 安全回复保护", "黑屋和安全温度只在 AstrBot 已验证身份的真实聊天中判断;本页不提供审核、释放或结算操作。", [ + ["回复防护", gateLabel], + ["安全温度", warmthLabel], + ["黑屋状态", confinementLabel], + ["人工审核", reviewLabel], ]); } @@ -13589,6 +13629,23 @@ function bindUserActions(detail) { await renderUserDetail(true); } }; + const scoreForm = $("#relationshipScoreForm"); + const scoreNumber = $("#relationshipScoreNumber"); + scoreForm?.addEventListener("submit", async (event) => { + event.preventDefault(); + const value = Number(scoreNumber?.value); + if (!Number.isInteger(value) || value < -1200 || value > 1200) { + showToast("陪伴亲密度必须是 -1200 到 1200 的整数", "error"); + return; + } + const saved = await runAction( + () => postJson("/user/update", { user_id: detail.user_id, companion_intimacy: value }), + "已保存陪伴亲密度", + event.submitter, + { reload: false }, + ); + if (saved) await refreshSelectedUserDetail(); + }); document.querySelector("[data-private-learning-clear]")?.addEventListener("click", async (event) => { const button = event.currentTarget; if (!requireSecondClick(button, `private-learning-clear:${detail.user_id}`, "再次点击清空该用户的行为习惯", "再次点击清空")) return; diff --git a/tests/test_chat_companion_intimacy_controls.py b/tests/test_chat_companion_intimacy_controls.py new file mode 100644 index 0000000..8f23d01 --- /dev/null +++ b/tests/test_chat_companion_intimacy_controls.py @@ -0,0 +1,203 @@ +from __future__ import annotations + +import ast +from copy import deepcopy +from pathlib import Path +import re +import unittest + + +ROOT = Path(__file__).resolve().parents[1] + + +def _class_method(path: Path, class_name: str, method_name: str) -> ast.FunctionDef | ast.AsyncFunctionDef: + tree = ast.parse(path.read_text(encoding="utf-8")) + owner = next( + node for node in tree.body + if isinstance(node, ast.ClassDef) and node.name == class_name + ) + return deepcopy(next( + node for node in owner.body + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == method_name + )) + + +def _compile_static_method(path: Path, class_name: str, method_name: str) -> object: + method = _class_method(path, class_name, method_name) + module = ast.Module( + body=[ + ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0), + ast.ClassDef(name="Probe", bases=[], keywords=[], body=[method], decorator_list=[]), + ], + type_ignores=[], + ) + namespace = {"re": re} + exec(compile(ast.fix_missing_locations(module), str(path), "exec"), namespace) + return getattr(namespace["Probe"], method_name) + + +class ChatCompanionIntimacyControlTests(unittest.TestCase): + def test_projection_is_bounded_and_has_the_public_contract(self) -> None: + projection = _compile_static_method( + ROOT / "page_api.py", + "PrivateCompanionPageApi", + "_relationship_intimacy_projection", + ) + cases = { + -1200: ("deeply_distant", "极度疏离"), + -801: ("deeply_distant", "极度疏离"), + -800: ("strongly_distant", "强烈疏离"), + -400: ("distant", "疏离"), + 0: ("acquaintance", "初识"), + 200: ("familiar", "熟悉"), + 600: ("close", "亲近"), + 900: ("intimate", "亲密"), + 1200: ("deeply_bonded", "深度联结"), + } + for value, (phase_key, phase_label) in cases.items(): + with self.subTest(value=value): + result = projection(value) + self.assertEqual( + {"value", "band", "phase", "min", "max", "trend"}, + set(result), + ) + self.assertEqual(value, result["value"]) + self.assertEqual(phase_label, result["band"]) + self.assertEqual({"key": phase_key, "label": phase_label}, result["phase"]) + self.assertEqual(-1200, result["min"]) + self.assertEqual(1200, result["max"]) + self.assertEqual("unknown", result["trend"]) + self.assertEqual(-1200, projection(-99999)["value"]) + self.assertEqual(1200, projection(99999)["value"]) + + def test_manual_input_accepts_only_range_limited_integers(self) -> None: + parser = _compile_static_method( + ROOT / "page_api_users_groups.py", + "PrivateCompanionPageApiUsersGroupsMixin", + "_relationship_score_input", + ) + for raw, expected in ((-1200, -1200), (0, 0), (1200, 1200), (" +42 ", 42)): + with self.subTest(raw=raw): + self.assertEqual(expected, parser(raw)) + for raw in (True, False, 12.0, "", " ", "1.0", "1e2", "1201", "-1201"): + with self.subTest(raw=raw): + with self.assertRaises(ValueError): + parser(raw) + + def test_update_contract_rejects_duplicate_fields_and_writes_legacy_score_inside_lock(self) -> None: + path = ROOT / "page_api_users_groups.py" + update_user = _class_method(path, "PrivateCompanionPageApiUsersGroupsMixin", "update_user") + constants = {node.value for node in ast.walk(update_user) if isinstance(node, ast.Constant) and type(node.value) is str} + self.assertTrue({"companion_intimacy", "relationship_score"}.issubset(constants)) + self.assertTrue({"person_id", "candidate_id", "attestation", "ledger", "affinity", "confinement"}.isdisjoint(constants)) + + locks = [ + node for node in ast.walk(update_user) + if isinstance(node, ast.AsyncWith) + and any( + isinstance(item.context_expr, ast.Attribute) + and item.context_expr.attr == "_data_lock" + for item in node.items + ) + ] + self.assertEqual(1, len(locks)) + writes = [ + node for node in ast.walk(update_user) + if isinstance(node, ast.Assign) + and any( + isinstance(target, ast.Subscript) + and isinstance(target.value, ast.Name) + and target.value.id == "user" + and isinstance(target.slice, ast.Constant) + and target.slice.value == "relationship_score" + for target in node.targets + ) + ] + self.assertEqual(1, len(writes)) + self.assertGreater(writes[0].lineno, locks[0].lineno) + self.assertLessEqual(writes[0].end_lineno or writes[0].lineno, locks[0].end_lineno or locks[0].lineno) + + def test_summary_and_relationship_panel_share_the_same_safe_projection(self) -> None: + path = ROOT / "page_api.py" + summary = _class_method(path, "PrivateCompanionPageApi", "_user_summary") + panel = _class_method(path, "PrivateCompanionPageApi", "_relationship_panel") + for function in (summary, panel): + calls = [ + node for node in ast.walk(function) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "_relationship_intimacy_projection" + ] + self.assertEqual(1, len(calls), function.name) + constants = {node.value for node in ast.walk(function) if isinstance(node, ast.Constant) and type(node.value) is str} + self.assertIn("relationship_intimacy", constants) + self.assertTrue( + {"person_id", "candidate_id", "attestation", "ledger", "affinity", "confinement"}.isdisjoint(constants), + function.name, + ) + + def test_frontend_uses_number_input_and_the_dedicated_update_field(self) -> None: + source = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8") + editor_start = source.index("function renderCompanionIntimacyEditor") + panel_start = source.index("function renderRelationshipPanel", editor_start) + editor = source[editor_start:panel_start] + bind_start = source.index("function bindUserActions") + bind_end = source.index("function renderGroups", bind_start) + bindings = source[bind_start:bind_end] + self.assertIn('type="number"', editor) + self.assertIn('name="companion_intimacy"', editor) + self.assertIn("当前亲密阶段", editor) + self.assertIn("不影响 P4 好感、黑屋、审核或安全权限", editor) + self.assertNotIn('type="range"', editor) + self.assertNotIn("relationship_score", source) + self.assertIn('postJson("/user/update", { user_id: detail.user_id, companion_intimacy: value })', bindings) + self.assertIn("Number.isInteger(value)", bindings) + self.assertIn("value < -1200 || value > 1200", bindings) + + def test_p4_page_status_is_fixed_and_cannot_resolve_a_user(self) -> None: + projection = _compile_static_method( + ROOT / "page_api.py", + "PrivateCompanionPageApi", + "_p4_page_status_projection", + ) + status = projection() + self.assertEqual( + { + "schema_version", + "scope", + "reply_gate", + "warmth", + "confinement", + "manual_review", + "action_available", + }, + set(status), + ) + self.assertEqual("chat_event_only", status["scope"]) + self.assertFalse(status["action_available"]) + self.assertEqual("not_migrated", status["manual_review"]) + + get_user = _class_method(ROOT / "page_api_users_groups.py", "PrivateCompanionPageApiUsersGroupsMixin", "get_user") + calls = [ + node for node in ast.walk(get_user) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "_p4_page_status_projection" + ] + self.assertEqual(1, len(calls)) + self.assertEqual([], calls[0].args) + constants = {node.value for node in ast.walk(get_user) if isinstance(node, ast.Constant) and type(node.value) is str} + self.assertTrue({"person_id", "ledger", "candidate_id", "attestation"}.isdisjoint(constants)) + + source = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8") + start = source.index("function renderUserP4RuntimeStatus") + end = source.index("function renderPrivateDeliveryRoute", start) + panel = source[start:end] + self.assertIn("页面不读取个人黑屋状态", panel) + self.assertIn("页面不能审核", panel) + for forbidden in ("approve", "reject", "release", "candidate_id", "attestation", "ledger"): + self.assertNotIn(forbidden, panel) + + +if __name__ == "__main__": + unittest.main()