Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): preserve accepted prompt guidance across turns
thinhlpgea191cf8f18c
diff --git a/docs/src/pages/docs/agent/context.mdx b/docs/src/pages/docs/agent/context.mdxindex f400ddedf..ca773a82b 100644--- a/docs/src/pages/docs/agent/context.mdx+++ b/docs/src/pages/docs/agent/context.mdx@@ -126,9 +126,11 @@ sit at the front of every request.- The stable part of the system prompt (identity, guidelines, working directory, skills, memorycatalog) is written once at the head of the conversation and never rewritten.-- Per-turn context (today's date, memory recall, plan and todo state) is appended after the- conversation as marked guidance. Previously sent messages stay untouched, and provider- adapters do not lift the changing guidance into the system prompt.+- Per-run context (today's date, memory recall, plan and todo state) starts after the+ conversation as marked guidance. Once a request succeeds, that block stays at the position+ the model received it, including across tool steps and saved-session resumes. A new run adds+ fresh guidance after history; old blocks are bounded by normal compaction. Provider adapters+ do not lift this guidance into the system prompt.- A stable prompt that changes mid-session - an edited `agent.toml`, a skill installed whilethe session is open, a mode switch - is retained as a new system message. Providers combinesystem messages into one instruction field, so a change to these prefix contributors stilldiff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex 3faba4473..7cdfd187e 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -139,14 +139,11 @@ pub enum StreamEvent {/// Nothing is being generated until a ping resumes the run, which the next/// `Step` marks. Lets a consumer say "watching" rather than "working".Parked,- /// The loop's compaction reduced the conversation while retrying a- /// context overflow. The client should replace its session history with- /// `messages` for subsequent turns. This turn's per-turn block is not in- /// here: it is projection input the loop regenerates for every request, and- /// a client that stored it would resend it as history on the next turn.- MessagesUpdated {- messages: Vec<serde_json::Value>,- },+ /// The client should replace its session history with `messages` before+ /// subsequent turns. Includes accepted prompt guidance in its original+ /// position, but not a pending block from an unsuccessful request. Also+ /// carries compacted history when the loop retries a context overflow.+ MessagesUpdated { messages: Vec<serde_json::Value> },/// The `ask` tool is waiting for structured interactive input. Carries the/// `ask_timeout_secs` deadline (seconds until the loop auto-selects the/// recommended option) as `timeout_secs`, or `None` when no timeout isdiff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 985cc7e0a..06862b617 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -2115,10 +2115,9 @@ fn build_run_system_prompt(/// with this project's resolved sandbox/scratch and `[prompt]` policy). Used by/// the CLI `/context` view to size the system segments: routing it through the/// same builder is what keeps the reported breakdown from drifting away from-/// what is actually sent. What it sizes is the stable prompt a run caches, so-/// the per-turn additions a run composes on top are excluded: the date, git-/// state, query-dependent memory recall, and plan/todo state all land in the-/// volatile block below the cache line rather than in the prefix this reports.+/// what is actually sent. It sizes all project-composed blocks, including+/// blocks demoted to the tail, but excludes the run's date, git state,+/// query-dependent memory recall, and plan/todo additions./// `None` when no prompt would be built, or/// when the project's `[prompt]` policy cannot be honored (the run itself/// reports that failure with the same message).@@ -2437,9 +2436,9 @@ async fn orchestrate_inner(// The history becomes a canonical record and the prompt becomes an event// the projection places: at the head while it is unchanged, appended behind// the history when it changes, so a turn cannot invalidate the bytes an- // earlier request already sent. The per-turn block stays projection input:- // recording yesterday's date as history is how a resumed session ends up- // carrying yesterday's date forever.+ // earlier request already sent. Per-turn guidance starts as projection+ // input, then is recorded at its sent position once a request succeeds.+ // Later tool steps and client resumes must retain those accepted bytes.//// The stable half is the cacheable one; `[prompt]` decides which blocks// reach it, and a composer the policy moves down is carried in the tail@@ -3071,16 +3070,9 @@ fn project(/// The message list a client adopts as its session history/// (`StreamEvent::MessagesUpdated`).///-/// Deliberately not the request's messages. The per-turn block is projection-/// input the loop regenerates on every turn, and a client that kept it would-/// send it back inside its next history, where [`Transcript::from_history`]-/// cannot tell it from a reminder the model actually received -- the wire-/// shape is the same one -- so it would record it as history. Every turn would-/// then append another block behind the last: yesterday's date carried-/// forward, and a request that grows by a block per turn. The published-/// history is therefore the conversation without this turn's block, and the-/// client's next request gets the fresh one appended at the tail, where the-/// projection puts it.+/// Keep accepted guidance in the published history at the position the model+/// saw it. Only a pending block from a request that has not succeeded is+/// excluded. Removing an accepted block would break the next run's prefix.fn client_history(transcript: &Transcript, send_reasoning: bool) -> Vec<serde_json::Value> {project(transcript, None, send_reasoning)}@@ -3371,6 +3363,13 @@ async fn run_turn_cycle(}};+ // This request succeeded: its guidance is now part of the accepted+ // history, before the assistant response and any tool results. Keep it+ // there instead of projecting it at the moving tail of every step.+ if let Some(text) = volatile_system.as_deref() {+ transcript.record_prompt_tail(text);+ }+let turn_usage = Usage::from_completion(&completion);// Publish before the tool calls run: the numbers describe the request// that just landed, and a long tool phase shouldn't sit on them.@@ -3860,14 +3859,10 @@ mod tests {);}- /// The client adopts the published history as its session history and sends- /// it back on the next turn, so this turn's block must not be in it. The- /// block takes a reminder's wire shape, and `from_history` records a resent- /// reminder as history on purpose (it arrived, so it stays), which makes a- /// handed-back block indistinguishable from one: every turn would append- /// another copy, and carry yesterday's date forward while it did.+ /// A client resumes from the published history, so it must retain the+ /// guidance the provider already accepted, not rebuild it after the answer.#[tokio::test]- async fn the_published_history_carries_no_per_turn_block() {+ async fn published_history_preserves_the_accepted_prompt_tail() {let volatile1 = "Today's date is 2026-09-21.";let volatile2 = "Today's date is 2026-09-22.";@@ -3929,13 +3924,11 @@ mod tests {// The client takes what was published -- not the bytes it asked with --// and adds its next user turn to it.let mut adopted = published(&mut rx).expect("turn one publishes its history");- assert!(- reminders(&adopted).is_empty(),- "the published history is the conversation, not the request: {adopted:?}"- );+ assert_eq!(adopted, request1, "publish the accepted request verbatim");+ adopted.push(json!({ "role": "assistant", "content": "reply" }));adopted.push(json!({ "role": "user", "content": "second" }));- // Turn two carries one block: this turn's.+ // Changed guidance follows the entire previous request and its answer.let (tx2, _rx2) = mpsc::unbounded_channel();let model2 = MockModel::new(vec![final_answer("reply 2")]);let mut budget2 = SessionBudget::new(None);@@ -3966,14 +3959,64 @@ mod tests {.clone();assert_eq!(reminders(&request2).len(),- 1,- "the previous turn's block must not survive into the next request: {request2:?}"+ 2,+ "one accepted block from each run: {request2:?}");assert_eq!(request2.last().unwrap()["content"],json!(crate::core::agent::reminder::wrap(volatile2)),- "the one block that is there is this turn's"+ "the newest guidance is last"+ );+ assert_eq!(+ serde_json::to_string(&request2[..request1.len()]).unwrap(),+ serde_json::to_string(&request1).unwrap(),+ "the next run must extend every message the provider accepted"+ );+ }++ #[tokio::test]+ async fn tool_steps_preserve_the_accepted_prompt_tail() {+ let (tx, _rx) = mpsc::unbounded_channel();+ let model = MockModel::new(vec![tool_call_completion(), final_answer("done")]);+ let mut budget = SessionBudget::new(None);+ run_turn_cycle(+ &tx,+ &json!({}),+ "m",+ &[],+ Transcript::from_history(vec![+ json!({"role": "system", "content": "Stable instructions."}),+ json!({"role": "user", "content": "search for Rust"}),+ ]),+ Some("Today's date is 2026-09-21.".to_string()),+ true,+ 8,+ &mut budget,+ &model,+ &MockTool::default(),+ crate::core::agent::plan::RunMode::Normal,+ None,+ None,+ None,+ None,+ )+ .await+ .expect("run completes");++ let requests = model.requests.lock().unwrap();+ let first = requests[0]["messages"].as_array().unwrap();+ let second = requests[1]["messages"].as_array().unwrap();+ assert_eq!(+ serde_json::to_string(&second[..first.len()]).unwrap(),+ serde_json::to_string(first).unwrap(),+ "a tool step must extend the accepted request, not move its guidance"+ );+ assert_eq!(+ second.len(),+ first.len() + 2,+ "only the call and result are new");+ assert_eq!(second.last().unwrap()["role"], "tool");}#[test]diff --git a/src-tauri/src/core/agent/prefix_stability.rs b/src-tauri/src/core/agent/prefix_stability.rsindex 2f1b25348..077d76167 100644--- a/src-tauri/src/core/agent/prefix_stability.rs+++ b/src-tauri/src/core/agent/prefix_stability.rs@@ -3,8 +3,8 @@//! Every failure in that epic was the same failure - two consecutive requests//! that should share a prefix, and did not - so that is what this suite//! measures. Each test assembles whole requests the way a run does (the-//! composed prompt through its placement policy, the per-turn block behind it,-//! the conversation after that, the tool array in front) and compares+//! composed prefix, accepted history, then pending per-turn guidance, with the+//! tool array in front) and compares//! *serialized bytes*, because those are what a provider caches. Comparing//! `Value`s instead would miss key order and whitespace, which are part of the//! prefix a provider matches on.@@ -20,11 +20,10 @@//! What they drive is the real production code for each contributor to the//! prefix - `compose_system_prompt` and the placement policy, the two helpers//! that place the stable prompt and marked tail guidance, `build_completion_request`,-//! and the tool-array assembly and reuse. The one thing not driven here is the-//! *order* in which `orchestrate_inner` calls those pieces, which is inline in-//! that function and only reachable with a live upstream. When that assembly is-//! extracted into a callable step, [`turn`] should call it instead of mirroring-//! it, and every assertion below keeps its meaning.+//! and the tool-array assembly and reuse. This module mirrors orchestration+//! order; `loop::tests` separately drives real tool steps and a published-history+//! round trip, so moving accepted guidance cannot pass only because this+//! fixture retained messages the production loop dropped.//!//! Each test says what it protects, and names the epic item behind it where//! there is one.diff --git a/src-tauri/src/core/agent/transcript.rs b/src-tauri/src/core/agent/transcript.rsindex 5d4c28921..b4e1b0966 100644--- a/src-tauri/src/core/agent/transcript.rs+++ b/src-tauri/src/core/agent/transcript.rs@@ -26,11 +26,10 @@//! them.//! - **The wire shape is projection-owned.** Where the stable prompt sits, how//! a changed prompt lands behind the history instead of rewriting the head-//! (see [`crate::core::agent::upstream::set_system_prompt`]), how the per-turn-//! block lands below the accepted history rather than in a system slot ahead-//! of it (see [`crate::core::agent::upstream::append_prompt_tail`]), and-//! whether a prior turn's reasoning is resent are all parameters of-//! [`Projection`], not edits to the record.+//! (see [`crate::core::agent::upstream::set_system_prompt`]), how pending+//! guidance lands below history, and whether reasoning is resent are+//! projection decisions. Once a request succeeds, its guidance is recorded+//! at the accepted position rather than moved to the next request's tail.//! - **`project` is pure.** Two calls over an unchanged record with the same//! options produce byte-identical output, which is the property the//! prefix-stability suite asserts against.@@ -59,6 +58,9 @@ pub(crate) enum Event {/// [`crate::core::agent::reminder::attach`]) rather than recorded as one,/// so the record keeps what actually arrived.Reminder(String),+ /// Prompt guidance from a successful request, fixed at the position where+ /// the model received it. Unlike a reminder, it is always its own message.+ PromptTail(String),/// A summary standing in for every event recorded before it. `covers` is/// the record index the kept tail begins at - a projection boundary, not a/// deletion: the events before it are still in the record.@@ -74,12 +76,10 @@ pub(crate) struct Transcript {/// What the wire needs that is not in the record.#[derive(Debug, Clone, Copy)]pub(crate) struct Projection<'a> {- /// The per-turn context block (today's date, query-specific memory recall,- /// plan/todo state), plus any composition block `[prompt]` moved below the- /// cache line. Per-turn by nature: it is appended behind the accepted- /// history, so changing it cannot disturb the bytes in front of it -- which- /// is exactly what the stable prompt (and the prefix cached behind it) is- /// there to protect.+ /// Pending guidance for this run. It is appended below history until a+ /// successful request records it as `Event::PromptTail`; later projections+ /// retain that event in place. If compaction covers it, the current block+ /// is appended again and recorded on the next successful request.pub volatile_system: Option<&'a str>,/// Resend a prior assistant turn's `reasoning_content`. `false` is a/// provider capability answer ("this route rejects the field"), so it@@ -112,17 +112,10 @@ impl Transcript {/// whole request - and healing here means the record only ever holds turns/// a strict upstream accepts.///- /// Two kinds of node are then read rather than recorded verbatim:- ///- /// - a stable prompt node becomes a [`Event::Prompt`], so the projection- /// places it the way the live list did (head, or appended behind the- /// history when it changed);- /// - the per-turn block in its slot is dropped: it is projection input,- /// regenerated from the current turn, and recording it would accumulate- /// yesterday's date in the history.- ///- /// A compaction summary is neither: it is history under the `system` role,- /// and it stays.+ /// System instructions become `Event::Prompt` entries; summaries and+ /// marked guidance remain conversation history. No array position owns a+ /// disposable slot: compaction can put two stable prompt updates next to+ /// each other, and both must survive a client round trip.pub(crate) fn from_history(mut messages: Vec<Value>) -> Self {let poisoned = drop_malformed_tool_calls(&mut messages);if poisoned > 0 {@@ -137,12 +130,8 @@ impl Transcript {log::warn!("agent: repaired {repaired} dangling tool call(s) with no prior result");}- let volatile = volatile_index(&messages);let mut events = Vec::with_capacity(messages.len());- for (index, message) in messages.into_iter().enumerate() {- if Some(index) == volatile {- continue;- }+ for message in messages {events.push(if is_system_node(&message) && !is_compaction_summary(&message) {match message.get("content").and_then(|c| c.as_str()) {@@ -173,6 +162,26 @@ impl Transcript {self.events.push(Event::Reminder(text.to_string()));}+ /// Freeze guidance where the successful request sent it. Repeated tool+ /// steps reuse the same event; compaction may require a fresh one.+ pub(crate) fn record_prompt_tail(&mut self, text: &str) {+ if !text.is_empty() && !self.has_prompt_tail(text) {+ self.events.push(Event::PromptTail(text.to_string()));+ }+ }++ fn has_prompt_tail(&self, text: &str) -> bool {+ self.events+ .iter()+ .skip(self.boundary())+ .rev()+ .find_map(|event| match event {+ Event::PromptTail(accepted) => Some(accepted.as_str()),+ _ => None,+ })+ == Some(text)+ }+/// Record a compaction point: `summary` stands in for the first `covers`/// events, which stay in the record.pub(crate) fn record_compaction(&mut self, summary: Value, covers: usize) {@@ -235,6 +244,10 @@ impl Transcript {reminder::attach(&mut messages, text);sources.resize(messages.len(), index);}+ Event::PromptTail(text) => {+ append_prompt_tail(&mut messages, text);+ sources.push(index);+ }Event::Prompt(_) | Event::Compaction { .. } => {}}}@@ -283,14 +296,14 @@ impl Transcript {match event {Event::Message(message) => out.push(message.clone()),Event::Reminder(text) => reminder::attach(&mut out, text),+ Event::PromptTail(text) => append_prompt_tail(&mut out, text),Event::Prompt(text) => set_system_prompt(&mut out, text),// Already emitted ahead of the range it covers.Event::Compaction { .. } => {}}}- // Last, and only once: everything the record holds was accepted by an- // earlier request (or is about to be sent), so this turn's block goes- // after all of it.+ // Pending guidance belongs at the tail. Accepted guidance is already+ // emitted at its recorded position and must not move on later steps.self.place_volatile(&mut out, projection);if !projection.send_reasoning {@@ -299,21 +312,16 @@ impl Transcript {out}- /// Put this turn's block below the accepted history.- ///- /// Not in a `system` node behind the stable prompt: the provider bridge- /// hoists system-role content into the request's system field, ahead of the- /// conversation, so a block that changes per turn (the date at midnight,- /// the memory recalled for this query) would invalidate every message the- /// previous request already sent. It takes the shape a mid-run reminder- /// does -- marked `user` guidance appended at the tail -- which leaves the- /// accepted bytes untouched. A run with no stable prompt has no head to- /// cache, so the block is simply the last thing in the request.+ /// Append guidance only when this run has not yet sent it successfully,+ /// or compaction covered its accepted event. A `system` node would be+ /// hoisted ahead of history by the provider bridge.fn place_volatile(&self, out: &mut Vec<Value>, projection: &Projection<'_>) {let Some(text) = projection.volatile_system.filter(|text| !text.is_empty()) else {return;};- append_prompt_tail(out, text);+ if !self.has_prompt_tail(text) {+ append_prompt_tail(out, text);+ }}/// What a compaction would summarize, and how far into the record its@@ -339,22 +347,6 @@ impl Transcript {}}-/// Index of the per-turn block in a history that came from outside, if it has-/// one: the slot the prompt writer owns, i.e. index 1 once a system node holds-/// index 0. A summary that happens to occupy the slot is history, not a block.-///-/// Only the slot is healed. A block a client hands back at the tail is not:-/// `append_prompt_tail` gives it the same wire shape `reminder::attach` gives a-/// reminder the model actually received, and those have to survive a resend. So-/// the writer must not hand one back in the first place -- see `loop::client_history`.-fn volatile_index(messages: &[Value]) -> Option<usize> {- let slot = usize::from(messages.first().is_some_and(is_system_node));- messages- .get(slot)- .filter(|message| is_system_node(message) && !is_compaction_summary(message))- .map(|_| slot)-}-#[cfg(test)]mod tests {use super::*;@@ -518,96 +510,6 @@ mod tests {);}- /// A history from outside carries the previous turn's blocks: the stable- /// prompt is read back as a `Prompt` event (so it is placed the same way),- /// the per-turn block is not recorded at all (it is regenerated), and a- /// compaction summary stays as history.- #[test]- fn from_history_splits_the_previous_turns_wire_shape() {- let summary = format!("{} stuff", crate::core::agent::compaction::SUMMARY_MARKER);- let history = vec![- json!({"role": "system", "content": "stable prompt"}),- json!({"role": "system", "content": "Today's date is 2026-09-17."}),- json!({"role": "system", "content": summary}),- json!({"role": "user", "content": "carry on"}),- ];- let transcript = Transcript::from_history(history);- assert_eq!(- transcript.events()[0],- Event::Prompt("stable prompt".to_string())- );- assert_eq!(- transcript.events().len(),- 3,- "the per-turn block is not history"- );- assert_eq!(- transcript.events()[1],- Event::Message(json!({- "role": "system",- "content": summary,- }))- );-- let projected = transcript.project(&Projection {- volatile_system: Some("Today's date is 2026-09-18."),- send_reasoning: true,- });- assert_eq!(projected[0]["content"], "stable prompt");- assert_eq!(- projected[1]["content"], summary,- "a compaction summary is history, not a per-turn block"- );- assert_eq!(projected[2]["content"], "carry on");- assert_eq!(- projected[3],- json!({- "role": "user",- "content": crate::core::agent::reminder::wrap(- "Today's date is 2026-09-18."- ),- }),- "the current block, below the history, not yesterday's: {projected:?}"- );- assert_eq!(projected.len(), 4, "{projected:?}");- }-- /// Equivalence with the live-list placement this replaced: a history and a- /// changed prompt produce the same bytes the `set_system_prompt` +- /// `append_prompt_tail` pair does.- #[test]- fn the_projection_places_the_prompt_like_the_live_list_did() {- let history = vec![- json!({"role": "system", "content": "old prompt"}),- json!({"role": "system", "content": "Today's date is 2026-09-17."}),- json!({"role": "user", "content": "hi"}),- json!({"role": "assistant", "content": "hello"}),- ];-- // The live list as a turn would build it: the previous per-turn block- // is not carried forward (the projection regenerates it), the prompt is- // updated in place by `set_system_prompt`, and this turn's block is- // appended behind the accepted history.- let mut live = vec![- json!({"role": "system", "content": "old prompt"}),- json!({"role": "user", "content": "hi"}),- json!({"role": "assistant", "content": "hello"}),- ];- set_system_prompt(&mut live, "new prompt");- append_prompt_tail(&mut live, "Today's date is 2026-09-18.");-- let mut transcript = Transcript::from_history(history);- transcript.record_prompt("new prompt");- let projected = transcript.project(&Projection {- volatile_system: Some("Today's date is 2026-09-18."),- send_reasoning: true,- });-- assert_eq!(- serde_json::to_string(&projected).unwrap(),- serde_json::to_string(&live).unwrap()- );- }/// The record only ever grows: recording does not reorder or rewrite what/// is already there.@@ -685,9 +587,43 @@ mod tests {prompts, expected,"prompt precedence must survive compaction");+ let published = transcript.project(¬hing());+ let resumed = Transcript::from_history(published.clone()).project(¬hing());+ assert_eq!(+ resumed, published,+ "resuming the compacted history must retain every stable prompt update"+ );}}+ #[test]+ fn compaction_restores_accepted_guidance_once() {+ let guidance = "Follow the project rules for this run.";+ let projection = Projection {+ volatile_system: Some(guidance),+ send_reasoning: true,+ };+ let mut transcript = Transcript::from_history(convo(4));+ transcript.record_prompt_tail(guidance);+ for message in convo(12) {+ transcript.record_message(message);+ }+ let plan = transcript.compaction_plan(4).unwrap();+ transcript.record_compaction(+ crate::core::agent::compaction::summary_message("earlier work"),+ plan.covers,+ );++ let retry = transcript.project(&projection);+ assert_eq!(retry.last().unwrap()["content"], reminder::wrap(guidance));+ transcript.record_prompt_tail(guidance);+ assert_eq!(transcript.project(¬hing()), retry);+ transcript.record_message(json!({"role": "assistant", "content": "continuing"}));+ let next = transcript.project(&projection);+ assert_eq!(&next[..retry.len()], retry.as_slice());+ assert_eq!(next.len(), retry.len() + 1, "no duplicate guidance");+ }+/// Nothing safe to drop means no compaction: a short history reports no/// plan rather than a summary of itself.#[test]