Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| daccc3fd10 | |||
| e62dd7b87b | |||
| 8ccf009958 |
@@ -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 = 269
|
||||
versionName = "2.0.69"
|
||||
versionCode = 272
|
||||
versionName = "2.0.72"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -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 → 这里落盘。
|
||||
@@ -203,6 +200,8 @@ fun AgentEditScreen(
|
||||
pickImage.launch(arrayOf("image/*"))
|
||||
},
|
||||
onClear = { vm.uploadAgentAsset(draft.id, "front:$preset", "", "") },
|
||||
// 立绘空着时显示内置默认人物 —— 那正是回退链的最后一级
|
||||
showDefaultPerson = true,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
@@ -555,6 +554,15 @@ private fun AssetRow(
|
||||
path: String,
|
||||
onPick: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
/**
|
||||
* 空的时候要不要显示**内置默认人物**的缩略图。
|
||||
*
|
||||
* ★ 只有**立绘**该显示它(那正是回退链的最后一级)。
|
||||
* 背景图 / 边框为空时显示一张**人物照**是误导 ——
|
||||
* 用户会以为"我没设背景,怎么有个女的"(截图反馈过)。
|
||||
* 那三个空着就画一个空框 + 一个「空」字,如实表达"这里什么都没有"。
|
||||
*/
|
||||
showDefaultPerson: Boolean = false,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
@@ -566,14 +574,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,
|
||||
|
||||
@@ -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 ?: "这张图没传上去") }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -604,6 +654,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 +1688,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):内核决定这一轮谁说话。
|
||||
// 界面据此换立绘/背景(设置里可关),并让用户知道
|
||||
|
||||
@@ -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)
|
||||
|
||||
139
android/app/src/main/java/com/doubao/lynxclone/ui/ImagePick.kt
Normal file
139
android/app/src/main/java/com/doubao/lynxclone/ui/ImagePick.kt
Normal 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
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||||
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||||
|
||||
## 为什么单独一个模块
|
||||
|
||||
@@ -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 = ('喜', '怒', '哀', '平常', '死亡')
|
||||
|
||||
@@ -1208,13 +1238,26 @@ 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(':')
|
||||
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 '平常'
|
||||
@@ -1249,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, {
|
||||
@@ -1274,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),
|
||||
@@ -1294,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)。
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
BIN
docs/screenshots/rd-verify-final.png
Normal file
BIN
docs/screenshots/rd-verify-final.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 509 KiB |
BIN
docs/screenshots/realdevice-drawer.png
Normal file
BIN
docs/screenshots/realdevice-drawer.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 296 KiB |
BIN
docs/screenshots/realdevice-launch.png
Normal file
BIN
docs/screenshots/realdevice-launch.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 426 KiB |
@@ -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
|
||||
|
||||
@@ -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):
|
||||
@@ -678,6 +685,203 @@ 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'})
|
||||
|
||||
# ---------------------------------------------------------------- 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:
|
||||
|
||||
Reference in New Issue
Block a user