Merge branch 'main' into jif/compact-v2-for-oai

This commit is contained in:
jif-oai
2026-05-20 18:44:33 +02:00
committed by GitHub
24 changed files with 1613 additions and 124 deletions
+23 -5
View File
@@ -1107,15 +1107,33 @@ jobs:
# If included in files: dist/**, release upload races on duplicate
# asset names and can fail with 404s.
find dist -type f -name 'cargo-timing.html' -delete
# Keep package-builder sidecar archives as workflow artifacts only
# until distribution channels are ready to consume them.
find dist -type f \
\( -name 'codex-package-*' -o -name 'codex-app-server-package-*' \) \
-delete
find dist -type d -empty -delete
ls -R dist/
- name: Add Codex package checksum manifest
run: |
set -euo pipefail
manifest="dist/codex-package_SHA256SUMS"
tmp_manifest="$(mktemp)"
find dist -type f \
\( -name 'codex-package-*.tar.gz' -o -name 'codex-app-server-package-*.tar.gz' \) \
-print |
sort |
while IFS= read -r archive; do
sha256sum "$archive" |
awk -v name="$(basename "$archive")" '{ print $1 " " name }'
done > "$tmp_manifest"
if [[ ! -s "$tmp_manifest" ]]; then
echo "No Codex package archives found for checksum manifest"
exit 1
fi
mv "$tmp_manifest" "$manifest"
cat "$manifest"
- name: Add config schema release asset
run: |
cp codex-rs/core/config.schema.json dist/config-schema.json
+1
View File
@@ -3024,6 +3024,7 @@ version = "0.0.0"
dependencies = [
"clap",
"codex-core",
"codex-install-context",
"codex-process-hardening",
"codex-protocol",
"codex-sandboxing",
+99
View File
@@ -1911,6 +1911,105 @@ async fn record_token_usage_info_notifies_extension_contributors() {
assert_eq!(expected, actual);
}
#[tokio::test]
async fn turn_start_lifecycle_exposes_turn_metadata_and_token_baseline() {
struct SessionTurnStartMarker;
struct ThreadTurnStartMarker;
#[derive(Debug, PartialEq, Eq)]
struct RecordedTurnStart {
session_level_id: String,
thread_level_id: String,
turn_level_id: String,
turn_id: String,
collaboration_mode: CollaborationMode,
token_usage_at_turn_start: TokenUsage,
saw_session_store: bool,
saw_thread_store: bool,
}
struct TurnStartRecorder {
records: Arc<std::sync::Mutex<Vec<RecordedTurnStart>>>,
}
#[async_trait::async_trait]
impl codex_extension_api::TurnLifecycleContributor for TurnStartRecorder {
async fn on_turn_start(&self, input: codex_extension_api::TurnStartInput<'_>) {
self.records
.lock()
.expect("turn start records lock")
.push(RecordedTurnStart {
session_level_id: input.session_store.level_id().to_string(),
thread_level_id: input.thread_store.level_id().to_string(),
turn_level_id: input.turn_store.level_id().to_string(),
turn_id: input.turn_id.to_string(),
collaboration_mode: input.collaboration_mode.clone(),
token_usage_at_turn_start: input.token_usage_at_turn_start.clone(),
saw_session_store: input
.session_store
.get::<SessionTurnStartMarker>()
.is_some(),
saw_thread_store: input.thread_store.get::<ThreadTurnStartMarker>().is_some(),
});
}
}
let (mut session, turn_context) = make_session_and_context().await;
let records = Arc::new(std::sync::Mutex::new(Vec::new()));
let mut builder = codex_extension_api::ExtensionRegistryBuilder::<crate::config::Config>::new();
builder.turn_lifecycle_contributor(Arc::new(TurnStartRecorder {
records: Arc::clone(&records),
}));
session.services.extensions = Arc::new(builder.build());
session
.services
.session_extension_data
.insert(SessionTurnStartMarker);
session
.services
.thread_extension_data
.insert(ThreadTurnStartMarker);
let token_usage_at_turn_start = TokenUsage {
input_tokens: 100,
cached_input_tokens: 40,
output_tokens: 25,
reasoning_output_tokens: 5,
total_tokens: 130,
};
set_total_token_usage(&session, token_usage_at_turn_start.clone()).await;
let expected = RecordedTurnStart {
session_level_id: session.session_id().to_string(),
thread_level_id: session.conversation_id.to_string(),
turn_level_id: turn_context.sub_id.clone(),
turn_id: turn_context.sub_id.clone(),
collaboration_mode: turn_context.collaboration_mode.clone(),
token_usage_at_turn_start,
saw_session_store: true,
saw_thread_store: true,
};
let sess = Arc::new(session);
sess.spawn_task(
Arc::new(turn_context),
Vec::new(),
NeverEndingTask {
kind: TaskKind::Regular,
listen_to_cancellation_token: true,
},
)
.await;
sess.abort_all_tasks(TurnAbortReason::Interrupted).await;
let actual = records
.lock()
.expect("turn start records lock")
.drain(..)
.collect::<Vec<_>>();
assert_eq!(vec![expected], actual);
}
#[tokio::test]
async fn config_change_contributor_observes_effective_config_changes() {
struct SessionConfigMarker;
+11 -2
View File
@@ -1,16 +1,25 @@
use codex_extension_api::ExtensionData;
use codex_protocol::protocol::TokenUsage;
use codex_protocol::protocol::TurnAbortReason;
use crate::session::session::Session;
use crate::session::turn_context::TurnContext;
impl Session {
pub(super) async fn emit_turn_start_lifecycle(&self, turn_store: &ExtensionData) {
pub(super) async fn emit_turn_start_lifecycle(
&self,
turn_context: &TurnContext,
token_usage_at_turn_start: &TokenUsage,
) {
for contributor in self.services.extensions.turn_lifecycle_contributors() {
contributor
.on_turn_start(codex_extension_api::TurnStartInput {
turn_id: turn_context.sub_id.as_str(),
collaboration_mode: &turn_context.collaboration_mode,
token_usage_at_turn_start,
session_store: &self.services.session_extension_data,
thread_store: &self.services.thread_extension_data,
turn_store,
turn_store: turn_context.extension_data.as_ref(),
})
.await;
}
+2 -2
View File
@@ -357,7 +357,7 @@ impl Session {
debug_assert!(turn.tasks.is_empty());
Arc::clone(&turn.turn_state)
};
turn_state.lock().await.token_usage_at_turn_start = token_usage_at_turn_start;
turn_state.lock().await.token_usage_at_turn_start = token_usage_at_turn_start.clone();
let mut pending_items = queued_response_items
.into_iter()
.map(TurnInput::ResponseInputItem)
@@ -366,7 +366,7 @@ impl Session {
self.input_queue
.extend_pending_input_for_turn_state(turn_state.as_ref(), pending_items)
.await;
self.emit_turn_start_lifecycle(turn_context.extension_data.as_ref())
self.emit_turn_start_lifecycle(turn_context.as_ref(), &token_usage_at_turn_start)
.await;
let turn_extension_data = Arc::clone(&turn_context.extension_data);
+19 -11
View File
@@ -367,19 +367,27 @@ fn build_code_mode_executors(
return vec![];
}
let code_mode_nested_tool_specs = executors
.iter()
.filter_map(|executor| {
if executor.exposure() == ToolExposure::DirectModelOnly {
return None;
}
let mut code_mode_nested_tool_specs = Vec::new();
let mut exec_prompt_tool_specs = Vec::new();
for executor in executors {
let exposure = executor.exposure();
if exposure == ToolExposure::DirectModelOnly {
continue;
}
executor.spec()
})
.collect::<Vec<_>>();
let namespace_descriptions = code_mode_namespace_descriptions(&code_mode_nested_tool_specs);
let Some(spec) = executor.spec() else {
continue;
};
if exposure != ToolExposure::Deferred {
exec_prompt_tool_specs.push(spec.clone());
}
code_mode_nested_tool_specs.push(spec);
}
let namespace_descriptions = code_mode_namespace_descriptions(&exec_prompt_tool_specs);
let mut enabled_tools =
collect_code_mode_exec_prompt_tool_definitions(code_mode_nested_tool_specs.iter());
collect_code_mode_exec_prompt_tool_definitions(exec_prompt_tool_specs.iter());
enabled_tools
.sort_by(|left, right| compare_code_mode_tools(left, right, &namespace_descriptions));
@@ -1,9 +1,17 @@
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::protocol::TokenUsage;
use codex_protocol::protocol::TurnAbortReason;
use crate::ExtensionData;
/// Input supplied when the host starts a turn.
pub struct TurnStartInput<'a> {
/// Stable host-owned turn identifier.
pub turn_id: &'a str,
/// Effective collaboration mode for this turn.
pub collaboration_mode: &'a CollaborationMode,
/// Total token usage snapshot captured when the turn started.
pub token_usage_at_turn_start: &'a TokenUsage,
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
+1
View File
@@ -3,4 +3,5 @@ load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "goal",
crate_name = "codex_goal_extension",
integration_compile_data_extra = ["src/accounting.rs"],
)
+269 -21
View File
@@ -1,23 +1,50 @@
use codex_protocol::config_types::ModeKind;
use codex_protocol::protocol::TokenUsage;
use codex_state::ThreadGoalStatus;
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::time::Duration;
use std::time::Instant;
#[derive(Debug, Default)]
pub(crate) struct GoalAccountingState {
inner: Mutex<GoalAccountingInner>,
}
#[derive(Debug, Default)]
#[derive(Debug)]
struct GoalAccountingInner {
current_turn_id: Option<String>,
turns: HashMap<String, GoalTurnAccounting>,
unflushed_token_delta: i64,
wall_clock: GoalWallClockAccounting,
}
#[derive(Debug, Default)]
#[derive(Debug)]
struct GoalTurnAccounting {
token_delta: i64,
stopped: bool,
current_token_usage: TokenUsage,
last_accounted_token_usage: TokenUsage,
active_goal_id: Option<String>,
account_tokens: bool,
}
#[derive(Debug)]
struct GoalWallClockAccounting {
last_accounted_at: Instant,
active_goal_id: Option<String>,
}
#[derive(Debug, Clone)]
pub(crate) struct GoalProgressSnapshot {
pub(crate) current_token_usage: TokenUsage,
pub(crate) expected_goal_id: String,
pub(crate) time_delta_seconds: i64,
pub(crate) token_delta: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BudgetLimitedGoalDisposition {
KeepActive,
ClearActive,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -27,36 +54,137 @@ pub(crate) struct RecordedTokenDelta {
}
impl GoalAccountingState {
pub(crate) fn start_turn(&self, turn_id: impl Into<String>) {
pub(crate) fn start_turn(
&self,
turn_id: impl Into<String>,
collaboration_mode: ModeKind,
token_usage_at_turn_start: &TokenUsage,
) {
let turn_id = turn_id.into();
self.inner().turns.entry(turn_id).or_default().stopped = false;
let mut inner = self.inner();
inner.current_turn_id = Some(turn_id.clone());
inner.turns.insert(
turn_id,
GoalTurnAccounting::new(
token_usage_at_turn_start.clone(),
!matches!(collaboration_mode, ModeKind::Plan),
),
);
}
pub(crate) fn current_turn_id(&self) -> Option<String> {
self.inner().current_turn_id.clone()
}
pub(crate) fn record_token_usage(
&self,
turn_id: impl Into<String>,
usage: &TokenUsage,
total_usage: &TokenUsage,
) -> Option<RecordedTokenDelta> {
let delta = goal_token_delta_for_usage(usage);
if delta <= 0 {
let turn_id = turn_id.into();
let mut inner = self.inner();
let turn = inner.turns.get_mut(&turn_id)?;
turn.current_token_usage = total_usage.clone();
if !turn.account_tokens {
return None;
}
let turn_id = turn_id.into();
let mut inner = self.inner();
let turn = inner.turns.entry(turn_id).or_default();
turn.token_delta = turn.token_delta.saturating_add(delta);
let turn_delta = turn.token_delta;
inner.unflushed_token_delta = inner.unflushed_token_delta.saturating_add(delta);
let delta = turn.token_delta_since_last_accounting();
if delta <= 0 {
return None;
}
Some(RecordedTokenDelta {
turn_delta,
thread_unflushed_delta: inner.unflushed_token_delta,
turn_delta: delta,
thread_unflushed_delta: inner.thread_unflushed_token_delta(),
})
}
pub(crate) fn stop_turn(&self, turn_id: &str) {
if let Some(turn) = self.inner().turns.get_mut(turn_id) {
turn.stopped = true;
pub(crate) fn mark_turn_goal_active(&self, turn_id: &str, goal_id: impl Into<String>) {
let mut inner = self.inner();
let goal_id = goal_id.into();
if let Some(turn) = inner.turns.get_mut(turn_id) {
turn.active_goal_id = Some(goal_id.clone());
if inner.current_turn_id.as_deref() == Some(turn_id) {
inner.wall_clock.mark_active_goal(goal_id);
}
}
}
pub(crate) fn mark_current_turn_goal_active(
&self,
goal_id: impl Into<String>,
) -> Option<String> {
let mut inner = self.inner();
let turn_id = inner.current_turn_id.clone()?;
let goal_id = goal_id.into();
let turn = inner.turns.get_mut(turn_id.as_str())?;
turn.active_goal_id = Some(goal_id.clone());
turn.reset_baseline_to_current();
inner.wall_clock.mark_active_goal(goal_id);
Some(turn_id)
}
pub(crate) fn clear_current_turn_goal(&self) -> Option<String> {
let mut inner = self.inner();
let turn_id = inner.current_turn_id.clone()?;
if let Some(turn) = inner.turns.get_mut(turn_id.as_str()) {
turn.active_goal_id = None;
}
inner.wall_clock.clear_active_goal();
Some(turn_id)
}
pub(crate) fn progress_snapshot(&self, turn_id: &str) -> Option<GoalProgressSnapshot> {
let inner = self.inner();
let turn = inner.turns.get(turn_id)?;
if !turn.account_tokens {
return None;
}
let expected_goal_id = turn.active_goal_id()?;
let token_delta = turn.token_delta_since_last_accounting();
let time_delta_seconds =
if inner.wall_clock.active_goal_id.as_deref() == Some(expected_goal_id.as_str()) {
inner.wall_clock.time_delta_since_last_accounting()
} else {
0
};
if time_delta_seconds == 0 && token_delta <= 0 {
return None;
}
Some(GoalProgressSnapshot {
current_token_usage: turn.current_token_usage.clone(),
expected_goal_id,
time_delta_seconds,
token_delta,
})
}
pub(crate) fn mark_progress_accounted_for_status(
&self,
turn_id: &str,
snapshot: &GoalProgressSnapshot,
status: ThreadGoalStatus,
budget_limited_goal_disposition: BudgetLimitedGoalDisposition,
) {
let clear_active_goal = should_clear_active_goal(status, budget_limited_goal_disposition);
let mut inner = self.inner();
if let Some(turn) = inner.turns.get_mut(turn_id) {
turn.last_accounted_token_usage = snapshot.current_token_usage.clone();
if clear_active_goal {
turn.active_goal_id = None;
}
}
inner.wall_clock.mark_accounted(snapshot.time_delta_seconds);
if clear_active_goal {
inner.wall_clock.clear_active_goal();
}
}
pub(crate) fn finish_turn(&self, turn_id: &str) {
let mut inner = self.inner();
inner.turns.remove(turn_id);
if inner.current_turn_id.as_deref() == Some(turn_id) {
inner.current_turn_id = None;
}
}
@@ -65,9 +193,129 @@ impl GoalAccountingState {
}
}
fn token_delta_since_last_accounting(last: &TokenUsage, current: &TokenUsage) -> i64 {
let delta = TokenUsage {
input_tokens: current.input_tokens.saturating_sub(last.input_tokens),
cached_input_tokens: current
.cached_input_tokens
.saturating_sub(last.cached_input_tokens),
output_tokens: current.output_tokens.saturating_sub(last.output_tokens),
reasoning_output_tokens: current
.reasoning_output_tokens
.saturating_sub(last.reasoning_output_tokens),
total_tokens: current.total_tokens.saturating_sub(last.total_tokens),
};
goal_token_delta_for_usage(&delta)
}
pub(crate) fn goal_token_delta_for_usage(usage: &TokenUsage) -> i64 {
usage
.input_tokens
.saturating_sub(usage.cached_input_tokens)
.saturating_add(usage.output_tokens.max(0))
}
impl Default for GoalAccountingInner {
fn default() -> Self {
Self {
current_turn_id: None,
turns: HashMap::new(),
wall_clock: GoalWallClockAccounting::new(),
}
}
}
impl GoalAccountingInner {
fn thread_unflushed_token_delta(&self) -> i64 {
self.turns
.values()
.filter(|turn| turn.account_tokens)
.fold(0_i64, |total, turn| {
total.saturating_add(turn.token_delta_since_last_accounting().max(0))
})
}
}
impl GoalTurnAccounting {
fn new(current_token_usage: TokenUsage, account_tokens: bool) -> Self {
Self {
last_accounted_token_usage: current_token_usage.clone(),
current_token_usage,
active_goal_id: None,
account_tokens,
}
}
fn active_goal_id(&self) -> Option<String> {
self.active_goal_id.clone()
}
fn reset_baseline_to_current(&mut self) {
self.last_accounted_token_usage = self.current_token_usage.clone();
}
fn token_delta_since_last_accounting(&self) -> i64 {
token_delta_since_last_accounting(
&self.last_accounted_token_usage,
&self.current_token_usage,
)
}
}
impl GoalWallClockAccounting {
fn new() -> Self {
Self {
last_accounted_at: Instant::now(),
active_goal_id: None,
}
}
fn time_delta_since_last_accounting(&self) -> i64 {
i64::try_from(self.last_accounted_at.elapsed().as_secs()).unwrap_or(i64::MAX)
}
fn mark_accounted(&mut self, accounted_seconds: i64) {
if accounted_seconds <= 0 {
return;
}
let advance = Duration::from_secs(u64::try_from(accounted_seconds).unwrap_or(u64::MAX));
self.last_accounted_at = self
.last_accounted_at
.checked_add(advance)
.unwrap_or_else(Instant::now);
}
fn reset_baseline(&mut self) {
self.last_accounted_at = Instant::now();
}
fn mark_active_goal(&mut self, goal_id: impl Into<String>) {
let goal_id = goal_id.into();
if self.active_goal_id.as_deref() != Some(goal_id.as_str()) {
self.reset_baseline();
self.active_goal_id = Some(goal_id);
}
}
fn clear_active_goal(&mut self) {
self.active_goal_id = None;
self.reset_baseline();
}
}
fn should_clear_active_goal(
status: ThreadGoalStatus,
budget_limited_goal_disposition: BudgetLimitedGoalDisposition,
) -> bool {
match status {
ThreadGoalStatus::Active => false,
ThreadGoalStatus::BudgetLimited => matches!(
budget_limited_goal_disposition,
BudgetLimitedGoalDisposition::ClearActive
),
ThreadGoalStatus::Paused
| ThreadGoalStatus::Blocked
| ThreadGoalStatus::UsageLimited
| ThreadGoalStatus::Complete => true,
}
}
+119 -29
View File
@@ -18,13 +18,15 @@ use codex_extension_api::TurnLifecycleContributor;
use codex_extension_api::TurnStartInput;
use codex_extension_api::TurnStopInput;
use codex_protocol::ThreadId;
use codex_protocol::protocol::ThreadGoal;
use codex_protocol::protocol::TokenUsageInfo;
use codex_protocol::protocol::TurnAbortReason;
use crate::accounting::BudgetLimitedGoalDisposition;
use crate::accounting::GoalAccountingState;
use crate::events::GoalEventEmitter;
use crate::spec::UPDATE_GOAL_TOOL_NAME;
use crate::tool::GoalToolExecutor;
use crate::tool::protocol_goal_from_state;
#[derive(Clone, Debug)]
pub struct GoalExtensionConfig {
@@ -108,10 +110,39 @@ where
return;
}
// TODO: TurnStartInput should expose collaboration mode and token usage
// at turn start. Goals need mode to suppress plan-mode accounting and
// the token baseline to account deltas exactly.
accounting_state(input.thread_store).start_turn(input.turn_store.level_id());
let accounting = accounting_state(input.thread_store);
accounting.start_turn(
input.turn_id,
input.collaboration_mode.mode,
input.token_usage_at_turn_start,
);
if matches!(
input.collaboration_mode.mode,
codex_protocol::config_types::ModeKind::Plan
) {
accounting.clear_current_turn_goal();
return;
}
let Ok(thread_id) = ThreadId::from_string(input.thread_store.level_id()) else {
return;
};
let Ok(goal) = self
.state_dbs
.thread_goals()
.get_thread_goal(thread_id)
.await
else {
return;
};
if let Some(goal) = goal
&& matches!(
goal.status,
codex_state::ThreadGoalStatus::Active
| codex_state::ThreadGoalStatus::BudgetLimited
)
{
accounting.mark_turn_goal_active(input.turn_id, goal.goal_id);
}
}
async fn on_turn_stop(&self, input: TurnStopInput<'_>) {
@@ -119,13 +150,16 @@ where
return;
}
// TODO: this should flush wall-clock and any unflushed token usage to
// persisted goal storage, emit ThreadGoalUpdated, and optionally inject
// budget-limit steering through a host event/input capability.
// TODO: the host also needs an idle/next-turn wake capability so an
// active goal can enqueue continuation context after the turn is fully
// cleared, only when there is no pending user or mailbox work.
accounting_state(input.thread_store).stop_turn(input.turn_store.level_id());
let turn_id = input.turn_store.level_id();
self.account_active_goal_progress(
input.thread_store,
turn_id,
&format!("{turn_id}:turn-stop"),
codex_state::GoalAccountingMode::ActiveOnly,
BudgetLimitedGoalDisposition::ClearActive,
)
.await;
accounting_state(input.thread_store).finish_turn(turn_id);
}
async fn on_turn_abort(&self, input: TurnAbortInput<'_>) {
@@ -133,11 +167,16 @@ where
return;
}
accounting_state(input.thread_store).stop_turn(input.turn_store.level_id());
if input.reason == TurnAbortReason::Interrupted {
// TODO: interrupted turns should pause the active goal via persisted
// goal storage and emit ThreadGoalUpdated with turn_id None.
}
let turn_id = input.turn_store.level_id();
self.account_active_goal_progress(
input.thread_store,
turn_id,
&format!("{turn_id}:turn-abort"),
codex_state::GoalAccountingMode::ActiveOnly,
BudgetLimitedGoalDisposition::ClearActive,
)
.await;
accounting_state(input.thread_store).finish_turn(turn_id);
}
}
@@ -158,15 +197,10 @@ where
}
let Some(_recorded) = accounting_state(thread_store)
.record_token_usage(turn_store.level_id(), &token_usage.last_token_usage)
.record_token_usage(turn_store.level_id(), &token_usage.total_token_usage)
else {
return;
};
// TODO: TokenUsageContributor needs a host goal storage capability so
// this recorded delta can be committed to the active persisted goal.
// It also needs an event/input capability to emit ThreadGoalUpdated and
// inject budget-limit steering when accounting changes goal status.
}
}
@@ -176,15 +210,21 @@ where
{
fn on_tool_finish<'a>(&'a self, input: ToolFinishInput<'a>) -> ToolLifecycleFuture<'a> {
Box::pin(async move {
let _should_count_for_goal_progress = goal_enabled(input.thread_store)
let should_count_for_goal_progress = goal_enabled(input.thread_store)
&& tool_attempt_counts_for_goal_progress(input.outcome)
&& !(input.tool_name.namespace.is_none()
&& input.tool_name.name == UPDATE_GOAL_TOOL_NAME);
// TODO: commit active goal progress through host goal storage and emit
// ThreadGoalUpdated when the persisted goal changes. This replaces
// GoalRuntimeEvent::ToolCompleted once the goal extension owns runtime
// accounting.
if !should_count_for_goal_progress {
return;
}
self.account_active_goal_progress(
input.thread_store,
input.turn_id,
input.call_id,
codex_state::GoalAccountingMode::ActiveOnly,
BudgetLimitedGoalDisposition::KeepActive,
)
.await;
})
}
}
@@ -215,16 +255,19 @@ where
Arc::new(GoalToolExecutor::get(
thread_id,
Arc::clone(&self.state_dbs),
accounting_state(thread_store),
self.event_emitter.clone(),
)),
Arc::new(GoalToolExecutor::create(
thread_id,
Arc::clone(&self.state_dbs),
accounting_state(thread_store),
self.event_emitter.clone(),
)),
Arc::new(GoalToolExecutor::update(
thread_id,
Arc::clone(&self.state_dbs),
accounting_state(thread_store),
self.event_emitter.clone(),
)),
]
@@ -274,3 +317,50 @@ fn tool_attempt_counts_for_goal_progress(outcome: ToolCallOutcome) -> bool {
| ToolCallOutcome::Aborted => false,
}
}
impl<C> GoalExtension<C> {
async fn account_active_goal_progress(
&self,
thread_store: &ExtensionData,
turn_id: &str,
event_id: &str,
mode: codex_state::GoalAccountingMode,
budget_limited_goal_disposition: BudgetLimitedGoalDisposition,
) -> Option<ThreadGoal> {
let Ok(thread_id) = ThreadId::from_string(thread_store.level_id()) else {
return None;
};
let accounting = accounting_state(thread_store);
let snapshot = accounting.progress_snapshot(turn_id)?;
let outcome = self
.state_dbs
.thread_goals()
.account_thread_goal_usage(
thread_id,
snapshot.time_delta_seconds,
snapshot.token_delta,
mode,
Some(snapshot.expected_goal_id.as_str()),
)
.await
.ok()?;
match outcome {
codex_state::GoalAccountingOutcome::Updated(goal) => {
accounting.mark_progress_accounted_for_status(
turn_id,
&snapshot,
goal.status,
budget_limited_goal_disposition,
);
let goal = protocol_goal_from_state(goal);
self.event_emitter.thread_goal_updated(
event_id.to_string(),
Some(turn_id.to_string()),
goal.clone(),
);
Some(goal)
}
codex_state::GoalAccountingOutcome::Unchanged(_) => None,
}
}
}
+4 -3
View File
@@ -60,9 +60,9 @@ pub fn create_update_goal_tool() -> ToolSpec {
let properties = BTreeMap::from([(
"status".to_string(),
JsonSchema::string_enum(
vec![json!("complete")],
vec![json!("complete"), json!("blocked")],
Some(
"Required. Set to complete only when the objective is achieved and no required work remains."
"Required. Set to complete only when the objective is achieved and no required work remains. Set to blocked only when the goal cannot currently proceed without a user decision, missing dependency, or external unblock."
.to_string(),
),
),
@@ -71,8 +71,9 @@ pub fn create_update_goal_tool() -> ToolSpec {
ToolSpec::Function(ResponsesApiTool {
name: UPDATE_GOAL_TOOL_NAME.to_string(),
description: r#"Update the existing goal.
Use this tool only to mark the goal achieved.
Use this tool only to mark the goal achieved or blocked.
Set status to `complete` only when the objective has actually been achieved and no required work remains.
Set status to `blocked` only when the goal cannot currently proceed until something external changes.
Do not mark a goal complete merely because its budget is nearly exhausted or because you are stopping work.
You cannot use this tool to pause, resume, or budget-limit a goal; those status changes are controlled by the user or system.
When marking a budgeted goal achieved with status `complete`, report the final token usage from the tool result to the user."#
+109 -19
View File
@@ -15,6 +15,8 @@ use codex_protocol::protocol::validate_thread_goal_objective;
use serde::Deserialize;
use serde::Serialize;
use crate::accounting::BudgetLimitedGoalDisposition;
use crate::accounting::GoalAccountingState;
use crate::events::GoalEventEmitter;
use crate::spec::CREATE_GOAL_TOOL_NAME;
use crate::spec::GET_GOAL_TOOL_NAME;
@@ -28,6 +30,7 @@ pub(crate) struct GoalToolExecutor {
kind: GoalToolKind,
thread_id: ThreadId,
state_db: Arc<codex_state::StateRuntime>,
accounting_state: Arc<GoalAccountingState>,
event_emitter: GoalEventEmitter,
}
@@ -69,12 +72,14 @@ impl GoalToolExecutor {
pub(crate) fn get(
thread_id: ThreadId,
state_db: Arc<codex_state::StateRuntime>,
accounting_state: Arc<GoalAccountingState>,
event_emitter: GoalEventEmitter,
) -> Self {
Self {
kind: GoalToolKind::Get,
thread_id,
state_db,
accounting_state,
event_emitter,
}
}
@@ -82,12 +87,14 @@ impl GoalToolExecutor {
pub(crate) fn create(
thread_id: ThreadId,
state_db: Arc<codex_state::StateRuntime>,
accounting_state: Arc<GoalAccountingState>,
event_emitter: GoalEventEmitter,
) -> Self {
Self {
kind: GoalToolKind::Create,
thread_id,
state_db,
accounting_state,
event_emitter,
}
}
@@ -95,12 +102,14 @@ impl GoalToolExecutor {
pub(crate) fn update(
thread_id: ThreadId,
state_db: Arc<codex_state::StateRuntime>,
accounting_state: Arc<GoalAccountingState>,
event_emitter: GoalEventEmitter,
) -> Self {
Self {
kind: GoalToolKind::Update,
thread_id,
state_db,
accounting_state,
event_emitter,
}
}
@@ -179,8 +188,11 @@ impl GoalToolExecutor {
)
})?;
fill_empty_thread_preview_if_possible(self.state_db.as_ref(), self.thread_id, &goal).await;
let turn_id = self
.accounting_state
.mark_current_turn_goal_active(goal.goal_id.clone());
let goal = protocol_goal_from_state(goal);
self.emit_goal_updated_from_tool_call(&invocation, goal.clone());
self.emit_goal_updated_from_tool_call(&invocation, turn_id, goal.clone());
goal_response(Some(goal), CompletionBudgetReport::Omit)
}
@@ -189,15 +201,29 @@ impl GoalToolExecutor {
invocation: ToolCall,
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
let args: UpdateGoalArgs = parse_arguments(invocation.function_arguments()?)?;
if args.status != ThreadGoalStatus::Complete {
if !matches!(
args.status,
ThreadGoalStatus::Complete | ThreadGoalStatus::Blocked
) {
return Err(FunctionCallError::RespondToModel(
"update_goal can only mark the existing goal complete; pause, resume, and budget-limited status changes are controlled by the user or system"
"update_goal can only mark the existing goal complete or blocked; pause, resume, budget-limited, and usage-limited status changes are controlled by the user or system"
.to_string(),
));
}
// TODO: update_goal needs a host callback before completion to flush
// final active-turn accounting with budget steering suppressed.
self.account_active_goal_progress(
match args.status {
ThreadGoalStatus::Complete => codex_state::GoalAccountingMode::ActiveOrComplete,
ThreadGoalStatus::Blocked => codex_state::GoalAccountingMode::ActiveOrStopped,
ThreadGoalStatus::Active
| ThreadGoalStatus::Paused
| ThreadGoalStatus::UsageLimited
| ThreadGoalStatus::BudgetLimited => unreachable!("status validated above"),
},
invocation.call_id.as_str(),
BudgetLimitedGoalDisposition::ClearActive,
)
.await?;
let goal = self
.state_db
.thread_goals()
@@ -205,14 +231,14 @@ impl GoalToolExecutor {
self.thread_id,
codex_state::GoalUpdate {
objective: None,
status: Some(codex_state::ThreadGoalStatus::Complete),
status: Some(state_status_from_protocol(args.status)),
token_budget: None,
expected_goal_id: None,
},
)
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!("failed to complete goal: {err}"))
FunctionCallError::RespondToModel(format!("failed to update goal: {err}"))
})?
.map(protocol_goal_from_state)
.ok_or_else(|| {
@@ -220,19 +246,72 @@ impl GoalToolExecutor {
"cannot update goal because this thread has no goal".to_string(),
)
})?;
self.emit_goal_updated_from_tool_call(&invocation, goal.clone());
goal_response(Some(goal), CompletionBudgetReport::Include)
let turn_id = self.accounting_state.clear_current_turn_goal();
self.emit_goal_updated_from_tool_call(&invocation, turn_id, goal.clone());
goal_response(
Some(goal),
if args.status == ThreadGoalStatus::Complete {
CompletionBudgetReport::Include
} else {
CompletionBudgetReport::Omit
},
)
}
fn emit_goal_updated_from_tool_call(&self, invocation: &ToolCall, goal: ThreadGoal) {
// TODO: ToolCall should expose the current turn submission id so goal
// tool events can set ThreadGoalUpdatedEvent.turn_id exactly as core
// does today. Until then, correlate the event with the tool call id.
self.event_emitter.thread_goal_updated(
invocation.call_id.clone(),
/*turn_id*/ None,
goal,
);
fn emit_goal_updated_from_tool_call(
&self,
invocation: &ToolCall,
turn_id: Option<String>,
goal: ThreadGoal,
) {
self.event_emitter
.thread_goal_updated(invocation.call_id.clone(), turn_id, goal);
}
async fn account_active_goal_progress(
&self,
mode: codex_state::GoalAccountingMode,
event_id: &str,
budget_limited_goal_disposition: BudgetLimitedGoalDisposition,
) -> Result<Option<ThreadGoal>, FunctionCallError> {
let Some(turn_id) = self.accounting_state.current_turn_id() else {
return Ok(None);
};
let Some(snapshot) = self.accounting_state.progress_snapshot(turn_id.as_str()) else {
return Ok(None);
};
let outcome = self
.state_db
.thread_goals()
.account_thread_goal_usage(
self.thread_id,
snapshot.time_delta_seconds,
snapshot.token_delta,
mode,
Some(snapshot.expected_goal_id.as_str()),
)
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!("failed to account goal progress: {err}"))
})?;
Ok(match outcome {
codex_state::GoalAccountingOutcome::Updated(goal) => {
self.accounting_state.mark_progress_accounted_for_status(
turn_id.as_str(),
&snapshot,
goal.status,
budget_limited_goal_disposition,
);
let goal = protocol_goal_from_state(goal);
self.event_emitter.thread_goal_updated(
event_id.to_string(),
Some(turn_id),
goal.clone(),
);
Some(goal)
}
codex_state::GoalAccountingOutcome::Unchanged(_) => None,
})
}
}
@@ -298,7 +377,7 @@ async fn fill_empty_thread_preview_if_possible(
}
}
fn protocol_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadGoal {
pub(crate) fn protocol_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadGoal {
ThreadGoal {
thread_id: goal.thread_id,
objective: goal.objective,
@@ -322,6 +401,17 @@ fn protocol_status_from_state(status: codex_state::ThreadGoalStatus) -> ThreadGo
}
}
fn state_status_from_protocol(status: ThreadGoalStatus) -> codex_state::ThreadGoalStatus {
match status {
ThreadGoalStatus::Active => codex_state::ThreadGoalStatus::Active,
ThreadGoalStatus::Paused => codex_state::ThreadGoalStatus::Paused,
ThreadGoalStatus::Blocked => codex_state::ThreadGoalStatus::Blocked,
ThreadGoalStatus::UsageLimited => codex_state::ThreadGoalStatus::UsageLimited,
ThreadGoalStatus::BudgetLimited => codex_state::ThreadGoalStatus::BudgetLimited,
ThreadGoalStatus::Complete => codex_state::ThreadGoalStatus::Complete,
}
}
fn completion_budget_report(goal: &ThreadGoal) -> Option<String> {
if goal.token_budget.is_none() && goal.time_used_seconds <= 0 {
None
+68
View File
@@ -0,0 +1,68 @@
#![allow(dead_code)]
#[path = "../src/accounting.rs"]
mod accounting;
use accounting::GoalAccountingState;
use codex_protocol::config_types::ModeKind;
use codex_protocol::protocol::TokenUsage;
use pretty_assertions::assert_eq;
#[test]
fn goal_accounting_uses_turn_start_baseline_for_exact_deltas() {
let state = GoalAccountingState::default();
state.start_turn(
"turn-1",
ModeKind::Default,
&token_usage(
/*input_tokens*/ 100, /*cached_input_tokens*/ 10, /*output_tokens*/ 30,
/*reasoning_output_tokens*/ 5, /*total_tokens*/ 135,
),
);
let recorded = state
.record_token_usage(
"turn-1",
&token_usage(
/*input_tokens*/ 120, /*cached_input_tokens*/ 14,
/*output_tokens*/ 42, /*reasoning_output_tokens*/ 8,
/*total_tokens*/ 162,
),
)
.expect("token delta should be recorded");
assert_eq!(28, recorded.turn_delta);
assert_eq!(28, recorded.thread_unflushed_delta);
}
#[test]
fn goal_accounting_ignores_plan_mode_turns() {
let state = GoalAccountingState::default();
state.start_turn("turn-1", ModeKind::Plan, &TokenUsage::default());
let recorded = state.record_token_usage(
"turn-1",
&token_usage(
/*input_tokens*/ 20, /*cached_input_tokens*/ 5, /*output_tokens*/ 8,
/*reasoning_output_tokens*/ 2, /*total_tokens*/ 30,
),
);
assert_eq!(None, recorded);
}
fn token_usage(
input_tokens: i64,
cached_input_tokens: i64,
output_tokens: i64,
reasoning_output_tokens: i64,
total_tokens: i64,
) -> TokenUsage {
TokenUsage {
input_tokens,
cached_input_tokens,
output_tokens,
reasoning_output_tokens,
total_tokens,
}
}
@@ -1,16 +1,32 @@
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionEventSink;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::FunctionCallError;
use codex_extension_api::ThreadStartInput;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolCallOutcome;
use codex_extension_api::ToolCallSource;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolFinishInput;
use codex_extension_api::ToolName;
use codex_extension_api::ToolPayload;
use codex_extension_api::TurnStartInput;
use codex_extension_api::TurnStopInput;
use codex_goal_extension::install_with_backend;
use codex_protocol::ThreadId;
use codex_protocol::ToolName;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::Settings;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::ThreadGoalStatus;
use codex_protocol::protocol::TokenUsage;
use codex_protocol::protocol::TokenUsageInfo;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
@@ -70,7 +86,8 @@ async fn installed_goal_tools_reject_duplicate_goal_creation() -> anyhow::Result
let runtime = test_runtime().await?;
let thread_id = test_thread_id()?;
seed_thread_metadata(runtime.as_ref(), thread_id).await?;
let tools = installed_tools(runtime, thread_id).await;
let harness = GoalExtensionHarness::new(runtime, thread_id).await?;
let tools = harness.tools();
let create_tool = tool_by_name(&tools, "create_goal");
let first = tool_call(
@@ -100,6 +117,273 @@ async fn installed_goal_tools_reject_duplicate_goal_creation() -> anyhow::Result
Ok(())
}
#[tokio::test]
async fn create_goal_resets_baseline_before_turn_stop_accounting() -> anyhow::Result<()> {
let runtime = test_runtime().await?;
let thread_id = test_thread_id()?;
seed_thread_metadata(runtime.as_ref(), thread_id).await?;
let harness = GoalExtensionHarness::new(runtime.clone(), thread_id).await?;
harness
.start_turn(
"turn-1",
&token_usage(
/*input_tokens*/ 100, /*cached_input_tokens*/ 10,
/*output_tokens*/ 30, /*reasoning_output_tokens*/ 5,
/*total_tokens*/ 135,
),
)
.await;
harness
.record_token_usage(
"turn-1",
&token_usage(
/*input_tokens*/ 120, /*cached_input_tokens*/ 14,
/*output_tokens*/ 42, /*reasoning_output_tokens*/ 8,
/*total_tokens*/ 162,
),
)
.await;
let tools = harness.tools();
let create_tool = tool_by_name(&tools, "create_goal");
create_tool
.handle(tool_call(
"create_goal",
"call-create-goal",
json!({ "objective": "ship goal extension backend" }),
))
.await?;
harness
.record_token_usage(
"turn-1",
&token_usage(
/*input_tokens*/ 127, /*cached_input_tokens*/ 16,
/*output_tokens*/ 52, /*reasoning_output_tokens*/ 10,
/*total_tokens*/ 189,
),
)
.await;
harness.stop_turn("turn-1").await;
let goal = runtime
.thread_goals()
.get_thread_goal(thread_id)
.await?
.ok_or_else(|| anyhow::anyhow!("goal should exist"))?;
assert_eq!(15, goal.tokens_used);
assert_eq!(ThreadGoalStatus::Active, protocol_status(goal.status));
Ok(())
}
#[tokio::test]
async fn tool_finish_accounts_active_goal_progress_and_emits_event() -> anyhow::Result<()> {
let runtime = test_runtime().await?;
let thread_id = test_thread_id()?;
seed_thread_metadata(runtime.as_ref(), thread_id).await?;
let harness = GoalExtensionHarness::new(runtime.clone(), thread_id).await?;
harness.start_turn("turn-1", &TokenUsage::default()).await;
let tools = harness.tools();
let create_tool = tool_by_name(&tools, "create_goal");
create_tool
.handle(tool_call(
"create_goal",
"call-create-goal",
json!({ "objective": "ship goal extension backend" }),
))
.await?;
harness.sink.clear();
harness
.record_token_usage(
"turn-1",
&token_usage(
/*input_tokens*/ 20, /*cached_input_tokens*/ 5, /*output_tokens*/ 8,
/*reasoning_output_tokens*/ 2, /*total_tokens*/ 30,
),
)
.await;
harness
.notify_tool_finish("turn-1", "call-shell", "shell")
.await;
let goal = runtime
.thread_goals()
.get_thread_goal(thread_id)
.await?
.ok_or_else(|| anyhow::anyhow!("goal should exist"))?;
assert_eq!(23, goal.tokens_used);
assert_eq!(
vec![CapturedGoalEvent {
event_id: "call-shell".to_string(),
turn_id: Some("turn-1".to_string()),
status: ThreadGoalStatus::Active,
tokens_used: 23,
}],
harness.sink.goal_events()
);
Ok(())
}
#[tokio::test]
async fn budget_limited_goal_keeps_accruing_until_turn_stop() -> anyhow::Result<()> {
let runtime = test_runtime().await?;
let thread_id = test_thread_id()?;
seed_thread_metadata(runtime.as_ref(), thread_id).await?;
let harness = GoalExtensionHarness::new(runtime.clone(), thread_id).await?;
harness.start_turn("turn-1", &TokenUsage::default()).await;
let tools = harness.tools();
let create_tool = tool_by_name(&tools, "create_goal");
create_tool
.handle(tool_call(
"create_goal",
"call-create-goal",
json!({
"objective": "ship goal extension backend",
"token_budget": 25,
}),
))
.await?;
harness.sink.clear();
harness
.record_token_usage(
"turn-1",
&token_usage(
/*input_tokens*/ 20, /*cached_input_tokens*/ 5,
/*output_tokens*/ 10, /*reasoning_output_tokens*/ 0,
/*total_tokens*/ 30,
),
)
.await;
harness
.notify_tool_finish("turn-1", "call-shell", "shell")
.await;
harness
.record_token_usage(
"turn-1",
&token_usage(
/*input_tokens*/ 24, /*cached_input_tokens*/ 5,
/*output_tokens*/ 16, /*reasoning_output_tokens*/ 0,
/*total_tokens*/ 40,
),
)
.await;
harness.stop_turn("turn-1").await;
let goal = runtime
.thread_goals()
.get_thread_goal(thread_id)
.await?
.ok_or_else(|| anyhow::anyhow!("goal should exist"))?;
assert_eq!(35, goal.tokens_used);
assert_eq!(codex_state::ThreadGoalStatus::BudgetLimited, goal.status);
assert_eq!(
vec![
CapturedGoalEvent {
event_id: "call-shell".to_string(),
turn_id: Some("turn-1".to_string()),
status: ThreadGoalStatus::BudgetLimited,
tokens_used: 25,
},
CapturedGoalEvent {
event_id: "turn-1:turn-stop".to_string(),
turn_id: Some("turn-1".to_string()),
status: ThreadGoalStatus::BudgetLimited,
tokens_used: 35,
},
],
harness.sink.goal_events()
);
Ok(())
}
#[tokio::test]
async fn update_goal_can_block_and_accounts_final_progress() -> anyhow::Result<()> {
let runtime = test_runtime().await?;
let thread_id = test_thread_id()?;
seed_thread_metadata(runtime.as_ref(), thread_id).await?;
let harness = GoalExtensionHarness::new(runtime.clone(), thread_id).await?;
harness.start_turn("turn-1", &TokenUsage::default()).await;
let tools = harness.tools();
let create_tool = tool_by_name(&tools, "create_goal");
create_tool
.handle(tool_call(
"create_goal",
"call-create-goal",
json!({ "objective": "ship goal extension backend" }),
))
.await?;
harness.sink.clear();
harness
.record_token_usage(
"turn-1",
&token_usage(
/*input_tokens*/ 20, /*cached_input_tokens*/ 5, /*output_tokens*/ 8,
/*reasoning_output_tokens*/ 2, /*total_tokens*/ 30,
),
)
.await;
let update_tool = tool_by_name(&tools, "update_goal");
let invocation = tool_call(
"update_goal",
"call-update-goal",
json!({ "status": "blocked" }),
);
let output = update_tool.handle(invocation.clone()).await?;
let result = output.code_mode_result(&invocation.payload);
assert_eq!(
result,
json!({
"goal": {
"threadId": thread_id,
"objective": "ship goal extension backend",
"status": "blocked",
"tokensUsed": 23,
"timeUsedSeconds": 0,
"createdAt": result["goal"]["createdAt"],
"updatedAt": result["goal"]["updatedAt"],
},
"remainingTokens": serde_json::Value::Null,
"completionBudgetReport": serde_json::Value::Null,
})
);
let goal = runtime
.thread_goals()
.get_thread_goal(thread_id)
.await?
.ok_or_else(|| anyhow::anyhow!("goal should exist"))?;
assert_eq!(23, goal.tokens_used);
assert_eq!(codex_state::ThreadGoalStatus::Blocked, goal.status);
assert_eq!(
vec![
CapturedGoalEvent {
event_id: "call-update-goal".to_string(),
turn_id: Some("turn-1".to_string()),
status: ThreadGoalStatus::Active,
tokens_used: 23,
},
CapturedGoalEvent {
event_id: "call-update-goal".to_string(),
turn_id: Some("turn-1".to_string()),
status: ThreadGoalStatus::Blocked,
tokens_used: 23,
},
],
harness.sink.goal_events()
);
Ok(())
}
async fn installed_tools(
runtime: Arc<codex_state::StateRuntime>,
thread_id: ThreadId,
@@ -126,6 +410,118 @@ async fn installed_tools(
.collect()
}
struct GoalExtensionHarness {
registry: codex_extension_api::ExtensionRegistry<()>,
session_store: ExtensionData,
thread_store: ExtensionData,
sink: Arc<RecordingEventSink>,
}
impl GoalExtensionHarness {
async fn new(
runtime: Arc<codex_state::StateRuntime>,
thread_id: ThreadId,
) -> anyhow::Result<Self> {
let sink = Arc::new(RecordingEventSink::default());
let mut builder = ExtensionRegistryBuilder::<()>::with_event_sink(sink.clone());
install_with_backend(&mut builder, runtime, |_| true);
let registry = builder.build();
let session_store = ExtensionData::new("session-1");
let thread_store = ExtensionData::new(thread_id.to_string());
for contributor in registry.thread_lifecycle_contributors() {
contributor
.on_thread_start(ThreadStartInput {
config: &(),
session_store: &session_store,
thread_store: &thread_store,
})
.await;
}
Ok(Self {
registry,
session_store,
thread_store,
sink,
})
}
fn tools(&self) -> Vec<Arc<dyn ToolExecutor<ToolCall>>> {
self.registry
.tool_contributors()
.iter()
.flat_map(|contributor| contributor.tools(&self.session_store, &self.thread_store))
.collect()
}
async fn start_turn(&self, turn_id: &str, usage: &TokenUsage) {
let turn_store = ExtensionData::new(turn_id);
let collaboration_mode = default_collaboration_mode();
for contributor in self.registry.turn_lifecycle_contributors() {
contributor
.on_turn_start(TurnStartInput {
turn_id,
collaboration_mode: &collaboration_mode,
token_usage_at_turn_start: usage,
session_store: &self.session_store,
thread_store: &self.thread_store,
turn_store: &turn_store,
})
.await;
}
}
async fn stop_turn(&self, turn_id: &str) {
let turn_store = ExtensionData::new(turn_id);
for contributor in self.registry.turn_lifecycle_contributors() {
contributor
.on_turn_stop(TurnStopInput {
session_store: &self.session_store,
thread_store: &self.thread_store,
turn_store: &turn_store,
})
.await;
}
}
async fn record_token_usage(&self, turn_id: &str, usage: &TokenUsage) {
let turn_store = ExtensionData::new(turn_id);
let token_usage = TokenUsageInfo {
total_token_usage: usage.clone(),
last_token_usage: TokenUsage::default(),
model_context_window: None,
};
for contributor in self.registry.token_usage_contributors() {
contributor
.on_token_usage(
&self.session_store,
&self.thread_store,
&turn_store,
&token_usage,
)
.await;
}
}
async fn notify_tool_finish(&self, turn_id: &str, call_id: &str, tool_name: &str) {
let turn_store = ExtensionData::new(turn_id);
let tool_name = codex_extension_api::ToolName::plain(tool_name);
for contributor in self.registry.tool_lifecycle_contributors() {
contributor
.on_tool_finish(ToolFinishInput {
session_store: &self.session_store,
thread_store: &self.thread_store,
turn_store: &turn_store,
turn_id,
call_id,
tool_name: &tool_name,
source: ToolCallSource::Direct,
outcome: ToolCallOutcome::Completed { success: true },
})
.await;
}
}
}
fn tool_by_name<'a>(
tools: &'a [Arc<dyn ToolExecutor<ToolCall>>],
name: &str,
@@ -139,7 +535,7 @@ fn tool_by_name<'a>(
fn tool_call(tool_name: &str, call_id: &str, arguments: serde_json::Value) -> ToolCall {
ToolCall {
call_id: call_id.to_string(),
tool_name: ToolName::plain(tool_name),
tool_name: codex_extension_api::ToolName::plain(tool_name),
payload: ToolPayload::Function {
arguments: arguments.to_string(),
},
@@ -169,3 +565,85 @@ async fn seed_thread_metadata(
);
runtime.upsert_thread(&builder.build("test-provider")).await
}
#[derive(Debug, Default)]
struct RecordingEventSink {
events: Mutex<Vec<Event>>,
}
impl RecordingEventSink {
fn goal_events(&self) -> Vec<CapturedGoalEvent> {
self.events()
.iter()
.filter_map(|event| match &event.msg {
EventMsg::ThreadGoalUpdated(updated) => Some(CapturedGoalEvent {
event_id: event.id.clone(),
turn_id: updated.turn_id.clone(),
status: updated.goal.status,
tokens_used: updated.goal.tokens_used,
}),
_ => None,
})
.collect()
}
fn clear(&self) {
self.events().clear();
}
fn events(&self) -> std::sync::MutexGuard<'_, Vec<Event>> {
self.events.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl ExtensionEventSink for RecordingEventSink {
fn emit(&self, event: Event) {
self.events().push(event);
}
}
#[derive(Debug, PartialEq, Eq)]
struct CapturedGoalEvent {
event_id: String,
turn_id: Option<String>,
status: ThreadGoalStatus,
tokens_used: i64,
}
fn default_collaboration_mode() -> CollaborationMode {
CollaborationMode {
mode: ModeKind::Default,
settings: Settings {
model: "gpt-5".to_string(),
reasoning_effort: None,
developer_instructions: None,
},
}
}
fn token_usage(
input_tokens: i64,
cached_input_tokens: i64,
output_tokens: i64,
reasoning_output_tokens: i64,
total_tokens: i64,
) -> TokenUsage {
TokenUsage {
input_tokens,
cached_input_tokens,
output_tokens,
reasoning_output_tokens,
total_tokens,
}
}
fn protocol_status(status: codex_state::ThreadGoalStatus) -> ThreadGoalStatus {
match status {
codex_state::ThreadGoalStatus::Active => ThreadGoalStatus::Active,
codex_state::ThreadGoalStatus::Paused => ThreadGoalStatus::Paused,
codex_state::ThreadGoalStatus::Blocked => ThreadGoalStatus::Blocked,
codex_state::ThreadGoalStatus::UsageLimited => ThreadGoalStatus::UsageLimited,
codex_state::ThreadGoalStatus::BudgetLimited => ThreadGoalStatus::BudgetLimited,
codex_state::ThreadGoalStatus::Complete => ThreadGoalStatus::Complete,
}
}
+71 -5
View File
@@ -124,7 +124,7 @@ impl InstallContext {
&& let Some(path_dir) = &package_layout.path_dir
{
let bundled_rg = path_dir.join(default_rg_command());
if bundled_rg.exists() {
if bundled_rg.is_file() {
return bundled_rg.into_path_buf();
}
}
@@ -135,13 +135,37 @@ impl InstallContext {
} = &self.method
{
let bundled_rg = resources_dir.join(default_rg_command());
if bundled_rg.exists() {
if bundled_rg.is_file() {
return bundled_rg.into_path_buf();
}
}
default_rg_command()
}
pub fn bundled_resource(&self, file_name: impl AsRef<Path>) -> Option<AbsolutePathBuf> {
if let Some(package_layout) = &self.package_layout
&& let Some(resources_dir) = &package_layout.resources_dir
{
let resource = resources_dir.join(file_name.as_ref());
if resource.is_file() {
return Some(resource);
}
}
if let InstallMethod::Standalone {
resources_dir: Some(resources_dir),
..
} = &self.method
{
let resource = resources_dir.join(file_name);
if resource.is_file() {
return Some(resource);
}
}
None
}
}
impl CodexPackageLayout {
@@ -242,6 +266,8 @@ mod tests {
use pretty_assertions::assert_eq;
use std::fs;
const TEST_RESOURCE_NAME: &str = "codex-test-helper";
#[test]
fn detects_standalone_install_from_release_layout() -> std::io::Result<()> {
let codex_home = tempfile::tempdir()?;
@@ -253,6 +279,7 @@ mod tests {
let exe_path = release_dir.join(if cfg!(windows) { "codex.exe" } else { "codex" });
fs::write(&exe_path, "")?;
fs::write(resources_dir.join(default_rg_command()), "")?;
fs::write(resources_dir.join(TEST_RESOURCE_NAME), "")?;
let canonical_release_dir =
AbsolutePathBuf::from_absolute_path(release_dir.canonicalize()?)?;
let canonical_resources_dir =
@@ -270,12 +297,16 @@ mod tests {
InstallContext {
method: InstallMethod::Standalone {
release_dir: canonical_release_dir,
resources_dir: Some(canonical_resources_dir),
resources_dir: Some(canonical_resources_dir.clone()),
platform: standalone_platform(),
},
package_layout: None,
}
);
assert_eq!(
context.bundled_resource(TEST_RESOURCE_NAME),
Some(canonical_resources_dir.join(TEST_RESOURCE_NAME))
);
Ok(())
}
@@ -312,6 +343,7 @@ mod tests {
fs::write(package_dir.path().join(PACKAGE_METADATA_FILENAME), "{}")?;
let exe_path = bin_dir.join(if cfg!(windows) { "codex.exe" } else { "codex" });
fs::write(&exe_path, "")?;
fs::write(resources_dir.join(TEST_RESOURCE_NAME), "")?;
fs::write(path_dir.join(default_rg_command()), "")?;
let canonical_package_dir =
AbsolutePathBuf::from_absolute_path(package_dir.path().canonicalize()?)?;
@@ -322,7 +354,7 @@ mod tests {
let package_layout = CodexPackageLayout {
package_dir: canonical_package_dir,
bin_dir: canonical_bin_dir,
resources_dir: Some(canonical_resources_dir),
resources_dir: Some(canonical_resources_dir.clone()),
path_dir: Some(canonical_path_dir.clone()),
};
@@ -346,6 +378,10 @@ mod tests {
.join(default_rg_command())
.into_path_buf()
);
assert_eq!(
context.bundled_resource(TEST_RESOURCE_NAME),
Some(canonical_resources_dir.join(TEST_RESOURCE_NAME))
);
Ok(())
}
@@ -364,6 +400,7 @@ mod tests {
fs::write(package_dir.join(PACKAGE_METADATA_FILENAME), "{}")?;
let exe_path = bin_dir.join(if cfg!(windows) { "codex.exe" } else { "codex" });
fs::write(&exe_path, "")?;
fs::write(resources_dir.join(TEST_RESOURCE_NAME), "")?;
fs::write(path_dir.join(default_rg_command()), "")?;
let canonical_package_dir =
AbsolutePathBuf::from_absolute_path(package_dir.canonicalize()?)?;
@@ -390,7 +427,7 @@ mod tests {
package_layout: Some(CodexPackageLayout {
package_dir: canonical_package_dir,
bin_dir: canonical_bin_dir,
resources_dir: Some(canonical_resources_dir),
resources_dir: Some(canonical_resources_dir.clone()),
path_dir: Some(canonical_path_dir.clone()),
}),
}
@@ -401,6 +438,10 @@ mod tests {
.join(default_rg_command())
.into_path_buf()
);
assert_eq!(
context.bundled_resource(TEST_RESOURCE_NAME),
Some(canonical_resources_dir.join(TEST_RESOURCE_NAME))
);
Ok(())
}
@@ -455,6 +496,31 @@ mod tests {
Ok(())
}
#[test]
fn bundled_file_lookups_ignore_directories() -> std::io::Result<()> {
let package_dir = tempfile::tempdir()?;
let bin_dir = package_dir.path().join(BIN_DIRNAME);
let resources_dir = package_dir.path().join(RESOURCES_DIRNAME);
let path_dir = package_dir.path().join(PATH_DIRNAME);
fs::create_dir_all(&bin_dir)?;
fs::create_dir_all(resources_dir.join(TEST_RESOURCE_NAME))?;
fs::create_dir_all(path_dir.join(default_rg_command()))?;
fs::write(package_dir.path().join(PACKAGE_METADATA_FILENAME), "{}")?;
let exe_path = bin_dir.join(if cfg!(windows) { "codex.exe" } else { "codex" });
fs::write(&exe_path, "")?;
let context = InstallContext::from_exe_with_codex_home(
/*is_macos*/ false,
/*current_exe*/ Some(&exe_path),
/*managed_by_npm*/ false,
/*managed_by_bun*/ false,
/*codex_home*/ None,
);
assert_eq!(context.rg_command(), default_rg_command());
assert_eq!(context.bundled_resource(TEST_RESOURCE_NAME), None);
Ok(())
}
#[test]
fn npm_and_bun_take_precedence() {
let npm_context = InstallContext::from_exe_with_codex_home(
+1
View File
@@ -18,6 +18,7 @@ workspace = true
[target.'cfg(target_os = "linux")'.dependencies]
clap = { workspace = true, features = ["derive"] }
codex-install-context = { workspace = true }
codex-process-hardening = { workspace = true }
codex-protocol = { workspace = true }
codex-sandboxing = { workspace = true }
+48 -8
View File
@@ -12,6 +12,7 @@ use std::sync::OnceLock;
use crate::bazel_bwrap;
use crate::exec_util::argv_to_cstrings;
use crate::exec_util::make_files_inheritable;
use codex_install_context::InstallContext;
use codex_utils_absolute_path::AbsolutePathBuf;
use sha2::Digest as _;
use sha2::Sha256;
@@ -26,7 +27,9 @@ pub(crate) struct BundledBwrapLauncher {
pub(crate) fn launcher() -> Option<BundledBwrapLauncher> {
let current_exe = std::env::current_exe().ok()?;
find_for_exe(&current_exe).map(|program| BundledBwrapLauncher { program })
find_for_install_context(InstallContext::current())
.or_else(|| find_legacy_for_exe(&current_exe))
.map(|program| BundledBwrapLauncher { program })
}
impl BundledBwrapLauncher {
@@ -66,8 +69,14 @@ impl BundledBwrapLauncher {
}
}
fn find_for_exe(exe: &Path) -> Option<AbsolutePathBuf> {
candidates_for_exe(exe)
fn find_for_install_context(context: &InstallContext) -> Option<AbsolutePathBuf> {
context
.bundled_resource("bwrap")
.filter(|path| is_executable_file(path))
}
fn find_legacy_for_exe(exe: &Path) -> Option<AbsolutePathBuf> {
legacy_candidates_for_exe(exe)
.into_iter()
.find(|candidate| is_executable_file(candidate))
.map(|path| {
@@ -80,7 +89,7 @@ fn find_for_exe(exe: &Path) -> Option<AbsolutePathBuf> {
})
}
fn candidates_for_exe(exe: &Path) -> Vec<PathBuf> {
fn legacy_candidates_for_exe(exe: &Path) -> Vec<PathBuf> {
let Some(exe_dir) = exe.parent() else {
return Vec::new();
};
@@ -180,13 +189,44 @@ fn bytes_to_hex(bytes: &[u8; 32]) -> String {
#[cfg(test)]
mod tests {
use super::*;
use codex_install_context::CodexPackageLayout;
use codex_install_context::InstallContext;
use codex_install_context::InstallMethod;
use pretty_assertions::assert_eq;
use std::fs;
use tempfile::NamedTempFile;
use tempfile::tempdir;
#[test]
fn finds_standalone_bundled_bwrap_next_to_exe_resources() {
fn finds_package_layout_bwrap_from_install_context() {
let temp_dir = tempdir().expect("temp dir");
let package_dir = temp_dir.path();
let bin_dir = package_dir.join("bin");
let resources_dir = package_dir.join("codex-resources");
let expected_bwrap = resources_dir.join("bwrap");
fs::create_dir_all(&bin_dir).expect("create bin dir");
write_executable(&expected_bwrap);
let context = InstallContext {
method: InstallMethod::Other,
package_layout: Some(CodexPackageLayout {
package_dir: AbsolutePathBuf::from_absolute_path(package_dir).expect("absolute"),
bin_dir: AbsolutePathBuf::from_absolute_path(&bin_dir).expect("absolute"),
resources_dir: Some(
AbsolutePathBuf::from_absolute_path(&resources_dir).expect("absolute"),
),
path_dir: None,
}),
};
assert_eq!(
find_for_install_context(&context),
Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute"))
);
}
#[test]
fn finds_legacy_standalone_bundled_bwrap_next_to_exe_resources() {
let temp_dir = tempdir().expect("temp dir");
let exe = temp_dir.path().join("codex");
let expected_bwrap = temp_dir.path().join("codex-resources").join("bwrap");
@@ -194,7 +234,7 @@ mod tests {
write_executable(&expected_bwrap);
assert_eq!(
find_for_exe(&exe),
find_legacy_for_exe(&exe),
Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute"))
);
}
@@ -209,7 +249,7 @@ mod tests {
write_executable(&expected_bwrap);
assert_eq!(
find_for_exe(&exe),
find_legacy_for_exe(&exe),
Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute"))
);
}
@@ -223,7 +263,7 @@ mod tests {
write_executable(&expected_bwrap);
assert_eq!(
find_for_exe(&exe),
find_legacy_for_exe(&exe),
Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute"))
);
}
@@ -7699,6 +7699,114 @@ mod tests {
}
}
#[test]
fn slash_popup_btw_for_bt_ui() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let (tx, _rx) = unbounded_channel::<AppEvent>();
let sender = AppEventSender::new(tx);
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
sender,
/*enhanced_keys_supported*/ false,
"Ask Codex to do anything".to_string(),
/*disable_paste_burst*/ false,
);
type_chars_humanlike(&mut composer, &['/', 'b', 't']);
let mut terminal = Terminal::new(TestBackend::new(60, 5)).expect("terminal");
terminal
.draw(|f| composer.render(f.area(), f.buffer_mut()))
.expect("draw composer");
insta::assert_snapshot!("slash_popup_bt", terminal.backend());
}
#[test]
fn slash_popup_btw_for_bt_logic() {
use super::super::command_popup::CommandItem;
let (tx, _rx) = unbounded_channel::<AppEvent>();
let sender = AppEventSender::new(tx);
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
sender,
/*enhanced_keys_supported*/ false,
"Ask Codex to do anything".to_string(),
/*disable_paste_burst*/ false,
);
type_chars_humanlike(&mut composer, &['/', 'b', 't']);
match &composer.popups.active {
ActivePopup::Command(popup) => match popup.selected_item() {
Some(CommandItem::Builtin(cmd)) => {
assert_eq!(cmd.command(), "btw")
}
Some(CommandItem::ServiceTier(command)) => {
panic!("expected btw command, got service tier {command:?}")
}
None => panic!("no selected command for '/bt'"),
},
_ => panic!("slash popup not active after typing '/bt'"),
}
}
#[test]
fn slash_popup_side_for_si_ui() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let (tx, _rx) = unbounded_channel::<AppEvent>();
let sender = AppEventSender::new(tx);
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
sender,
/*enhanced_keys_supported*/ false,
"Ask Codex to do anything".to_string(),
/*disable_paste_burst*/ false,
);
type_chars_humanlike(&mut composer, &['/', 's', 'i']);
let mut terminal = Terminal::new(TestBackend::new(60, 5)).expect("terminal");
terminal
.draw(|f| composer.render(f.area(), f.buffer_mut()))
.expect("draw composer");
insta::assert_snapshot!("slash_popup_si", terminal.backend());
}
#[test]
fn slash_popup_side_for_si_logic() {
use super::super::command_popup::CommandItem;
let (tx, _rx) = unbounded_channel::<AppEvent>();
let sender = AppEventSender::new(tx);
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
sender,
/*enhanced_keys_supported*/ false,
"Ask Codex to do anything".to_string(),
/*disable_paste_burst*/ false,
);
type_chars_humanlike(&mut composer, &['/', 's', 'i']);
match &composer.popups.active {
ActivePopup::Command(popup) => match popup.selected_item() {
Some(CommandItem::Builtin(cmd)) => {
assert_eq!(cmd.command(), "side")
}
Some(CommandItem::ServiceTier(command)) => {
panic!("expected side command, got service tier {command:?}")
}
None => panic!("no selected command for '/si'"),
},
_ => panic!("slash popup not active after typing '/si'"),
}
}
#[test]
fn service_tier_slash_command_dispatches_from_catalog_name() {
let (tx, _rx) = unbounded_channel::<AppEvent>();
+15 -2
View File
@@ -18,8 +18,9 @@ use crate::render::RectExt;
use crate::slash_command::SlashCommand;
// Hide alias commands in the default popup list so each unique action appears once.
// `quit` is an alias of `exit`, so we skip `quit` here.
const ALIAS_COMMANDS: &[SlashCommand] = &[SlashCommand::Quit];
// `quit` is an alias of `exit`, and `btw` is an alias of `side`, so we skip
// those aliases here.
const ALIAS_COMMANDS: &[SlashCommand] = &[SlashCommand::Quit, SlashCommand::Btw];
const COMMAND_COLUMN_WIDTH: ColumnWidthConfig = ColumnWidthConfig::new(
ColumnWidthMode::AutoAllRows,
/*name_column_width*/ None,
@@ -418,6 +419,18 @@ mod tests {
assert!(items.contains(&CommandItem::Builtin(SlashCommand::Quit)));
}
#[test]
fn btw_hidden_in_empty_filter_but_shown_for_prefix() {
let mut popup = CommandPopup::new(CommandPopupFlags::default(), Vec::new());
popup.on_composer_text_change("/".to_string());
let items = popup.filtered_items();
assert!(!items.contains(&CommandItem::Builtin(SlashCommand::Btw)));
popup.on_composer_text_change("/bt".to_string());
let items = popup.filtered_items();
assert!(items.contains(&CommandItem::Builtin(SlashCommand::Btw)));
}
#[test]
fn plan_command_hidden_when_collaboration_modes_disabled() {
let mut popup = CommandPopup::new(CommandPopupFlags::default(), Vec::new());
@@ -0,0 +1,9 @@
---
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" "
"› /bt "
" "
" "
" /btw start a side conversation in an ephemeral fork "
@@ -0,0 +1,9 @@
---
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" "
"› /si "
" "
" "
" /side start a side conversation in an ephemeral fork "
+18 -12
View File
@@ -30,8 +30,6 @@ struct PreparedSlashCommandArgs {
}
const SIDE_STARTING_CONTEXT_LABEL: &str = "Side starting...";
const SIDE_REVIEW_UNAVAILABLE_MESSAGE: &str =
"'/side' is unavailable while code review is running.";
const SIDE_SLASH_COMMAND_UNAVAILABLE_HINT: &str =
"Press Ctrl+C to return to the main thread first.";
const GOAL_USAGE: &str = "Usage: /goal <objective>";
@@ -114,9 +112,12 @@ impl ChatWidget {
});
}
fn request_empty_side_conversation(&mut self) {
fn request_empty_side_conversation(&mut self, cmd: SlashCommand) {
let Some(parent_thread_id) = self.thread_id else {
self.add_error_message("'/side' is unavailable before the session starts.".to_string());
let command = cmd.command();
self.add_error_message(format!(
"'/{command}' is unavailable before the session starts."
));
return;
};
@@ -239,8 +240,8 @@ impl ChatWidget {
);
}
}
SlashCommand::Side => {
self.request_empty_side_conversation();
SlashCommand::Side | SlashCommand::Btw => {
self.request_empty_side_conversation(cmd);
}
SlashCommand::Agent | SlashCommand::MultiAgents => {
self.app_event_tx.send(AppEvent::OpenAgentPicker);
@@ -745,11 +746,12 @@ impl ChatWidget {
self.bottom_pane.drain_pending_submission_state();
}
}
SlashCommand::Side if !trimmed.is_empty() => {
SlashCommand::Side | SlashCommand::Btw if !trimmed.is_empty() => {
let Some(parent_thread_id) = self.thread_id else {
self.add_error_message(
"'/side' is unavailable before the session starts.".to_string(),
);
let command = cmd.command();
self.add_error_message(format!(
"'/{command}' is unavailable before the session starts."
));
return;
};
let user_message = self.prepared_inline_user_message(
@@ -957,6 +959,7 @@ impl ChatWidget {
| SlashCommand::Plan
| SlashCommand::Goal
| SlashCommand::Side
| SlashCommand::Btw
| SlashCommand::Keymap
| SlashCommand::Agent
| SlashCommand::MultiAgents
@@ -1017,11 +1020,14 @@ impl ChatWidget {
}
fn ensure_side_command_allowed_outside_review(&mut self, cmd: SlashCommand) -> bool {
if cmd != SlashCommand::Side || !self.review.is_review_mode {
if !matches!(cmd, SlashCommand::Side | SlashCommand::Btw) || !self.review.is_review_mode {
return true;
}
self.add_error_message(SIDE_REVIEW_UNAVAILABLE_MESSAGE.to_string());
let command = cmd.command();
self.add_error_message(format!(
"'/{command}' is unavailable while code review is running."
));
self.bottom_pane.drain_pending_submission_state();
false
}
+113
View File
@@ -173,6 +173,59 @@ async fn slash_side_is_rejected_during_review_mode() {
);
}
#[tokio::test]
async fn slash_btw_is_rejected_during_review_mode() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.review.is_review_mode = true;
chat.dispatch_command(SlashCommand::Btw);
let event = rx
.try_recv()
.expect("expected review-mode btw conversation error");
match event {
AppEvent::InsertHistoryCell(cell) => {
let rendered = lines_to_single_string(&cell.display_lines(/*width*/ 80));
assert!(
rendered.contains("'/btw' is unavailable while code review is running."),
"expected review-mode btw conversation error, got {rendered:?}"
);
}
other => panic!("expected InsertHistoryCell error, got {other:?}"),
}
assert!(rx.try_recv().is_err(), "expected no follow-up events");
assert!(
op_rx.try_recv().is_err(),
"expected no side conversation op"
);
}
#[tokio::test]
async fn slash_btw_is_rejected_before_the_session_starts() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.dispatch_command(SlashCommand::Btw);
let event = rx
.try_recv()
.expect("expected pre-session btw conversation error");
match event {
AppEvent::InsertHistoryCell(cell) => {
let rendered = lines_to_single_string(&cell.display_lines(/*width*/ 80));
assert!(
rendered.contains("'/btw' is unavailable before the session starts."),
"expected pre-session btw conversation error, got {rendered:?}"
);
}
other => panic!("expected InsertHistoryCell error, got {other:?}"),
}
assert!(rx.try_recv().is_err(), "expected no follow-up events");
assert!(
op_rx.try_recv().is_err(),
"expected no side conversation op"
);
}
#[tokio::test]
async fn submit_user_message_as_plain_user_turn_does_not_run_shell_commands() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
@@ -219,6 +272,31 @@ async fn slash_side_without_args_starts_empty_side_conversation() {
assert!(chat.input_queue.queued_user_messages.is_empty());
}
#[tokio::test]
async fn slash_btw_without_args_starts_empty_side_conversation() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let parent_thread_id = ThreadId::new();
chat.thread_id = Some(parent_thread_id);
chat.on_task_started();
chat.bottom_pane
.set_composer_text("/btw".to_string(), Vec::new(), Vec::new());
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_matches!(
rx.try_recv(),
Ok(AppEvent::StartSide {
parent_thread_id: emitted_parent_thread_id,
user_message: None,
}) if emitted_parent_thread_id == parent_thread_id
);
assert!(
op_rx.try_recv().is_err(),
"bare /btw should not submit an op on the parent thread"
);
assert!(chat.input_queue.queued_user_messages.is_empty());
}
#[tokio::test]
async fn slash_side_requests_forked_side_question_while_task_running() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
@@ -268,6 +346,41 @@ async fn slash_side_requests_forked_side_question_while_task_running() {
);
}
#[tokio::test]
async fn slash_btw_requests_forked_side_question_while_task_running() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let parent_thread_id = ThreadId::new();
chat.thread_id = Some(parent_thread_id);
chat.on_task_started();
chat.bottom_pane.set_composer_text(
"/btw explore the codebase".to_string(),
Vec::new(),
Vec::new(),
);
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_matches!(
rx.try_recv(),
Ok(AppEvent::StartSide {
parent_thread_id: emitted_parent_thread_id,
user_message: Some(user_message),
}) if emitted_parent_thread_id == parent_thread_id
&& user_message
== UserMessage {
text: "explore the codebase".to_string(),
local_images: Vec::new(),
remote_image_urls: Vec::new(),
text_elements: Vec::new(),
mention_bindings: Vec::new(),
}
);
assert!(
op_rx.try_recv().is_err(),
"expected no op on the parent thread"
);
}
#[tokio::test]
async fn side_context_label_preserves_status_line_snapshot() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
+7 -2
View File
@@ -38,6 +38,7 @@ pub enum SlashCommand {
Goal,
Agent,
Side,
Btw,
Copy,
Raw,
Diff,
@@ -114,7 +115,9 @@ impl SlashCommand {
SlashCommand::Plan => "switch to Plan mode",
SlashCommand::Goal => "set or view the goal for a long-running task",
SlashCommand::Agent | SlashCommand::MultiAgents => "switch the active agent thread",
SlashCommand::Side => "start a side conversation in an ephemeral fork",
SlashCommand::Side | SlashCommand::Btw => {
"start a side conversation in an ephemeral fork"
}
SlashCommand::Permissions => "choose what Codex is allowed to do",
SlashCommand::Keymap => "remap TUI shortcuts",
SlashCommand::Vim => "toggle Vim mode for the composer",
@@ -154,6 +157,7 @@ impl SlashCommand {
| SlashCommand::Raw
| SlashCommand::Pets
| SlashCommand::Side
| SlashCommand::Btw
| SlashCommand::Resume
| SlashCommand::SandboxReadRoot
)
@@ -217,7 +221,8 @@ impl SlashCommand {
| SlashCommand::Ide
| SlashCommand::Quit
| SlashCommand::Exit
| SlashCommand::Side => true,
| SlashCommand::Side
| SlashCommand::Btw => true,
SlashCommand::Rollout => true,
SlashCommand::TestApproval => true,
SlashCommand::Realtime => true,