Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

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>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,243 @@
//! Copies this test executable into a private package and dispatches its fake helper before libtest.
//! The fixture validates protocol order; it never loads native libraries or opens audio devices.
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use akode_realtime_webrtc::AudioState;
use akode_realtime_webrtc::Message;
use akode_realtime_webrtc::encode_frame;
use akode_realtime_webrtc::read_message;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process::Command;
use std::process::Stdio;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
pub const BUILD_COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
pub const WAIT: Duration = Duration::from_secs(/*secs*/ 10);
const APP: &str = if cfg!(windows) { "akode.exe" } else { "codex" };
const HELPER: &str = if cfg!(windows) {
"akode-voice-host.exe"
} else {
"akode-voice-host"
};
pub fn wait_for(mut ready: impl FnMut() -> bool) -> Result<()> {
let deadline = Instant::now() + WAIT;
while !ready() {
ensure!(Instant::now() < deadline, "fixture deadline expired");
thread::sleep(Duration::from_millis(/*millis*/ 5));
}
Ok(())
}
#[cfg(unix)]
pub fn wait_for_helper_reaped(root: &std::path::Path) -> Result<()> {
let pid: libc::pid_t = fs::read_to_string(root.join("helper-pid"))?.parse()?;
wait_for(|| {
// SAFETY: Signal zero checks process existence without delivering a signal.
let result = unsafe {
libc::kill(pid, /*sig*/ 0)
};
result == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
})
}
struct Package(PathBuf);
impl Drop for Package {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
// The child discovers its installation through current_exe, exactly as the public facade does.
pub fn package(test: &str) -> Result<Option<PathBuf>> {
let source = std::env::current_exe()?;
if source.file_name().is_some_and(|name| name == APP) {
akode_build_info::BuildInfo::initialize(BUILD_COMMIT);
return Ok(Some(
source
.parent()
.context("bin")?
.parent()
.context("package")?
.to_owned(),
));
}
let nonce = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
let package =
Package(std::env::temp_dir().join(format!("voice-actor-{}-{nonce}", std::process::id())));
let root = &package.0;
fs::create_dir_all(root.join("bin"))?;
fs::create_dir_all(root.join("akode-resources/voice/bin"))?;
fs::write(root.join("akode-package.json"), "{}")?;
akode_utils_cargo_bin::copy_executable(&source, &root.join("bin").join(APP))?;
akode_utils_cargo_bin::copy_executable(
&source,
&root.join("akode-resources/voice/bin").join(HELPER),
)?;
let mut child = Command::new(root.join("bin").join(APP))
.args(["--exact", test, "--nocapture"])
.current_dir(root)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let deadline = Instant::now() + WAIT * 3;
while child.try_wait()?.is_none() {
if Instant::now() >= deadline {
child.kill()?;
child.wait()?;
anyhow::bail!("packaged test timed out");
}
thread::sleep(Duration::from_millis(/*millis*/ 10));
}
let output = child.wait_with_output()?;
ensure!(
output.status.success(),
"packaged test failed: {}\n{}\nfixture: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
fs::read_to_string(root.join("fixture-error")).unwrap_or_default()
);
Ok(None)
}
#[ctor::ctor]
fn dispatch_helper() {
if std::env::current_exe()
.ok()
.and_then(|path| path.file_name().map(std::ffi::OsStr::to_owned))
.is_some_and(|name| name == HELPER)
{
if let Err(error) = helper() {
let _ = fs::write("fixture-error", format!("{error:#}"));
std::process::exit(1);
}
std::process::exit(0);
}
}
#[derive(PartialEq)]
enum Stage {
Hello,
Initialize,
Offer,
Answer,
Devices,
Controls,
Running,
}
fn helper() -> Result<()> {
let root = std::env::current_dir()?;
fs::write(root.join("helper-pid"), std::process::id().to_string())?;
let mut input = std::io::stdin().lock();
let mut output = std::io::stdout().lock();
let mut stage = Stage::Hello;
let mut controls_history = Vec::new();
while let Some(request) = read_message(&mut input)? {
let response = match request {
Message::Hello {
protocol: 1,
build_commit,
} if stage == Stage::Hello => {
ensure!(build_commit == BUILD_COMMIT, "wrong executable build stamp");
stage = Stage::Initialize;
Message::Ready {}
}
Message::ListDevices { kind } if stage == Stage::Initialize => Message::DeviceList {
devices: vec![akode_realtime_webrtc::AudioDevice {
name: match kind {
akode_realtime_webrtc::AudioDeviceKind::Input => "Interface",
akode_realtime_webrtc::AudioDeviceKind::Output => "Headphones",
}
.into(),
channels: 16,
is_default: true,
}],
},
Message::InitializeRuntime {} if stage == Stage::Initialize => {
fs::write(root.join("initializing"), [])?;
if root.join("hold-initialization").exists() {
wait_for(|| root.join("release").exists())?;
}
if root.join("fail-initialization").exists() {
anyhow::bail!("synthetic private runtime diagnostic");
}
stage = Stage::Offer;
Message::RuntimeReady {}
}
Message::StartTransport {} if stage == Stage::Offer => {
stage = Stage::Answer;
Message::Offer {
sdp: "synthetic-offer"
.to_owned()
.try_into()
.map_err(anyhow::Error::msg)?,
}
}
Message::ApplyAnswer { sdp } if stage == Stage::Answer => {
ensure!(
sdp.into_sdp() == "synthetic-answer",
"unexpected fixture answer"
);
fs::write(root.join("answer"), [])?;
wait_for(|| root.join("release").exists())?;
stage = Stage::Devices;
Message::TransportReady {}
}
Message::OpenDevices { selection } if stage == Stage::Devices => {
fs::write(
root.join("input-selection"),
serde_json::to_vec(&selection)?,
)?;
if root.join("fail-devices").exists() {
anyhow::bail!("synthetic private device diagnostic");
}
stage = Stage::Controls;
Message::DevicesOpened {}
}
Message::SetAudioControls { controls }
if stage == Stage::Controls || stage == Stage::Running =>
{
controls_history.push(controls);
fs::write(
root.join("controls"),
serde_json::to_vec(&controls_history)?,
)?;
stage = Stage::Running;
Message::AudioControlsApplied {}
}
Message::InspectAudio {} if stage == Stage::Answer || stage == Stage::Running => {
if root.join("exit").exists() {
return Ok(());
}
Message::AudioState {
state: if stage == Stage::Running {
AudioState {
microphone_peak: 123,
speaker_peak: 456,
}
} else {
AudioState::default()
},
}
}
Message::Close {} => {
output.write_all(&encode_frame(&Message::Closed {})?)?;
output.flush()?;
return Ok(());
}
_ => anyhow::bail!("unexpected fixture protocol sequence"),
};
output.write_all(&encode_frame(&response)?)?;
output.flush()?;
}
Ok(())
}

View File

@@ -0,0 +1,204 @@
//! Exercises the public session actor against a separate framed-IPC helper, without native audio.
mod common;
use anyhow::Result;
use akode_realtime_webrtc::AudioControls;
use akode_realtime_webrtc::AudioDeviceKind;
use akode_realtime_webrtc::AudioDeviceSelection;
use akode_realtime_webrtc::RealtimeWebrtcSession;
use futures::future::AbortHandle;
use pretty_assertions::assert_eq;
use std::fs;
use std::thread;
#[test]
fn startup_controls_meters_and_helper_loss() -> Result<()> {
let Some(root) = common::package("startup_controls_meters_and_helper_loss")? else {
return Ok(());
};
#[cfg(target_os = "linux")]
{
assert!(!RealtimeWebrtcSession::is_supported());
let libraries = root.join("akode-resources/voice/lib");
fs::create_dir_all(&libraries)?;
fs::write(libraries.join("libgstreamer-1.0.so.0"), b"fixture runtime")?;
assert!(RealtimeWebrtcSession::is_supported());
}
let (_abort, registration) = AbortHandle::new_pair();
let started = RealtimeWebrtcSession::start(
registration,
AudioDeviceSelection {
microphone: Some("Zen Go Synergy Core Playback".into()),
speaker: Some("Headphones".into()),
channel: Some(vec![
std::num::NonZeroU16::new(/*n*/ 1).unwrap(),
std::num::NonZeroU16::new(/*n*/ 2).unwrap(),
]),
},
)?;
assert_eq!(started.offer_sdp, "synthetic-offer");
let handle = started.handle;
handle.set_microphone_muted(/*muted*/ true)?;
let answer_handle = handle.clone();
let answer = thread::spawn(move || answer_handle.apply_answer_sdp("synthetic-answer".into()));
common::wait_for(|| root.join("answer").exists())?;
handle.set_speaker_suppressed(/*suppressed*/ true);
fs::write(root.join("release"), [])?;
answer.join().expect("answer thread")?;
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&fs::read(root.join("input-selection"))?)?,
serde_json::json!({"microphone": "Zen Go Synergy Core Playback", "speaker": "Headphones", "channel": [1, 2]})
);
let initial: Vec<AudioControls> = serde_json::from_slice(&fs::read(root.join("controls"))?)?;
assert_eq!(
initial,
vec![AudioControls {
microphone_muted: true,
speaker_suppressed: true
}]
);
handle.set_microphone_muted(/*muted*/ false)?;
handle.set_speaker_suppressed(/*suppressed*/ false);
let expected = serde_json::to_vec(&vec![
AudioControls {
microphone_muted: true,
speaker_suppressed: true,
},
AudioControls {
microphone_muted: false,
speaker_suppressed: true,
},
AudioControls {
microphone_muted: false,
speaker_suppressed: false,
},
])?;
common::wait_for(|| fs::read(root.join("controls")).is_ok_and(|data| data == expected))?;
common::wait_for(|| handle.take_microphone_peak() == 123)?;
common::wait_for(|| handle.take_speaker_peak() == 456)?;
fs::write(root.join("exit"), [])?;
let mut error = None;
common::wait_for(|| {
error = handle.take_error();
error.is_some()
})?;
assert_eq!(
error,
Some((
akode_realtime_webrtc::ConnectionError::AudioSession,
"voice audio session stopped unexpectedly".into()
))
);
assert_eq!(handle.take_error(), None);
Ok(())
}
#[test]
fn external_cancellation_interrupts_startup() -> Result<()> {
let Some(root) = common::package("external_cancellation_interrupts_startup")? else {
return Ok(());
};
fs::write(root.join("hold-initialization"), [])?;
let (abort, registration) = AbortHandle::new_pair();
let (result, received) = std::sync::mpsc::sync_channel(/*bound*/ 1);
let startup = thread::spawn(move || {
let _ = result.send(RealtimeWebrtcSession::start(
registration,
AudioDeviceSelection::default(),
));
});
common::wait_for(|| root.join("initializing").exists())?;
abort.abort();
assert!(
received
.recv_timeout(std::time::Duration::from_secs(/*secs*/ 2))?
.is_err()
);
startup.join().expect("startup thread");
#[cfg(unix)]
common::wait_for_helper_reaped(&root)?;
Ok(())
}
#[cfg(unix)]
#[test]
fn last_owner_drop_reaps_helper() -> Result<()> {
let Some(root) = common::package("last_owner_drop_reaps_helper")? else {
return Ok(());
};
let (_abort, registration) = AbortHandle::new_pair();
let started = RealtimeWebrtcSession::start(registration, AudioDeviceSelection::default())?;
drop(started);
common::wait_for_helper_reaped(&root)
}
#[test]
fn device_failure_reaches_startup_completion_without_duplicate_error() -> Result<()> {
let Some(root) =
common::package("device_failure_reaches_startup_completion_without_duplicate_error")?
else {
return Ok(());
};
fs::write(root.join("fail-devices"), [])?;
fs::write(root.join("release"), [])?;
let (_abort, registration) = AbortHandle::new_pair();
let started = RealtimeWebrtcSession::start(registration, AudioDeviceSelection::default())?;
assert_eq!(
started.handle.apply_answer_sdp("synthetic-answer".into()),
Err(akode_realtime_webrtc::ConnectionError::AudioDevices)
);
started.handle.set_microphone_muted(/*muted*/ true)?;
assert_eq!(started.handle.take_error(), None);
started.handle.close();
#[cfg(unix)]
common::wait_for_helper_reaped(&root)?;
Ok(())
}
#[test]
fn runtime_failure_reaches_offer_caller_without_native_error_text() -> Result<()> {
let Some(root) =
common::package("runtime_failure_reaches_offer_caller_without_native_error_text")?
else {
return Ok(());
};
fs::write(root.join("fail-initialization"), [])?;
let (_abort, registration) = AbortHandle::new_pair();
let error =
RealtimeWebrtcSession::start(registration, AudioDeviceSelection::default()).unwrap_err();
assert_eq!(
error.downcast_ref::<akode_realtime_webrtc::ConnectionError>(),
Some(&akode_realtime_webrtc::ConnectionError::RuntimeInitialization)
);
assert_eq!(
format!("{error:#}"),
"voice audio runtime could not initialize"
);
#[cfg(unix)]
common::wait_for_helper_reaped(&root)?;
Ok(())
}
#[tokio::test]
async fn device_discovery_does_not_start_capture() -> Result<()> {
let Some(root) = common::package("device_discovery_does_not_start_capture")? else {
return Ok(());
};
let package = akode_install_context::InstallContext::current()
.package_layout
.as_ref()
.unwrap();
let mut host = akode_realtime_webrtc::VoiceHost::connect(package, common::BUILD_COMMIT).await?;
assert_eq!(
host.list_devices(AudioDeviceKind::Input).await?,
vec![akode_realtime_webrtc::AudioDevice {
name: "Interface".into(),
channels: 16,
is_default: true,
}]
);
host.close().await?;
assert!(!root.join("initializing").exists());
Ok(())
}