luckfun233 commited on
Commit
cf6e1f1
·
1 Parent(s): 854ad36

fix(sse): 修复片段快照导致正文被误判为 reasoning 的空回复

Browse files

- 支持上游 2.7.5 起不带 o 字段的 response/fragments 片段快照,
在 THINK → RESPONSE 时正确切换当前片段类型,避免正文全部进入
reasoning_content 并触发 upstream_empty_output
- completion/continue 自动注入 shumei_device_id(2.7.5 新必填字段)
- 修正 upstream_empty_output 的误导性 429 限流文案
- 补充解析器回归测试与 2.7.5 逆向/故障复盘文档

docs/deepseek-android-275-sse-fix-research.md ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DeepSeek Android 2.7.5 逆向 & 2026-11 空回复故障复盘
2
+
3
+ > 研究对象:`https://download.deepseek.com/apk/deepseek.apk`
4
+ > 包名:`com.deepseek.chat` | `versionName 2.7.5` / `versionCode 295`
5
+ > 样本:`Last-Modified: 2026-11-06 03:01:11 GMT`(北京时间 2026-11-06 11:01)
6
+ > 大小:`22,210,268` 字节
7
+ > SHA-256:`ddc52ef868b991fd33e634de834a3e2c022b0cd7ff9e854f4f141996aaeadb70`
8
+ > MD5:`ae0042c8a100d5db0567e2a2c00ed61d`
9
+ > 工具:jadx 1.5.3、apktool 2.11.1、OpenJDK 25、Ghidra(`librscrypto.so` 对照)
10
+ > 对照:`docs/deepseek-android-reverse-research.md`(2.6.2 / 2026-10-13)、`deepseek-recall-research.md`
11
+
12
+ ---
13
+
14
+ ## 0. 结论(TL;DR)
15
+
16
+ 1. **2026-11-07 的“限流 / 不可用”不是账号被限流,也不是封号。**
17
+ 日志里的 `429 Upstream account hit a rate limit...` 是 ds2api 自己的错误归类,真实原因是 ds2api 的 SSE 解析器把**正文**误判成了**思考内容**,最终可见正文为空。
18
+ 2. **直接触发因素是上游 SSE 片段格式变化:**
19
+ 思考结束、正文开始时,上游现在下发**不带 `o` 字段的片段快照**:
20
+ ```json
21
+ {"p":"response/fragments","v":[
22
+ {"id":2,"type":"THINK","content":"……完整思考……"},
23
+ {"id":3,"type":"RESPONSE","content":"我是"}
24
+ ]}
25
+ ```
26
+ 旧代码只在 `o == "APPEND"` 时更新“当前片段类型”,遇到这种快照会继续把后续 `RESPONSE` 增量当成 `THINK`,于是整段正文进入 `reasoning_content`,`content` 为空。
27
+ 3. **新 APK 2.7.5 同时收紧了风控协议:**
28
+ - `ChatFullCompletionRequest` 新增**必填**字段 `shumei_device_id`;
29
+ - `continue` / `edit_message` / `regenerate` / `call/start` 也新增该字段;
30
+ - 新增 `x-device-id` 请求头(Android ID + BRAND 派生);
31
+ - `x-rangers-id` 实际是火山 AppLog 的 `bd_did` / `device_id`,不是账号哈希。
32
+ 4. **修复:**
33
+ - 解析器支持“无 `o` 的片段快照”,正确切换 THINK → RESPONSE;
34
+ - completion / continue 自动注入账号绑定的 `shumei_device_id`;
35
+ - 修正误导性的 429 文案(保留 429 仅为兼容空输出重试/切号逻辑)。
36
+ 5. **用提供的账号实测:**非流式、流式、长文三段式均返回正常正文,`reasoning_content` 与 `content` 正确分离。
37
+
38
+ ---
39
+
40
+ ## 1. 故障现象与日志证据
41
+
42
+ 日志窗口:`2026-11-07 17:37:15` ~ `18:23:33`(Asia/Shanghai),覆盖 3 个账号、两个模型。
43
+
44
+ 典型记录:
45
+
46
+ ```json
47
+ {
48
+ "model": "deepseek-v4-flash",
49
+ "stream": true,
50
+ "status": "error",
51
+ "status_code": 429,
52
+ "finish_reason": "upstream_empty_output",
53
+ "error": "Upstream account hit a rate limit and returned reasoning without visible output.",
54
+ "reasoning_content": "我们需要回答用户中文请求:用一句话介绍自己。……最终只给答案。,我是DeepSeek,由深度求索公司创造的AI助手……"
55
+ }
56
+ ```
57
+
58
+ 关键特征:
59
+
60
+ - `reasoning_content` 末尾**包含完整答案**(“我是 DeepSeek,由……”);
61
+ - `content` 为空;
62
+ - 请求本身是成功的(HTTP 200 + SSE 正常结束),没有上游错误码;
63
+ - 三个账号同时出现,排除单账号限流。
64
+
65
+ 这说明:**模型已经生成了正文,但 ds2api 把正文错误地并入了 reasoning。**
66
+
67
+ ---
68
+
69
+ ## 2. 根因:SSE 片段快照没有 `o` 字段
70
+
71
+ ### 2.1 实测上游流(2.7.5 头 / 2.5.2 头都一样)
72
+
73
+ ```text
74
+ data: {"v":{"response":{"message_id":2,"thinking_enabled":true,"status":"WIP",
75
+ "fragments":[{"id":2,"type":"THINK","content":"我们需要"}]}}}
76
+
77
+ data: {"p":"response/fragments/-1/content","o":"APPEND","v":"回答"}
78
+ data: {"v":"中文"}
79
+ ...
80
+ data: {"p":"response/fragments/-1/elapsed_secs","o":"SET","v":1.0248}
81
+
82
+ # 关键帧:片段快照,没有 "o"
83
+ data: {"p":"response/fragments","v":[
84
+ {"id":2,"type":"THINK","content":"……完整思考……"},
85
+ {"id":3,"type":"RESPONSE","content":"我是"}
86
+ ]}
87
+
88
+ data: {"p":"response/fragments/-1/content","o":"APPEND","v":"Deep"}
89
+ data: {"v":"Se"}
90
+ data: {"v":"ek"}
91
+ ...
92
+ data: {"p":"response/status","o":"SET","v":"FINISHED"}
93
+ ```
94
+
95
+ ### 2.2 旧解析器为什么吞正文
96
+
97
+ `internal/sse/parser.go` 的旧逻辑:
98
+
99
+ ```go
100
+ func collectDirectFragments(path string, chunk map[string]any, v any, ...) {
101
+ if path != "response/fragments" { return }
102
+ op, _ := chunk["o"].(string)
103
+ if !strings.EqualFold(op, "APPEND") { return } // ← 快照没有 o,直接返回
104
+ ...
105
+ }
106
+ ```
107
+
108
+ 快照帧没有 `o`,因此:
109
+
110
+ 1. `newType` 保持 `thinking`,不会切到 `text`;
111
+ 2. 后续 `{"p":"response/fragments/-1/content","o":"APPEND","v":"Deep"}` 走 `resolvePartType`,仍按 `newType=thinking` 处理;
112
+ 3. 整段正文被写入 `Thinking`,`Text` 为空;
113
+ 4. `assistantturn.ValidateTurn` 看到“有 thinking、无 text”,返回
114
+ `429 upstream_empty_output`。
115
+
116
+ 另外,旧代码的 `extractContentRecursive` 只处理带 `"v"` 的 patch;片段快照里的对象用的是 `"content"`,没有 `"v"`,所以连快照里的���个正文分片(示例中的“我是”)也会被丢弃。
117
+
118
+ ### 2.3 复现
119
+
120
+ 把抓到的真实流重放进 `sse.CollectStream`:
121
+
122
+ - 修复前:`TEXT=""`,`THINKING="……完整思考……DeepSeek,由深度求索公司创造的AI助手……"`
123
+ - 修复后:`TEXT="我是DeepSeek,由深度求索公司创造的AI助手……"`,`THINKING="……完整思考……"`
124
+
125
+ 修复前后的差异与线上日志完全一致。
126
+
127
+ ---
128
+
129
+ ## 3. 修复内容
130
+
131
+ ### 3.1 解析器(`internal/sse/parser.go`)
132
+
133
+ - `collectDirectFragments` 现在接受两种形态:
134
+ - `o: "APPEND"`:增量片段,追加所有片段内容;
135
+ - 无 `o` / `SET` / `BATCH`:快照,只更新当前片段类型,并且只追加**最后一个(活跃)片段**的内容,避免重复拼接历史 THINK。
136
+ - 快照处理后不再走通用 `appendChunkValueContent`,避免同一 chunk 被重复解析。
137
+ - 新增回归测试:
138
+ - `TestParseSSEChunkForContentFragmentsSnapshotSwitchToResponse`
139
+ - `TestParseSSEChunkForContentFragmentsSnapshotThinkOnlyDoesNotDuplicate`
140
+ - `TestCollectStreamFragmentsSnapshotKeepsResponseText`
141
+
142
+ ### 3.2 设备 ID 注入(`internal/deepseek/client`)
143
+
144
+ 2.7.5 把 `shumei_device_id` 标成必填。ds2api 登录时已经拿到/持久化了数美 `device_id`,但 completion / continue 请求体没有带。
145
+
146
+ 现在:
147
+
148
+ - `CallCompletion` 在发请求前调用 `injectShumeiDeviceID`,把 `a.Account.DeviceID` 写入 payload(显式值优先,空值不写);
149
+ - `callContinue` 的 continue payload 同样携带;
150
+ - Vercel 流式预置响应里的 `payload` 也补上;
151
+ - 新增单元测试覆盖“账号值写入 / 显式值优先 / 空值不写”。
152
+
153
+ ### 3.3 错误文案
154
+
155
+ `upstream_empty_output` 的 429 保留(空输出重试、切号逻辑依赖该状态码),但文案改为:
156
+
157
+ > Upstream returned reasoning without visible output (empty final answer).
158
+
159
+ 避免再把协议异常误报成“账号被限流”。
160
+
161
+ ---
162
+
163
+ ## 4. 风险控制逆向(2.7.5)
164
+
165
+ ### 4.1 三条设备身份线
166
+
167
+ | Header / 字段 | 来源 | 说明 |
168
+ |---|---|---|
169
+ | `device_id`(登录体) | 数美 SDK `SmAntiFraud` 的 serverId | 形如 `B...` 的 Base64;服务端 `RISK_DEVICE_DETECTED` 会校验它是否为数美签发 |
170
+ | `shumei_device_id`(聊天体) | 同上 | 2.7.5 新增,completion/continue/edit/regenerate/call 必填 |
171
+ | `x-device-id`(请求头) | Android ID + Build.BRAND 派生 | `Base64(AES/CBC/PKCS5(MD5(packageName), android_id + "_" + BRAND, IV=0))`,仅用户同意服务协议后发送 |
172
+ | `x-rangers-id`(请求头) | 火山 AppLog 的 `bd_did` / `device_id` | 真实值是 AppLog 注册的设备 ID;ds2api 目前用账号哈希伪造 19 位数字,存在被判定为异常设备的风险 |
173
+
174
+ 证据:
175
+
176
+ - `defpackage/db.java:20-34`:注入 `x-device-id` / `x-rangers-id`;
177
+ - `defpackage/x06.java:130-137`:`Referer`、`x-client-platform/version/locale/bundle-id`;
178
+ - `defpackage/kw3.java:31-68`:`x-device-id` 派生;
179
+ - `defpackage/rkc.java:164-170`:`getDid()` 返回 `bd_did`,回退 `device_id`;
180
+ - `defpackage/a4a.java:19-55`:数美 `SmAntiFraud.SmOption` 配置(organization `P9usCUBauxft8eAmUXaZ`、`appId=default`、海内外两套 fp 域名);
181
+ - `com/ishumei/smantifraud/l111l11I1IIIl.java:45-46`:serverId 回调返回 `"B" + str`。
182
+
183
+ ### 4.2 聊天请求模型新增必填字段
184
+
185
+ 2.6.2 的 `ChatFullCompletionRequest` 是 10 个字段;2.7.5 是 11 个:
186
+
187
+ ```text
188
+ chat_session_id, parent_message_id, prompt, ref_file_ids?,
189
+ thinking_enabled?, search_enabled?, audio_id?, preempt,
190
+ model_type?, action?, shumei_device_id
191
+ ```
192
+
193
+ `shumei_device_id` 在 kotlinx.serialization 描述符里是 `optional=false`(必填)。
194
+ 同类新增:
195
+
196
+ | 请求 | 证据 | 新增字段 |
197
+ |---|---|---|
198
+ | `ChatContinueRequest` | `defpackage/hx1.java:12-19` | `shumei_device_id` |
199
+ | `ChatEditMessageRequest` | `defpackage/px1.java:12-22` | `shumei_device_id` |
200
+ | `ChatRegenerateRequest` | `defpackage/pf2.java:12-19` | `shumei_device_id` |
201
+ | `TrtcCallStartRequest` | `defpackage/a7b.java:12-18` | `shumei_device_id` |
202
+ | `MfaCreateVerificationCodeRequest` | `defpackage/bd7.java` | `shumei_device_id` + `shumei_verification` |
203
+ | `CreateEmailVerificationCodeRequest` | `defpackage/zd3.java:12-20` | `shumei_verification` / `hcaptcha_token` / `turnstile_token` |
204
+
205
+ ### 4.3 数美 SDK 与设备指纹
206
+
207
+ - SDK 在 `App` 启动时注册:`SmAntiFraud.create(context, option)`;
208
+ - `SmAntiFraud.registerServerIdCallback` 异步拿到 serverId,聊天请求前通过 `a4a.c()` 取回并写入 `shumei_device_id`;
209
+ - `should_use_sm_device_id` 远端开关默认 `true`(`defpackage/fx2.java:14`),即默认使用数美 ID;
210
+ - 旧版“本地伪造 device_id”会被判 `RISK_DEVICE_DETECTED`,ds2api 已改为向数美真实申请(`internal/shumei`)。
211
+
212
+ ### 4.4 MFA / 人机验证
213
+
214
+ 2.7.5 的登录/验证链路新增:
215
+
216
+ - `ChallengeResponse`:`provider`、`challenge_id`、`shumei_verification`、`shumei_device_id`、`hcaptcha_token`;
217
+ - 邮��验证码请求:`shumei_verification`、`hcaptcha_token`、`turnstile_token`;
218
+ - `hcaptcha_enabled` 远端开关默认 `true`(`defpackage/fx2.java:19`);
219
+ - 一旦账号触发 MFA/验证码,纯账号密码登录会拿到 `mfa_ticket` 而不是 token。
220
+
221
+ ds2api 目前没有实现 MFA/hCaptcha 交互;遇到被挑战的账号需要人工在 App 完成验证,或改用已登录 token。
222
+
223
+ ### 4.5 远端风控配置
224
+
225
+ `/api/v0/client/settings` 下发的大量开关(`defpackage/hx2.java:1484`),与本次相关的:
226
+
227
+ | Key | 默认值 | 含义 |
228
+ |---|---|---|
229
+ | `should_use_sm_device_id` | `true` | 是否在聊天请求中使用数美 device id |
230
+ | `authed_pow_functions` | `{"search","deep_think","completion","file"}` | 哪些功能需要/允许 PoW |
231
+ | `pow_prefetch` / `pow_prefetch_count` | `false` / `1` | 是否预取 PoW |
232
+ | `completion/continue/edit/regenerate/resume_request_timeout_ms` | 数秒级 | 各接口超时 |
233
+ | `max_upload_file_size` | 100 MiB | 上传上限 |
234
+ | `max_input_file_count` | — | 单次输入文件数 |
235
+ | `hcaptcha_enabled` | `true` | 国外 IP 是否启用人机验证 |
236
+ | `files_host` | `files.deepseeksvc.com` | 文件服务域名 |
237
+
238
+ > 结论:服务端已经把“功能 → 是否要求 PoW / 设备指纹”做成可远程切换的策略。客户端(以及 ds2api)必须按 `authed_pow_functions` 和 `should_use_sm_device_id` 的语义发请求,不能假设“只要能登录就一定能聊天”。
239
+
240
+ ---
241
+
242
+ ## 5. PoW 全链路
243
+
244
+ ### 5.1 挑战
245
+
246
+ `POST /api/v0/chat/create_pow_challenge`
247
+
248
+ ```json
249
+ {"target_path": "/api/v0/chat/completion"}
250
+ ```
251
+
252
+ 响应:
253
+
254
+ ```json
255
+ {"code":0,"data":{"biz_data":{"challenge":{
256
+ "algorithm":"DeepSeekHashV1",
257
+ "challenge":"<64 hex>",
258
+ "salt":"<hex>",
259
+ "signature":"<64 hex>",
260
+ "difficulty":144000,
261
+ "expire_at":1794048736903,
262
+ "expire_after":300000,
263
+ "target_path":"/api/v0/chat/completion"
264
+ }}}}
265
+ ```
266
+
267
+ 模型证据:`defpackage/l75.java`(GuestChallengeRequest)、`defpackage/rs9.java`(ServerChatChallenge,8 字段)、`defpackage/ff0.java`(AuthedPowSolution,6 字段)。
268
+
269
+ ### 5.2 求解
270
+
271
+ `DeepSeekHashV1` = SHA3-256 但跳过 Keccak-f[1600] 的第 0 轮,只执行 1..23 轮。
272
+ 搜索 `nonce ∈ [0, difficulty)`,使:
273
+
274
+ ```text
275
+ DeepSeekHashV1(salt + "_" + expire_at + "_" + nonce) == challenge
276
+ ```
277
+
278
+ ds2api 的纯 Go 实现在 `pow/deepseek_hash.go` / `pow/deepseek_pow.go`,通过 Keccak 状态预吸收前缀,实测 144000 难度约 30ms。
279
+
280
+ ### 5.3 提交
281
+
282
+ ```http
283
+ POST /api/v0/chat/completion
284
+ x-ds-pow-response: base64({"algorithm","challenge","salt","answer","signature","target_path"})
285
+ ```
286
+
287
+ 要点:
288
+
289
+ - `target_path` 必须与申请时一致(completion / upload_file / continue 各不相同);
290
+ - **一次性**:同一个 PoW 头重复使用会得到 `{"code":40301,"msg":"INVALID_POW_RESPONSE"}`(已实测);
291
+ - 文件上传也要 PoW(`target_path=/api/v0/file/upload_file`),缺头会被 `MISSING_HEADER` 拒绝;
292
+ - `pow_prefetch` 是客户端优化,不影响协议本身。
293
+
294
+ ---
295
+
296
+ ## 6. 发送消息全链路
297
+
298
+ ```text
299
+ login
300
+ → /api/v0/users/current(校验 token)
301
+ → /api/v0/chat_session/create(空 body,agent=chat)
302
+ → /api/v0/chat/create_pow_challenge
303
+ → /api/v0/chat/completion(SSE)
304
+ ├─ 正常 FINISHED
305
+ ├─ INCOMPLETE / AUTO_CONTINUE → /api/v0/chat/continue
306
+ └─ 断流 → /api/v0/chat/resume_stream
307
+ ```
308
+
309
+ ### 6.1 completion 请求体(2.7.5)
310
+
311
+ ```json
312
+ {
313
+ "chat_session_id": "...",
314
+ "parent_message_id": null,
315
+ "prompt": "...",
316
+ "ref_file_ids": [],
317
+ "thinking_enabled": true,
318
+ "search_enabled": false,
319
+ "audio_id": null,
320
+ "preempt": false,
321
+ "model_type": "default",
322
+ "action": null,
323
+ "shumei_device_id": "B..."
324
+ }
325
+ ```
326
+
327
+ - `parent_message_id=null`:从当前会话叶子节点续接;
328
+ - `preempt=true`:打断进行中的流;
329
+ - `model_type`:default / 其它服务端下发值;ds2api 只使用 `default`;
330
+ - `action`:客户端动作标记(重试等),可为空。
331
+
332
+ ### 6.2 SSE 事件
333
+
334
+ 外层是 JSON-Patch 风格:
335
+
336
+ ```json
337
+ {"p":"response/status","o":"SET","v":"WIP"}
338
+ {"p":"response/fragments","o":"APPEND","v":[{"type":"THINK","content":"..."}]}
339
+ {"p":"response/fragments/-1/content","o":"APPEND","v":"..."}
340
+ {"p":"response","o":"BATCH","v":[{"p":"accumulated_token_usage","v":85},{"p":"quasi_status","v":"FINISHED"}]}
341
+ {"status":"ready"}
342
+ ```
343
+
344
+ 片段类型:
345
+
346
+ | type | 含义 |
347
+ |---|---|
348
+ | `THINK` | 思考过程 |
349
+ | `RESPONSE` | 正文 |
350
+ | `SEARCH` | 联网搜索卡片(非思考) |
351
+ | `TOOL_SEARCH` / `TOOL_OPEN` | 思考流程中的搜索/打开网页卡片 |
352
+ | `TEMPLATE_RESPONSE` | 内容过滤后的模板话术 |
353
+
354
+ 状态机(`defpackage/dec.java:176`):
355
+
356
+ ```text
357
+ WIP ──► FINISHED
358
+ ├──► INCOMPLETE(上下文/长度等原因未完成)
359
+ ├──► INTERRUPTED(用户打断)
360
+ └──► CONTENT_FILTER(内容过滤/撤回)
361
+ ```
362
+
363
+ `quasi_status` 会先于 `status` 给出准状态。
364
+
365
+ ### 6.3 自动续��
366
+
367
+ - `INCOMPLETE` 或 `auto_continue=true`:客户端调用 `/api/v0/chat/continue`;
368
+ - `continue` 请求体:`chat_session_id`、`message_id`、`fallback_to_resume`、`shumei_device_id`;
369
+ - 上游可能通过 `auto_resume` / `resume_stream` 恢复断流;ds2api 只实现了 `continue`,没有实现 `resume_stream`。
370
+
371
+ ---
372
+
373
+ ## 7. 撤回 / 内容过滤
374
+
375
+ 撤回不是“删除消息”,而是服务端在流结束后追加覆盖 patch:
376
+
377
+ ```json
378
+ {"v":[
379
+ {"p":"ban_regenerate","v":true},
380
+ {"p":"status","v":"CONTENT_FILTER"},
381
+ {"p":"quasi_status","v":"CONTENT_FILTER"},
382
+ {"p":"fragments","v":[{"id":5,"type":"TEMPLATE_RESPONSE","content":"你好,这个问题我暂时无法回答,让我们换个话题再聊聊吧。"}]}
383
+ ]}
384
+ ```
385
+
386
+ 客户端处理(2.7.5 与 2.6.2 一致):
387
+
388
+ - `status/quasi_status` → 状态机 `CONTENT_FILTER`;
389
+ - `ban_edit` / `ban_regenerate` → 禁用“修改 / 重新生成”;
390
+ - `fragments` → 整体清空并替换为 `TEMPLATE_RESPONSE`;
391
+ - 原文在客户端内存中即刻消失,App 没有“防撤回”能力;
392
+ - 服务端 `/api/v0/chat/history_messages` 返回的也是撤回后的状态,并会同步到本地 WCDB(未加密)。
393
+
394
+ 证据:`defpackage/fy.java`(AppStaticMessage 19 字段)、`defpackage/lv4.java`(片段类型反序列化,含 `TEMPLATE_RESPONSE`)、`defpackage/da8.java:1736`(展示时忽略 `TEMPLATE_RESPONSE`)。
395
+
396
+ ---
397
+
398
+ ## 8. 文件上传全链路
399
+
400
+ ### 8.1 上传
401
+
402
+ ```http
403
+ POST /api/v0/file/upload_file
404
+ Content-Type: multipart/form-data; boundary=...
405
+ x-model-type: default
406
+ x-file-size: <bytes>
407
+ x-thinking-enabled: 1
408
+ x-ds-pow-response: <PoW(target_path=/api/v0/file/upload_file)>
409
+
410
+ --boundary
411
+ Content-Disposition: form-data; name="file"; filename="..."
412
+ Content-Type: <mime>
413
+
414
+ <binary>
415
+ --boundary--
416
+ ```
417
+
418
+ 响应关键字段(对应 `AppChatFile`,`defpackage/is.java:16-32`):
419
+
420
+ ```text
421
+ id, status, file_name, file_size, inserted_at, updated_at,
422
+ token_usage, previewable, from_share, signed_path, is_image,
423
+ audit_result, width, height, retryable, local_outcome
424
+ ```
425
+
426
+ 文件状态(`defpackage/zx1.java:20-36`):
427
+
428
+ ```text
429
+ PENDING → PARSING → SUCCESS
430
+ ├→ FAILED
431
+ ├→ CONTENT_FILTER
432
+ ├→ CONTENT_TOO_LONG
433
+ ├→ CONTENT_EMPTY
434
+ └→ CANCELED / UNKNOWN
435
+ ```
436
+
437
+ ### 8.2 轮询
438
+
439
+ 上传成功后文件通常是异步解析:
440
+
441
+ ```http
442
+ GET /api/v0/file/fetch_files?file_ids=<id>
443
+ ```
444
+
445
+ ds2api 的 `waitForUploadedFile` 会轮询到 `processed/ready/done/...`,并读取 `audit_result`:
446
+
447
+ - `unknown`:待审;
448
+ - `pass`:通过;
449
+ - `reject/denied/blocked/...`:拒绝。
450
+
451
+ ### 8.3 引用
452
+
453
+ 聊天时把文件 ID 放入 `ref_file_ids`,服务端会把解析后的 token 计入上下文。ds2api 还会把文件内容以纯文本形式注入 prompt,兼容不支持文件引用的上游。
454
+
455
+ ### 8.4 其它文件接口
456
+
457
+ - `/api/v0/file/fork_file_task`:从分享/会话复制文件任务;
458
+ - `/api/v0/share/*`:分享链接;
459
+ - `files.deepseeksvc.com`:默认文件服务域名;
460
+ - 上限:`max_upload_file_size`(默认 100 MiB)、`max_input_file_count`。
461
+
462
+ ---
463
+
464
+ ## 9. 图片上传全链路
465
+
466
+ 2.7.5 没有独立图片端点,图片走**同一条文件上传链路**:
467
+
468
+ ```text
469
+ 相册/相机
470
+ → 本地压缩(camera_compress_ratio / photo_picker_compress_ratio / picture_compress_format)
471
+ → POST /api/v0/file/upload_file(multipart,is_image 由服务端判定)
472
+ → fetch_files 轮询(audit_result / width / height)
473
+ → completion 的 ref_file_ids 引用
474
+ ```
475
+
476
+ 证据:
477
+
478
+ - `AppChatFile` 含 `is_image`、`width`、`height`;
479
+ - 远端设置含 `camera_compress_ratio`、`photo_picker_compress_ratio`、`picture_compress_format`、`max_input_file_count`;
480
+ - 上传响应含 `model_kind`(`VISION` / `NORMAL`),服务端据此选择视觉/普通模型;
481
+ - 审核失败会返回 `CONTENT_FILTER`,与文本撤回同一套审核体系。
482
+
483
+ ---
484
+
485
+ ## 10. 语音 / TTS / 通话(简表)
486
+
487
+ | 功能 | 端点 | 备注 |
488
+ |---|---|---|
489
+ | 语音识别 | `/api/v0/asr/ws` | WebSocket |
490
+ | TTS | `/api/v0/chat/tts/*`、`/tts/voices` | 语音朗读 |
491
+ | 通话 | `/api/v0/call/{start,update,stop,config}` | 腾讯 TRTC/LiteAV;`call/start` 也要求 `shumei_device_id` |
492
+
493
+ ---
494
+
495
+ ## 11. 2.7.5 与 2.6.2 的差异清单
496
+
497
+ | 项 | 2.6.2(2026-10-13) | 2.7.5(2026-11-06) |
498
+ |---|---|---|
499
+ | versionName / versionCode | 2.6.2 / 281 | **2.7.5 / 295** |
500
+ | compileSdk | 36 | **37** |
501
+ | `ChatFullCompletionRequest` | 10 字段 | **11 字段,新增必填 `shumei_device_id`** |
502
+ | continue / edit / regenerate / call | 无 `shumei_device_id` | **全部新增** |
503
+ | `x-device-id` | 旧版未在报告中记录 | **明确存在,Android ID + BRAND 派生** |
504
+ | `x-rangers-id` | 旧报告未展开 | **AppLog `bd_did`/`device_id`** |
505
+ | MFA / hCaptcha / Turnstile | 未展开 | **新增 `shumei_verification`、`hcaptcha_token`、`turnstile_token`** |
506
+ | SSE 片段快照 | 旧���以 `o=APPEND` 为主 | **出现无 `o` 的完整片段快照** |
507
+ | 文件模型 | 未展开 | **16 字段 AppChatFile,含 is_image/width/height/audit_result** |
508
+
509
+ ---
510
+
511
+ ## 12. 验证(使用提供的账号)
512
+
513
+ 环境:本地启动 ds2api,账号配置真实 `device_id`,通过 SOCKS5→HTTP CONNECT 桥接访问上游(沙箱限制)。
514
+
515
+ ### 12.1 非流式
516
+
517
+ ```bash
518
+ curl /v1/chat/completions -d '{"model":"deepseek-v4-flash","messages":[{"role":"user","content":"你好,请用一句话介绍你自己。"}],"stream":false}'
519
+ ```
520
+
521
+ 结果:
522
+
523
+ ```text
524
+ content: 你好,我是DeepSeek,一个乐于助人的AI助手,可以回答问题并协助你完成任务。
525
+ reasoning_len: 163
526
+ finish_reason: stop
527
+ ```
528
+
529
+ ### 12.2 流式
530
+
531
+ 结果:40 个 reasoning chunk + 5 个 content chunk + `finish_reason=stop`,正文完整。
532
+
533
+ ### 12.3 长文
534
+
535
+ 约 300 字、三段式西湖介绍:
536
+
537
+ ```text
538
+ content_len: 289
539
+ reasoning_len: 820
540
+ finish_reason: stop
541
+ ```
542
+
543
+ 正文分段完整,无重复、无缺失。
544
+
545
+ ---
546
+
547
+ ## 13. 建议与后续
548
+
549
+ 1. **不要再把 `upstream_empty_output` 当成限流。** 它是“正文为空”的信号,优先检查 SSE 片段类型/快照格式。
550
+ 2. **`shumei_device_id` 必须带。** 即使当前服务端对部分账号仍容忍缺失,2.7.5 已把它标为必填,缺失会降低设备信任分。
551
+ 3. **不要伪造 `x-rangers-id`。** 真实值是火山 AppLog 注册的设备 ID;账号哈希派生的 19 位数字在风控升级后可能被识别。若要长期稳定,建议从真机抓包填入账号级 `rangers_id`(配置已支持)。
552
+ 4. **`x-device-id` 可选但建议。** 它由 Android ID + BRAND 派生;没有真实 Android ID 时,宁可不发也不要随机生成,避免与数美指纹冲突。
553
+ 5. **补 MFA/hCaptcha 处理。** 账号被挑战时登录返回 `mfa_ticket`,需要走验证码/人机验证流程。
554
+ 6. **监控上游 SSE 形态。** 建议在 `devcapture` 中记录 `p/o/v` 路径统计,出现新的片段形态时尽早发现。
555
+ 7. **`resume_stream` 尚未实现。** 长流断线时只能 `continue`;如上游大量使用 `auto_resume`,可考虑补齐。
556
+
557
+ ---
558
+
559
+ ## 附录 A:证据索引
560
+
561
+ | 主题 | 证据 |
562
+ |---|---|
563
+ | 版本信息 | `apktool.yml`:versionName 2.7.5 / versionCode 295 |
564
+ | 通用请求头 | `defpackage/x06.java:130-137` |
565
+ | x-device-id / x-rangers-id | `defpackage/db.java:20-34`、`kw3.java:31-68`、`rkc.java:164-170` |
566
+ | completion 请求 | `defpackage/oy1.java:16-28` |
567
+ | continue 请求 | `defpackage/hx1.java:12-19` |
568
+ | edit 请求 | `defpackage/px1.java:12-22` |
569
+ | regenerate 请求 | `defpackage/pf2.java:12-19` |
570
+ | call 请求 | `defpackage/a7b.java:12-18` |
571
+ | 消息模型 | `defpackage/fy.java:16-34` |
572
+ | 状态机 | `defpackage/dec.java:176` |
573
+ | 撤回模板 | `defpackage/lv4.java`、`da8.java:1736` |
574
+ | 文件模型 | `defpackage/is.java:16-32` |
575
+ | 文件状态 | `defpackage/zx1.java:20-36` |
576
+ | PoW 模型 | `defpackage/l75.java`、`rs9.java`、`ff0.java` |
577
+ | 数美 SDK | `defpackage/a4a.java:19-55`、`com/ishumei/smantifraud/l111l11I1IIIl.java:45-46` |
578
+ | 风控开关 | `defpackage/fx2.java:12-20`、`hx2.java:1484` |
579
+ | MFA/验证码 | `defpackage/bd7.java`、`zd3.java:12-20`、`sq1.java:12-19` |
580
+ | ds2api 修复 | `internal/sse/parser.go`、`internal/deepseek/client/client_completion.go`、`client_continue.go` |
581
+
582
+ ## 附录 B:关键 JSON 速查
583
+
584
+ ```jsonc
585
+ // completion
586
+ {
587
+ "chat_session_id": "...", "parent_message_id": null, "prompt": "...",
588
+ "ref_file_ids": [], "thinking_enabled": true, "search_enabled": false,
589
+ "audio_id": null, "preempt": false, "model_type": "default",
590
+ "action": null, "shumei_device_id": "B..."
591
+ }
592
+
593
+ // continue
594
+ {
595
+ "chat_session_id": "...", "message_id": 2,
596
+ "fallback_to_resume": true, "shumei_device_id": "B..."
597
+ }
598
+
599
+ // 片段快照(2.7.5 新增形态)
600
+ {"p":"response/fragments","v":[
601
+ {"id":2,"type":"THINK","content":"..."},
602
+ {"id":3,"type":"RESPONSE","content":"..."}
603
+ ]}
604
+
605
+ // 撤回
606
+ {"v":[
607
+ {"p":"ban_regenerate","v":true},
608
+ {"p":"status","v":"CONTENT_FILTER"},
609
+ {"p":"quasi_status","v":"CONTENT_FILTER"},
610
+ {"p":"fragments","v":[{"type":"TEMPLATE_RESPONSE","content":"..."}]}
611
+ ]}
612
+ ```
internal/assistantturn/turn.go CHANGED
@@ -216,7 +216,9 @@ func UpstreamEmptyOutputDetail(contentFilter bool, text, thinking string) (int,
216
  return http.StatusBadRequest, "Upstream content filtered the response and returned no output.", "content_filter"
217
  }
218
  if strings.TrimSpace(thinking) != "" {
219
- return http.StatusTooManyRequests, "Upstream account hit a rate limit and returned reasoning without visible output.", "upstream_empty_output"
 
 
220
  }
221
  return http.StatusServiceUnavailable, "Upstream service is unavailable and returned no output.", "upstream_unavailable"
222
  }
 
216
  return http.StatusBadRequest, "Upstream content filtered the response and returned no output.", "content_filter"
217
  }
218
  if strings.TrimSpace(thinking) != "" {
219
+ // 保留 429 仅为兼容既有的空输出重试/切号逻辑;该状态不是上游限流,
220
+ // 而是上游只下发了 reasoning、没有下发正文(协议异常或风控降级)。
221
+ return http.StatusTooManyRequests, "Upstream returned reasoning without visible output (empty final answer).", "upstream_empty_output"
222
  }
223
  return http.StatusServiceUnavailable, "Upstream service is unavailable and returned no output.", "upstream_unavailable"
224
  }
internal/deepseek/client/client_completion.go CHANGED
@@ -6,6 +6,7 @@ import (
6
  dsprotocol "ds2api/internal/deepseek/protocol"
7
  "encoding/json"
8
  "net/http"
 
9
 
10
  "ds2api/internal/auth"
11
  "ds2api/internal/config"
@@ -14,6 +15,7 @@ import (
14
 
15
  func (c *Client) CallCompletion(ctx context.Context, a *auth.RequestAuth, payload map[string]any, powResp string, maxAttempts int) (*http.Response, error) {
16
  _ = maxAttempts
 
17
  clients := c.requestClientsForAuth(ctx, a)
18
  headers := c.authHeadersWithAuth(a)
19
  headers["x-ds-pow-response"] = powResp
@@ -77,3 +79,20 @@ func (c *Client) streamPostWithFallback(ctx context.Context, doer trans.Doer, ur
77
  }
78
  return resp, nil
79
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  dsprotocol "ds2api/internal/deepseek/protocol"
7
  "encoding/json"
8
  "net/http"
9
+ "strings"
10
 
11
  "ds2api/internal/auth"
12
  "ds2api/internal/config"
 
15
 
16
  func (c *Client) CallCompletion(ctx context.Context, a *auth.RequestAuth, payload map[string]any, powResp string, maxAttempts int) (*http.Response, error) {
17
  _ = maxAttempts
18
+ injectShumeiDeviceID(a, payload)
19
  clients := c.requestClientsForAuth(ctx, a)
20
  headers := c.authHeadersWithAuth(a)
21
  headers["x-ds-pow-response"] = powResp
 
79
  }
80
  return resp, nil
81
  }
82
+
83
+ // injectShumeiDeviceID 把账号绑定的数美 device_id 写入 completion 请求体。
84
+ //
85
+ // DeepSeek Android 2.7.5 的 ChatFullCompletionRequest 将 shumei_device_id 标记为
86
+ // 必填字段(2.6.x 及更早版本没有该字段)。缺失时服务端可能按低信任设备处理,
87
+ // 出现只返回 reasoning、不下发正文的降级响应。
88
+ func injectShumeiDeviceID(a *auth.RequestAuth, payload map[string]any) {
89
+ if a == nil || payload == nil {
90
+ return
91
+ }
92
+ if v, ok := payload["shumei_device_id"].(string); ok && strings.TrimSpace(v) != "" {
93
+ return
94
+ }
95
+ if id := strings.TrimSpace(a.Account.DeviceID); id != "" {
96
+ payload["shumei_device_id"] = id
97
+ }
98
+ }
internal/deepseek/client/client_completion_test.go CHANGED
@@ -7,6 +7,7 @@ import (
7
  "testing"
8
 
9
  "ds2api/internal/auth"
 
10
  )
11
 
12
  func TestCallCompletionDoesNotFallbackForNonIdempotentCompletion(t *testing.T) {
@@ -34,3 +35,28 @@ func TestCallCompletionDoesNotFallbackForNonIdempotentCompletion(t *testing.T) {
34
  t.Fatal("completion fallback should not be called for a non-idempotent request")
35
  }
36
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  "testing"
8
 
9
  "ds2api/internal/auth"
10
+ "ds2api/internal/config"
11
  )
12
 
13
  func TestCallCompletionDoesNotFallbackForNonIdempotentCompletion(t *testing.T) {
 
35
  t.Fatal("completion fallback should not be called for a non-idempotent request")
36
  }
37
  }
38
+
39
+ func TestInjectShumeiDeviceIDSetsAccountDeviceID(t *testing.T) {
40
+ payload := map[string]any{"prompt": "hello"}
41
+ injectShumeiDeviceID(&auth.RequestAuth{Account: config.Account{DeviceID: " B-issued "}}, payload)
42
+ if got := payload["shumei_device_id"]; got != "B-issued" {
43
+ t.Fatalf("unexpected shumei_device_id: %#v", got)
44
+ }
45
+ }
46
+
47
+ func TestInjectShumeiDeviceIDKeepsExplicitValue(t *testing.T) {
48
+ payload := map[string]any{"shumei_device_id": "explicit"}
49
+ injectShumeiDeviceID(&auth.RequestAuth{Account: config.Account{DeviceID: "B-issued"}}, payload)
50
+ if got := payload["shumei_device_id"]; got != "explicit" {
51
+ t.Fatalf("explicit value should win: %#v", got)
52
+ }
53
+ }
54
+
55
+ func TestInjectShumeiDeviceIDEmptyDeviceIDLeavesPayloadUntouched(t *testing.T) {
56
+ payload := map[string]any{"prompt": "hello"}
57
+ injectShumeiDeviceID(&auth.RequestAuth{}, payload)
58
+ if _, ok := payload["shumei_device_id"]; ok {
59
+ t.Fatalf("unexpected shumei_device_id: %#v", payload["shumei_device_id"])
60
+ }
61
+ injectShumeiDeviceID(nil, payload)
62
+ }
internal/deepseek/client/client_continue.go CHANGED
@@ -66,6 +66,9 @@ func (c *Client) callContinue(ctx context.Context, a *auth.RequestAuth, sessionI
66
  "message_id": responseMessageID,
67
  "fallback_to_resume": true,
68
  }
 
 
 
69
  config.Logger.Info("[auto_continue] calling continue", "session_id", sessionID, "message_id", responseMessageID)
70
  captureSession := c.capture.Start("deepseek_continue", dsprotocol.DeepSeekContinueURL, a.AccountID, payload)
71
  resp, err := c.streamPost(ctx, clients.stream, dsprotocol.DeepSeekContinueURL, headers, payload)
 
66
  "message_id": responseMessageID,
67
  "fallback_to_resume": true,
68
  }
69
+ if id := strings.TrimSpace(a.Account.DeviceID); id != "" {
70
+ payload["shumei_device_id"] = id
71
+ }
72
  config.Logger.Info("[auto_continue] calling continue", "session_id", sessionID, "message_id", responseMessageID)
73
  captureSession := c.capture.Start("deepseek_continue", dsprotocol.DeepSeekContinueURL, a.AccountID, payload)
74
  resp, err := c.streamPost(ctx, clients.stream, dsprotocol.DeepSeekContinueURL, headers, payload)
internal/httpapi/openai/chat/vercel_stream.go CHANGED
@@ -226,7 +226,7 @@ func (h *Handler) handleVercelStreamSwitch(w http.ResponseWriter, r *http.Reques
226
  }
227
  a := lease.Auth
228
  if !a.UseConfigToken || !a.SwitchAccount(r.Context()) {
229
- writeOpenAIErrorWithCode(w, http.StatusTooManyRequests, "Upstream account hit a rate limit and returned reasoning without visible output.", "upstream_empty_output")
230
  return
231
  }
232
 
@@ -255,6 +255,10 @@ func (h *Handler) handleVercelStreamSwitch(w http.ResponseWriter, r *http.Reques
255
  return
256
  }
257
  h.updateStreamLeaseState(leaseID, stdReq, sessionID)
 
 
 
 
