Compare commits

...

2 Commits

Author SHA1 Message Date
l
e62dd7b87b fix(ui): 上传成功但页面没变化 + 回话消失(v2.0.71)
用户连报三个现象,根因是两个,都找到了。

## ① 上传成功但页面没变化

图**确实存下来了**(用户截图里编辑页五档显示了不同的图就是证据),
问题在**界面读不到**:

    /api/state 的形状:  { id, name, image: {...}, portrait: "路径" }
                                                  ↑ **顶层**
    Kotlin 却在这里读:  optJSONObject("image").toAgentImage().portrait
                                                          ↑ 从 image 里面读

`portrait` 是内核在顶层拼上去的,`image` 对象里没有这个键 →
永远解析成空 → 界面一直回退到内置默认人物。

**编辑页为什么能显示**:它读 `image.front`(五档表本身),那条路是对的。
"编辑页有图、列表和聊天页没图"这个矛盾就是这么来的。

**修**:`toAgent()` 把顶层的 `portrait` 补进 `AgentImage`。

★ 真机验证:传一张红色测试图给豆包 → **列表缩略图变成红色** ✓

## ② 回话直接消失

    is StreamEvent.Rebased -> { openConversation(event.conversationId) }

`openConversation` 先 `messages.clear()` 再拉服务端 —— 可这时候**回复还没落盘**,
拉回来是空的;流还在继续往 `messages` 追加,**清空就再也回不来了**。

表现:发一句 → 看到回复 → **它自己没了**。

**修**:只换 id,不调 `openConversation`。顺带加一行提示 + 「知道了」。

## ③ 顺带:背景/边框位置显示人物照

`AssetRow` 空时统一显示 `agent_default_character`。立绘显示它是对的,
但背景图/边框为空时显示人物照是误导(用户截图里那三行都有人物照)。
**修**:只有立绘显示,那三个写「空」字。

## 验证

真机:豆包缩略图 = 传入的图;未传图的仍默认。八个探针全绿。
2026-10-16 21:42:40 +08:00
l
8ccf009958 fix(v1.2): 立绘传不上去(500)+ 已设的图丢失(v2.0.70)
用户报的两个问题都是真的,而且都是**上次改五档立绘时引入的**。

## ① 角色图设置不了 —— 接口直接 500

真机实测 `POST /api/agents/<id>/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 是文本,项目支持)。下一版给它们各画一张能区分的默认立绘。
2026-10-16 21:05:41 +08:00
7 changed files with 208 additions and 25 deletions

View File

@@ -30,8 +30,8 @@ android {
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
* 改小了会装不上)。
*/
versionCode = 269
versionName = "2.0.69"
versionCode = 271
versionName = "2.0.71"
ndk {
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份

View File

@@ -1,4 +1,4 @@
package com.doubao.lynxclone.ui
package com.doubao.lynxclone.ui
import android.util.Base64
import androidx.activity.compose.rememberLauncherForActivityResult
@@ -203,6 +203,8 @@ fun AgentEditScreen(
pickImage.launch(arrayOf("image/*"))
},
onClear = { vm.uploadAgentAsset(draft.id, "front:$preset", "", "") },
// 立绘空着时显示内置默认人物 —— 那正是回退链的最后一级
showDefaultPerson = true,
)
Spacer(Modifier.height(6.dp))
}
@@ -555,6 +557,15 @@ private fun AssetRow(
path: String,
onPick: () -> Unit,
onClear: () -> Unit,
/**
* 空的时候要不要显示**内置默认人物**的缩略图。
*
* ★ 只有**立绘**该显示它(那正是回退链的最后一级)。
* 背景图 / 边框为空时显示一张**人物照**是误导 ——
* 用户会以为"我没设背景,怎么有个女的"(截图反馈过)。
* 那三个空着就画一个空框 + 一个「空」字,如实表达"这里什么都没有"。
*/
showDefaultPerson: Boolean = false,
) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Box(
@@ -566,14 +577,18 @@ private fun AssetRow(
contentAlignment = Alignment.Center,
) {
if (path.isBlank()) {
Image(
painter = painterResource(R.drawable.agent_default_character),
contentDescription = null,
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
contentScale = ContentScale.Crop,
alignment = Alignment.TopCenter,
alpha = 0.35f,
)
if (showDefaultPerson) {
Image(
painter = painterResource(R.drawable.agent_default_character),
contentDescription = null,
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
contentScale = ContentScale.Crop,
alignment = Alignment.TopCenter,
alpha = 0.35f,
)
} else {
Text("空", fontSize = 11.sp, color = doubaoTextSecondary())
}
} else {
AssetImage(
path = path,

View File

@@ -604,6 +604,19 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
}
}
/**
* 内核给这条对话"换了归属"时的说明(非空 = 界面上提示一句)。
*
* ★ 它是个**用户能感知**的变化:对话突然换了个身份。
* 不提示的话用户会以为自己点错了什么。显示一次就清掉。
*/
var rebasedNote by mutableStateOf("")
private set
fun clearRebasedNote() {
rebasedNote = ""
}
/** 这一轮谁在说话(群聊仲裁的结果,v1.2 §3.9) */
var currentSpeakerId by mutableStateOf("")
private set
@@ -1625,9 +1638,21 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
})
}
// ★ 内核说"这个会话不是当前智能体的,我另起了一个"(兜底路径)。
// 界面必须跟着切,否则会继续往老会话上追加 —— 还是串味。
//
// ★★ **只换 id,绝不要调 `openConversation`** —— 踩过:
// `openConversation` 会先 `messages.clear()` 再去服务端拉,
// 而这时候**这一轮的回复还没落盘**,拉回来是空的;
// 流还在继续往 `messages` 里追加,清空之后就再也回不来了。
// 表现就是用户说的"**回话直接消失了**"(发一句、看到回复、
// 然后它自己没了)。
//
// 只换 id 就够了:流会照常往本地列表追加,
// 而 `saved` 事件之后服务端那边的会话对象也是新的。
is StreamEvent.Rebased -> {
if (event.conversationId.isNotBlank()) openConversation(event.conversationId)
if (event.conversationId.isNotBlank()) {
activeConversationId = event.conversationId
rebasedNote = "这条对话原本属于别的智能体,已经为它新开了一个"
}
}
// ★ 群聊的**发言权仲裁**结果(v1.2 §3.9):内核决定这一轮谁说话。
// 界面据此换立绘/背景(设置里可关),并让用户知道

View File

@@ -348,6 +348,21 @@ fun ChatScreen(vm: AppViewModel) {
} else {
// 本次对话的用量(需求 4.1)跟着输入条一起显示 ——
// 放在输入框正上方是因为它是"这次对话"的属性,而输入框就是这次对话的入口
// ★ 对话被换了归属时的提示(见 AppViewModel 的 rebasedNote)
if (vm.rebasedNote.isNotBlank()) {
Row(
Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
vm.rebasedNote,
fontSize = 11.sp,
color = doubaoTextSecondary(),
modifier = Modifier.weight(1f),
)
RowAction("知道了") { vm.clearRebasedNote() }
}
}
// ★ 群聊的成员快捷条(v1.2 §3.9):点头像 = @ 点名,被点的人这一轮一定发言
GroupQuickBar(vm)
SessionUsageBar(vm)

View File

@@ -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(':')

View File

@@ -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

View File

@@ -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: