Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 49 additions & 26 deletions codex-rs/core/src/context/world_state/collaboration_mode.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
use super::WorldStateHash;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
use codex_protocol::config_types::CollaborationMode;
Expand All @@ -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>,
}

Expand All @@ -28,24 +28,39 @@ 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,
}
}
}

#[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),
}

Expand All @@ -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 {
Expand All @@ -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;
}

Expand Down
115 changes: 67 additions & 48 deletions codex-rs/core/src/context/world_state/collaboration_mode_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

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()
);
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;

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]
Expand Down Expand Up @@ -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 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()
);
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),
);

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()
);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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>
Loading
Loading