Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
423 lines
15 KiB
Rust
423 lines
15 KiB
Rust
use super::*;
|
|
use async_channel::bounded;
|
|
use akode_extension_api::ExtensionFuture;
|
|
use akode_extension_api::ExtensionRegistryBuilder;
|
|
use akode_extension_api::ThreadLifecycleContributor;
|
|
use akode_extension_api::ThreadStartInput;
|
|
use akode_protocol::capabilities::CapabilityRootLocation;
|
|
use akode_protocol::capabilities::SelectedCapabilityRoot;
|
|
use akode_protocol::error::CodexErrorDetails;
|
|
use akode_protocol::models::ResponseItem;
|
|
use akode_protocol::protocol::AgentStatus;
|
|
use akode_protocol::protocol::EventMsg;
|
|
use akode_protocol::protocol::McpStartupCompleteEvent;
|
|
use akode_protocol::protocol::McpStartupStatus;
|
|
use akode_protocol::protocol::McpStartupUpdateEvent;
|
|
use akode_protocol::protocol::RawResponseItemEvent;
|
|
use akode_protocol::protocol::TurnAbortReason;
|
|
use akode_protocol::protocol::TurnAbortedEvent;
|
|
use akode_protocol::protocol::TurnEnvironmentSelection;
|
|
use futures::FutureExt;
|
|
use pretty_assertions::assert_eq;
|
|
use std::sync::Arc;
|
|
use std::sync::atomic::AtomicUsize;
|
|
use std::sync::atomic::Ordering;
|
|
use tokio::sync::watch;
|
|
use tokio::time::timeout;
|
|
|
|
struct ThreadStartRecorder(Arc<AtomicUsize>);
|
|
|
|
impl ThreadLifecycleContributor<Config> for ThreadStartRecorder {
|
|
fn on_thread_start<'a>(
|
|
&'a self,
|
|
_input: ThreadStartInput<'a, Config>,
|
|
) -> ExtensionFuture<'a, ()> {
|
|
self.0.fetch_add(1, Ordering::SeqCst);
|
|
Box::pin(std::future::ready(()))
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn forward_events_filters_private_events_before_blocked_send_is_cancelled() {
|
|
let (tx_events, rx_events) = bounded(SUBMISSION_CHANNEL_CAPACITY);
|
|
let (tx_sub, rx_sub) = bounded(SUBMISSION_CHANNEL_CAPACITY);
|
|
let (_agent_status_tx, agent_status) = watch::channel(AgentStatus::PendingInit);
|
|
let io = Arc::new(SessionIo {
|
|
tx_sub,
|
|
rx_event: rx_events,
|
|
agent_status,
|
|
session_loop_termination: completed_session_loop_termination(),
|
|
});
|
|
|
|
let (tx_out, rx_out) = bounded(1);
|
|
tx_out
|
|
.send(Event {
|
|
id: "full".to_string(),
|
|
msg: EventMsg::TurnAborted(TurnAbortedEvent {
|
|
root_turn_id: None,
|
|
turn_id: Some("turn-1".to_string()),
|
|
started_at: None,
|
|
reason: TurnAbortReason::Interrupted,
|
|
error: None,
|
|
completed_at: None,
|
|
duration_ms: None,
|
|
}),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
|
|
let cancel = CancellationToken::new();
|
|
let forward = tokio::spawn(forward_events(
|
|
Arc::clone(&io),
|
|
tx_out.clone(),
|
|
cancel.clone(),
|
|
));
|
|
|
|
for msg in [
|
|
EventMsg::McpStartupUpdate(McpStartupUpdateEvent {
|
|
server: "pending".to_string(),
|
|
status: McpStartupStatus::Starting,
|
|
}),
|
|
EventMsg::McpStartupComplete(McpStartupCompleteEvent::default()),
|
|
] {
|
|
tx_events
|
|
.send(Event {
|
|
id: "delegate-startup".to_string(),
|
|
msg,
|
|
})
|
|
.await
|
|
.unwrap();
|
|
}
|
|
let visible_msg = EventMsg::RawResponseItem(RawResponseItemEvent {
|
|
item: ResponseItem::CustomToolCall {
|
|
encrypted_content: None,
|
|
id: None,
|
|
status: None,
|
|
call_id: "call-1".to_string(),
|
|
name: "tool".to_string(),
|
|
namespace: None,
|
|
input: "{}".to_string(),
|
|
internal_chat_message_metadata_passthrough: None,
|
|
},
|
|
});
|
|
for id in ["visible-1", "visible-2", "blocked"] {
|
|
tx_events
|
|
.send(Event {
|
|
id: id.to_string(),
|
|
msg: visible_msg.clone(),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
}
|
|
|
|
drop(tx_events);
|
|
let received = rx_out.recv().await.expect("prefilled event missing");
|
|
assert_eq!(received.id, "full");
|
|
let received = rx_out.recv().await.expect("visible event missing");
|
|
assert_eq!(received.id, "visible-1");
|
|
cancel.cancel();
|
|
timeout(std::time::Duration::from_millis(1000), forward)
|
|
.await
|
|
.expect("forward_events hung")
|
|
.expect("forward_events join error");
|
|
|
|
let mut ops = Vec::new();
|
|
while let Ok(sub) = rx_sub.try_recv() {
|
|
ops.push(sub.op);
|
|
}
|
|
assert!(
|
|
ops.iter().any(|op| matches!(op, Op::Interrupt)),
|
|
"expected Interrupt op after cancellation"
|
|
);
|
|
assert!(
|
|
ops.iter().any(|op| matches!(op, Op::Shutdown)),
|
|
"expected Shutdown op after cancellation"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn forward_ops_preserves_submission_trace_context() {
|
|
let (tx_sub, rx_sub) = bounded(SUBMISSION_CHANNEL_CAPACITY);
|
|
let (_tx_events, rx_events) = bounded(SUBMISSION_CHANNEL_CAPACITY);
|
|
let (_agent_status_tx, agent_status) = watch::channel(AgentStatus::PendingInit);
|
|
let io = Arc::new(SessionIo {
|
|
tx_sub,
|
|
rx_event: rx_events,
|
|
agent_status,
|
|
session_loop_termination: completed_session_loop_termination(),
|
|
});
|
|
let (tx_ops, rx_ops) = bounded(1);
|
|
let cancel = CancellationToken::new();
|
|
let forward = tokio::spawn(forward_ops(Arc::clone(&io), rx_ops, cancel));
|
|
|
|
let submission = Submission {
|
|
id: "sub-1".to_string(),
|
|
op: Op::Interrupt,
|
|
turn_extension_init: None,
|
|
trace: Some(akode_protocol::protocol::W3cTraceContext {
|
|
traceparent: Some(
|
|
"00-1234567890abcdef1234567890abcdef-1234567890abcdef-01".to_string(),
|
|
),
|
|
tracestate: Some("vendor=state".to_string()),
|
|
}),
|
|
parent_turn_id: Some("parent-turn".to_string()),
|
|
root_turn_id: Some("root-turn".to_string()),
|
|
residency_guard: None,
|
|
message_delivery: None,
|
|
};
|
|
tx_ops.send(submission).await.unwrap();
|
|
drop(tx_ops);
|
|
|
|
let forwarded = timeout(Duration::from_secs(1), rx_sub.recv())
|
|
.await
|
|
.expect("forward_ops hung")
|
|
.expect("forwarded submission missing");
|
|
assert_eq!("sub-1", forwarded.id);
|
|
assert!(matches!(forwarded.op, Op::Interrupt));
|
|
assert_eq!(
|
|
forwarded.trace,
|
|
Some(akode_protocol::protocol::W3cTraceContext {
|
|
traceparent: Some(
|
|
"00-1234567890abcdef1234567890abcdef-1234567890abcdef-01".to_string(),
|
|
),
|
|
tracestate: Some("vendor=state".to_string()),
|
|
})
|
|
);
|
|
assert_eq!(Some("parent-turn".to_string()), forwarded.parent_turn_id);
|
|
|
|
timeout(Duration::from_secs(1), forward)
|
|
.await
|
|
.expect("forward_ops did not exit")
|
|
.expect("forward_ops join error");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn run_codex_thread_interactive_respects_pre_cancelled_spawn() {
|
|
for shutdown_requested in [false, true] {
|
|
let (parent_session, parent_ctx, _rx_events) =
|
|
crate::session::tests::make_session_and_context_with_rx().await;
|
|
if shutdown_requested {
|
|
parent_session
|
|
.services
|
|
.local_agent_runtime
|
|
.request_shutdown();
|
|
}
|
|
let mut config = parent_ctx.config.as_ref().clone();
|
|
config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never);
|
|
let cancel_token = CancellationToken::new();
|
|
cancel_token.cancel();
|
|
let parent_environments = parent_ctx.initial_environments.clone();
|
|
|
|
let result = timeout(
|
|
Duration::from_secs(/*secs*/ 1),
|
|
run_codex_thread_interactive(
|
|
config,
|
|
Arc::clone(&parent_session.services.auth_manager),
|
|
Arc::clone(&parent_session.services.models_manager),
|
|
parent_session,
|
|
parent_ctx,
|
|
parent_environments,
|
|
cancel_token,
|
|
SubAgentSource::Review,
|
|
akode_extension_api::SessionIsolation::Inherit,
|
|
/*initial_history*/ None,
|
|
crate::session::GitEnrichmentPolicy::Fresh,
|
|
akode_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
|
|
),
|
|
)
|
|
.await
|
|
.expect("cancelled delegate spawn should not hang");
|
|
|
|
let error = result.err().expect("cancelled delegate spawn should fail");
|
|
assert!(
|
|
matches!(error.details(), CodexErrorDetails::TurnAborted),
|
|
"unexpected cancelled delegate spawn error (shutdown_requested={shutdown_requested}): {error}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn delegate_isolation_does_not_depend_on_attribution() {
|
|
let (mut parent_session, mut parent_ctx, _rx_events) =
|
|
crate::session::tests::make_session_and_context_with_rx().await;
|
|
Arc::get_mut(&mut parent_ctx)
|
|
.expect("parent turn should be uniquely owned")
|
|
.disabled_plugin_ids = vec!["parent-root".to_string()];
|
|
let thread_starts = Arc::new(AtomicUsize::new(0));
|
|
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
|
|
extensions
|
|
.thread_lifecycle_contributor(Arc::new(ThreadStartRecorder(Arc::clone(&thread_starts))));
|
|
Arc::get_mut(&mut parent_session)
|
|
.expect("parent session should be uniquely owned")
|
|
.services
|
|
.extensions = Arc::new(extensions.build());
|
|
|
|
let request = parent_ctx
|
|
.initial_environments
|
|
.inheritable_requests()
|
|
.into_iter()
|
|
.next()
|
|
.expect("parent environment");
|
|
let root = SelectedCapabilityRoot {
|
|
id: "parent-root".to_string(),
|
|
location: CapabilityRootLocation::Environment {
|
|
environment_id: request.environment_id.clone(),
|
|
path: request.cwd.clone(),
|
|
},
|
|
};
|
|
parent_session
|
|
.services
|
|
.turn_environments
|
|
.update_selections(&[TurnEnvironmentSelection::new(
|
|
request,
|
|
std::slice::from_ref(&root),
|
|
)]);
|
|
let parent_environments = parent_session.services.turn_environments.snapshot().await;
|
|
|
|
for (subagent_source, isolation, expected_thread_starts, expected_thread_source) in [
|
|
(
|
|
SubAgentSource::Other(crate::guardian::GUARDIAN_REVIEWER_NAME.to_string()),
|
|
akode_extension_api::SessionIsolation::Isolated,
|
|
0,
|
|
ThreadSource::GuardianReview,
|
|
),
|
|
(
|
|
SubAgentSource::Review,
|
|
akode_extension_api::SessionIsolation::Isolated,
|
|
0,
|
|
ThreadSource::Subagent,
|
|
),
|
|
(
|
|
SubAgentSource::Review,
|
|
akode_extension_api::SessionIsolation::Inherit,
|
|
1,
|
|
ThreadSource::Subagent,
|
|
),
|
|
] {
|
|
let mut config = parent_ctx.config.as_ref().clone();
|
|
config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never);
|
|
let (session, io) = run_codex_thread_interactive(
|
|
config,
|
|
Arc::clone(&parent_session.services.auth_manager),
|
|
Arc::clone(&parent_session.services.models_manager),
|
|
Arc::clone(&parent_session),
|
|
Arc::clone(&parent_ctx),
|
|
parent_environments.clone(),
|
|
CancellationToken::new(),
|
|
subagent_source,
|
|
isolation,
|
|
/*initial_history*/ None,
|
|
crate::session::GitEnrichmentPolicy::Fresh,
|
|
akode_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
|
|
)
|
|
.await
|
|
.expect("delegate session should start");
|
|
|
|
assert_eq!(
|
|
session
|
|
.services
|
|
.extensions
|
|
.thread_lifecycle_contributors()
|
|
.len(),
|
|
expected_thread_starts
|
|
);
|
|
assert_eq!(thread_starts.load(Ordering::SeqCst), expected_thread_starts);
|
|
assert_eq!(
|
|
session.thread_config_snapshot().await.thread_source,
|
|
Some(expected_thread_source)
|
|
);
|
|
let expected_roots = match isolation {
|
|
akode_extension_api::SessionIsolation::Inherit => vec![root.clone()],
|
|
akode_extension_api::SessionIsolation::Isolated => Vec::new(),
|
|
};
|
|
assert_eq!(session.services.selected_capability_roots, expected_roots);
|
|
let expected_disabled_plugins = match isolation {
|
|
akode_extension_api::SessionIsolation::Inherit => vec!["parent-root".to_string()],
|
|
akode_extension_api::SessionIsolation::Isolated => Vec::new(),
|
|
};
|
|
assert_eq!(
|
|
session.thread_settings_snapshot().await.disabled_plugin_ids,
|
|
expected_disabled_plugins,
|
|
);
|
|
assert_eq!(
|
|
session
|
|
.services
|
|
.turn_environments
|
|
.snapshot()
|
|
.await
|
|
.selected_capability_roots(),
|
|
expected_roots,
|
|
);
|
|
io.shutdown_and_wait()
|
|
.await
|
|
.expect("delegate session should shut down");
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn run_codex_thread_interactive_rejects_approval_policy_that_can_prompt() {
|
|
let (parent_session, parent_ctx, _rx_events) =
|
|
crate::session::tests::make_session_and_context_with_rx().await;
|
|
let mut config = parent_ctx.config.as_ref().clone();
|
|
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
|
|
let parent_environments = parent_ctx.initial_environments.clone();
|
|
|
|
let result = run_codex_thread_interactive(
|
|
config,
|
|
Arc::clone(&parent_session.services.auth_manager),
|
|
Arc::clone(&parent_session.services.models_manager),
|
|
parent_session,
|
|
parent_ctx,
|
|
parent_environments,
|
|
CancellationToken::new(),
|
|
SubAgentSource::Review,
|
|
akode_extension_api::SessionIsolation::Inherit,
|
|
/*initial_history*/ None,
|
|
crate::session::GitEnrichmentPolicy::Fresh,
|
|
akode_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
|
|
)
|
|
.await;
|
|
|
|
assert!(matches!(
|
|
result,
|
|
Err(err)
|
|
if matches!(
|
|
err.details(),
|
|
CodexErrorDetails::InvalidRequest(message)
|
|
if message == "Codex delegates require approval policy `never`"
|
|
)
|
|
));
|
|
}
|
|
|
|
/// Private delegates participate in tree shutdown even though they are not manager-visible.
|
|
#[tokio::test]
|
|
async fn tree_shutdown_waits_for_private_delegate() {
|
|
let (parent, context, _events) =
|
|
crate::session::tests::make_session_and_context_with_rx().await;
|
|
let mut config = context.config.as_ref().clone();
|
|
config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never);
|
|
let (_, io) = run_codex_thread_interactive(
|
|
config,
|
|
Arc::clone(&parent.services.auth_manager),
|
|
Arc::clone(&parent.services.models_manager),
|
|
Arc::clone(&parent),
|
|
Arc::clone(&context),
|
|
context.initial_environments.clone(),
|
|
CancellationToken::new(),
|
|
SubAgentSource::Review,
|
|
akode_extension_api::SessionIsolation::Isolated,
|
|
/*initial_history*/ None,
|
|
crate::session::GitEnrichmentPolicy::Fresh,
|
|
akode_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
|
|
)
|
|
.await
|
|
.expect("start private delegate");
|
|
|
|
let shutdown = parent.services.local_agent_runtime.request_shutdown();
|
|
timeout(Duration::from_secs(/*secs*/ 10), shutdown.wait())
|
|
.await
|
|
.expect("tree shutdown should wait for the private delegate")
|
|
.expect("private delegate should shut down cleanly");
|
|
assert!(io.session_loop_termination.now_or_never().is_some());
|
|
}
|