Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): preserve and resend reasoning_content, preserve tools on every abnormal exit

Akarshan Biswasc6c9dd84c12a
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 7fb05da98..68bd1f263 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -1594,6 +1594,32 @@ async fn orchestrate_inner(
/// overflowing request fails loudly instead of looping forever.
const MAX_COMPACTION_ATTEMPTS: usize = 4;
+/// Deep-copy `messages` with `reasoning_content` removed from every assistant
+/// turn. The request builder applies this when the caller opts out of resending
+/// reasoning ([agent].send_reasoning=false). Mirror of the desktop app's
+/// `stripAssistantReasoningInBody`; kept in one place so every surface (TUI,
+/// headless, subagents) strips consistently. Only assistant messages carry the
+/// field, but the filter is defensive and targets just that role.
+fn strip_assistant_reasoning(messages: &[serde_json::Value]) -> Vec<serde_json::Value> {
+ messages
+ .iter()
+ .map(|m| {
+ if m.get("role").and_then(|r| r.as_str()) != Some("assistant") {
+ return m.clone();
+ }
+ let Some(obj) = m.as_object() else {
+ return m.clone();
+ };
+ if !obj.contains_key("reasoning_content") {
+ return m.clone();
+ }
+ let mut out = obj.clone();
+ out.remove("reasoning_content");
+ serde_json::Value::Object(out)
+ })
+ .collect()
+}
+
/// Build one OpenAI chat-completion request from the current conversation.
fn build_completion_request(
model_id: &str,
@@ -1602,11 +1628,22 @@ fn build_completion_request(
json_body: &serde_json::Value,
forced_tool_choice: Option<&str>,
) -> serde_json::Value {
+ // `[agent].send_reasoning` is forwarded per-request; default true (resend
+ // reasoning). False opts out of resending prior reason on every turn.
+ let send_reasoning = json_body
+ .get("send_reasoning")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(true);
+ let messages = if send_reasoning {
+ conversation_messages.to_vec()
+ } else {
+ strip_assistant_reasoning(conversation_messages)
+ };
let mut completion_map = serde_json::Map::new();
completion_map.insert("model".to_string(), serde_json::json!(model_id));
completion_map.insert(
"messages".to_string(),
- serde_json::Value::Array(conversation_messages.to_vec()),
+ serde_json::Value::Array(messages),
);
let tool_choice = forced_tool_choice
.filter(|name| {
@@ -1936,11 +1973,22 @@ async fn run_turn_cycle(
.get("content")
.cloned()
.unwrap_or(serde_json::Value::Null);
- conversation_messages.push(serde_json::json!({
+ let mut msg = serde_json::json!({
"role": "assistant",
"content": assistant_content,
"tool_calls": tool_calls.clone()
- }));
+ });
+ // Carry this turn's reasoning back onto the resumed conversation so
+ // a follow-up request (and the final `MessagesUpdated`) can resend
+ // it. Kept out of `content`, matching the upstream shape.
+ if let Some(r) = choice_message
+ .get("reasoning_content")
+ .and_then(|v| v.as_str())
+ .filter(|r| !r.is_empty())
+ {
+ msg["reasoning_content"] = serde_json::json!(r);
+ }
+ conversation_messages.push(msg);
} else {
conversation_messages.push(serde_json::json!({
"role": "assistant",
@@ -2340,6 +2388,77 @@ mod tests {
);
}
+ /// Reasoning is resent by default: providers exposing it natively expect it
+ /// back, and llama.cpp templates with `preserve_thinking` re-emit prior
+ /// reasoning from this field (dropping it shrinks earlier turns and forces
+ /// the KV-cache prefix to be reprocessed).
+ #[test]
+ fn assistant_reasoning_is_resent_by_default() {
+ let messages = vec![json!({
+ "role": "assistant",
+ "content": "the answer",
+ "reasoning_content": "the thinking"
+ })];
+ let request = build_completion_request("m", &messages, &[], &json!({}), None);
+ assert_eq!(
+ request["messages"][0]["reasoning_content"], "the thinking",
+ "reasoning must be resent unless the user opts out: {request}"
+ );
+ }
+
+ /// `send_reasoning = false` drops the field from every assistant turn,
+ /// for a strict upstream that rejects it (Groq's validator) or to keep long
+ /// chains of thought out of the context budget.
+ #[test]
+ fn send_reasoning_false_strips_it_from_assistant_turns() {
+ let messages = vec![
+ json!({ "role": "user", "content": "q" }),
+ json!({
+ "role": "assistant",
+ "content": "the answer",
+ "reasoning_content": "the thinking"
+ }),
+ ];
+ let request = build_completion_request(
+ "m",
+ &messages,
+ &[],
+ &json!({ "send_reasoning": false }),
+ None,
+ );
+ assert!(
+ request["messages"][1].get("reasoning_content").is_none(),
+ "opted out, so reasoning must not reach the upstream: {request}"
+ );
+ // The rest of the turn is untouched.
+ assert_eq!(request["messages"][1]["content"], "the answer");
+ assert_eq!(request["messages"][0]["content"], "q");
+ }
+
+ /// Stripping keeps a tool-call turn's `tool_calls` intact: dropping those
+ /// alongside the reasoning would leave a dangling `role: "tool"` reply that
+ /// OpenAI-compatible upstreams reject outright.
+ #[test]
+ fn stripping_reasoning_preserves_tool_calls() {
+ let messages = vec![json!({
+ "role": "assistant",
+ "content": null,
+ "reasoning_content": "need to grep",
+ "tool_calls": [{ "id": "c1", "type": "function",
+ "function": { "name": "bash", "arguments": "{}" } }]
+ })];
+ let request = build_completion_request(
+ "m",
+ &messages,
+ &[],
+ &json!({ "send_reasoning": false }),
+ None,
+ );
+ let msg = &request["messages"][0];
+ assert!(msg.get("reasoning_content").is_none());
+ assert_eq!(msg["tool_calls"][0]["id"], "c1");
+ }
+
#[test]
fn forced_tool_choice_requires_an_advertised_tool() {
let messages = vec![json!({ "role": "user", "content": "build a flappy bird clone" })];
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index 000e722a6..e8c6488c0 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -110,6 +110,16 @@ pub(crate) struct AgentSection {
/// this flips the default for every block in the session.
#[serde(default)]
pub show_reasoning: Option<bool>,
+ /// Resend a prior assistant turn's `reasoning_content` to the model with the
+ /// rest of the conversation. Default true: providers that expose reasoning
+ /// natively generally expect it back, and local llama.cpp templates with
+ /// `preserve_thinking` re-emit prior reasoning from this field (dropping it
+ /// shrinks earlier turns and forces the KV-cache prefix to be reprocessed).
+ /// Set false for a strict upstream that rejects the key on assistant turns
+ /// (Groq's validator is the known case), or to keep long chains of thought
+ /// out of the context budget.
+ #[serde(default)]
+ pub send_reasoning: Option<bool>,
}
#[derive(Debug, Clone, Default, Deserialize)]
@@ -150,6 +160,7 @@ const AGENT_TOML_TEMPLATE: &str = r#"[agent]
# max_tokens = 4096 # cap on tokens the model generates per response (OpenAI max_tokens); omitted if unset
# max_parallel_subagents = 10 # max concurrently-running subagents per run; extra dispatches queue FIFO
# show_reasoning = false # expand reasoning in the transcript (Ctrl-O still toggles)
+# send_reasoning = true # resend prior reasoning to the model; false drops it from the request
# Project-local provider override. Wins over ~/.jan/config.toml and any
# provider inherited from Jan Desktop's settings.json. Most projects don't
@@ -587,6 +598,28 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ /// `send_reasoning` is unset in the template, which the callers read as the
+ /// resend-by-default policy; an explicit false round-trips so a strict
+ /// upstream can be opted out of it.
+ #[cfg(feature = "cli")]
+ #[test]
+ fn send_reasoning_parses_and_round_trips() {
+ let root = unique_root("send_reasoning");
+ ensure_project(&root).expect("scaffold");
+ let cfg = load_agent_config(&root).expect("load");
+ assert_eq!(cfg.agent.send_reasoning, None, "template leaves it unset");
+
+ let path = agent_toml_path(&root);
+ set_agent_key(&path, "send_reasoning", Some(toml_edit::value(false)))
+ .expect("write");
+ let cfg = load_agent_config(&root).expect("load");
+ assert_eq!(cfg.agent.send_reasoning, Some(false));
+ set_agent_key(&path, "send_reasoning", None).expect("unset");
+ let cfg = load_agent_config(&root).expect("load");
+ assert_eq!(cfg.agent.send_reasoning, None);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[cfg(feature = "cli")]
#[test]
fn dotted_keys_write_and_remove_under_their_section() {
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index 69ecfa2d1..2dda97b18 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -105,6 +105,19 @@ pub(crate) fn parse_openai_messages(
let mut obj = serde_json::Map::new();
obj.insert("role".to_string(), serde_json::json!(role));
obj.insert("content".to_string(), content);
+ // Preserve a resent assistant turn's reasoning alongside its content and
+ // tool calls. Some providers require prior reasoning to be resubmitted
+ // to keep a (local llama.cpp `preserve_thinking`) chat template honest:
+ // dropping it would shrink earlier assistant turns and force reprocessing
+ // of the KV-cache prefix. Only assistant messages carry it; user/tool/
+ // system passes are untouched by construction.
+ if role == "assistant" {
+ if let Some(r) = msg.get("reasoning_content").and_then(|v| v.as_str()) {
+ if !r.is_empty() {
+ obj.insert("reasoning_content".to_string(), serde_json::json!(r));
+ }
+ }
+ }
if has_tool_calls {
obj.insert("tool_calls".to_string(), msg["tool_calls"].clone());
}
@@ -637,6 +650,11 @@ struct ToolCallAccum {
#[derive(Default)]
struct SseAccumulator {
content: String,
+ /// Natively streamed reasoning (`reasoning_content` deltas), accumulated so
+ /// the reconstructed completion carries it back on the assistant message.
+ /// Kept apart from `content`: reasoning is never part of the answer prose,
+ /// but a caller resending assistant turns may forward it to the model.
+ reasoning: String,
tool_calls: Vec<ToolCallAccum>,
finish_reason: Option<String>,
usage: Option<serde_json::Value>,
@@ -710,6 +728,7 @@ impl SseAccumulator {
// through `Token`; consumers keep the tag-stripping fallback for them.
if let Some(text) = delta.get("reasoning_content").and_then(|v| v.as_str()) {
if !text.is_empty() {
+ self.reasoning.push_str(text);
let _ = events.send(StreamEvent::Reasoning {
text: text.to_string(),
});
@@ -814,6 +833,13 @@ impl SseAccumulator {
serde_json::json!(self.content)
},
);
+ // Reasoning stays out of `content` but is carried on the message so a
+ // caller that resends assistant turns to the model can forward it (and
+ // so a turn that only reasoned still surfaces its reasoning). Empty is
+ // omitted so non-reasoning providers produce an unchanged shape.
+ if !self.reasoning.is_empty() {
+ message.insert("reasoning_content".to_string(), serde_json::json!(self.reasoning));
+ }
if !tool_calls.is_empty() {
message.insert(
"tool_calls".to_string(),
@@ -1174,10 +1200,14 @@ mod tests {
&tx,
);
- // Reasoning must not leak into the reconstructed message sent back to the
- // model as history; only the answer prose is persisted.
+ // Reasoning stays out of the answer prose, but is preserved on the
+ // reconstructed message so a caller can resend it as history.
let completion = acc.into_completion();
assert_eq!(completion["choices"][0]["message"]["content"], "answer");
+ assert_eq!(
+ completion["choices"][0]["message"]["reasoning_content"],
+ "let me think"
+ );
drop(tx);
let mut reasoning = Vec::new();
@@ -1225,6 +1255,85 @@ mod tests {
assert!(tokens.is_empty(), "no content tokens for a reasoning-only turn: {tokens:?}");
}
+ /// A completion with no `reasoning_content` deltas must keep exactly the
+ /// shape it always had: the field is omitted, not emitted empty, so a
+ /// provider that rejects unknown assistant keys is unaffected.
+ #[test]
+ fn a_turn_without_reasoning_omits_the_field_entirely() {
+ let (tx, _rx) = sink();
+ let mut acc = SseAccumulator::default();
+ acc.ingest(
+ &json!({ "choices": [{ "delta": { "content": "answer" } }] }).to_string(),
+ &tx,
+ );
+ let completion = acc.into_completion();
+ let message = &completion["choices"][0]["message"];
+ assert_eq!(message["content"], "answer");
+ assert!(
+ message.get("reasoning_content").is_none(),
+ "no reasoning streamed, so the key must be absent: {message}"
+ );
+ }
+
+ /// A tool-call turn's reasoning is preserved too: the model reasons about
+ /// which tool to call, and that reasoning has to survive onto the assistant
+ /// turn the loop resends with its `tool_calls`.
+ #[test]
+ fn reasoning_is_preserved_on_a_tool_call_turn() {
+ let (tx, _rx) = sink();
+ let mut acc = SseAccumulator::default();
+ acc.ingest(
+ &json!({ "choices": [{ "delta": { "reasoning_content": "need to grep" } }] })
+ .to_string(),
+ &tx,
+ );
+ acc.ingest(
+ &json!({ "choices": [{ "delta": { "tool_calls": [{
+ "index": 0,
+ "id": "c1",
+ "function": { "name": "bash", "arguments": "{}" }
+ }] } }] })
+ .to_string(),
+ &tx,
+ );
+ let completion = acc.into_completion();
+ let message = &completion["choices"][0]["message"];
+ assert_eq!(message["reasoning_content"], "need to grep");
+ assert_eq!(message["tool_calls"][0]["id"], "c1");
+ }
+
+ /// A resent assistant turn keeps its `reasoning_content` through the message
+ /// normalizer. Local llama.cpp templates with `preserve_thinking` re-emit
+ /// prior reasoning from this field; dropping it would shrink earlier turns
+ /// and force the KV-cache prefix to be reprocessed.
+ #[test]
+ fn parse_messages_preserves_assistant_reasoning_content() {
+ let messages = json!([{
+ "role": "assistant",
+ "content": "the answer",
+ "reasoning_content": "the thinking"
+ }]);
+ let out = parse_openai_messages(&messages).unwrap();
+ assert_eq!(out[0]["content"], "the answer");
+ assert_eq!(out[0]["reasoning_content"], "the thinking");
+ }
+
+ /// Only assistant turns carry reasoning back. A stray field on another role
+ /// is not part of the protocol, so it is dropped rather than forwarded.
+ #[test]
+ fn parse_messages_drops_reasoning_on_non_assistant_roles() {
+ let messages = json!([
+ { "role": "user", "content": "q", "reasoning_content": "nope" },
+ { "role": "assistant", "content": "a" },
+ ]);
+ let out = parse_openai_messages(&messages).unwrap();
+ assert!(out[0].get("reasoning_content").is_none());
+ assert!(
+ out[1].get("reasoning_content").is_none(),
+ "an assistant turn with no reasoning stays unchanged"
+ );
+ }
+
/// Providers that inline `<think>` tags in `content` (no reasoning_content
/// field) keep streaming through Token untouched: the tag-stripping
/// fallback lives in the consumers.
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index f8db7d836..dd793f930 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -763,6 +763,10 @@ pub(crate) struct AgentSession {
pub limits: SessionLimits,
/// Whether the TUI expands `<think>` reasoning blocks (default false).
pub show_reasoning: bool,
+ /// Whether to resend a prior assistant turn's reasoning to the model
+ /// (default true). False drops `reasoning_content` from outgoing assistant
+ /// messages; the display journal still keeps reasoning for a resume.
+ pub send_reasoning: bool,
/// Shared MCP connection map (same Arc held by `args`), so the TUI can
/// connect/disconnect servers live via `/mcp` and later turns pick them up.
pub mcp_servers: crate::core::state::SharedMcpServers,
@@ -785,6 +789,9 @@ impl AgentSession {
if let Some(max) = self.limits.max_tokens {
body["max_tokens"] = serde_json::json!(max);
}
+ // Reasoning resend policy: the request-level flag the loop reads to
+ // decide whether prior assistant `reasoning_content` goes back out.
+ body["send_reasoning"] = serde_json::json!(self.send_reasoning);
body
}
}
@@ -928,6 +935,7 @@ fn prepare_agent_session(
max_session_tokens: cfg.budget.max_tokens.unwrap_or(DEFAULT_MAX_SESSION_TOKENS),
},
show_reasoning: cfg.agent.show_reasoning.unwrap_or(false),
+ send_reasoning: cfg.agent.send_reasoning.unwrap_or(true),
mcp_servers,
mcp_task,
})
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 09f044346..889016073 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -1268,6 +1268,12 @@ struct App {
/// from `[agent].show_reasoning` in agent.toml (false). Ctrl-O toggles every
/// existing block between its summary row and full detail for the session.
show_reasoning: bool,
+ /// Whether a prior assistant turn's reasoning is resent to the model.
+ /// Defaults from `[agent].send_reasoning` in agent.toml (true). False keeps
+ /// long chains of thought out of the request (and satisfies upstreams that
+ /// reject the key); the display journal keeps reasoning for a resume either
+ /// way.
+ send_reasoning: bool,
/// Transcript row indices of collapsed regions (tool groups or reasoning
/// blocks) the user has expanded to full detail.
expanded: std::collections::HashSet<usize>,
@@ -1666,6 +1672,8 @@ impl App {
pending_rows: Vec::new(),
reasoning_blocks: Vec::new(),
show_reasoning,
+ // Overwritten from the session config right after construction.
+ send_reasoning: true,
expanded: std::collections::HashSet::new(),
reveal: None,
input: String::new(),
@@ -3070,6 +3078,11 @@ impl App {
if self.goal.as_ref().is_some_and(|g| g.is_active()) {
body["goal_mode"] = serde_json::json!(true);
}
+ // Reasoning resend policy: forwarded only when the user opted out, so a
+ // default session sends an unchanged body (the loop defaults to true).
+ if !self.send_reasoning {
+ body["send_reasoning"] = serde_json::json!(false);
+ }
body
}
@@ -3661,6 +3674,18 @@ impl App {
answer
}
+ /// The concatenated natively-streamed reasoning text for the current turn.
+ /// Used to resend the final answer's reasoning on the wire. Inline
+ /// ` thinking` blocks (which arrive through `Token` and live in the buffer)
+ /// are handled separately by `answer_without_reasoning` and the loop path;
+ /// this covers the `reasoning_content` delta case, which never touches the
+ /// buffer.
+ fn native_reasoning_text(&self) -> String {
+ self.reasoning_segs
+ .iter()
+ .map(|s| s.text.clone())
+ .collect::<String>()
+ }
fn on_done(&mut self, stop_reason: String, usage: Option<Usage>) {
self.finalize_tool_group();
// Done is terminal: nothing more arrives on this stream, so a call that
@@ -3670,11 +3695,23 @@ impl App {
// arrive on its stream. Any panel still open here never got its own
// `SubagentEnd`.
self.close_live_subagents();
+ // Capture the turn's reasoning before `take_answer` flushes it: native
+ // reasoning lives in `reasoning_segs` until the flush, and inline
+ // ` thinking` blocks are folded into the buffer. Preserved so the
+ // final assistant turn can be resent with its reasoning (see below).
+ let reasoning = self.native_reasoning_text();
let answer = self.take_answer();
let wire = answer_without_reasoning(&answer);
if !wire.is_empty() {
- self.history
- .push(serde_json::json!({ "role": "assistant", "content": wire }));
+ let mut msg = serde_json::json!({ "role": "assistant", "content": wire });
+ // Resend the final answer's reasoning on the wire turn, mirroring
+ // how tool-call turns are threaded in the loop. Kept out of
+ // `content`; only added when the upstream actually streamed it, so
+ // non-reasoning providers send an unchanged shape.
+ if !reasoning.is_empty() {
+ msg["reasoning_content"] = serde_json::json!(reasoning);
+ }
+ self.history.push(msg);
}
// A closing receipt for the turn: when, how much context went up, how
// much came back, how long it took, how fast. Cheap to skim, and the
@@ -3823,6 +3860,16 @@ impl App {
/// `finish_compaction` when an overflow recovery is abandoned, so the two
/// paths cannot drift.
fn halt_turn(&mut self) {
+ // A run that died on an error rather than Esc is still an abnormal exit:
+ // it may well have run tools whose side effects exist on disk, but a
+ // mid-turn `MessagesUpdated` was never published (the stream errored
+ // before a natural stop), so those calls are absent from `history`.
+ // Fold them in exactly as a hard cancel does, so a later prompt or
+ // /resume sees the tools it ran and what they returned. The overflow-
+ // retry path deliberately avoids this (see `on_error`): that turn
+ // re-runs, so folding now would resend completed calls into the retried
+ // request before the model asks for them again.
+ self.append_cancelled_turn_tools();
// An errored turn halts the goal loop; the user decides how to recover.
self.goal_eval_pending = false;
if let Some(goal) = self.goal.as_ref() {
@@ -3910,10 +3957,16 @@ impl App {
// answer in history so the next turn and a later /resume both see it.
self.abort_tool_rows();
self.append_cancelled_turn_tools();
+ // Captured before the flush clears it, like `on_done`, so a cancelled
+ // turn's partial answer keeps the reasoning that produced it.
+ let reasoning = self.native_reasoning_text();
let answer = answer_without_reasoning(&self.take_answer());
if !answer.is_empty() {
- self.history
- .push(serde_json::json!({ "role": "assistant", "content": answer }));
+ let mut msg = serde_json::json!({ "role": "assistant", "content": answer });
+ if !reasoning.is_empty() {
+ msg["reasoning_content"] = serde_json::json!(reasoning);
+ }
+ self.history.push(msg);
}
self.status = Status::Idle;
self.run_started = None;
@@ -5371,6 +5424,7 @@ pub async fn run(
smol_model,
limits,
show_reasoning,
+ send_reasoning,
mcp_servers,
mcp_task,
} = session;
@@ -5420,6 +5474,7 @@ pub async fn run(
repo_root,
);
app.smol_model = smol_model;
+ app.send_reasoning = send_reasoning;
app.args = Some(args.clone());
// Adopt the session's startup run mode (e.g. `--plan`) so the header badge
// shows immediately; a resumed thread overrides this via restore_run_mode.
@@ -5801,6 +5856,11 @@ async fn chat_loop<B: Backend>(
if app.status == Status::Running {
app.flush_assistant();
app.abort_tool_rows();
+ // The task was killed without a natural stop, so the
+ // mid-turn `MessagesUpdated` that would have folded the
+ // completed tool calls never fired -- fold them here,
+ // exactly as the cancel/error paths do.
+ app.append_cancelled_turn_tools();
app.status = Status::Idle;
app.run_started = None;
}
@@ -7410,6 +7470,12 @@ const AGENT_SETTINGS: &[AgentSettingDef] = &[
desc: "expand reasoning in the transcript (Ctrl-O still toggles)",
kind: AgentSettingKind::Bool { default: false },
},
+ AgentSettingDef {
+ key: "send_reasoning",
+ label: "send_reasoning",
+ desc: "resend prior reasoning to the model (false drops it from requests)",
+ kind: AgentSettingKind::Bool { default: true },
+ },
];
/// Docked edit prompt for one `/settings` row: value field, inline validation
@@ -16002,6 +16068,101 @@ mod tests {
);
}
+ #[test]
+ fn on_error_preserves_completed_tool_calls_and_results_in_history() {
+ let mut app = test_app();
+ app.submit_user("do a thing".into());
+ app.apply(StreamEvent::ToolCall {
+ id: "c1".into(),
+ name: "bash".into(),
+ args: json!({ "command": "grep -n foo src/" }),
+ });
+ app.apply(StreamEvent::ToolResult {
+ id: "c1".into(),
+ content: "match on line 3\n[exit 0]".into(),
+ is_error: false,
+ diff: None,
+ });
+ // The run dies on an upstream error before the model emits any answer
+ // prose. The backend never publishes a mid-turn `MessagesUpdated`, so
+ // the completed call must be folded into history by the error path
+ // (the same guarantee the Esc-cancel path already provides).
+ app.on_error("upstream".into(), "connection reset".into());
+ let wire = app
+ .history
+ .iter()
+ .map(serde_json::Value::to_string)
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(
+ wire.contains("\"tool_calls\"") && wire.contains("c1"),
+ "tool call missing from wire history on error: {wire}"
+ );
+ assert!(
+ wire.contains("\"tool_call_id\":\"c1\"") && wire.contains("match on line 3"),
+ "tool result missing from wire history on error: {wire}"
+ );
+ }
+
+ #[test]
+ fn on_error_pairs_in_flight_calls_with_a_placeholder_result() {
+ let mut app = test_app();
+ app.submit_user("do a thing".into());
+ app.apply(StreamEvent::ToolCall {
+ id: "c1".into(),
+ name: "bash".into(),
+ args: json!({ "command": "sleep 300" }),
+ });
+ // The call was still in flight when the stream errored; no ToolResult
+ // ever arrives. It must still reach the wire, paired with a placeholder
+ // result so the exchange is protocol-valid for a later prompt.
+ app.on_error("upstream".into(), "connection reset".into());
+ let wire = app
+ .history
+ .iter()
+ .map(serde_json::Value::to_string)
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(
+ wire.contains("\"tool_calls\"") && wire.contains("c1"),
+ "interrupted call missing from wire history on error: {wire}"
+ );
+ assert!(
+ wire.contains("\"tool_call_id\":\"c1\""),
+ "interrupted call must be paired with a result: {wire}"
+ );
+ }
+
+ #[test]
+ fn on_error_does_not_double_fold_when_flush_assistant_committed_prose() {
+ let mut app = test_app();
+ app.submit_user("do a thing".into());
+ app.apply(StreamEvent::ToolCall {
+ id: "c1".into(),
+ name: "bash".into(),
+ args: json!({ "command": "ls" }),
+ });
+ app.apply(StreamEvent::ToolResult {
+ id: "c1".into(),
+ content: "ok".into(),
+ is_error: false,
+ diff: None,
+ });
+ // Some prose streamed before the error, so `on_error`'s flush_assistant
+ // commits it. The completed call must still be folded - and folded only
+ // once regardless of the prose that preceded the error.
+ app.apply(StreamEvent::Token {
+ text: "I found it".into(),
+ });
+ app.on_error("upstream".into(), "connection reset".into());
+ let assistant_tool_turns = app
+ .history
+ .iter()
+ .filter(|m| m.get("tool_calls").is_some())
+ .count();
+ assert_eq!(assistant_tool_turns, 1, "tool call folded exactly once");
+ }
+
#[test]
fn cancel_surfaces_interrupted_calls_paired_with_a_placeholder_result() {
let mut app = test_app();
@@ -18149,15 +18310,75 @@ mod tests {
});
app.on_done("stop".into(), None);
assert_eq!(app.reasoning_blocks.len(), 1, "reasoning folded into one block");
- // The wire history carries the answer without the reasoning.
- let wire = app
- .history
- .iter()
- .map(serde_json::Value::to_string)
- .collect::<Vec<_>>()
- .join("\n");
- assert!(wire.contains("Here is the answer"), "answer missing: {wire}");
- assert!(!wire.contains("ponder the plan"), "reasoning leaked into history: {wire}");
+ // The wire history carries the answer, with the reasoning preserved on
+ // the message's `reasoning_content` rather than inlined into `content`.
+ let last = app.history.last().expect("assistant turn in history");
+ assert_eq!(last["content"], "Here is the answer");
+ assert_eq!(
+ last["reasoning_content"], "ponder the plan",
+ "reasoning must be preserved for resend: {last}"
+ );
+ assert!(
+ !last["content"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("ponder the plan"),
+ "reasoning must not be inlined into the answer content: {last}"
+ );
+ }
+
+ /// The resend policy reaches the wire: a default session sends an unchanged
+ /// body (the loop defaults to resending), and opting out forwards the flag.
+ #[test]
+ fn send_reasoning_opt_out_is_forwarded_in_the_request_body() {
+ let mut app = test_app();
+ app.submit_user("go".into());
+ assert!(
+ app.body().get("send_reasoning").is_none(),
+ "the default session must send an unchanged body"
+ );
+ app.send_reasoning = false;
+ assert_eq!(
+ app.body()["send_reasoning"],
+ serde_json::json!(false),
+ "opting out must reach the loop"
+ );
+ }
+
+ /// A cancelled turn keeps the reasoning that produced its partial answer,
+ /// so the next prompt resumes with the same context the model had.
+ #[test]
+ fn cancel_preserves_native_reasoning_on_the_partial_answer() {
+ let mut app = test_app();
+ app.submit_user("go".into());
+ app.apply(StreamEvent::Reasoning {
+ text: "half a thought".into(),
+ });
+ app.apply(StreamEvent::Token {
+ text: "Partial answer".into(),
+ });
+ app.cancel_run();
+ let last = app.history.last().expect("assistant turn in history");
+ assert_eq!(last["content"], "Partial answer");
+ assert_eq!(last["reasoning_content"], "half a thought");
+ }
+
+ /// A turn with no native reasoning must not grow a `reasoning_content` key:
+ /// providers that reject unknown assistant fields see an unchanged shape.
+ #[test]
+ fn a_turn_without_reasoning_adds_no_reasoning_key_to_history() {
+ let mut app = test_app();
+ app.submit_user("go".into());
+ app.apply(StreamEvent::Token {
+ text: "Just an answer".into(),
+ });
+ app.on_done("stop".into(), None);
+ let last = app.history.last().expect("assistant turn in history");
+ assert_eq!(last["content"], "Just an answer");
+ assert!(
+ last.get("reasoning_content").is_none(),
+ "no reasoning streamed, so the key must be absent: {last}"
+ );
}
/// The `[thinking]` badge and the orange placeholder must close when the
@@ -18246,15 +18467,14 @@ mod tests {
text,
"<think>first thought</think>Part one.<think>second thought</think> Part two."
);
- // The wire answer carries neither thought.
- let wire = app
- .history
- .iter()
- .map(serde_json::Value::to_string)
- .collect::<Vec<_>>()
- .join("\n");
- assert!(wire.contains("Part one. Part two."), "answer missing: {wire}");
- assert!(!wire.contains("thought"), "reasoning leaked into history: {wire}");
+ // The wire answer is prose only; both thoughts ride along on
+ // `reasoning_content`, concatenated in emission order.
+ let last = app.history.last().expect("assistant turn in history");
+ assert_eq!(last["content"], "Part one. Part two.");
+ assert_eq!(
+ last["reasoning_content"], "first thoughtsecond thought",
+ "both stretches must be preserved for resend: {last}"
+ );
}
#[test]