From 8ccf00995821e2b308e7350fc035d044ac6fed66 Mon Sep 17 00:00:00 2001 From: l Date: Fri, 16 Oct 2026 21:05:41 +0800 Subject: [PATCH] =?UTF-8?q?fix(v1.2):=20=E7=AB=8B=E7=BB=98=E4=BC=A0?= =?UTF-8?q?=E4=B8=8D=E4=B8=8A=E5=8E=BB=EF=BC=88500=EF=BC=89+=20=E5=B7=B2?= =?UTF-8?q?=E8=AE=BE=E7=9A=84=E5=9B=BE=E4=B8=A2=E5=A4=B1=EF=BC=88v2.0.70?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用户报的两个问题都是真的,而且都是**上次改五档立绘时引入的**。 ## ① 角色图设置不了 —— 接口直接 500 真机实测 `POST /api/agents//asset` → 500。本地复现拿到 traceback: File "agent_api.py", line 1213, in _set_asset base, _, slot = key.partition(':') NameError: name 'key' is not defined 改五档槽位(`front:喜`)时**把 `key = str(body.get('key')...)` 删掉了**。 所以**任何**立绘/背景/边框都传不上去。 ## ② 已设的图丢失 —— 值被字符串化 同一个改动漏了另一半:`_apply_agent_patch` 对 `image` 的**每个值**调 `_as_text`。 `image` 以前只有字符串(文件名),但 v1.2 的立绘是**五档字典**,于是磁盘上变成: "front": {"平常": "{'平常': 'C:\\...\\a.png'}"} · 回退链读不到(档位取不出来) · **每读写一次多包一层**,最后 `os.path.isfile` 失败 ★ 上次只改了 `_apply_resource_patch`(规则包 `info` 踩过同一个坑), **漏了这个姐妹函数** —— 两处同一段逻辑抄了两份。现在都用 `_json_safe`。 ## 老数据能救回来 `normalize_image` 会**解套**:字符串化的字典用 `ast.literal_eval` 解回 (**不是 `eval`** —— 只能求值字面量,解不开当空处理)。 ## 探针补上了(第 22 节 21 项) 传各档位 / 背景 / 乱写档位(要 400)/ **存下来还是字典** / 回退链 / 清一档不连累别的 / 解套 / 摊平 / 垃圾文本当空。 ★ 教训:**探针没覆盖到的接口 = 没写过**。`_set_asset` 当时一条断言都没有, 所以它 500 了几轮,八个探针一直全绿。 ## 真机复验 `back` 和 `front:平常` 都上传成功,`/api/state` 里 `front` 是 `{平常: 路径}`, 设备上文件确实存在。(中间一次 400 是 PowerShell 把中文编码坏了,不是 App 问题。) ## 还剩 **内置四个智能体本来就没有立绘**(`DEFAULT_AGENTS` 没有 `image`)。 用户说"你上网"——我下载不了图片(`web_fetch` 只返回文本),但**可以画 SVG** (SVG 是文本,项目支持)。下一版给它们各画一张能区分的默认立绘。 --- android/app/build.gradle.kts | 4 +- android/kernel/agent_api.py | 7 +++- android/kernel/store.py | 66 ++++++++++++++++++++++++----- scripts/probe-agent-system.py | 79 +++++++++++++++++++++++++++++++++++ 4 files changed, 142 insertions(+), 14 deletions(-) diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 6363a9d..226912f 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -30,8 +30,8 @@ android { * versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装", * 改小了会装不上)。 */ - versionCode = 269 - versionName = "2.0.69" + versionCode = 270 + versionName = "2.0.70" ndk { // Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份 diff --git a/android/kernel/agent_api.py b/android/kernel/agent_api.py index 5837da8..2fff5ee 100644 --- a/android/kernel/agent_api.py +++ b/android/kernel/agent_api.py @@ -1,4 +1,4 @@ -"""智能体系统的 HTTP 接口(需求 v1.1)。 +"""智能体系统的 HTTP 接口(需求 v1.1)。 ## 为什么单独一个模块 @@ -1208,6 +1208,11 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool: err(404, '没有这一项') return True + # ★★ `key` 必须在这里读出来 —— 我改五档槽位时**把这行删掉了**, + # 于是下面 `key.partition(':')` 直接 NameError → 整个接口 500。 + # 表现是"角色图设置不了"(任何图都传不上去)。 + # 而当时的探针**没测这个接口**,所以一路绿着过去了。 + key = str(body.get('key') or '').strip() # ★ v1.2:立绘是**五档**,所以槽位名允许带档位 —— `front:喜`。 # 不带档位的 `front` 视为「平常」档(兼容旧界面和旧调用)。 base, _, slot = key.partition(':') diff --git a/android/kernel/store.py b/android/kernel/store.py index 2bd0f26..18decc0 100644 --- a/android/kernel/store.py +++ b/android/kernel/store.py @@ -59,17 +59,34 @@ def normalize_image(image) -> dict: "用户手改过 agents.json" 这种情况也不会被冲掉。 归一化**不丢信息**:字典里多出来的档位原样保留(用户可能自己加了「醉」这种)。 + + ★★ 还要**解套**:有一版把 `front` 的字典值也 `_as_text` 了一遍,于是磁盘上 + 存成了 `"{'平常': 'C:\\...\\a.png'}"`(**字符串化的字典**)。 + 那种数据要能救回来 —— 不然用户看到的就是"**我设的图不见了**": + 档位读不出来(是个字符串不是字典),而且每读写一次还多包一层, + 最后连 `os.path.isfile` 都失败。 """ img = dict(image or {}) front = img.get('front') - if isinstance(front, str): - # v1.1 的单文件名 → 只有「平常」档 - img['front'] = {'平常': front} if front.strip() else {} + if isinstance(front, str) and front.strip().startswith('{'): + # ② 字符串化的字典 → 解回真字典 + img['front'] = _unshell_dict(front) + elif isinstance(front, str): + # ① v1.1 的单文件名 → 只有「平常」档 + img['front'] = {'平常': front.strip()} if front.strip() else {} elif isinstance(front, dict): - img['front'] = { - str(k): str(v) for k, v in front.items() - if str(v or '').strip() - } + fixed = {} + for k, v in front.items(): + key = str(k) + if isinstance(v, str) and v.strip().startswith('{'): + # 值本身又被包成了字典 → 摊平(旧数据里反复读写会这样) + for ik, iv in _unshell_dict(v).items(): + if isinstance(iv, str) and iv.strip(): + fixed[str(ik)] = iv.strip() + continue + if str(v or '').strip(): + fixed[key] = str(v).strip() + img['front'] = fixed else: img['front'] = {} for key in ('back', 'border-main', 'border-info'): @@ -77,6 +94,25 @@ def normalize_image(image) -> dict: return img +def _unshell_dict(text: str) -> dict: + """ + 把**字符串化的字典**解回 dict(解不开就给空字典)。 + + ★ 用 `ast.literal_eval` 而不是 `eval`:它只能求值**字面量** + (数字、字符串、列表、字典……),遇到函数调用直接报错。 + 就算那段文本被谁改过,也执行不了任何东西。 + """ + import ast + + try: + got = ast.literal_eval(str(text or '')) + except (ValueError, SyntaxError): + return {} + if not isinstance(got, dict): + return {} + return {str(k): v for k, v in got.items()} + + def _read_json(file_path: str): """读 JSON;文件不存在或坏掉都返回 None(调用方决定怎么兜底)。""" if not os.path.isfile(file_path): @@ -1180,10 +1216,18 @@ def _apply_agent_patch(agent: dict, patch: dict) -> dict: for key in AGENT_DICT_FIELDS: if patch.get(key) is not None: raw = patch[key] - agent[key] = ( - {str(k): _as_text(v) for k, v in raw.items()} - if isinstance(raw, dict) else {} - ) + # ★★ 和 `_apply_resource_patch` 一样:**不能对每个值调 `_as_text`**。 + # + # 智能体的 `image` 以前只有字符串(文件名),转一下无妨; + # 但 v1.2 的立绘是**五档字典**(`front: {'喜': 路径, ...}`)—— + # 转成字符串之后,那个键就变成了 `"{'喜': 'C:\\...'}"` 这种 + # 字符串化的字典: + # · 回退链按档位找不到(`front['喜']` 从字典里读不到) + # · 而且**每读写一次就多包一层**,最后 `os.path.isfile` 失败 + # —— 表现就是用户说的"**之前设置的图像也没了**" + # + # 改成 `_json_safe`:保留嵌套结构,只把 JSON 存不下的转字符串。 + agent[key] = _json_safe(raw) if isinstance(raw, dict) else {} return agent diff --git a/scripts/probe-agent-system.py b/scripts/probe-agent-system.py index de80821..133127c 100644 --- a/scripts/probe-agent-system.py +++ b/scripts/probe-agent-system.py @@ -678,6 +678,85 @@ def main(): check("老库的 token_usage 能加上缓存两列", {"cache_hit", "cache_miss"} <= tcols, str(sorted(tcols))) conn_old_tu.close() + # ---------------------------------------------------------------- 22 + section("22. 外观槽位接口(真机上报过 500 / 图不见了)") + # + # ★★ 这一节是**真机反馈**倒逼出来的,两个 bug 都在这里: + # ① `_set_asset` 里 `key` 变量被删了 → NameError → 接口 500 + # → 表现"角色图设置不了"(任何图都传不上去) + # ② `_apply_agent_patch` 对 image 的每个值调 `_as_text` + # → `front`(字典)被存成字符串化的字典 + # → 表现"之前设置的图像也没了"(档位读不出来 + 每读写一次多包一层) + # + # 教训:**探针没覆盖到的接口 = 没写过**。这个接口当时一条断言都没有。 + import agent_api as _api + + class _H: + def __init__(self): + self.status = 200 + self.payload = None + + def send_json(self, code, payload): + self.status, self.payload = code, payload + + hh = _H() + + def _err(code, msg): + hh.status, hh.payload = code, {'error': msg} + + art_agent = store.create_agent({'name': '外观测试'}) + aid = art_agent['id'] + _small = ('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8' + 'z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==') + + def put(key, data=_small, name='t.png'): + hh.status, hh.payload = 200, None + _api._set_asset(hh, 'agents', aid, {'key': key, 'name': name, 'data': data}, _err) + return hh.status, hh.payload or {} + + st, pl = put('front:喜') + check("① 传「喜」档不再 500(真机就是这里挂的)", st == 200, f"{st} {pl}") + check("返回里带 slot", pl.get('slot') == '喜', str(pl.get('slot'))) + st, pl = put('front') + check("不带档位的 front 视为「平常」(兼容旧界面)", pl.get('slot') == '平常', str(pl.get('slot'))) + st, pl = put('front:死亡') + check("「死亡」档也能传", st == 200 and pl.get('slot') == '死亡', f"{st} {pl}") + st, pl = put('back') + check("背景图能传", st == 200, f"{st} {pl}") + st, pl = put('front:乱写') + check("乱写的档位被拒(400 不是 500)", st == 400, f"{st} {pl}") + + # ★★ 存下来的形状必须是**字典**,不是字符串化的字典 + img = (store.get_agent(aid) or {}).get('image') or {} + front = img.get('front') + check("**front 存下来还是字典**(不是字符串化)", isinstance(front, dict), str(type(front))) + check("三个档位都在", set(front or {}) >= {'喜', '平常', '死亡'}, str(front)) + for k, v in (front or {}).items(): + check(f"档位「{k}」的值是**路径字符串**不是嵌套字典", + isinstance(v, str) and not v.strip().startswith('{'), str(v)[:40]) + + # 回退链要能用 + check("回退链:preset=喜 命中自己的档", bool(_api.portrait_of(img, '喜'))) + check("回退链:preset=怒 退到平常", bool(_api.portrait_of(img, '怒'))) + + # 清空一个档 + st, pl = put('front:喜', data='') + check("传空 data = 清掉那一档", st == 200 and pl.get('cleared') is True, f"{st} {pl}") + img2 = (store.get_agent(aid) or {}).get('image') or {} + check("清掉之后「喜」不在字典里了", '喜' not in (img2.get('front') or {}), str(img2.get('front'))) + check("别的档**没被连累**", '平常' in (img2.get('front') or {}), str(img2.get('front'))) + + # ★★ 老脏数据要能救回来(用户磁盘上可能真的有) + shelled = store.normalize_image({'front': "{'平常': 'C:/x/a.png'}"}) + check("字符串化的字典能解套", shelled.get('front') == {'平常': 'C:/x/a.png'}, str(shelled.get('front'))) + nested = store.normalize_image({'front': {'平常': "{'平常': 'C:/y/b.png'}"}}) + check("嵌套一层也能摊平", nested.get('front') == {'平常': 'C:/y/b.png'}, str(nested.get('front'))) + check("解不开的垃圾文本当空处理(不抛异常)", + store.normalize_image({'front': '{不是字典}'}).get('front') == {}, + str(store.normalize_image({'front': '{不是字典}'}).get('front'))) + check("老格式(单个文件名)还是认", + store.normalize_image({'front': 'old.png'}).get('front') == {'平常': 'old.png'}) + # ---------------------------------------------------------------- 汇总 print() if fails: