Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

fix(proxy): surface reasoning-only truncated or empty Codex turns instead of completing silently (#8528)

Jason36ccf3a2cf00
diff --git a/src-tauri/src/proxy/handler_config.rs b/src-tauri/src/proxy/handler_config.rs
index 7ef5b636e..799f5a828 100644
--- a/src-tauri/src/proxy/handler_config.rs
+++ b/src-tauri/src/proxy/handler_config.rs
@@ -47,7 +47,10 @@ fn openai_stream_usage_event_filter(data: &str) -> bool {
}
pub fn codex_stream_usage_event_filter(data: &str) -> bool {
- data.contains("\"response.completed\"") || data.contains("\"usage\"")
+ data.contains("\"response.completed\"")
+ || data.contains("\"response.incomplete\"")
+ || data.contains("\"response.failed\"")
+ || data.contains("\"usage\"")
}
fn gemini_stream_usage_event_filter(data: &str) -> bool {
diff --git a/src-tauri/src/proxy/handlers.rs b/src-tauri/src/proxy/handlers.rs
index ed4d98c8a..d22a152fb 100644
--- a/src-tauri/src/proxy/handlers.rs
+++ b/src-tauri/src/proxy/handlers.rs
@@ -1990,40 +1990,26 @@ async fn handle_codex_chat_to_responses_transform(
};
let successful_terminal =
terminal_hook.is_some() && terminal_value_response_succeeded(&chat_response);
- let responses_response = transform_codex_chat::chat_completion_to_response_with_context(
+ // The upstream has already billed this request even if output conversion fails.
+ let chat_response = transform::unwrap_chat_completion_envelope(chat_response);
+ let usage = chat_response.get("usage").and_then(|usage| {
+ TokenUsage::from_codex_response(&json!({
+ "id": chat_response["id"].as_str().filter(|id| !id.is_empty())
+ .map(|id| transform_codex_chat::response_id_from_chat_id(Some(id))),
+ "model": chat_response.get("model"),
+ "usage": transform_codex_chat::chat_usage_to_responses_usage(Some(usage)),
+ }))
+ });
+ let converted = transform_codex_chat::chat_completion_to_response_with_context(
chat_response,
&tool_context,
- )
- .map_err(|e| {
- log::error!("[Codex] Chat → Responses 响应转换失败: {e}");
- e
- })?;
- if successful_terminal {
- if let Some(hook) = terminal_hook.take() {
- hook().await;
- }
- }
- state
- .codex_chat_history
- .record_response(
- &responses_response,
- ctx.session_client_provided
- .then_some(ctx.session_id.as_str()),
- )
- .await;
+ );
- // 上游非流式 Chat 省略 usage 时,chat_usage_to_responses_usage 会合成全 0 usage
- // (transform_codex_chat.rs:1581),from_codex_response 对 input/output 字段存在(哪怕=0)
- // 即返回 Some。用 has_billable_tokens 闸门跳过全 0,避免空行虚增请求数——与流式分支
- // 及 Claude transform handler 的 skip 行为对齐。
- if let Some(usage) = TokenUsage::from_codex_response_auto(&responses_response)
- .filter(TokenUsage::has_billable_tokens)
- {
- let model = responses_response
- .get("model")
- .and_then(|m| m.as_str())
- .filter(|m| !m.is_empty())
- .map(str::to_string)
+ if let Some(usage) = usage.filter(TokenUsage::has_billable_tokens) {
+ let model = usage
+ .model
+ .clone()
+ .filter(|model| !model.is_empty())
.or_else(|| ctx.outbound_model.clone())
.unwrap_or_else(|| ctx.request_model.clone());
let request_model = ctx.request_model.clone();
@@ -2032,7 +2018,7 @@ async fn handle_codex_chat_to_responses_transform(
.clone()
.unwrap_or_else(|| ctx.request_model.clone());
let app_type_str = ctx.app_type_str;
- tokio::spawn({
+ let write = {
let state = state.clone();
let provider_id = ctx.provider.id.clone();
let multiplier = crate::provider::billing_multiplier(&ctx.provider);
@@ -2056,8 +2042,29 @@ async fn handle_codex_chat_to_responses_transform(
)
.await;
}
- });
+ };
+ if converted.is_err() {
+ write.await;
+ } else {
+ tokio::spawn(write);
+ }
+ }
+ let responses_response = converted.inspect_err(|error| {
+ log::error!("[Codex] Chat → Responses 响应转换失败: {error}");
+ })?;
+ if successful_terminal {
+ if let Some(hook) = terminal_hook.take() {
+ hook().await;
+ }
}
+ state
+ .codex_chat_history
+ .record_response(
+ &responses_response,
+ ctx.session_client_provided
+ .then_some(ctx.session_id.as_str()),
+ )
+ .await;
strip_entity_headers_for_rebuilt_body(&mut response_headers);
strip_hop_by_hop_response_headers(&mut response_headers);
@@ -4501,6 +4508,60 @@ data: [DONE]\n\n";
assert_eq!(anthropic["stop_reason"], "end_turn");
}
+ #[tokio::test]
+ async fn reasoning_only_chat_error_records_nonstreaming_usage_once() {
+ use crate::mode::stack::StackTarget;
+ use crate::provider::Provider;
+ use crate::proxy::{
+ handler_context::RequestContext, hyper_client::ProxyResponse, server::ProxyState,
+ };
+ use serde_json::json;
+
+ let state = ProxyState::for_test(Arc::new(Database::memory().unwrap()));
+ state.config.write().await.enable_logging = true;
+ let ctx = RequestContext::new(
+ &state,
+ &json!({"model": "gpt-test"}),
+ &HeaderMap::new(),
+ crate::app_config::AppType::Codex,
+ "Codex",
+ "codex",
+ Some(StackTarget {
+ provider: Provider::with_id("test".into(), "Test".into(), json!({}), None),
+ upstream_model: "gpt-test".into(),
+ original_model: "gpt-test".into(),
+ }),
+ )
+ .await
+ .unwrap();
+ let chat = json!({"data":{
+ "id":"chatcmpl_123", "model":"gpt-test",
+ "choices":[{"message":{"role":"assistant","reasoning_content":"thinking","content":"\n"},"finish_reason":"stop"}],
+ "usage":{"prompt_tokens":32,"completion_tokens":12,"prompt_tokens_details":{"cached_tokens":8}}
+ }});
+ let upstream = ProxyResponse::buffered(
+ StatusCode::OK,
+ HeaderMap::new(),
+ Bytes::from(chat.to_string()),
+ );
+ let error = super::handle_codex_chat_to_responses_transform(
+ upstream,
+ &ctx,
+ &state,
+ false,
+ None,
+ Default::default(),
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(error, ProxyError::TransformError(_)));
+ let totals: (u32, u32, u32, u32) = state.db.conn.lock().unwrap().query_row(
+ "SELECT COUNT(*), SUM(input_tokens), SUM(output_tokens), SUM(cache_read_tokens) FROM proxy_request_logs",
+ [], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
+ ).unwrap();
+ assert_eq!(totals, (1, 32, 12, 8));
+ }
+
#[tokio::test]
async fn claude_model_validation_receives_json_when_upstream_forces_sse() {
use crate::app_config::AppType;
diff --git a/src-tauri/src/proxy/providers/codex_responses_sse.rs b/src-tauri/src/proxy/providers/codex_responses_sse.rs
index 836791b78..1a9e8372f 100644
--- a/src-tauri/src/proxy/providers/codex_responses_sse.rs
+++ b/src-tauri/src/proxy/providers/codex_responses_sse.rs
@@ -53,8 +53,12 @@ pub(crate) fn response_completed(response: &Value) -> Bytes {
)
}
-/// `response.incomplete`. Codex treats it as a retryable stream error; the converters
-/// only use it for compaction turns, where a truncated summary must not be installed.
+/// `response.incomplete`. Emitted for truncated compaction turns and for
+/// truncated turns that produced no assistant text or tool calls (e.g., when
+/// reasoning tokens exhaust `max_output_tokens`) instead of silently ending an
+/// empty turn. Codex >= 0.163.0 treats it as a terminal `ResponseIncomplete`
+/// error; Codex <= 0.162.1 treats it as a retryable `ApiError::Stream` (up to
+/// `DEFAULT_STREAM_MAX_RETRIES = 5`).
pub(crate) fn response_incomplete(response: &Value) -> Bytes {
sse_event(
"response.incomplete",
diff --git a/src-tauri/src/proxy/providers/inline_think.rs b/src-tauri/src/proxy/providers/inline_think.rs
index c54ccaf79..23ca369fd 100644
--- a/src-tauri/src/proxy/providers/inline_think.rs
+++ b/src-tauri/src/proxy/providers/inline_think.rs
@@ -208,9 +208,9 @@ impl InlineThinkSplitter {
}
}
- /// 是否还扣着未下发的非空白内容。
+ /// 是否还扣着未下发的非空白正文(Detecting/Text 缓冲,不含未闭合的思考块)。
pub(crate) fn has_pending_content(&self) -> bool {
- !self.buffer.trim().is_empty()
+ self.mode != InlineThinkMode::Reasoning && !self.buffer.trim().is_empty()
}
}
diff --git a/src-tauri/src/proxy/providers/streaming_codex_anthropic.rs b/src-tauri/src/proxy/providers/streaming_codex_anthropic.rs
index 11d58d539..91760623c 100644
--- a/src-tauri/src/proxy/providers/streaming_codex_anthropic.rs
+++ b/src-tauri/src/proxy/providers/streaming_codex_anthropic.rs
@@ -17,8 +17,9 @@ use super::transform_codex_anthropic::{
decode_anthropic_thinking_block, ANTHROPIC_THINKING_ENCRYPTED_PREFIX,
};
use super::transform_codex_chat::{
- response_message_item_id_indexed, response_tool_call_item_from_chat_name,
- response_tool_call_item_id_from_chat_name, CodexToolContext,
+ is_actionable_response_item, response_message_item_id_indexed,
+ response_tool_call_item_from_chat_name, response_tool_call_item_id_from_chat_name,
+ CodexToolContext,
};
use super::transform_responses::sanitize_anthropic_tool_use_input_json;
use crate::proxy::json_canonical::canonicalize_tool_arguments_str;
@@ -446,11 +447,14 @@ impl AnthropicToResponsesState {
/// started tool call). Used to distinguish a truncated-with-output stream (report
/// incomplete) from one that produced nothing (report failed).
fn has_substantive_output(&self) -> bool {
- !self.output_items.is_empty()
+ self.output_items
+ .iter()
+ .any(|(_, item)| is_actionable_response_item(item))
|| self.blocks.values().any(|b| {
- !b.accum.trim().is_empty()
- || !b.call_id.trim().is_empty()
- || !b.name.trim().is_empty()
+ b.kind != BlockKind::Thinking
+ && (!b.accum.trim().is_empty()
+ || !b.call_id.trim().is_empty()
+ || !b.name.trim().is_empty())
})
}
@@ -481,10 +485,16 @@ impl AnthropicToResponsesState {
let mut output = self.output_items.clone();
output.sort_by_key(|(output_index, _)| *output_index);
let output: Vec<Value> = output.into_iter().map(|(_, item)| item).collect();
+ let has_actionable_output = output.iter().any(is_actionable_response_item);
let mut response = self.base_response(status, output);
if let Some(reason) = incomplete_reason {
response["incomplete_details"] = json!({ "reason": reason });
+ if !has_actionable_output {
+ events.push(sse::response_incomplete(&response));
+ self.completed = true;
+ return events;
+ }
}
events.push(sse::response_completed(&response));
@@ -1137,6 +1147,20 @@ mod tests {
assert_eq!(block["thinking"], "hmm");
}
+ #[test]
+ fn empty_text_block_after_thinking_still_reports_max_tokens() {
+ let output = render_message_events(&json!({
+ "id": "msg_capped", "type": "message", "stop_reason": "max_tokens",
+ "content": [
+ {"type": "thinking", "thinking": "thinking", "signature": "sig"},
+ {"type": "text", "text": ""}
+ ]
+ }));
+ assert!(output.contains("event: response.incomplete"));
+ assert!(output.contains("max_output_tokens"));
+ assert!(!output.contains("event: response.completed"));
+ }
+
#[tokio::test]
async fn test_max_tokens_incomplete() {
let input = concat!(
diff --git a/src-tauri/src/proxy/providers/streaming_codex_chat.rs b/src-tauri/src/proxy/providers/streaming_codex_chat.rs
index 45dad4cce..4051df8b7 100644
--- a/src-tauri/src/proxy/providers/streaming_codex_chat.rs
+++ b/src-tauri/src/proxy/providers/streaming_codex_chat.rs
@@ -9,10 +9,11 @@ use super::{
codex_compaction,
inline_think::InlineThinkSplitter,
transform_codex_chat::{
- chat_error_to_response_error, chat_reasoning_item_id, chat_usage_to_responses_usage,
- custom_tool_input_from_chat_arguments, response_id_from_chat_id, response_message_item_id,
- response_status_from_finish_reason, response_tool_call_item_from_chat_name,
- response_tool_call_item_id_from_chat_name, CodexToolContext,
+ chat_error_to_response_error, chat_reasoning_item_id, chat_response_status,
+ chat_usage_to_responses_usage, custom_tool_input_from_chat_arguments,
+ is_actionable_response_item, response_id_from_chat_id, response_message_item_id,
+ response_tool_call_item_from_chat_name, response_tool_call_item_id_from_chat_name,
+ CodexToolContext,
},
};
use crate::proxy::json_canonical::canonicalize_tool_arguments_str;
@@ -449,16 +450,20 @@ impl ChatToResponsesState {
fn has_substantive_output(&self) -> bool {
!self.text.text.trim().is_empty()
- || !self.reasoning.text.trim().is_empty()
|| self.inline_think.has_pending_content()
- || !self.output_items.is_empty()
- || self.tools.values().any(|state| {
- state.added
- || !state.call_id.trim().is_empty()
- || !state.name.trim().is_empty()
- || !state.arguments.trim().is_empty()
- || !state.reasoning_content.trim().is_empty()
- })
+ || self.has_actionable_output()
+ || self
+ .tools
+ .values()
+ .any(|state| !state.name.trim().is_empty())
+ }
+
+ /// Whether finalized output contains at least one user-visible assistant
+ /// message or usable tool call (as opposed to reasoning-only output).
+ fn has_actionable_output(&self) -> bool {
+ self.output_items
+ .iter()
+ .any(|(_, item)| is_actionable_response_item(item))
}
/// 本回合最终产出里是否至少有一个可被 Codex 识别的工具调用 item。
@@ -486,7 +491,7 @@ impl ChatToResponsesState {
return self.finish_compaction(events);
}
- let status = response_status_from_finish_reason(self.finish_reason.as_deref());
+ let (status, incomplete_reason) = chat_response_status(self.finish_reason.as_deref());
// 丢弃过工具调用、且最终一个工具调用都没剩下时,Codex 会收到一个
// "status=completed 但 output 里没有任何工具调用" 的回合,agent loop 必然
@@ -508,9 +513,27 @@ impl ChatToResponsesState {
return events;
}
- let mut response = self.base_response(status, self.completed_output_items());
- if status == "incomplete" {
- response["incomplete_details"] = json!({ "reason": "max_output_tokens" });
+ let has_actionable_output = self.has_actionable_output();
+ let output = self.completed_output_items();
+ if status == "completed" && self.reasoning.added && !has_actionable_output {
+ events.push(
+ self.failed_event(
+ "Upstream returned reasoning without any assistant message or tool call"
+ .to_string(),
+ Some("upstream_reasoning_only_turn".to_string()),
+ ),
+ );
+ return events;
+ }
+
+ let mut response = self.base_response(status, output);
+ if let Some(reason) = incomplete_reason {
+ response["incomplete_details"] = json!({ "reason": reason });
+ if reason == "content_filter" || !has_actionable_output {
+ events.push(sse::response_incomplete(&response));
+ self.completed = true;
+ return events;
+ }
}
events.push(sse::response_completed(&response));
@@ -1415,6 +1438,122 @@ mod tests {
}
}
+ /// `finish_reason=length`(token 截断)时工具调用往往只到一半就没了 name。
+ /// 这不是"上游发了畸形数据",而是截断——归因必须是 incomplete,不能报成
+ /// tool_call_dropped,否则诊断信息本身就是错的。
+ #[tokio::test]
+ async fn truncated_turn_stays_incomplete_instead_of_failed() {
+ let output = collect(vec![
+ "data: {\"id\":\"chatcmpl_trunc\",\"model\":\"kimi-k3\",\"choices\":[{\"delta\":{\"content\":\"我来看看\"}}]}\n\n",
+ "data: {\"id\":\"chatcmpl_trunc\",\"model\":\"kimi-k3\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_cut\",\"type\":\"function\",\"function\":{\"arguments\":\"{\\\"pa\"}}]},\"finish_reason\":\"length\"}]}\n\n",
+ "data: [DONE]\n\n",
+ ])
+ .await;
+
+ assert!(output.contains("event: response.completed"));
+ assert!(output.contains("\"status\":\"incomplete\""));
+ assert!(!output.contains("event: response.failed"));
+ }
+
+ #[tokio::test]
+ async fn reasoning_only_length_truncated_turn_emits_response_incomplete() {
+ let output = collect(vec![
+ "data: {\"id\":\"chatcmpl_think_cap\",\"model\":\"gemini-4-argon\",\"choices\":[{\"delta\":{\"reasoning_content\":\"looping thought\"}}]}\n\n",
+ "data: {\"id\":\"chatcmpl_think_cap\",\"model\":\"gemini-4-argon\",\"choices\":[{\"delta\":{},\"finish_reason\":\"length\"}],\"usage\":{\"prompt_tokens\":100,\"completion_tokens\":65536,\"total_tokens\":65636,\"completion_tokens_details\":{\"reasoning_tokens\":65533}}}\n\n",
+ "data: [DONE]\n\n",
+ ])
+ .await;
+ let events = parse_sse_events(&output);
+ let last = events.last().unwrap();
+
+ assert!(output.contains("event: response.incomplete"));
+ assert!(!output.contains("event: response.completed"));
+ assert!(!output.contains("event: response.failed"));
+ assert_eq!(last["type"], "response.incomplete");
+ assert_eq!(last["response"]["status"], "incomplete");
+ assert_eq!(
+ last["response"]["incomplete_details"]["reason"],
+ "max_output_tokens"
+ );
+ assert_eq!(last["response"]["usage"]["output_tokens"], 65536);
+ }
+
+ #[tokio::test]
+ async fn truncated_and_filtered_turns_preserve_reason_and_text() {
+ for (finish_reason, text, terminal_type, reason) in [
+ ("length", "\n", "response.incomplete", "max_output_tokens"),
+ (
+ "length",
+ " partial ",
+ "response.completed",
+ "max_output_tokens",
+ ),
+ (
+ "content_filter",
+ "",
+ "response.incomplete",
+ "content_filter",
+ ),
+ (
+ "content_filter",
+ " partial ",
+ "response.incomplete",
+ "content_filter",
+ ),
+ ] {
+ let chunk = json!({"choices":[{"delta":{"reasoning_content":"thinking","content":text},
+ "finish_reason":finish_reason}]});
+ let frame = format!("data: {chunk}\n\n");
+ let output = collect(vec![&frame, "data: [DONE]\n\n"]).await;
+ let events = parse_sse_events(&output);
+ let last = events.last().unwrap();
+ assert_eq!(last["type"], terminal_type);
+ assert_eq!(last["response"]["incomplete_details"]["reason"], reason);
+ if !text.is_empty() {
+ assert_eq!(last["response"]["output"][1]["content"][0]["text"], text);
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn reasoning_only_completed_turn_emits_failed_instead_of_silent_complete() {
+ let output = collect(vec![
+ "data: {\"id\":\"chatcmpl_think_stop\",\"model\":\"gemini-4-argon\",\"choices\":[{\"delta\":{\"reasoning_content\":\"only thinking\"},\"finish_reason\":\"stop\"}]}\n\n",
+ "data: [DONE]\n\n",
+ ])
+ .await;
+
+ assert!(output.contains("event: response.failed"));
+ assert!(output.contains("upstream_reasoning_only_turn"));
+ assert!(!output.contains("event: response.completed"));
+ }
+
+ #[tokio::test]
+ async fn stream_end_with_reasoning_only_without_finish_reason_emits_failed() {
+ let output = collect(vec![
+ "data: {\"id\":\"chatcmpl_think_eof\",\"model\":\"gemini-4-argon\",\"choices\":[{\"delta\":{\"reasoning_content\":\"partial thought\"}}]}\n\n",
+ ])
+ .await;
+
+ assert!(output.contains("event: response.failed"));
+ assert!(output.contains("stream_truncated"));
+ assert!(!output.contains("event: response.completed"));
+ }
+ /// 纯空白函数名对应不到任何已发布工具,必须与空名同等对待,
+ /// 否则它会伪装成"本回合还有工具调用"而绕过判据。
+ #[tokio::test]
+ async fn whitespace_only_tool_name_is_dropped() {
+ let output = collect(vec![
+ "data: {\"id\":\"chatcmpl_ws\",\"model\":\"kimi-k3\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_ws\",\"type\":\"function\",\"function\":{\"name\":\" \",\"arguments\":\"{}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n",
+ "data: [DONE]\n\n",
+ ])
+ .await;
+
+ assert!(output.contains("event: response.failed"));
+ assert!(output.contains("upstream_tool_call_dropped"));
+ assert!(!output.contains("event: response.completed"));
+ }
+
/// 纯文本回合(从未出现过工具调用增量)不受判据影响。
#[tokio::test]
async fn text_only_turn_still_completes() {
diff --git a/src-tauri/src/proxy/providers/transform_codex_chat.rs b/src-tauri/src/proxy/providers/transform_codex_chat.rs
index 52614c46c..01f88ee10 100644
--- a/src-tauri/src/proxy/providers/transform_codex_chat.rs
+++ b/src-tauri/src/proxy/providers/transform_codex_chat.rs
@@ -2323,10 +2323,8 @@ pub(crate) fn chat_completion_to_response_with_context(
// 🔴 与流式分支一致,只对本应 `completed` 的回合生效:`finish_reason=length`
// 是截断,工具调用缺 name 是截断的后果而非上游发了畸形数据,报成
// tool_call_dropped 会给出错误的归因。
- if response_status_from_finish_reason(finish_reason) == "completed"
- && tool_calls.dropped > 0
- && tool_calls.items.is_empty()
- {
+ let (status, incomplete_reason) = chat_response_status(finish_reason);
+ if incomplete_reason.is_none() && tool_calls.dropped > 0 && tool_calls.items.is_empty() {
return Err(ProxyError::TransformError(format!(
"Upstream returned {} tool call(s) without a function name, \
leaving no usable tool call in this turn",
@@ -2335,18 +2333,27 @@ pub(crate) fn chat_completion_to_response_with_context(
}
output.extend(tool_calls.items);
+ if incomplete_reason.is_none()
+ && reasoning.is_some()
+ && !output.iter().any(is_actionable_response_item)
+ {
+ return Err(ProxyError::TransformError(
+ "Upstream returned reasoning without any assistant message or tool call".to_string(),
+ ));
+ }
+
let mut response = json!({
"id": response_id,
"object": "response",
"created_at": created_at,
- "status": response_status_from_finish_reason(finish_reason),
+ "status": status,
"model": model,
"output": output,
"usage": chat_usage_to_responses_usage(body.get("usage"))
});
- if finish_reason == Some("length") {
- response["incomplete_details"] = json!({ "reason": "max_output_tokens" });
+ if let Some(reason) = incomplete_reason {
+ response["incomplete_details"] = json!({ "reason": reason });
}
Ok(response)
@@ -2841,10 +2848,28 @@ pub(crate) fn response_message_item_id_indexed(
format!("{}_{output_index}", response_message_item_id(response_id))
}
-pub(crate) fn response_status_from_finish_reason(finish_reason: Option<&str>) -> &'static str {
+pub(crate) fn chat_response_status(
+ finish_reason: Option<&str>,
+) -> (&'static str, Option<&'static str>) {
match finish_reason {
- Some("length") => "incomplete",
- _ => "completed",
+ Some("length") => ("incomplete", Some("max_output_tokens")),
+ Some("content_filter") => ("incomplete", Some("content_filter")),
+ _ => ("completed", None),
+ }
+}
+
+pub(crate) fn is_actionable_response_item(item: &Value) -> bool {
+ match item["type"].as_str() {
+ Some("message") => item["content"].as_array().is_some_and(|parts| {
+ parts.iter().any(|part| {
+ part.get("text")
+ .or_else(|| part.get("refusal"))
+ .and_then(Value::as_str)
+ .is_some_and(|text| !text.trim().is_empty())
+ })
+ }),
+ Some("function_call" | "custom_tool_call" | "tool_search_call") => true,
+ _ => false,
}
}
diff --git a/src-tauri/src/proxy/providers/transform_codex_chat/tests.rs b/src-tauri/src/proxy/providers/transform_codex_chat/tests.rs
index 3d7697937..7cc263245 100644
--- a/src-tauri/src/proxy/providers/transform_codex_chat/tests.rs
+++ b/src-tauri/src/proxy/providers/transform_codex_chat/tests.rs
@@ -5453,3 +5453,39 @@ fn duplicate_exact_tool_identity_is_idempotent_without_panic() {
assert_eq!(tools[1]["function"]["name"], "shell");
assert_eq!(tools[1]["function"]["description"], "First shell.");
}
+#[test]
+fn chat_response_reasoning_only_completed_turn_is_an_error() {
+ let chat = json!({
+ "id": "chatcmpl_reason_only",
+ "object": "chat.completion",
+ "created": 123,
+ "model": "gemini-4-argon",
+ "choices": [{
+ "message": {
+ "role": "assistant",
+ "reasoning_content": "only thinking",
+ "content": ""
+ },
+ "finish_reason": "stop"
+ }]
+ });
+
+ let err =
+ chat_completion_to_response_with_context(chat, &CodexToolContext::default()).unwrap_err();
+ assert!(matches!(err, ProxyError::TransformError(_)));
+ assert!(err
+ .to_string()
+ .contains("reasoning without any assistant message"));
+}
+
+#[test]
+fn filtered_reasoning_preserves_content_filter_in_json() {
+ let chat = json!({"choices": [{
+ "message": {"role":"assistant", "reasoning_content":"thinking"},
+ "finish_reason":"content_filter"
+ }]});
+ let response =
+ chat_completion_to_response_with_context(chat, &CodexToolContext::default()).unwrap();
+ assert_eq!(response["status"], "incomplete");
+ assert_eq!(response["incomplete_details"]["reason"], "content_filter");
+}
diff --git a/src-tauri/src/proxy/usage/parser.rs b/src-tauri/src/proxy/usage/parser.rs
index df15ec802..7ce320fef 100644
--- a/src-tauri/src/proxy/usage/parser.rs
+++ b/src-tauri/src/proxy/usage/parser.rs
@@ -379,12 +379,15 @@ impl TokenUsage {
pub fn from_codex_stream_events_auto(events: &[Value]) -> Option<Self> {
log::debug!("[Codex] 智能解析流式事件,共 {} 个事件", events.len());
- // 先尝试 Codex Responses API 格式 (response.completed 事件)
+ // 先尝试 Codex Responses API 终态事件 (response.completed / response.incomplete / response.failed)
for event in events {
if let Some(event_type) = event.get("type").and_then(|v| v.as_str()) {
- if event_type == "response.completed" {
+ if matches!(
+ event_type,
+ "response.completed" | "response.incomplete" | "response.failed"
+ ) {
if let Some(response) = event.get("response") {
- log::debug!("[Codex] 找到 response.completed 事件");
+ log::debug!("[Codex] 找到 {event_type} 事件");
return Self::from_codex_response_auto(response);
}
}
@@ -1379,6 +1382,49 @@ mod tests {
assert_eq!(usage.model, Some("o3".to_string()));
}
+ #[test]
+ fn test_codex_stream_events_auto_incomplete_and_failed_record_usage() {
+ for terminal_type in ["response.incomplete", "response.failed"] {
+ let events = vec![
+ json!({
+ "type": "response.created",
+ "response": {
+ "id": "resp_think",
+ "model": "gemini-4-argon",
+ "usage": {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "input_tokens_details": { "cached_tokens": 0 }
+ }
+ }
+ }),
+ json!({
+ "type": terminal_type,
+ "response": {
+ "id": "resp_think",
+ "model": "gemini-4-argon",
+ "status": if terminal_type == "response.incomplete" { "incomplete" } else { "failed" },
+ "usage": {
+ "input_tokens": 252770,
+ "output_tokens": 65536,
+ "input_tokens_details": {
+ "cached_tokens": 250708
+ }
+ }
+ }
+ }),
+ ];
+
+ let usage = TokenUsage::from_codex_stream_events_auto(&events)
+ .unwrap_or_else(|| panic!("{terminal_type} usage should be parsed"));
+ assert_eq!(usage.input_tokens, 252770);
+ assert_eq!(usage.output_tokens, 65536);
+ assert_eq!(usage.cache_read_tokens, 250708);
+ assert_eq!(usage.model, Some("gemini-4-argon".to_string()));
+ assert!(usage.has_billable_tokens());
+ }
+ }
+
#[test]
fn test_codex_stream_events_auto_openai_format() {
// OpenAI Chat Completions 流式格式 (最后一个 chunk 包含 usage)