fix(token-stats): 修复 token 统计异常和响应时间为 0 的 Bug #86
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
动机
透明代理的 token 统计功能存在两个关键 bug:
response_time_ms字段都是 0output_tokens为 1-5(message_start 的初始值),而非实际的最终值(数百)根本原因是 SSE 流完成检测机制使用了固定延迟(2秒) + 轮询稳定性检测,导致统计任务在流真正结束前就执行,错过了包含最终 token 数据的
message_delta事件。主要改动点
1. 修复响应时间统计 (commit 4eb7899)
问题:
RequestLogContext创建新Instant::now()而非使用传入的response_time_mselapsed_ms()返回从上下文创建到统计的时间(约 0ms),而非真实响应时间修复:
RequestLogContext.start_time: Instant改为response_time_ms: Option<i64>proxy_instance.rs计算响应时间后直接传入上下文context.response_time_ms影响文件:
src-tauri/src/services/proxy/log_recorder/context.rssrc-tauri/src/services/proxy/log_recorder/recorder.rssrc-tauri/src/services/proxy/headers/claude_processor.rs2. 添加详细调试日志 (commit f652cfd)
为排查
output_tokens异常问题添加完整的日志链路:extractor.rs:
manager.rs:
影响文件:
src-tauri/src/services/token_stats/extractor.rs(+15 行日志)src-tauri/src/services/token_stats/manager.rs(+27 行日志)3. 使用流完成信号替代轮询检测 (commit 3d2bb93)
问题:
修复:
架构优势:
tokio::sync::oneshot通道 +futures_util::stream::chain()await真正等待流结束,无任何预测逻辑影响文件:
src-tauri/src/services/proxy/proxy_instance.rs(+67 行)测试情况
功能验证
修复前日志:
修复后日志:
代码质量
数据库验证建议
风险评估
低风险
流完成检测机制变更:
futures_util(无新依赖).filter()移除标记,不影响下游上下文字段变更:
RequestLogContext简化为接收预计算的response_time_ms日志增强:
测试覆盖
向后兼容
潜在影响
可能影响: 历史统计数据对比
output_tokens偏低,response_time_ms为 0关联 Issue
无 (内部发现的 bug)
变更总结