258
  writeJSON(w, http.StatusOK, map[string]any{
259
  "session_id": sessionID,
260
  "lease_id": leaseID,
@@ -265,7 +269,7 @@ func (h *Handler) handleVercelStreamSwitch(w http.ResponseWriter, r *http.Reques
265
  "tool_names": stdReq.ToolNames,
266
  "deepseek_token": a.DeepSeekToken,
267
  "pow_header": powHeader,
268
- "payload": stdReq.CompletionPayload(sessionID),
269
  })
270
  }
271
 
 
226
  }
227
  a := lease.Auth
228
  if !a.UseConfigToken || !a.SwitchAccount(r.Context()) {
229
+ writeOpenAIErrorWithCode(w, http.StatusTooManyRequests, "Upstream returned reasoning without visible output (empty final answer).", "upstream_empty_output")
230
  return
231
  }
232
 
 
255
  return
256
  }
257
  h.updateStreamLeaseState(leaseID, stdReq, sessionID)
258
+ payload := stdReq.CompletionPayload(sessionID)
259
+ if id := strings.TrimSpace(a.Account.DeviceID); id != "" {
260
+ payload["shumei_device_id"] = id
261
+ }
262
  writeJSON(w, http.StatusOK, map[string]any{
263
  "session_id": sessionID,
264
  "lease_id": leaseID,
 
269
  "tool_names": stdReq.ToolNames,
270
  "deepseek_token": a.DeepSeekToken,
271
  "pow_header": powHeader,
272
+ "payload": payload,
273
  })
