From fd1f8be5893e6b4e43be60ce4b283fb3712a206b Mon Sep 17 00:00:00 2001 From: timeance <30307526+timeance@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:59:00 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=85=A8=E5=B1=80?= =?UTF-8?q?=E8=B5=84=E6=96=99=E9=A2=84=E8=A7=88=E5=B9=B6=E6=8A=98=E5=8F=A0?= =?UTF-8?q?=E5=AE=8C=E6=95=B4=E6=8F=90=E7=A4=BA=E8=AF=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 14 +-- api/page_api.py | 22 +++- docs/RELATION_MATERIALS.md | 8 +- main.py | 2 +- metadata.yaml | 2 +- pages/dashboard/app.css | 7 +- pages/dashboard/app.js | 51 +++++++-- services/inject_service.py | 11 +- tests/dashboard.test.cjs | 50 +++++++++ tests/test_relation_materials.py | 172 ++++++++++++++++++++++++++++++- 10 files changed, 303 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7443f45..45c080e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,14 +1,8 @@ # 更新说明 -## 0.7.1 — 2026-11-14 +## 0.7.2 — 2026-11-15 -- **印象跟得上相处的变化**:新互动可以修正旧判断,同一件事只作为一份依据。撤销错误记录后,受影响的印象也会停止用于回复。 -- **保留玩笑和自述的语境**:整理资料时保留来源与限定,提醒模型区分成员自述、临时角色扮演和已确认的关系。 -- **当前资料,一键预览**:在成员详情查看当前选用的关系、印象和经历,以及取舍原因。预览不调用模型,也不改变关系状态。 -- **回复依据,可以回看**:在系统诊断查看当轮实际提供的关系资料与筛选原因。正文需当时开启「完整上下文」且记录完整保留;未保存的内容不会补写。 +- **全部群也能预览**:全局空间无需先选群,即可查看当前成员的关系资料。选择具体群后,预览会采用该群生效的模板。 +- **先看资料,再看提示词**:预览直接展示关系释义、选中的印象和经历;筛选原因、完整注入文本按需展开,不再被大段提示词占满。历史诊断中的完整文本也改为折叠查看。 -原有关系评分规则不变,自定义提示词和模板继续保留,无需清空旧数据。 - -诊断未设置档位时,默认改为「原文+评估」;已有明确设置不变,新安装仍默认关闭诊断。 - -**升级提醒**:本次包含数据结构升级。请先停止插件,备份代码、配置和完整数据目录;回退时需一并恢复升级前的备份。详见 [使用与升级说明](docs/RELATION_MATERIALS.md)。 +预览仍不调用模型、不改变关系状态;全局空间不披露其他群的印象或经历。关系评分、自定义模板和诊断档位保持不变。 diff --git a/api/page_api.py b/api/page_api.py index 91f9322..cbccd0a 100644 --- a/api/page_api.py +++ b/api/page_api.py @@ -407,7 +407,7 @@ async def run(): if request.method != "GET": raise _PageRequestError bot_id, mode = self._target(params) - group_id = self._required_account(params, "group_id") + group_id = self._relation_group(params, mode) user_id = self._required_account(params, "user_id") deps = self._runtime.peek(bot_id, mode) if deps is None: @@ -433,8 +433,15 @@ async def run(): description = deps.favor.describe_relation( rec.familiarity, rec.favor, rec.trust ) + # 全局聚合关系不绑定真实群,沿用全局模板,不猜测群级覆盖。 + preview_group = None if group_id == GLOBAL_GROUP else group_id + template = ( + deps.prompts.resolve("behavior") + if preview_group is None + else deps.prompts.resolve("behavior", bot_id, preview_group) + ) preview = deps.inject.build_relation_materials( - deps.prompts.resolve("behavior", bot_id, group_id), + template, relationship=description.text, impression=rec.impression, events=events, @@ -442,18 +449,25 @@ async def run(): identity=dict( bot_id=bot_id, scope_mode=mode, - group_id=group_id, + group_id=preview_group, user_id=user_id, ), captured_at=now, selection=selection, impression_valid=rec.impression_valid, impression_origin=rec.impression_origin, + include_content=True, ) preview.update( available=True, injection_enabled=deps.inject_enabled, - note="当前有效数据的只读预览;不是历史实际输入。" + note="当前有效资料的只读预览。" + + ("全局空间仅提供关系释义。" if mode == "global" else "") + + ( + "全部群使用全局模板;选择具体群可预览该群模板。" + if preview_group is None + else "" + ) + ("注入当前已关闭。" if not deps.inject_enabled else ""), ) return self._response({"success": True, "preview": preview}) diff --git a/docs/RELATION_MATERIALS.md b/docs/RELATION_MATERIALS.md index 9f4493f..1c795b7 100644 --- a/docs/RELATION_MATERIALS.md +++ b/docs/RELATION_MATERIALS.md @@ -1,10 +1,12 @@ -# 关系资料与印象(0.7.1) +# 关系资料与印象 Bond 提供当前关系释义、可修正的成员印象和少量有效经历。关系计算、事件分类、评分、衰减、独立保温、额度、舍入和被动熟悉度规则均沿用 0.7.0。 ## 使用 -- 成员详情 →「当前关系资料预览」→「只读预览」。先选择 Bot、空间和真实群。只读当前状态,不生成回复、不调用模型、不刷新印象、不生成称谓、不结束临时关系、不提交衰减或推进评估进度。未加载空间显示缺少资料,不为预览初始化空间。全局关系仍不披露其他群的印象或经历。 +- 成员详情 →「当前关系资料预览」→「只读预览」。先选择 Bot、空间和成员;按群空间须指定群,全局空间可保留「全部群」。全部群使用全局模板,选择具体群后使用该 Bot、该群生效的模板。全局空间仅提供共享关系释义,不披露其他群的印象或经历。 +- 预览默认展示选中的关系释义、成员印象和经历;「筛选说明」查看取舍原因,「完整注入文本(含提示词)」查看本次完整文本。内容来自同一次构建的筛选结果,不从提示词中截取或另行推断;自定义模板未采用、已失效或超出预算的资料不会显示为已选用。 +- 预览只读当前状态,不生成回复、不调用模型、不刷新印象、不生成称谓、不结束临时关系、不提交衰减或推进评估进度。未加载空间显示缺少资料,不为预览初始化空间。 - 设置 → 系统诊断 →「查看历史关系资料」。最多显示最近20条已保留的注入记录及程序筛选理由。历史正文来自当时保存的请求,不查当前关系回填。完整上下文记录遭脱敏、裁剪、容量淘汰或没有元信息时,明确显示无法还原或未记录。 - 历史记录表示 Bond 处理边界实际提供、观察到的内容,不保证是所有后续插件处理后的最终网络请求,也不是主回复模型的隐藏推理。 - 清除诊断会清除诊断文件、待写副本和页面已加载副本;不删除关系、评估流水或 AstrBot 历史。关闭/降低档位不会改写已保存历史。 @@ -46,7 +48,7 @@ schema 21 仅增加印象局部版本、可用标记、来源种类和日志依 ## 升级与回退 -停止插件写入后备份插件代码、AstrBot 配置和完整插件数据目录,安装0.7.1包后重载。无需清空关系数据或重新生成全部印象。回退时停止插件并成组恢复原代码、配置和升级前数据备份;旧版本不能直接打开 schema 21。备份与恢复也可使用已有管理功能。本地包交付不包含推送、发布或生产部署。 +停止插件写入后备份插件代码、AstrBot 配置和完整插件数据目录,安装新包后重载。无需清空关系数据或重新生成全部印象。0.7.2 沿用 0.7.1 的 schema 21,从 0.7.1 升级不迁移数据;回退到 0.7.1 可恢复原插件代码。从 0.7.0 及更早版本升级涉及 schema 21,回退须成组恢复原代码、配置和升级前数据备份。备份与恢复也可使用已有管理功能。 ## 验证与模型行为对照 diff --git a/main.py b/main.py index 03bdeb0..99e8084 100644 --- a/main.py +++ b/main.py @@ -84,7 +84,7 @@ def _group_entry_id(event) -> str | None: "astrbot_plugin_bond", "yiwuerxin, Timeance", "Bond 关系好感系统:三维关系与成员印象", - "0.7.1", + "0.7.2", "https://github.com/timeance/Astrbot_plugin_bond", ) class BondPlugin(Star): diff --git a/metadata.yaml b/metadata.yaml index 642c79d..e7ae084 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -2,7 +2,7 @@ name: astrbot_plugin_bond display_name: Bond 关系好感系统 short_desc: 按 Bot 隔离的三维关系与成员印象 desc: 保存熟悉度、亲近度、信任度与成员印象,支持分级评估、人格适配及管理面板。 -version: 0.7.1 +version: 0.7.2 author: yiwuerxin, Timeance repo: https://github.com/timeance/Astrbot_plugin_bond tags: diff --git a/pages/dashboard/app.css b/pages/dashboard/app.css index 110a8c1..b255a0d 100644 --- a/pages/dashboard/app.css +++ b/pages/dashboard/app.css @@ -1179,6 +1179,11 @@ button:focus-visible, select:focus-visible, input:focus-visible, textarea:focus- white-space: pre-wrap; word-break: break-word; } +/* 完整提示词在折叠区内独立滚动,沿用正文与主题样式。 */ +.xx-material-block { + max-height: 18rem; + overflow: auto; +} .xx-modal-actions { display: flex; justify-content: flex-end; @@ -1539,7 +1544,7 @@ details.xx-form-card[open] > summary::after { font-weight: 600; cursor: pointer; } -.xx-member-history[open] summary { +.xx-member-history[open] > summary { color: var(--xx-accent-deep); border-bottom: 1px solid var(--xx-line); margin-bottom: 8px; diff --git a/pages/dashboard/app.js b/pages/dashboard/app.js index 9800837..cb4dc4a 100644 --- a/pages/dashboard/app.js +++ b/pages/dashboard/app.js @@ -664,13 +664,12 @@ createApp({ const snapshot = scopeSnapshot(); const revision = scopeRevision.value; const target = memberRequestTarget.value; - const member = memberDetail.value; - if (!snapshot || !member || !target || materialPreviewLoading.value) return; + if (!canPreviewMaterials.value || materialPreviewLoading.value) return; materialPreviewLoading.value = true; materialPreview.value = null; try { const data = await scopedGet("member", { - action: "preview", group_id: member.group_id, user_id: member.user_id, + action: "preview", group_id: target.group_id, user_id: target.user_id, }, snapshot); if (!isCurrentMemberRequest(target, revision)) return; if (!data.success) throw new Error(data.error || "预览失败"); @@ -682,6 +681,12 @@ createApp({ } }; const memberDetail = ref(null); + const canPreviewMaterials = computed(() => { + const target = memberRequestTarget.value; + return !!memberDetail.value && isCurrentMemberRequest(target, scopeRevision.value) + && isRealAccount(target.user_id) + && (isRealAccount(target.group_id) || (target.scope_mode === "global" && !target.group_id)); + }); const memberLoading = ref(false); let expiryTimer; const clearExpiryTimer = () => { clearTimeout(expiryTimer); expiryTimer = undefined; }; @@ -1400,7 +1405,7 @@ createApp({ undoPreview, openUndo, closeUndo, confirmUndo, selectedLog, selectedLogGroup, showDetail, showLogMember, backToLogGroup, closeDetail, isPassiveLog, isPassiveGroup, passiveLogMembers, passiveLogPreview, passiveLogDelta, logGroupLabel, isLogReversed, - materialPreview, materialPreviewLoading, previewMaterials, materialReason, materialKind, materialHistory, + materialPreview, materialPreviewLoading, canPreviewMaterials, previewMaterials, materialReason, materialKind, materialHistory, memberDetail, memberLoading, memberNotice, memberNoticeError, memberSaveLoading, relationEditMode, temporaryMinutes, endTemporary, relationForm, profileForm, openMember, closeMember, refreshNames, saveRelation, saveProfile, refreshImpression, fetchBots, selectBot, applyMode, backupScope, prepareRestore, @@ -1885,7 +1890,10 @@ createApp({

