Compare commits

...

1 Commits

Author SHA1 Message Date
l
daccc3fd10 fix(assets): 手机大图传不上去(请求体上限 4MB + 错误信息误导 + 换图自删)
真机报「背景图设置不了」——选相册里的照片,那行还是显示「空」。
三个原因叠在一起:

1. 照片 30~55MB,base64 后 38~73MB,撞上 read_json_body 的默认 4MB 上限
2. 异常被 body() 吞成空 dict,报出来的是「不认识的外观槽位」
3. 失败只闪一句「这张图没传上去」

修:
- 新增 ui/ImagePick.kt:位图按最长边 1600 采样(28.9MB → 774KB),
  GIF/SVG 不压(丢动画 / 毁矢量);读图整体挪进 ViewModel 的 IO 线程
- agent_api:上传类接口统一 UPLOAD_BODY_LIMIT(图片 + 四种包导入)
- body() 失败时把原因挂到 handler,_set_asset 如实报,不再伪装成槽位错
- _drop_replaced:换图时新旧同路径不删(否则同一张图传第二次会把自己删掉)
- AppViewModel:两个 upload 都把服务端原因显示出来
  (世界观那个原来把 runCatching 结果整个丢掉了)

探针加第 23、24 节共 19 条断言,并验证过撤掉修复会变红。八个探针全绿。
真机(Android 16/arm64)实测:28.9MB → 774KB,连传两次文件都在。
2026-10-16 22:53:49 +08:00
11 changed files with 433 additions and 35 deletions

View File

@@ -1,4 +1,4 @@
plugins {
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.plugin.compose")
@@ -30,8 +30,8 @@ android {
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
* 改小了会装不上)。
*/
versionCode = 271
versionName = "2.0.71"
versionCode = 272
versionName = "2.0.72"
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
@@ -104,12 +104,9 @@ fun AgentEditScreen(
val slot = pendingSlot
pendingSlot = ""
if (uri == null || slot.isBlank()) return@rememberLauncherForActivityResult
runCatching {
val bytes = ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
val name = (uri.lastPathSegment ?: "image.png").substringAfterLast('/')
val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
vm.uploadAgentAsset(draft.id, slot, name, b64)
}.onFailure { vm.showHint("读不出这张图") }
// 读图 / 压缩 / 上传全在 ViewModel 的 IO 线程里 ——
// launcher 回调是**主线程**,解码一张 30MB 的手机照片放这儿会卡死界面
vm.uploadAgentAssetFrom(ctx.applicationContext, draft.id, slot, uri)
}
// 导出智能体包(需求 2.5):内核打包成 zip → base64 → 这里落盘。

View File

@@ -1,5 +1,7 @@
package com.doubao.lynxclone.ui
package com.doubao.lynxclone.ui
import android.content.Context
import android.net.Uri
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
@@ -222,10 +224,13 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
*/
fun uploadAgentAsset(agentId: String, key: String, name: String, base64: String) {
viewModelScope.launch {
val saved = runCatching {
val err = runCatching {
withContext(Dispatchers.IO) { client.setAgentAsset(agentId, key, name, base64) }
}.getOrNull()
if (saved == null) showHint("这张图没传上去") else refresh()
}.exceptionOrNull()
// ★ 把服务端那句话**原样**带出来。上一版一律显示「这张图没传上去」,
// 于是"图太大 / 请求体不是合法 JSON / 槽位不对"三种完全不同的原因
// 在用户眼里一模一样 —— 只能来问,而这一问就是好几轮。
if (err != null) showHint(err.message ?: "这张图没传上去") else refresh()
}
}
@@ -312,13 +317,58 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
}
}
/**
* 从选图器给的 URI 直接上传一张外观图(读图 / 压缩 / base64 / 上传全在 IO 线程)。
*
* ★ 为什么不让界面自己读字节再调 [uploadAgentAsset]:
* ① launcher 的回调跑在**主线程**上,而这里要解码的可能是 30MB 的手机照片,
* 放主线程就是几百毫秒到几秒的卡死;
* ② 智能体编辑页和世界观编辑页各抄一份读图代码的话,
* 下次修"大图"这种坑必然只修一份 —— 这个仓库里已经反复出现过。
*/
fun uploadAgentAssetFrom(context: Context, agentId: String, key: String, uri: Uri) {
viewModelScope.launch {
val outcome = runCatching {
val picked = withContext(Dispatchers.IO) { readImageForUpload(context, uri) }
withContext(Dispatchers.IO) {
client.setAgentAsset(agentId, key, picked.name, picked.base64)
}
picked
}
outcome
// 成功也说一句"压到多大了" —— 用户传 30MB 的图回来看到 300KB,
// 不说清楚会以为图被弄坏了
.onSuccess { showHint(it.note); refresh() }
// 失败原因原样带出来:图太大 / 读不出 / 服务端拒绝,是三件事
.onFailure { showHint(it.message ?: "这张图没传上去") }
}
}
/** 上传世界观的一张外观图(和智能体走同一个接口形状,只是路径不同) */
fun uploadWorldviewAsset(id: String, key: String, name: String, base64: String) {
viewModelScope.launch {
runCatching {
val err = runCatching {
withContext(Dispatchers.IO) { client.setWorldviewAsset(id, key, name, base64) }
}.exceptionOrNull()
// ★ 这里原来把 runCatching 的结果**整个丢掉了** —— 传失败也照样 refresh,
// 界面一动不动,用户只能说"设置不了"。失败必须说出来。
if (err != null) showHint(err.message ?: "这张图没传上去") else refresh()
}
}
/** 世界观的选图上传,和 [uploadAgentAssetFrom] 同一条路 */
fun uploadWorldviewAssetFrom(context: Context, id: String, key: String, uri: Uri) {
viewModelScope.launch {
val outcome = runCatching {
val picked = withContext(Dispatchers.IO) { readImageForUpload(context, uri) }
withContext(Dispatchers.IO) {
client.setWorldviewAsset(id, key, picked.name, picked.base64)
}
picked
}
refresh()
outcome
.onSuccess { showHint(it.note); refresh() }
.onFailure { showHint(it.message ?: "这张图没传上去") }
}
}

View File

@@ -0,0 +1,139 @@
package com.doubao.lynxclone.ui
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Base64
import java.io.ByteArrayOutputStream
/**
* 选图 → 读成能上传的 base64。
*
* ## 为什么必须在这里压缩(这是真机上报回来的 bug)
*
* 用户选的是**手机相册里的照片**,现在动辄 30~55MB(一亿像素)。
* 原样读进来会连撞三堵墙:
*
* ① `readBytes()` 把 55MB 全读进内存,`Base64` 再翻 4/3 倍 → 低端机直接 OOM;
* ② 内核 `read_json_body()` 每条接口有自己的上限,图片这条路走的是小上限,
* 38MB 的请求体一进去就被判「请求体过大」;
* ③ 更糟的是那个异常被上层吞掉,最后报出来的是
* **「不认识的外观槽位」** —— 一个和真实原因毫无关系的错误,
* 用户只看到"设置不了",查代码的人也会往槽位名上去找。
*
* 所以压缩不是优化,是**这条链路能不能用**的前提:
* 一张 4000×3000 的照片按最长边 1600 采样后大约是 200~400KB,
* 比原来小两个数量级,上面三堵墙一次全绕过。
*
* ## 两种图**不能**压
*
* - **GIF**:缩放会丢动画(这个 App 明确支持动图,"动图会动"是写在界面上的);
* - **SVG**:本来就是矢量,栅格化等于自毁。
*
* 这两种原样传,只在超过内核 20MB 上限时明确报错 —— 让用户换个文件,
* 而不是静默失败。
*/
/** 压缩后最长边不超过它。1600 在手机上看立绘/背景已经够清楚 */
private const val MAX_EDGE = 1600
/** 压到这么大就收手。经验值:1600 边长的 JPEG 通常在 200~400KB */
private const val TARGET_BYTES = 3 * 1024 * 1024
/** 内核 `_set_asset` 的硬上限,超过它一定传不上去,这里提前拦下来把话说清楚 */
private const val MAX_BYTES = 20 * 1024 * 1024
/** 一张选好的图。[note] 是给用户看的一句话,说明这张图被怎么处理了 */
data class PickedImage(val name: String, val base64: String, val note: String)
private fun mb(n: Int): String = String.format("%.1f", n / 1048576.0)
/**
* 读一张图并压到能传的大小。
*
* 失败时抛 [IllegalStateException],**消息是可以直接显示给用户的中文** ——
* 调用方 `catch` 之后原样 `showHint(e.message)` 就行,
* 不要再包一层"上传失败",那样又把原因盖掉了。
*/
fun readImageForUpload(ctx: Context, uri: Uri): PickedImage {
val resolver = ctx.contentResolver
val rawName = (uri.lastPathSegment ?: "image").substringAfterLast('/').ifBlank { "image" }
// ★ 名字靠不住:SAF 给的常常是 `image_1000018030` 这种没有扩展名的。
// MIME 才是可信的(getType 对 content:// 会去查 provider)。
val mime = (resolver.getType(uri) ?: "").lowercase()
val isGif = mime.contains("gif")
val isSvg = mime.contains("svg")
if (isGif || isSvg) {
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
?: throw IllegalStateException("读不出这个文件")
if (bytes.isEmpty()) throw IllegalStateException("这个文件是空的")
if (bytes.size > MAX_BYTES) {
throw IllegalStateException("这张图 ${mb(bytes.size)}MB,超过 20MB 上限了,换一张吧")
}
return PickedImage(
name = rawName,
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
note = if (isGif) "动图原样上传(压缩会丢动画)" else "SVG 原样上传",
)
}
// ---- 位图:先只问尺寸,不解码像素 ----
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
throw IllegalStateException("这不是一张能识别的图片")
}
// 压不下来就一轮轮降:边长 ×3/4、质量 ×4/5。四轮足够把任何照片压进 3MB
var edge = MAX_EDGE
var quality = 88
var last = 0
repeat(4) {
val opts = BitmapFactory.Options().apply { inSampleSize = sampleFor(bounds, edge) }
val bmp = resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, opts) }
?: throw IllegalStateException("读不出这张图")
val hasAlpha = bmp.hasAlpha()
val out = ByteArrayOutputStream()
bmp.compress(if (hasAlpha) Bitmap.CompressFormat.PNG else Bitmap.CompressFormat.JPEG, quality, out)
val w = bmp.width
val h = bmp.height
bmp.recycle()
val bytes = out.toByteArray()
last = bytes.size
if (bytes.size <= TARGET_BYTES) {
return PickedImage(
// ★ 扩展名要跟着真实格式走:压成 JPEG 却叫 .png,虽然解码器看魔数也能认,
// 但导出的包里会留下一个名不副实的文件
name = "${rawName.substringBeforeLast('.')}.${if (hasAlpha) "png" else "jpg"}",
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
note = "已压到 ${w}×${h}、${bytes.size / 1024}KB 再上传",
)
}
edge = edge * 3 / 4
quality = (quality * 4) / 5
}
throw IllegalStateException("这张图压到 ${mb(last)}MB 还是太大,换一张吧")
}
/**
* 采样率(2 的幂,`BitmapFactory` 只认这个)。
*
* ★ 判据是**最长边**(写成 `||`),不是"宽高都超"。
* 写成 `&&` 的话 4000×3000 一张只缩到 4000(短边 3000 没到阈值就停了),
* JPEG 出来还有 2.2MB;按长边缩一档到 2000×1500 就只有它的三分之一。
*
* 取**解码后仍然 ≥ maxEdge** 的那一档 —— 宁可多留一点,
* 后面还有缩小/降质的循环兜着;反过来取小了就再也补不回清晰度。
*/
private fun sampleFor(bounds: BitmapFactory.Options, maxEdge: Int): Int {
var sample = 1
while (bounds.outWidth / (sample * 2) >= maxEdge ||
bounds.outHeight / (sample * 2) >= maxEdge
) {
sample *= 2
}
return sample
}

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
@@ -447,11 +447,9 @@ private fun ResourceEditScreen(
val slot = pendingSlot
pendingSlot = ""
if (uri == null || slot.isBlank() || id == null) return@rememberLauncherForActivityResult
runCatching {
val bytes = ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
val name = (uri.lastPathSegment ?: "image.png").substringAfterLast('/')
vm.uploadWorldviewAsset(id, slot, name, Base64.encodeToString(bytes, Base64.NO_WRAP))
}.onFailure { vm.showHint("读不出这张图") }
// 和智能体编辑页**同一份实现** —— 这条链路的坑(大图、GIF、SAF 没扩展名)
// 两边一模一样,抄两份迟早只修一份
vm.uploadWorldviewAssetFrom(ctx.applicationContext, id, slot, uri)
}
// 上传完 image 会变,跟着刷新预览
vm.state.worldviews.firstOrNull { it.id == id }?.let {

View File

@@ -362,7 +362,7 @@ def handle(handler, pathname: str, method: str) -> bool:
if len(seg) < 2 or seg[0] != 'api':
return False
def body():
def body(limit: int = 0):
"""
解析请求体。
@@ -370,10 +370,22 @@ def handle(handler, pathname: str, method: str) -> bool:
★ 但注意:往下传的时候必须**调用它**(`body()`)——
直接把函数对象当 dict 传,报的是 `'function' object has no attribute 'get'`,
而那个错看起来像"字段名写错了"。这里踩过一次。
★ [limit] 给了就用它,不给就走 `read_json_body` 的默认小上限 ——
图片那条路是唯一的例外,见 `ASSET_BODY_LIMIT`。
★★ 失败时**不能只 `return {}`**:那样"请求体太大 / 不是合法 JSON"
会在下游表现成"某个字段是空的",于是报出牛头不对马嘴的错误
(真机上就是大图报「不认识的外观槽位」)。原因挂到 handler 上,
需要的地方用 `body_error(handler)` 取出来。
"""
# 每次进来先清掉上一次的残留,否则一次失败会永远跟着后面所有请求
handler.body_error = ''
try:
if limit:
return handler.read_json_body(limit)
return handler.read_json_body()
except Exception: # noqa: BLE001
except Exception as exc: # noqa: BLE001
handler.body_error = str(exc)
return {}
def err(code: int, msg: str):
@@ -390,7 +402,7 @@ def handle(handler, pathname: str, method: str) -> bool:
return True
if seg[1] == 'agents' and len(seg) == 3 and seg[2] == 'import' and method == 'POST':
return _import_agent(handler, body(), err)
return _import_agent(handler, body(UPLOAD_BODY_LIMIT), err)
if seg[1] == 'agents' and len(seg) == 3:
aid = seg[2]
@@ -547,7 +559,7 @@ def handle(handler, pathname: str, method: str) -> bool:
# ---------------- 外观图片(四件套)----------------
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
return _set_asset(handler, 'agents', seg[2], body(), err)
return _set_asset(handler, 'agents', seg[2], body(UPLOAD_BODY_LIMIT), err)
# ---------------- 单条记忆 ----------------
if seg[1] == 'memories' and len(seg) == 3:
@@ -636,7 +648,7 @@ def _memories(handler, method: str, seg: list, body, err) -> bool:
# /memories/import
if tail == ['import'] and method == 'POST':
return _memory_import(handler, agent, body(), err)
return _memory_import(handler, agent, body(UPLOAD_BODY_LIMIT), err)
return False
@@ -979,12 +991,12 @@ def _resource_route(handler, seg: list, method: str, body, err):
if len(seg) == 4 and seg[3] in ('package', 'export') and method == 'GET':
return _export_rulepack(handler, seg[2], err)
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
return _import_rulepack(handler, body(), err)
return _import_rulepack(handler, body(UPLOAD_BODY_LIMIT), err)
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
return _resource_import(handler, name, body(), err)
return _resource_import(handler, name, body(UPLOAD_BODY_LIMIT), err)
if len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
# 世界观的外观图(需求 3.6:沿用同一套四件套)
return _set_asset(handler, 'worldviews', seg[2], body(), err)
return _set_asset(handler, 'worldviews', seg[2], body(UPLOAD_BODY_LIMIT), err)
if len(seg) == 4 and seg[3] == 'memories' and method == 'GET':
# 世界观的**共享记忆**(大家共同记得什么)—— 只读视角
return _world_memories(handler, seg[2], err)
@@ -1144,6 +1156,24 @@ def _export_agent(handler, agent_id: str, err) -> bool:
#: 外观四件套的槽位名(和需求 2.5 的 smartInfo.json 一一对应)
ASSET_KEYS = ('front', 'back', 'border-main', 'border-info')
#: **上传类**接口单独给的请求体上限(图片槽位 + 四种包导入)。
#:
#: ★ 为什么别的接口 4MB、这里要 48MB:这些东西进 JSON 之前都要 base64,
#: 体积是原件的 4/3 还要加转义。
#: - 图片:真机上用户选的是**手机相册的照片**(30~55MB 很常见),
#: base64 之后 38~73MB。默认那 4MB 一进去就被 read_json_body 判
#: 「请求体过大」,而上层那个 `except` 把异常吞成空 dict,
#: 最后报出来的是「不认识的外观槽位」—— 和真实原因毫无关系的一句话,
#: 用户只看到"设置不了"。(这就是真机上报回来的那个 bug。)
#: - 包导入:带外观图片的智能体包,zip 上到十几 MB,base64 之后还要再大。
#:
#: 现在前端会先把位图压到 3MB 以内(见 ImagePick.kt),走这里的常态是几百 KB;
#: 这个上限留给**不压缩的 GIF/SVG** 和包导入兜底。
#:
#: ★ 别把这个上限按"最小的那个调用方"给 —— 这个仓库里已经出现过一次
#: 「内核说这图可以(20MB),通道却说请求体太大(4MB)」的自相矛盾。
UPLOAD_BODY_LIMIT = 48 * 1024 * 1024
#: v1.2 立绘表支持的五档(和情绪 preset 对齐,需求 2.5)
PORTRAIT_PRESETS = ('喜', '怒', '哀', '平常', '死亡')
@@ -1219,7 +1249,15 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
base = base.strip()
slot = slot.strip()
if base not in ASSET_KEYS:
err(400, f'不认识的外观槽位:{base}(可选:{"、".join(ASSET_KEYS)})')
# ★ 先看请求体是不是根本没读进来(太大 / 不是合法 JSON)。
# 那种情况下 `key` 必然是空的,报"槽位不认识"等于把人往完全错误的
# 方向带 —— 真机上就是这么发生的:30MB 的照片 → 请求体超上限 →
# 报的却是「不认识的外观槽位」,查了半天槽位名。
why = getattr(handler, 'body_error', '')
if why:
err(400, f'上传内容没收全:{why}')
else:
err(400, f'不认识的外观槽位:{base}(可选:{"、".join(ASSET_KEYS)})')
return True
if base == 'front':
slot = slot or '平常'
@@ -1254,7 +1292,7 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
dest = os.path.join(_asset_dir(owner_id), f'front-{_safe_segment(slot)}-{name}')
with open(dest, 'wb') as fh:
fh.write(blob)
_drop_file(fronts.get(slot)) # 换图时把旧的那张删掉,不然越攒越多
_drop_replaced(fronts.get(slot), dest) # 换图时删旧的那张,不然越攒越多
fronts[slot] = dest
image['front'] = fronts
return _send_json_ok(handler, {
@@ -1279,7 +1317,7 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
dest = os.path.join(_asset_dir(owner_id), f'{base}-{name}')
with open(dest, 'wb') as fh:
fh.write(blob)
_drop_file(image.get(base))
_drop_replaced(image.get(base), dest)
image[base] = dest
return _send_json_ok(handler, {
'item': save(image),
@@ -1299,6 +1337,33 @@ def _drop_file(path) -> None:
pass
def _drop_replaced(old, keep: str) -> None:
"""
换图时删掉旧的那张 —— 但**新旧是同一个文件时,千万不能删**。
★★ 这个 bug 是真机上踩出来的(而且随手试一次碰不到):
落盘名是 `<槽位>-<原始文件名>`,所以**同一个文件传第二次时新旧同名**,
于是这段顺序出问题:
open(dest,'wb') 写新内容
_drop_file(旧路径) ← 旧路径 == dest,刚写的那张被自己删了
image[base] = dest ← 留下一个指向**不存在文件**的引用
结果:资源目录空着,state 里却指着一个幽灵路径,界面回退到默认图。
表现是"同一张图传第二次就没了"。
第一次传时用的是 SAF 给的 `image_1000018033` 这种 segment,名字不一样,
所以只有"第二次"才触发 —— 用户报的"设置不了"里就混着这一种。
"""
p = str(old or '').strip()
if not p:
return
try:
if os.path.abspath(p) == os.path.abspath(str(keep or '')):
return
except (OSError, ValueError):
pass
_drop_file(p)
def _import_agent(handler, body, err) -> bool:
"""
导入智能体包(需求 2.5)。

Binary file not shown.

After

Width:  |  Height:  |  Size: 509 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 296 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 426 KiB

View File

@@ -44,9 +44,19 @@ v1.1 那张对照表在下面第 1 节;v1.2 新增的部分单列在这儿,
| **`Text` 不渲染 Markdown** | `Text("**粗体**")` 把星号原样显示 | 不报错、不警告,只有截图能发现 |
| **按下标定位消息** | 界面和存储的列表不一一对应 → **静默标错**到别的消息上 | 下标是两边各自数的;改成按内容定位 |
| **`dict` 字段被 `_as_text` 压平** | 规则包的 `info` 里嵌套 list 变成字符串 → 整个规则引擎静默失效 | 嵌套结构要 `_json_safe` |
| **请求体上限按最小的调用方给** | 手机照片 28.9MB → base64 38MB,撞上 `read_json_body` 默认的 4MB;异常又被吞成空 dict,最后报的是**「不认识的外观槽位」** | 上限按**最大**的用;吞异常等于把原因丢掉 |
| **探针绕过了真正出问题的那一层** | 第 22 节直接调 `_set_asset`,而卡住的是 `handle()` 里的 `body()` → 探针全绿,真机全挂 | 探针**必须走生产同一条调用路径** |
| **换图时"自己删自己"** | 落盘名是 `<槽位>-<原始文件名>`;同一张图传第二次时新旧同路径 → 写完新的立刻被当旧的删掉,`image` 里留下**指向不存在文件**的路径,目录空着界面回退默认图 | 删旧文件前先比路径;"先写后删"的顺序里藏着这个坑 |
这类问题的共同点:**三层各自看都对,只有真的跑一遍才看得见**。
> 最后一条是 v2.0.72 修「背景图设置不了」时补上的:用户选的是手机相册里的照片
> (30~55MB),这条链路上有三堵墙,**每一堵单独看都合理**:
> 前端把 55MB 原样 `readBytes` + base64;内核每条接口卡 4MB;异常被 `body()` 吞掉。
> 现在的分工是:前端**先把位图压到 3MB 以内**(`ui/ImagePick.kt`,GIF/SVG 不压,
> 因为缩放会丢动画、栅格化会毁矢量),内核把**上传类**接口的上限统一放到
> `UPLOAD_BODY_LIMIT`(图片 + 四种包导入),并且读不出来时**如实报原因**。
---
## 1. 需求 → 实现对照
@@ -237,14 +247,28 @@ assets/… # 四件套图片(front / back / border-main / border-in
| 脚本 | 验什么 |
|---|---|
| `python scripts/probe-agent-system.py` | 12 节 70+ 项:UUID、记忆 CRUD、pinned、共享限权、提示词注入顺序、20 多个接口、包导入导出边界、多模型解析 |
| `python scripts/probe-agent-system.py` | 23 节:UUID、记忆 CRUD、pinned、共享限权、提示词注入顺序、20 多个接口、包导入导出边界、多模型解析、数值/状态、外观槽位、**上传请求体上限和错误信息** |
| `python scripts/probe-degraded.py` | 幻觉检测(该报的报、不该报的不报)+ 降级调用的解析/执行/剥离/坏输入 |
| `python scripts/probe-rule-engine.py` | 数值/状态的定义、钳制、脚本、状态过期 |
| `python scripts/probe-rule-sandbox.py` | 脚本沙箱挡得住什么、挡不住什么 |
| `python scripts/probe-context-window.py` | 成批对齐裁剪 + 重要标记破格携带 |
| `python scripts/probe-group-chat.py` | 群聊点名制仲裁 |
| `python scripts/audit-ui-tree.py` | 文档里的界面和代码是否一致 |
| `python scripts/audit-ui-entries.py` | 每个界面都有入口(没有死代码) |
两个都**不需要装机、不需要网络**:把 `DOUBAO_DATA` 指到一个临时目录,
八个都不需要装机、不需要网络:把 `DOUBAO_DATA` 指到一个临时目录,
内核的存储层是无状态的,整条链路就能在一个进程里跑完。
**比装机验证快得多,而且能断言具体字段**(截图只能看个大概)。
### 写探针的一条硬纪律:走**生产同一条**调用路径
第 22 节直接调 `_set_asset(...)`,于是它**永远测不到**卡住真机的那一层 ——
上限是在 `handle()` 里的 `body()` 卡的。结果:探针全绿,真机选一张照片就挂。
所以第 23 节改成 `h.call('/api/agents/<id>/asset', 'POST', {...})`,
从 HTTP 路径进去,一路走到存储。**能绕过的那一层,就是下次会出问题的那一层。**
### 改内核之后必须做的一件事
```bash

View File

@@ -74,12 +74,19 @@ class FakeHandler:
def __init__(self):
self.status = 200
self.payload = None
#: 设一个消息就模拟"请求体读不出来"(太大 / 不是合法 JSON)
self.body_error_exc = None
#: 记下这次收到的 limit —— 用来断言"图片这条路真的被单独放行了"
self.last_limit = None
def send_json(self, code, payload):
self.status = code
self.payload = payload
def read_json_body(self, *a, **k):
self.last_limit = a[0] if a else k.get('limit')
if self.body_error_exc is not None:
raise ValueError(self.body_error_exc)
return self._body
def call(self, pathname, method, body=None):
@@ -757,6 +764,124 @@ def main():
check("老格式(单个文件名)还是认",
store.normalize_image({'front': 'old.png'}).get('front') == {'平常': 'old.png'})
# ---------------------------------------------------------------- 23
section("23. 大图上传:请求体上限 + 错误信息(真机上报过「背景图设置不了」)")
#
# ★★ 真机现场:用户选的是**手机相册里的照片**(30~55MB),base64 之后
# 38~73MB。read_json_body 的默认上限是 4MB,于是请求体一进去就被判
# 「请求体过大」;而那个异常被 body() 吞成空 dict,
# 最后报出来的是「不认识的外观槽位」—— 和真实原因毫无关系的一句话,
# 用户只看到"设置不了",查的人也会往槽位名上去找。
#
# ★ 这一节**必须走 handle()**,不能像上一节那样直接调 _set_asset:
# 上限是在 handle 里的 `body()` 那一层卡的,绕过它就等于没测。
# (第 22 节正是直接调 _set_asset 的 —— 所以它一直没盖到这条路径。)
big = store.create_agent({'name': '大图测试'})
big_id = big['id']
h.body_error_exc = None
h.last_limit = None
pl = h.call(f'/api/agents/{big_id}/asset', 'POST',
{'key': 'back', 'name': 'bg.png', 'data': _small})
check("图片上传正常返回", h.status == 200 and bool(pl.get('path')), f"{h.status} {pl}")
check("图片这条路的请求体上限被单独放行(不是默认的 4MB)",
h.last_limit == _api.UPLOAD_BODY_LIMIT,
f"实际收到 {h.last_limit},期望 {_api.UPLOAD_BODY_LIMIT}")
# 两个上限必须自洽:内核允许单张图到 20MB,base64 之后是 4/3 倍。
# 请求体上限比它小的话,就会出现"内核说这图可以,通道却传不进来"
need = 20 * 1024 * 1024 * 4 // 3
check("请求体上限装得下内核允许的最大图(20MB → base64 约 27MB)",
_api.UPLOAD_BODY_LIMIT > need,
f"{_api.UPLOAD_BODY_LIMIT} 要 > {need}")
# ★★ 请求体读失败时,必须报真正的原因
h.body_error_exc = '请求体过大'
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': 'back', 'data': _small})
check("请求体读不出来时报的是真原因",
h.status == 400 and '请求体过大' in str(pl.get('error', '')),
f"{h.status} {pl}")
check("不再把「请求体过大」伪装成「不认识的外观槽位」",
'不认识的外观槽位' not in str(pl.get('error', '')),
str(pl.get('error')))
h.body_error_exc = None
# 正常的参数错误不能被这次改动带坏
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': '乱写的槽位', 'data': _small})
check("槽位名写错仍然报「不认识的外观槽位」",
h.status == 400 and '不认识的外观槽位' in str(pl.get('error', '')),
f"{h.status} {pl}")
# 上一次的失败不能跟着到下一个请求上(body_error 是挂在 handler 上的)
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': 'back', 'data': _small})
check("上一次失败不污染下一次请求", h.status == 200 and 'error' not in pl, f"{h.status} {pl}")
# 世界观走的是同一个 _set_asset —— 上限也得跟上,别只改一边
world = store.create_resource('worldviews', {'name': '大图世界观', 'setting': ''}) or {}
world_id = world.get('id')
if world_id:
h.last_limit = None
pl = h.call(f'/api/worldviews/{world_id}/asset', 'POST', {'key': 'back', 'data': _small})
check("世界观那条路也放行了(同一个 _set_asset,别只改一边)",
h.status == 200 and h.last_limit == _api.UPLOAD_BODY_LIMIT,
f"{h.status} limit={h.last_limit} {pl}")
# ★ 同一类坑还有四处:四种**包导入**也是 base64 进 JSON。
# 带外观图片的智能体包 zip 上到十几 MB,走默认的 4MB 一样进不来。
# 这里不要求导入成功(空包必然失败),只要求**上限确实传下去了**。
for path in ('/api/agents/import', '/api/worldviews/import', '/api/rulepacks/import'):
h.last_limit = None
h.call(path, 'POST', {})
check(f"{path} 也放行了(包里有图片时才不会卡在 4MB)",
h.last_limit == _api.UPLOAD_BODY_LIMIT,
f"limit={h.last_limit}")
# ---------------------------------------------------------------- 24
section("24. 换图时新旧同名(真机上报过「同一张图传第二次就没了」)")
#
# ★★ 落盘名是 `<槽位>-<原始文件名>`,所以**同一个文件传第二次时新旧同名**。
# 原来的顺序是"写新的 → 删旧的",而旧路径正好就是新路径 ——
# 刚写的那张被自己删掉,image 里留下一个指向不存在文件的路径:
# 资源目录空着,界面回退到默认图。表现是"第二次传同一张图就没了"。
#
# 第一次传时名字来自 SAF 的 segment(`image_1000018033` 这种),
# 和第二次不同名,所以随手试一次碰不到 —— 必须**故意传两次同名**才复现。
twice = store.create_agent({'name': '重传测试'})
tid = twice['id']
def put_named(key, name):
return h.call(f'/api/agents/{tid}/asset', 'POST',
{'key': key, 'name': name, 'data': _small})
pl1 = put_named('back', 'same.png')
path1 = pl1.get('path') or ''
check("第一次传:文件确实落了盘", bool(path1) and os.path.isfile(path1), path1)
pl2 = put_named('back', 'same.png')
path2 = pl2.get('path') or ''
check("第二次传同名文件:路径不变(本来就是同一个文件)", path1 == path2, f"{path1} vs {path2}")
check("**第二次传完文件还在**(旧版在这里把它自己删了)",
bool(path2) and os.path.isfile(path2),
f"{path2} 存在={os.path.isfile(path2) if path2 else None}")
img = (store.get_agent(tid) or {}).get('image') or {}
check("image 里指的是一个真实存在的文件",
bool(img.get('back')) and os.path.isfile(img['back']), str(img.get('back')))
# 立绘那条分支是同一份逻辑,也要过一遍 —— 别只修一边
pf1 = put_named('front:喜', 'same.png')
pf2 = put_named('front:喜', 'same.png')
fpath = pf2.get('path') or ''
check("立绘连传两次同名文件也还在", bool(fpath) and os.path.isfile(fpath),
f"{fpath} 存在={os.path.isfile(fpath) if fpath else None}")
check("立绘两次的路径相同", (pf1.get('path') or '') == fpath, f"{pf1.get('path')} vs {fpath}")
# ★ 反向:换一张**不同名**的图时,旧文件必须真的被清掉
# (别为了修上面的问题,把"不然越攒越多"的清理一起弄没了)
pl3 = put_named('back', 'other.png')
path3 = pl3.get('path') or ''
check("换不同名的新图:新文件在", bool(path3) and os.path.isfile(path3), path3)
check("换不同名的新图:**旧文件被清掉了**", not os.path.isfile(path2), f"{path2} 还在")
# ---------------------------------------------------------------- 汇总
print()
if fails: