Refresh collaboration instructions when their content changes (#39163)

## Why

Collaboration guidance can change without changing the active mode or model, such as after a model catalog refresh. Tracking only the mode and model leaves the earlier guidance in retained history.

## What changed

- Include a hash of the rendered collaboration instructions in the world-state snapshot so changed guidance is appended to retained history once.
- Emit one empty collaboration fragment when guidance is removed, preventing stale instructions from remaining active without repeatedly clearing them.
- Refresh legacy snapshots that lack an instruction hash once on resume.

## Testing

Cover same-mode catalog updates, clearing missing or explicitly empty guidance, retained-history behavior, and cold resume from legacy snapshots.

GitOrigin-RevId: 69f690adeccd1fb9794a6b15647e6efae3fec4f6
This commit is contained in:
rhan-oai
2026-08-18 07:32:03 +00:00
committed by copyberry
parent 4216123b3d
commit e2eea07140
4 changed files with 387 additions and 129 deletions
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
use super::WorldStateHash;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
use codex_protocol::config_types::CollaborationMode;
@@ -12,8 +13,7 @@ use serde::Serialize;
/// Collaboration-mode instructions currently visible to the model.
#[derive(Clone, Debug)]
pub(crate) struct CollaborationModeState {
mode: ModeKind,
model: String,
snapshot: CollaborationModeSnapshot,
instructions: Option<String>,
}
@@ -28,16 +28,25 @@ impl CollaborationModeState {
ModeKind::Plan => messages.plan.as_ref(),
});
Self {
let instructions = catalog_instructions.cloned().or_else(|| {
collaboration_mode
.settings
.developer_instructions
.clone()
.filter(|instructions| !instructions.is_empty())
});
// Keep an empty-state snapshot so removing instructions clears retained history only once.
let fragment = CollaborationModeInstructions {
instructions: instructions.clone().unwrap_or_default(),
};
let snapshot = CollaborationModeSnapshot::Current {
mode: collaboration_mode.mode,
model: collaboration_mode.settings.model.clone(),
instructions: catalog_instructions.cloned().or_else(|| {
collaboration_mode
.settings
.developer_instructions
.clone()
.filter(|instructions| !instructions.is_empty())
}),
instructions: Some(WorldStateHash::from_fragment(&fragment)),
};
Self {
snapshot,
instructions,
}
}
}
@@ -45,7 +54,13 @@ impl CollaborationModeState {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub(crate) enum CollaborationModeSnapshot {
Current { mode: ModeKind, model: String },
Current {
mode: ModeKind,
model: String,
// Older object snapshots do not have an instruction hash.
#[serde(default, skip_serializing_if = "Option::is_none")]
instructions: Option<WorldStateHash>,
},
Legacy(ModeKind),
}
@@ -54,14 +69,7 @@ impl WorldStateSection for CollaborationModeState {
type Snapshot = CollaborationModeSnapshot;
fn snapshot(&self) -> Self::Snapshot {
CollaborationModeSnapshot::Current {
mode: self.mode,
model: self.model.clone(),
}
}
fn should_persist(&self) -> bool {
self.instructions.is_some()
self.snapshot.clone()
}
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
@@ -80,13 +88,28 @@ impl WorldStateSection for CollaborationModeState {
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
) -> Option<Box<dyn ContextualUserFragment>> {
if matches!(
previous,
PreviousSectionState::Known(CollaborationModeSnapshot::Current { mode, model })
if *mode == self.mode && model == &self.model
) || matches!(previous, PreviousSectionState::Unknown)
|| (self.instructions.is_none() && matches!(previous, PreviousSectionState::Absent))
{
let unchanged = match previous {
PreviousSectionState::Absent => self.instructions.is_none(),
PreviousSectionState::Unknown => false,
PreviousSectionState::Known(previous) => {
previous == &self.snapshot
|| (self.instructions.as_deref().is_none_or(str::is_empty)
&& matches!(
(previous, &self.snapshot),
(
CollaborationModeSnapshot::Current {
instructions: Some(previous_hash),
..
},
CollaborationModeSnapshot::Current {
instructions: Some(current_hash),
..
},
) if previous_hash == current_hash
))
}
};
if unchanged {
return None;
}
@@ -30,29 +30,44 @@ fn snapshots() {
}
#[test]
fn persisted_instructions_are_restored_only_when_missing_from_history() {
let state = collaboration_mode_state(ModeKind::Default, "pair with the user");
let retained: ResponseItem = ContextualUserFragment::into(CollaborationModeInstructions {
instructions: state.instructions.clone().expect("test instructions"),
});
let mut world_state = WorldState::default();
world_state.add_section(state);
let snapshot = world_state.snapshot();
fn instruction_updates_are_applied_once_in_retained_history() {
let mut history: Vec<ResponseItem> = vec![ContextualUserFragment::into(
CollaborationModeInstructions {
instructions: "old instructions".to_string(),
},
)];
let mut previous = None;
assert!(
world_state
.render_history_diff(/*previous*/ None, std::slice::from_ref(&retained))
.is_empty()
);
assert_eq!(
world_state.render_history_diff(Some(&snapshot), &[]).len(),
1,
);
assert!(
world_state
.render_history_diff(Some(&snapshot), &[retained])
.is_empty()
);
for instructions in [Some("old instructions"), Some("new instructions"), None] {
let mut world_state = WorldState::default();
world_state.add_section(CollaborationModeState::from_collaboration_mode(
&collaboration_mode(ModeKind::Default, instructions),
/*catalog_messages*/ None,
));
let expected: ResponseItem = ContextualUserFragment::into(CollaborationModeInstructions {
instructions: instructions.unwrap_or_default().to_string(),
});
let updates = world_state
.render_history_diff(previous.as_ref(), &history)
.into_iter()
.map(ContextualUserFragment::into_boxed_response_item)
.collect::<Vec<_>>();
assert_eq!(updates, vec![expected]);
history.extend(updates);
previous = Some(world_state.snapshot());
assert!(
world_state
.render_history_diff(previous.as_ref(), &history)
.is_empty()
);
assert_eq!(
world_state
.render_history_diff(previous.as_ref(), &[])
.len(),
usize::from(instructions.is_some()),
);
}
}
#[test]
@@ -114,31 +129,35 @@ fn missing_catalog_collaboration_message_uses_legacy_instructions() {
#[test]
fn legacy_collaboration_mode_snapshots_refresh_catalog_messages_once() {
let previous = serde_json::from_str::<CollaborationModeSnapshot>("\"default\"")
.expect("legacy collaboration mode snapshot");
for serialized in ["\"default\"", r#"{"mode":"default","model":"test-model"}"#] {
let previous = serde_json::from_str::<CollaborationModeSnapshot>(serialized)
.expect("legacy collaboration mode snapshot");
for instructions in ["catalog instructions", ""] {
let messages = CollaborationModeMessages {
default: Some(instructions.to_string()),
plan: None,
};
let state = CollaborationModeState::from_collaboration_mode(
&collaboration_mode(ModeKind::Default, Some("stale legacy instructions")),
Some(&messages),
);
for instructions in ["catalog instructions", ""] {
let messages = CollaborationModeMessages {
default: Some(instructions.to_string()),
plan: None,
};
let state = CollaborationModeState::from_collaboration_mode(
&collaboration_mode(ModeKind::Default, Some("stale legacy instructions")),
Some(&messages),
);
assert_eq!(
state
.render_diff(PreviousSectionState::Known(&previous))
.expect("legacy snapshot should refresh collaboration instructions")
.render(),
format!("{COLLABORATION_MODE_OPEN_TAG}{instructions}{COLLABORATION_MODE_CLOSE_TAG}")
);
assert!(
state
.render_diff(PreviousSectionState::Known(&state.snapshot()))
.is_none()
);
assert_eq!(
state
.render_diff(PreviousSectionState::Known(&previous))
.expect("legacy snapshot should refresh collaboration instructions")
.render(),
format!(
"{COLLABORATION_MODE_OPEN_TAG}{instructions}{COLLABORATION_MODE_CLOSE_TAG}"
)
);
assert!(
state
.render_diff(PreviousSectionState::Known(&state.snapshot()))
.is_none()
);
}
}
}
@@ -5,17 +5,17 @@ expression: "render_section_cases(&[(Absent, Absent), (Absent, Known(&default)),
Absent -> Absent
None
Absent -> {"mode":"default","model":"test-model"} (role - developer)
Absent -> {"instructions":"90f8f6675171813762488f76c60b062fc8adeaec","mode":"default","model":"test-model"} (role - developer)
<collaboration_mode>pair with the user</collaboration_mode>
{"mode":"default","model":"test-model"} -> {"mode":"default","model":"test-model"}
{"instructions":"90f8f6675171813762488f76c60b062fc8adeaec","mode":"default","model":"test-model"} -> {"instructions":"90f8f6675171813762488f76c60b062fc8adeaec","mode":"default","model":"test-model"}
None
{"mode":"default","model":"test-model"} -> {"mode":"default","model":"test-model"}
None
{"instructions":"1bfc0435f0536e09f08dbfe37c09920d3344e925","mode":"default","model":"test-model"} -> {"instructions":"8c3a0740268ef8f622810f31715b1924540de415","mode":"default","model":"test-model"} (role - developer)
<collaboration_mode>new instructions</collaboration_mode>
{"mode":"default","model":"test-model"} -> {"mode":"plan","model":"test-model"} (role - developer)
{"instructions":"90f8f6675171813762488f76c60b062fc8adeaec","mode":"default","model":"test-model"} -> {"instructions":"bc50ed412c1138502df45ef1b6634a6ef618da4c","mode":"plan","model":"test-model"} (role - developer)
<collaboration_mode>make a plan</collaboration_mode>
Unknown -> {"mode":"default","model":"test-model"}
None
Unknown -> {"instructions":"90f8f6675171813762488f76c60b062fc8adeaec","mode":"default","model":"test-model"} (role - developer)
<collaboration_mode>pair with the user</collaboration_mode>