274
  }
275
 
internal/httpapi/openai/shared/upstream_empty.go CHANGED
@@ -15,7 +15,8 @@ func UpstreamEmptyOutputDetail(contentFilter bool, text, thinking string) (int,
15
  return http.StatusBadRequest, "Upstream content filtered the response and returned no output.", "content_filter"
16
  }
17
  if thinking != "" {
18
- return http.StatusTooManyRequests, "Upstream account hit a rate limit and returned reasoning without visible output.", "upstream_empty_output"
 
19
  }
20
  return http.StatusServiceUnavailable, "Upstream service is unavailable and returned no output.", "upstream_unavailable"
21
  }
 
15
  return http.StatusBadRequest, "Upstream content filtered the response and returned no output.", "content_filter"
16
  }
17
  if thinking != "" {
18
+ // 429 仅用于沿用空输出重试/切号语义;实际含义是上游没有下发正文。
19
+ return http.StatusTooManyRequests, "Upstream returned reasoning without visible output (empty final answer).", "upstream_empty_output"
20
  }
21
  return http.StatusServiceUnavailable, "Upstream service is unavailable and returned no output.", "upstream_unavailable"
22
  }
internal/js/chat-stream/vercel_stream_impl.js CHANGED
@@ -664,7 +664,7 @@ function upstreamEmptyOutputDetail(contentFilter, _text, thinking) {
664
  if (thinking !== '') {
665
  return {
666
  status: 429,
667
- message: 'Upstream account hit a rate limit and returned reasoning without visible output.',
668
  code: 'upstream_empty_output',
669
  };
670
  }
 
664
  if (thinking !== '') {
665
  return {
666
  status: 429,
667
+ message: 'Upstream returned reasoning without visible output (empty final answer).',
668
  code: 'upstream_empty_output',
669
  };
670
  }
internal/sse/consumer_test.go CHANGED
@@ -28,3 +28,28 @@ func TestCollectStreamDedupesContinueSnapshotReplay(t *testing.T) {
28
  t.Fatalf("unexpected thinking after dedupe: %q", got.Thinking)
29
  }
30
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  t.Fatalf("unexpected thinking after dedupe: %q", got.Thinking)
29
  }
