From baa75d05086294d4990f8a6c3ed67eb2c03736ae Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sat, 1 Aug 2026 01:32:27 +0800 Subject: [PATCH] feat(panel): edit companion intimacy directly --- page_api.py | 46 ++++++++++--- page_api_users_groups.py | 26 +++++++ pages/陪伴面板/app.css | 53 +++++++++++++++ pages/陪伴面板/app.js | 50 ++++++++++++-- tests/test_companion_intimacy_controls.py | 82 +++++++++++++++++++++++ 5 files changed, 244 insertions(+), 13 deletions(-) create mode 100644 tests/test_companion_intimacy_controls.py diff --git a/page_api.py b/page_api.py index cbb0717..ef7fe1b 100644 --- a/page_api.py +++ b/page_api.py @@ -9113,6 +9113,35 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): } ) + @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", + } + def _user_summary(self, user_id: str, user: dict[str, Any]) -> dict[str, Any]: last_seen = user.get("last_seen", 0) last_sent = user.get("last_sent", 0) @@ -9164,14 +9193,10 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): 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_score = self._int(user.get("relationship_score")) + relationship_intimacy = self._relationship_intimacy_projection(self._int(user.get("relationship_score"))) relationship_basis = { - "value": relationship_score, - "band": ( - "亲近基础" if relationship_score >= 55 - else "熟悉基础" if relationship_score >= 3 - else "初始基础" - ), + "value": relationship_intimacy["value"], + "band": relationship_intimacy["phase"]["label"], } return { "user_id": user_id_text, @@ -9243,6 +9268,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): "reply_count": user.get("reply_count", 0), "proactive_sent_count": user.get("proactive_sent_count", 0), "relationship_basis": relationship_basis, + "relationship_intimacy": relationship_intimacy, "relationship_stage": relationship_stage, "relationship_state": relationship_state, "pending_emotion_judgement": pending_emotion_judgement, @@ -9272,6 +9298,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): ) -> dict[str, Any]: """Build a safe, user-scoped relationship display projection.""" score = self._int(user.get("relationship_score")) + relationship_intimacy = self._relationship_intimacy_projection(score) inbound = max(0, self._int(user.get("inbound_count"))) proactive = max(0, self._int(user.get("proactive_sent_count"))) replies = max(0, self._int(user.get("reply_count"))) @@ -9332,10 +9359,11 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): pending_count = max(0, self._int(worldbook_member.get("pending_observation_count"))) return { "relationship_basis": { - "value": score, - "band": "亲近基础" if score >= 55 else "熟悉基础" if score >= 3 else "初始基础", + "value": relationship_intimacy["value"], + "band": relationship_intimacy["phase"]["label"], }, "relationship_stage": self._single_line(relationship_stage, 20) or "未分层", + "relationship_intimacy": relationship_intimacy, "interaction": { "inbound_count": inbound, "reply_count": replies, diff --git a/page_api_users_groups.py b/page_api_users_groups.py index 037e39d..9b466ad 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 relationship 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: @@ -82,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: @@ -106,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 fbe166b..fa0ad6a 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 4b70441..6d85d01 100644 --- a/pages/陪伴面板/app.js +++ b/pages/陪伴面板/app.js @@ -12054,7 +12054,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_basis?.band || "初始基础")} + ${escapeHtml(user.enabled ? "启用" : "停用")} ${escapeHtml(user.relationship_role_label || "次要用户")} ${escapeHtml(user.relationship_stage || "未分层")}
陪伴亲密度 ${escapeHtml(user.relationship_intimacy?.value ?? user.relationship_basis?.value ?? 0)} · ${escapeHtml(user.relationship_intimacy?.phase?.label || user.relationship_intimacy?.band || user.relationship_basis?.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)} @@ -12124,8 +12124,9 @@ async function renderUserDetail(forceFetch = false) { + ${renderCompanionIntimacyEditor(detail)}
- ${scoreGauge("关系基础", detail.relationship_basis?.value || 0, -20, 40)} + ${scoreGauge("陪伴亲密度", detail.relationship_intimacy?.value ?? detail.relationship_basis?.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))} @@ -12149,16 +12150,40 @@ 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 : {}; const reply = data.reply_temperature && typeof data.reply_temperature === "object" ? data.reply_temperature : {}; const momentumLabels = { rising: "正在升温", cooling: "正在降温", steady: "保持稳定", unknown: "暂不可确认" }; return detailBlock("关系面板", "好感、当前状态和上下文会在真实聊天中合成为本轮最终回复温度。", [ - ["关系基础", basis.band || "初始基础"], + ["陪伴亲密度", `${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.label || "暂不可用"} · ${momentumLabels[memory.momentum_band] || "暂不可确认"}`], @@ -13369,6 +13394,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_companion_intimacy_controls.py b/tests/test_companion_intimacy_controls.py new file mode 100644 index 0000000..6ce9d54 --- /dev/null +++ b/tests/test_companion_intimacy_controls.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +import importlib.util +from pathlib import Path +import sys +import types +import unittest + +from tests._host_stub import install + + +install() + +ROOT = Path(__file__).resolve().parents[1] + + +def _user_api_mixin() -> type: + module_name = "companion_intimacy_test.page_api_users_groups" + if module_name in sys.modules: + return sys.modules[module_name].PrivateCompanionPageApiUsersGroupsMixin + quart = types.ModuleType("quart") + quart.request = object() + sys.modules.setdefault("quart", quart) + package = types.ModuleType("companion_intimacy_test") + package.__path__ = [str(ROOT)] + sys.modules[package.__name__] = package + spec = importlib.util.spec_from_file_location(module_name, ROOT / "page_api_users_groups.py") + if spec is None or spec.loader is None: + raise AssertionError("could not load user page API test module") + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + spec.loader.exec_module(module) + return module.PrivateCompanionPageApiUsersGroupsMixin + + +class CompanionIntimacyInputTests(unittest.TestCase): + def test_manual_value_accepts_only_bounded_integers(self) -> None: + parser = _user_api_mixin()._relationship_score_input + self.assertEqual(-1200, parser(-1200)) + self.assertEqual(0, parser(" 0 ")) + self.assertEqual(1200, parser("+1200")) + + for value in (True, False, "", "2.5", 2.0, -1201, 1201, object()): + with self.subTest(value=repr(value)): + with self.assertRaises(ValueError): + parser(value) + + def test_update_path_has_a_dedicated_public_field_and_locked_write(self) -> None: + source = (ROOT / "page_api_users_groups.py").read_text(encoding="utf-8") + start = source.index("async def update_user") + end = source.index("async def delete_user", start) + update_path = source[start:end] + self.assertIn('"companion_intimacy"', update_path) + self.assertIn("async with self.plugin._data_lock", update_path) + self.assertIn('user["relationship_score"] = relationship_score', update_path) + self.assertIn("self.plugin._save_data_sync()", update_path) + + +class CompanionIntimacyPageWiringTests(unittest.TestCase): + def test_safe_dto_and_editor_are_wired_without_p4_actions(self) -> None: + page_api = (ROOT / "page_api.py").read_text(encoding="utf-8") + app_js = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8") + + self.assertGreaterEqual(page_api.count('"relationship_intimacy"'), 2) + self.assertIn('"min": -1200', page_api) + self.assertIn('"max": 1200', page_api) + self.assertIn('"phase": {"key": phase_key, "label": phase_label}', page_api) + self.assertIn("function renderCompanionIntimacyEditor", app_js) + self.assertNotIn('id="relationshipScoreRange"', app_js) + self.assertIn("当前亲密阶段", app_js) + self.assertIn("companion_intimacy: value", app_js) + self.assertIn("不影响 P4 好感、黑屋、审核或安全权限", app_js) + + editor_start = app_js.index("function renderCompanionIntimacyEditor") + editor_end = app_js.index("function renderRelationshipPanel", editor_start) + editor = app_js[editor_start:editor_end] + for forbidden in ("ledger", "attestation", "candidate_id", "person_id"): + self.assertNotIn(forbidden, editor) + + +if __name__ == "__main__": + unittest.main()