{{ item.note }}

筛选说明未记录

{{ materialKind(entry.kind) }} #{{ entry.log_id }}:{{ materialReason(entry.reason) }}

-
{{ item.block }}
+
+ 完整注入文本(含提示词) +
{{ item.block }}
+

诊断记录占用:当前空间 {{ diagnosticSize(diagnosticStats?.size_available ? diagnosticStats.disk_bytes : null) }} · 全部 {{ diagnosticSize(diagnosticStats?.size_available ? diagnosticStats.total_disk_bytes : null) }} / {{ diagnosticSize(diagnosticStats?.max_bytes) }}

@@ -2033,12 +2041,35 @@ createApp({
临时关系操作记录({{ memberDetail.temporary_audit.length }})

{{ fmtTime(item.ts) }} · {{ item.actor }} · {{ ({created:'创建',updated:'修改',cancelled:'结束',expired:'到期'})[item.action] || item.action }} · 熟悉度 {{ item.details.values.familiarity }},亲近度 {{ item.details.values.affinity }},信任度 {{ item.details.values.trust }} · 截至 {{ fmtTime(item.details.expires_at) }} · {{ item.details.reason }}

当前关系资料预览 -

按当前有效资料模拟选择,不调用模型。请先选择真实群;历史输入在诊断中查看。

- +

查看当前会选用的资料,不调用模型、不改变关系。历史输入在系统诊断中查看。

+
diff --git a/services/inject_service.py b/services/inject_service.py index 1a845ec..11a254e 100644 --- a/services/inject_service.py +++ b/services/inject_service.py @@ -206,6 +206,7 @@ def build_relation_materials( impression_valid=True, impression_origin="legacy", budget=MATERIAL_BUDGET, + include_content: bool = False, ) -> dict: """整个块共用长度预算;只舍弃完整条目,不截断主语、否定和条件。""" import hashlib @@ -301,7 +302,7 @@ def render(imp, items): for decision in decisions: if decision["reason"] == "selected": decision["reason"] = "length_budget" - return dict( + result = dict( block=block, selection=decisions, captured_at=captured_at, @@ -310,6 +311,14 @@ def render(imp, items): budget=budget, chars=len(block), ) + if include_content: + # 管理预览直接呈现本次选中的内容;消息快照和诊断不另存正文副本。 + result["content"] = dict( + relationship=relationship if block and "relationship" in fields else "", + impression=imp if block else "", + events=items if block else [], + ) + return result def inject(self, req, block: str) -> None: """把档案块追加到 req.system_prompt(只追加不覆盖)。""" diff --git a/tests/dashboard.test.cjs b/tests/dashboard.test.cjs index 70b8a21..629ae99 100644 --- a/tests/dashboard.test.cjs +++ b/tests/dashboard.test.cjs @@ -1187,3 +1187,53 @@ test('diagnostic history comes from recorded rows and clear removes the displaye pending[0].resolve({success:true,diagnostics:{}});await cleared; assert.equal(ui.materialHistory.value.length,0); }); + + +for(const group of ['', '7001']) test(`global preview binds the selected member and group ${group || 'all'}`,async()=>{ + const {ui,pendingGets,pending}=harness(); + ui.selectedMode.value='global';ui.filterGroup.value=group; + ui.groups.value=[{group_id:'7001'},{group_id:'7002'}]; + assert.equal(ui.canPreviewMaterials.value,false); + const opened=ui.openMember({group_id:'7002',user_id:'8001'}); + pendingGets[0].resolve({success:true,member:{group_id:group,user_id:'8001',tags:[],impression:''}});await opened; + assert.equal(ui.canPreviewMaterials.value,true); + const preview=ui.previewMaterials(); + const params=pendingGets[1].params; + assert.equal(params.bot_id,'10001');assert.equal(params.scope_mode,'global'); + assert.equal(params.group_id,group);assert.equal(params.user_id,'8001');assert.equal(params.action,'preview'); + await ui.previewMaterials();assert.equal(pendingGets.length,2);assert.equal(pending.length,0); + const content={relationship:'熟悉,但信任仍有保留。',impression:'',events:[]}; + pendingGets[1].resolve({success:true,preview:{available:true,content,block:'完整提示词',selection:[]}});await preview; + assert.equal(ui.materialPreview.value.content,content); + assert.equal(ui.materialPreviewLoading.value,false); + ui.selectedMode.value='per_group'; + assert.equal(ui.canPreviewMaterials.value,false); + await ui.previewMaterials();assert.equal(pendingGets.length,2); + ui.closeMember();assert.equal(ui.canPreviewMaterials.value,false); +}); + +test('per-group preview still requires a real group and ignores an old scope result',async()=>{ + const {ui,pendingGets}=harness(); + await ui.openMember({group_id:'',user_id:'8001'}); + assert.equal(ui.canPreviewMaterials.value,false);assert.equal(pendingGets.length,0); + await ui.previewMaterials();assert.equal(pendingGets.length,0); + const opened=ui.openMember({group_id:'7001',user_id:'8001'}); + pendingGets[0].resolve({success:true,member:{group_id:'7001',user_id:'8001',tags:[]}});await opened; + const preview=ui.previewMaterials(); + ui.selectedBot.value='20002';await ui.selectBot(); + pendingGets[1].resolve({success:true,preview:{block:'旧Bot资料'}});await preview; + assert.equal(ui.materialPreview.value,null);assert.equal(ui.materialPreviewLoading.value,false); +}); + +test('preview presents selected content as text and keeps full prompts collapsed',()=>{ + const source=fs.readFileSync(path.join(__dirname,'../pages/dashboard/app.js'),'utf8'); + const section=source.slice(source.indexOf('当前关系资料预览'),source.indexOf('近期评审')); + assert.match(section,/:disabled="materialPreviewLoading \|\| !canPreviewMaterials"/); + assert.ok(section.includes('{{ materialPreview.content.relationship }}')); + assert.ok(section.includes('{{ materialPreview.content.impression }}')); + assert.ok(section.includes('materialPreview.content.events')); + assert.doesNotMatch(section,/v-html|]*\sopen(?:\s|>|=)/); + assert.match(section,/
]*>\s*完整注入文本(含提示词)<\/summary>\s*]*>{{ materialPreview.block }}<\/pre>\s*<\/details>/); + assert.match(source,/
]*>\s*完整注入文本(含提示词)<\/summary>/); + assert.ok(!section.includes('请先选择真实群')); +}); diff --git a/tests/test_relation_materials.py b/tests/test_relation_materials.py index a61b16f..bd9b624 100644 --- a/tests/test_relation_materials.py +++ b/tests/test_relation_materials.py @@ -4,7 +4,7 @@ import json import sqlite3 from types import SimpleNamespace -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock, Mock, patch import pytest @@ -302,12 +302,16 @@ def test_schema21_keeps_old_data_and_rolls_back_failed_upgrade(): conn.close() +@pytest.mark.parametrize( + "mode,group", + [("per_group", "7001"), ("global", "7001"), ("global", ""), ("global", None)], +) def test_preview_is_read_only_even_after_override_expiry( - tmp_path, page_module, monkeypatch + tmp_path, page_module, monkeypatch, mode, group ): async def run(listener): router = BotScopeStorageRouter(tmp_path) - deps = await make_deps(listener, router, tmp_path) + deps = await make_deps(listener, router, tmp_path, mode=mode) await seed(deps.favor._storage, 1) await deps.favor.set_temporary( "7001", @@ -329,8 +333,8 @@ async def run(listener): AsyncMock( return_value=dict( bot_id="10001", - scope_mode="per_group", - group_id="7001", + scope_mode=mode, + group_id=group, user_id="8001", action="preview", ) @@ -364,6 +368,10 @@ async def run(listener): {"group_id": ""}, {"scope_mode": "other"}, {"user_id": '{"id":"8002"}'}, + {"scope_mode": "global", "group_id": "__global__"}, + {"scope_mode": "global", "group_id": "not-a-group"}, + {"scope_mode": "global", "group_id": "", "bot_id": ""}, + {"scope_mode": "global", "group_id": "", "user_id": ""}, ], ) def test_preview_requires_authenticated_explicit_binding( @@ -411,6 +419,7 @@ async def run(listener, components): req = request() await listener.on_llm_request(deps, event, req) assert req._bond_injected_snapshot is frozen + assert "content" not in json.loads(frozen.materials_json) assert frozen.block in req.system_prompt exported = await recorder.export("10001", "per_group") history = recorder.material_history(exported) @@ -721,3 +730,156 @@ async def run(): await db.close() asyncio.run(run()) + + +@pytest.mark.parametrize("group", [None, "", "7001", "7002"]) +def test_global_preview_uses_shared_relation_and_explicit_template( + tmp_path, page_module, monkeypatch, group +): + async def run(listener): + router = BotScopeStorageRouter(tmp_path / "db") + deps = await make_deps(listener, router, tmp_path, mode="global") + await deps.favor.set_relation( + "7001", + "8001", + familiarity=80, + affinity=80, + trust=80, + reason="不可跨群提供的经历", + event_id="global-event", + ) + await deps.favor._storage.set_impression( + "__global__", + "8001", + "不可跨群提供的印象", + [], + ) + await deps.favor.set_relation( + "7002", + "8002", + familiarity=0, + affinity=0, + trust=-80, + reason="其他成员的经历", + event_id="other-member-event", + ) + deps.prompts.set_template( + "behavior", + mode="custom", + template="全局模板 {relationship} / {impression} / {events}", + ) + deps.prompts.set_template( + "behavior", + "10001", + "7001", + mode="custom", + template="指定群模板 {relationship} / {impression} / {events}", + ) + deps.prompts.set_template( + "behavior", + "20002", + "7001", + mode="custom", + template="其他Bot模板 {relationship}", + ) + saved = deps.prompts.path.read_bytes() + before = "\n".join(deps.favor._storage._c().iterdump()) + runtime = SimpleNamespace( + known_bot_ids=lambda: ["10001", "20002"], + peek=Mock(return_value=deps), + select=AsyncMock(side_effect=AssertionError("不能装配空间")), + ) + page = page_module.PageApi(runtime) + params = dict( + bot_id="10001", scope_mode="global", user_id="8001", action="preview" + ) + if group is not None: + params["group_id"] = group + monkeypatch.setattr(page, "_params", AsyncMock(return_value=params)) + monkeypatch.setattr(page_module, "request", SimpleNamespace(method="GET")) + payload, status = await page.handle_member() + assert status == 200 and payload["preview"]["available"] + preview = payload["preview"] + assert preview["content"] == dict( + relationship=deps.favor.describe_relation(80, 80, 80).text, + impression="", + events=[], + ) + assert ("指定群模板" if group == "7001" else "全局模板") in preview["block"] + assert "其他Bot模板" not in preview["block"] + assert "不可跨群" not in json.dumps(preview, ensure_ascii=False) + assert "其他成员" not in json.dumps(preview, ensure_ascii=False) + identity = json.loads(preview["block"].splitlines()[1].split(":", 1)[1]) + assert identity == dict( + bot_id="10001", + scope_mode="global", + group_id=group or None, + user_id="8001", + captured_at=NOW, + ) + assert ("全部群使用全局模板" in preview["note"]) == (not group) + runtime.peek.assert_called_once_with("10001", "global") + runtime.select.assert_not_called() + assert deps.prompts.path.read_bytes() == saved + assert before == "\n".join(deps.favor._storage._c().iterdump()) + assert deps.registry.size == 0 + await router.close() + + with offline_listener() as (listener, _, _), patch("time.time", return_value=NOW): + asyncio.run(run(listener)) + + +@pytest.mark.parametrize( + "case", + ["selected", "omitted", "no_fields", "invalid", "event_budget", "block_budget"], +) +def test_preview_content_is_the_same_selected_material_without_prompt_parsing(case): + template = "自定义提示 {relationship} / {impression} / {events}" + duplicate, revoked = row(), row(2) + revoked["reversed"] = True + kwargs = dict( + relationship="熟悉,但信任仍有保留。\n按当前状态交流。", + impression="成员表示愿意帮忙,尚未看到实际行动。", + events=[row(), duplicate, revoked], + ) + if case == "omitted": + template = "只选经历 {events}" + if case == "no_fields": + template = "用户自定义的固定提示" + if case == "invalid": + kwargs["impression_valid"] = False + if case == "event_budget": + kwargs["budget"] = ( + len(InjectService.build_relation_block(template, **kwargs)) - 1 + ) + if case == "block_budget": + kwargs["budget"] = 1 + ordinary = InjectService.build_relation_materials(template, **kwargs) + preview = InjectService.build_relation_materials( + template, include_content=True, **kwargs + ) + content = preview.pop("content") + assert ordinary == preview # 预览展示选项不改变注入、预算、选择原因或哈希。 + assert content["relationship"] == ( + kwargs["relationship"] + if case not in ("omitted", "no_fields", "block_budget") + else "" + ) + assert content["impression"] == ( + kwargs["impression"] + if case not in ("omitted", "no_fields", "invalid", "block_budget") + else "" + ) + assert len(content["events"]) == ( + 0 if case in ("no_fields", "event_budget", "block_budget") else 1 + ) + if content["events"]: + item = content["events"][0] + assert item["log_id"] == 1 and item["subject"] == "8001" + assert item["assessment"] == row()["reason"] + assert "不独立确认" in item["certainty"] + assert "member_expression" not in item + assert json.dumps(content["events"], ensure_ascii=False) in preview["block"] + for name in ("relationship", "impression"): + if content[name]: + assert json.dumps(content[name], ensure_ascii=False) in preview["block"]