30
  }
31
+
32
+ // 复现 2026-11 上游片段快照(无 o 字段)导致正文全部落入 reasoning 的问题。
33
+ func TestCollectStreamFragmentsSnapshotKeepsResponseText(t *testing.T) {
34
+ body := strings.Join([]string{
35
+ `data: {"v":{"response":{"message_id":2,"thinking_enabled":true,"status":"WIP","fragments":[{"id":2,"type":"THINK","content":"思考"}]}}}`,
36
+ ``,
37
+ `data: {"p":"response/fragments/-1/content","o":"APPEND","v":"过程"}`,
38
+ ``,
39
+ `data: {"p":"response/fragments","v":[{"id":2,"type":"THINK","content":"思考过程"},{"id":3,"type":"RESPONSE","content":"答"}]}`,
40
+ ``,
41
+ `data: {"p":"response/fragments/-1/content","o":"APPEND","v":"案"}`,
42
+ ``,
43
+ `data: {"p":"response/status","o":"SET","v":"FINISHED"}`,
44
+ ``,
45
+ }, "\n")
46
+
47
+ resp := &http.Response{Body: io.NopCloser(strings.NewReader(body))}
48
+ got := CollectStream(resp, true, true)
49
+ if got.Text != "答案" {
50
+ t.Fatalf("expected visible answer, got text=%q thinking=%q", got.Text, got.Thinking)
51
+ }
52
+ if got.Thinking != "思考过程" {
53
+ t.Fatalf("unexpected thinking: %q", got.Thinking)
54
+ }
55
+ }
internal/sse/parser.go CHANGED
@@ -93,15 +93,20 @@ func ParseSSEChunkForContentDetailed(chunk map[string]any, thinkingEnabled bool,
93
  newType := currentFragmentType
94
  parts := make([]ContentPart, 0, 8)
95
  updateTypeFromExplicitPath(path, thinkingEnabled, &newType)
96
- collectDirectFragments(path, chunk, v, &newType, &parts)
97
- updateTypeFromNestedResponse(path, v, &newType)
 
 
98
  partType := resolvePartType(path, thinkingEnabled, newType)
99
  // 当前位置是工具卡片片段(TOOL_SEARCH/TOOL_OPEN 等)时,其 content/status
100
  // 补丁只是前端卡片文案,不产出正文或思考内容。
101
  if newType == "tool" && isFragmentScopedPath(path) {
102
  return nil, nil, false, newType
103
  }
104
- finished := appendChunkValueContent(v, partType, &newType, &parts, path)
 
 
 
105
  if finished {
106
  return nil, nil, true, newType
107
  }
@@ -144,19 +149,31 @@ func selectThinkingParts(parts []ContentPart) []ContentPart {
144
  return out
145
  }
146
 
147
- func collectDirectFragments(path string, chunk map[string]any, v any, newType *string, parts *[]ContentPart) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  if path != "response/fragments" {
149
- return
150
- }
151
- op, _ := chunk["o"].(string)
152
- if !strings.EqualFold(op, "APPEND") {
153
- return
154
  }
155
  frags, ok := v.([]any)
156
  if !ok {
157
- return
158
  }
159
- for _, frag := range frags {
 
 
160
  m, ok := frag.(map[string]any)
161
  if !ok {
162
  continue
@@ -165,21 +182,29 @@ func collectDirectFragments(path string, chunk map[string]any, v any, newType *s
165
  if typeName == "" {
166
  typeName = fragType
167
  }
 
168
  switch typeName {
169
  case "THINK", "THINKING":
170
  *newType = "thinking"
171
- appendContentPart(parts, content, "thinking")
 
 
172
  case "RESPONSE":
173
  *newType = "text"
174
- appendContentPart(parts, content, "text")
 
 
175
  default:
176
  if isToolFragmentType(typeName) {
177
  *newType = "tool"
178
  continue
179
  }
180
- appendContentPart(parts, content, "text")
 
 
181
  }
182
  }
 
183
  }
184
 
185
  func updateTypeFromNestedResponse(path string, v any, newType *string) {
 
93
  newType := currentFragmentType
94
  parts := make([]ContentPart, 0, 8)
95
  updateTypeFromExplicitPath(path, thinkingEnabled, &newType)
96
+ fragmentList := collectDirectFragments(path, chunk, v, &newType, &parts)
97
+ if !fragmentList {
98
+ updateTypeFromNestedResponse(path, v, &newType)
99
+ }
100
  partType := resolvePartType(path, thinkingEnabled, newType)
101
  // 当前位置是工具卡片片段(TOOL_SEARCH/TOOL_OPEN 等)时,其 content/status
102
  // 补丁只是前端卡片文案,不产出正文或思考内容。
103
  if newType == "tool" && isFragmentScopedPath(path) {
104
  return nil, nil, false, newType
105
  }
106
+ finished := false
107
+ if !fragmentList {
108
+ finished = appendChunkValueContent(v, partType, &newType, &parts, path)
109
+ }
110
  if finished {
111
  return nil, nil, true, newType
112
  }
 
149
  return out
150
  }
151
 
152
+ // collectDirectFragments 处理 p=response/fragments 的片段列表补丁。
153
+ //
154
+ // 上游存在两种形态:
155
+ // - 增量:{"p":"response/fragments","o":"APPEND","v":[新片段...]}
156
+ // - 快照:{"p":"response/fragments","v":[完整片段列表...]}(无 o 字段)
157
+ //
158
+ // 早期实现只在 o=APPEND 时更新片段类型,导致快照形态下 THINK → RESPONSE
159
+ // 的类型切换被忽略:后续正文增量仍按 thinking 处理,最终正文全被吞进
160
+ // reasoning_content,表现为 upstream_empty_output。
161
+ //
162
+ // 快照里只有最后一个片段是当前活跃片段,其 content 是尚未通过增量下发的新
163
+ // 内容;更早的片段内容已由增量补齐,不能重复追加。
164
+ //
165
+ // 返回 true 表示该 chunk 已由片段列表处理完毕,调用方不应再做通用内容提取。
166
+ func collectDirectFragments(path string, chunk map[string]any, v any, newType *string, parts *[]ContentPart) bool {
167
  if path != "response/fragments" {
168
+ return false
 
 
 
 
169
  }
170
  frags, ok := v.([]any)
171
  if !ok {
172
+ return false
173
  }
174
+ op, _ := chunk["o"].(string)
175
+ appendAll := strings.EqualFold(op, "APPEND")
176
+ for i, frag := range frags {
177
  m, ok := frag.(map[string]any)
178
  if !ok {
179
  continue
 
182
  if typeName == "" {
183
  typeName = fragType
184
  }
185
+ isLast := i == len(frags)-1
186
  switch typeName {
187
  case "THINK", "THINKING":
188
  *newType = "thinking"
189
+ if appendAll {
190
+ appendContentPart(parts, content, "thinking")
191
+ }
192
  case "RESPONSE":
193
  *newType = "text"
194
+ if appendAll || isLast {
195
+ appendContentPart(parts, content, "text")
196
+ }
197
  default:
198
  if isToolFragmentType(typeName) {
199
  *newType = "tool"
200
  continue
201
  }
202
+ if appendAll || isLast {
203
+ appendContentPart(parts, content, "text")
204
+ }
205
  }
206
  }
207
+ return true
208
  }
209
 
210
  func updateTypeFromNestedResponse(path string, v any, newType *string) {
internal/sse/parser_test.go CHANGED
@@ -71,6 +71,57 @@ func TestParseSSEChunkForContentFragmentsAppendSwitchToResponse(t *testing.T) {
71
  }
72
  }
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  func TestParseSSEChunkForContentAfterAppendUsesUpdatedType(t *testing.T) {
75
  chunk := map[string]any{
76
  "p": "response/fragments/-1/content",
 
71
  }
72
  }
73
 
74
+ // 上游 2026-11 起会在思考结束后下发不带 o 字段的片段快照:
75
+ // {"p":"response/fragments","v":[THINK..., RESPONSE...]}
76
+ // 快照必须把当前片段类型切换到 RESPONSE,否则后续正文增量会被当作 thinking。
77
+ func TestParseSSEChunkForContentFragmentsSnapshotSwitchToResponse(t *testing.T) {
78
+ chunk := map[string]any{
79
+ "p": "response/fragments",
80
+ "v": []any{
81
+ map[string]any{"type": "THINK", "content": "思考"},
82
+ map[string]any{"type": "RESPONSE", "content": "答"},
83
+ },
84
+ }
85
+ parts, finished, nextType := ParseSSEChunkForContent(chunk, true, "thinking")
86
+ if finished {
87
+ t.Fatal("expected unfinished")
88
+ }
89
+ if nextType != "text" {
90
+ t.Fatalf("expected next type text, got %q", nextType)
91
+ }
92
+ // 快照里只有最后一个片段是新增内容;THINK 已由增量下发,不能重复。
93
+ if len(parts) != 1 || parts[0].Type != "text" || parts[0].Text != "答" {
94
+ t.Fatalf("unexpected parts: %#v", parts)
95
+ }
96
+
97
+ parts2, _, nextType2 := ParseSSEChunkForContent(map[string]any{"v": "案"}, true, nextType)
98
+ if nextType2 != "text" {
99
+ t.Fatalf("expected continuation type text, got %q", nextType2)
100
+ }
101
+ if len(parts2) != 1 || parts2[0].Type != "text" || parts2[0].Text != "案" {
102
+ t.Fatalf("unexpected continuation parts: %#v", parts2)
103
+ }
104
+ }
105
+
106
+ func TestParseSSEChunkForContentFragmentsSnapshotThinkOnlyDoesNotDuplicate(t *testing.T) {
107
+ chunk := map[string]any{
108
+ "p": "response/fragments",
109
+ "v": []any{
110
+ map[string]any{"type": "THINK", "content": "完整思考"},
111
+ },
112
+ }
113
+ parts, finished, nextType := ParseSSEChunkForContent(chunk, true, "thinking")
114
+ if finished {
115
+ t.Fatal("expected unfinished")
116
+ }
117
+ if nextType != "thinking" {
118
+ t.Fatalf("expected next type thinking, got %q", nextType)
119
+ }
120
+ if len(parts) != 0 {
121
+ t.Fatalf("expected no duplicate thinking parts, got %#v", parts)
122
+ }
123
+ }
124
+
125
  func TestParseSSEChunkForContentAfterAppendUsesUpdatedType(t *testing.T) {
126
  chunk := map[string]any{
127
  "p": "response/fragments/-1/content",