Rimossi /app e i controlli dell'app Desktop di OpenAI (B)
Da 25de1e70: eliminati il comando /app (apertura di codex:// / OpenAI.Codex) e i controlli
desktop di `akode doctor` con relativi test e snapshot.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -75,7 +75,6 @@ use serde::Serialize;
|
||||
use supports_color::Stream;
|
||||
|
||||
mod background;
|
||||
mod desktop;
|
||||
mod disk;
|
||||
mod filesystem_paths;
|
||||
mod git;
|
||||
@@ -92,10 +91,6 @@ mod updates;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows_dev_drive;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "doctor/desktop_tests.rs"]
|
||||
mod desktop_tests;
|
||||
|
||||
use background::background_server_check;
|
||||
use git::git_check;
|
||||
use output::HumanOutputOptions;
|
||||
@@ -567,12 +562,6 @@ async fn build_report(
|
||||
}
|
||||
}
|
||||
|
||||
progress.begin("desktop");
|
||||
if let Some(desktop) = desktop::collect().await {
|
||||
progress.finish("desktop", overall_status(&desktop.checks));
|
||||
checks.extend(desktop.checks);
|
||||
}
|
||||
|
||||
progress.settle();
|
||||
|
||||
report_from_checks(checks)
|
||||
|
||||
@@ -1,314 +0,0 @@
|
||||
use std::cmp::Reverse;
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::FixedOffset;
|
||||
use chrono::Utc;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos_security;
|
||||
pub(super) mod platform;
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
mod windows_security;
|
||||
|
||||
const MAX_DIRECTORY_ENTRIES: usize = 256;
|
||||
const MAX_LOG_FILES: usize = 64;
|
||||
const MAX_SESSION_LOG_FILES: usize = 8;
|
||||
const MAX_LOG_SEGMENT_BYTES: u64 = 10 * 1024 * 1024;
|
||||
const HANDSHAKE_CHECK_ID: &str = "desktop.app_server.handshake";
|
||||
|
||||
pub(super) struct DesktopDiagnostics {
|
||||
pub(super) checks: Vec<DoctorCheck>,
|
||||
}
|
||||
|
||||
struct DesktopLog {
|
||||
path: PathBuf,
|
||||
session_id: String,
|
||||
process_id: u32,
|
||||
modified: SystemTime,
|
||||
}
|
||||
|
||||
struct HandshakeEvent {
|
||||
timestamp: DateTime<FixedOffset>,
|
||||
outcome: HandshakeOutcome,
|
||||
websocket: bool,
|
||||
}
|
||||
|
||||
enum HandshakeOutcome {
|
||||
Success,
|
||||
Failure,
|
||||
}
|
||||
|
||||
enum DesktopLogEvent {
|
||||
ConnectionContext { local_websocket: bool },
|
||||
Handshake(HandshakeEvent),
|
||||
}
|
||||
|
||||
pub(super) async fn collect() -> Option<DesktopDiagnostics> {
|
||||
let application = match platform::installed_app().await {
|
||||
Ok(Some(application)) => application,
|
||||
Ok(None) => return None,
|
||||
Err(_) => {
|
||||
return Some(DesktopDiagnostics {
|
||||
checks: vec![
|
||||
unavailable(
|
||||
"desktop.app.version",
|
||||
"the desktop application installation could not be inspected",
|
||||
),
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_security::collect().await,
|
||||
],
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let directory = desktop_log_root(application.identity);
|
||||
let (running, handshake) = match &directory {
|
||||
Some(root) => inspect_desktop_session(
|
||||
&root.join(Utc::now().format("%Y/%m/%d").to_string()),
|
||||
|pid| platform::application_running(&application, pid),
|
||||
),
|
||||
None => (false, stopped_desktop_check()),
|
||||
};
|
||||
let log_directory = directory
|
||||
.as_deref()
|
||||
.map_or_else(|| "unavailable".to_string(), redacted_path);
|
||||
let application_check = platform::desktop_check(
|
||||
"desktop.app.version",
|
||||
CheckStatus::Ok,
|
||||
"the desktop application is installed",
|
||||
)
|
||||
.detail(format!("version: {}", application.version))
|
||||
.detail(format!("running: {running}"))
|
||||
.detail(format!("log directory: {log_directory}"));
|
||||
|
||||
Some(DesktopDiagnostics {
|
||||
checks: vec![
|
||||
application_check,
|
||||
handshake,
|
||||
#[cfg(target_os = "macos")]
|
||||
macos_security::collect(&application.bundle).await,
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_security::collect().await,
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn inspect_desktop_session(
|
||||
directory: &Path,
|
||||
application_running: impl Fn(u32) -> bool,
|
||||
) -> (bool, DoctorCheck) {
|
||||
let logs = discover_desktop_logs(directory);
|
||||
let Some(session) = logs.iter().find(|log| application_running(log.process_id)) else {
|
||||
return (false, stopped_desktop_check());
|
||||
};
|
||||
|
||||
let check = latest_session_handshake(&logs, &session.session_id).map_or_else(
|
||||
|| {
|
||||
platform::desktop_check(
|
||||
HANDSHAKE_CHECK_ID,
|
||||
CheckStatus::Ok,
|
||||
"no desktop app-server handshake was recorded",
|
||||
)
|
||||
},
|
||||
|event| event.outcome.into_check(),
|
||||
);
|
||||
|
||||
(true, check)
|
||||
}
|
||||
|
||||
fn desktop_log_root(identity: &str) -> Option<PathBuf> {
|
||||
let root = match env::consts::OS {
|
||||
"macos" => PathBuf::from(env::var_os("HOME")?)
|
||||
.join("Library/Logs")
|
||||
.join(identity),
|
||||
"windows" => {
|
||||
let local = env::var_os("LOCALAPPDATA").map(PathBuf::from).or_else(|| {
|
||||
env::var_os("USERPROFILE").map(|home| PathBuf::from(home).join("AppData/Local"))
|
||||
})?;
|
||||
local.join("Codex/Logs")
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
Some(root)
|
||||
}
|
||||
|
||||
fn discover_desktop_logs(directory: &Path) -> Vec<DesktopLog> {
|
||||
let Ok(entries) = fs::read_dir(directory) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut logs = entries
|
||||
.take(MAX_DIRECTORY_ENTRIES)
|
||||
.filter_map(Result::ok)
|
||||
.filter_map(DesktopLog::from_entry)
|
||||
.collect::<Vec<_>>();
|
||||
logs.sort_unstable_by_key(|log| Reverse(log.modified));
|
||||
logs.truncate(MAX_LOG_FILES);
|
||||
logs
|
||||
}
|
||||
|
||||
fn latest_session_handshake(logs: &[DesktopLog], session_id: &str) -> Option<HandshakeEvent> {
|
||||
let mut latest: Option<HandshakeEvent> = None;
|
||||
|
||||
for log in logs
|
||||
.iter()
|
||||
.filter(|log| log.session_id == session_id)
|
||||
.take(MAX_SESSION_LOG_FILES)
|
||||
{
|
||||
let Ok(contents) = read_log_segment(&log.path) else {
|
||||
continue;
|
||||
};
|
||||
let mut local_websocket = false;
|
||||
|
||||
for line in String::from_utf8_lossy(&contents).lines() {
|
||||
match DesktopLogEvent::parse(line) {
|
||||
Some(DesktopLogEvent::ConnectionContext {
|
||||
local_websocket: local,
|
||||
}) => {
|
||||
local_websocket = local;
|
||||
}
|
||||
Some(DesktopLogEvent::Handshake(event))
|
||||
if (!event.websocket || local_websocket)
|
||||
&& latest
|
||||
.as_ref()
|
||||
.is_none_or(|current| event.timestamp >= current.timestamp) =>
|
||||
{
|
||||
latest = Some(event);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
latest
|
||||
}
|
||||
|
||||
impl DesktopLog {
|
||||
fn from_entry(entry: fs::DirEntry) -> Option<Self> {
|
||||
let metadata = entry.metadata().ok()?;
|
||||
if !metadata.is_file() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let name = entry.file_name();
|
||||
let name = name
|
||||
.to_str()?
|
||||
.strip_prefix("codex-desktop-")?
|
||||
.strip_suffix(".log")?;
|
||||
let (session_and_pid, _) = name.split_once("-t")?;
|
||||
let (session_id, process_id) = session_and_pid.rsplit_once('-')?;
|
||||
|
||||
Some(Self {
|
||||
path: entry.path(),
|
||||
session_id: session_id.to_string(),
|
||||
process_id: process_id.parse().ok().filter(|pid| *pid > 0)?,
|
||||
modified: metadata.modified().ok()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn read_log_segment(path: &Path) -> io::Result<Vec<u8>> {
|
||||
let mut contents = Vec::new();
|
||||
fs::File::open(path)?
|
||||
.take(MAX_LOG_SEGMENT_BYTES)
|
||||
.read_to_end(&mut contents)?;
|
||||
Ok(contents)
|
||||
}
|
||||
|
||||
impl DesktopLogEvent {
|
||||
fn parse(line: &str) -> Option<Self> {
|
||||
let (timestamp, line) = line.split_once(' ')?;
|
||||
let timestamp = DateTime::parse_from_rfc3339(timestamp).ok()?;
|
||||
let (_, message) = line.split_once(" [AppServerConnection] ")?;
|
||||
|
||||
if let Some(fields) = message
|
||||
.strip_prefix("Starting app-server connection ")
|
||||
.or_else(|| message.strip_prefix("app_server_connection.state_changed "))
|
||||
{
|
||||
return Some(Self::ConnectionContext {
|
||||
local_websocket: log_field(fields, "hostId") == Some("local")
|
||||
&& log_field(fields, "transport") == Some("websocket"),
|
||||
});
|
||||
}
|
||||
|
||||
let fields = message.strip_prefix("initialize_handshake_result ")?;
|
||||
let outcome = match log_field(fields, "outcome")? {
|
||||
"success" => HandshakeOutcome::Success,
|
||||
"failure" => HandshakeOutcome::Failure,
|
||||
_ => return None,
|
||||
};
|
||||
let websocket = match log_field(fields, "transportKind")? {
|
||||
"stdio" => false,
|
||||
"websocket" => true,
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
Some(Self::Handshake(HandshakeEvent {
|
||||
timestamp,
|
||||
outcome,
|
||||
websocket,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl HandshakeOutcome {
|
||||
fn into_check(self) -> DoctorCheck {
|
||||
let (status, summary) = match self {
|
||||
Self::Success => (
|
||||
CheckStatus::Ok,
|
||||
"the desktop app-server initialized successfully",
|
||||
),
|
||||
Self::Failure => (
|
||||
CheckStatus::Fail,
|
||||
"the desktop app-server failed to initialize",
|
||||
),
|
||||
};
|
||||
|
||||
platform::desktop_check(HANDSHAKE_CHECK_ID, status, summary)
|
||||
}
|
||||
}
|
||||
|
||||
fn log_field<'a>(fields: &'a str, name: &str) -> Option<&'a str> {
|
||||
fields.split_whitespace().rev().find_map(|field| {
|
||||
let (key, value) = field.split_once('=')?;
|
||||
(key == name).then_some(value)
|
||||
})
|
||||
}
|
||||
|
||||
fn stopped_desktop_check() -> DoctorCheck {
|
||||
platform::desktop_check(
|
||||
HANDSHAKE_CHECK_ID,
|
||||
CheckStatus::Ok,
|
||||
"the desktop application is not running",
|
||||
)
|
||||
}
|
||||
|
||||
fn unavailable(id: &'static str, summary: &'static str) -> DoctorCheck {
|
||||
platform::desktop_check(id, CheckStatus::Warning, summary)
|
||||
.remediation("restore desktop diagnostic access and rerun akode doctor")
|
||||
}
|
||||
|
||||
fn redacted_path(path: &Path) -> String {
|
||||
for variable in ["HOME", "USERPROFILE"] {
|
||||
if let Some(home) = env::var_os(variable)
|
||||
&& let Ok(relative) = path.strip_prefix(Path::new(&home))
|
||||
{
|
||||
return Path::new("$HOME").join(relative).display().to_string();
|
||||
}
|
||||
}
|
||||
path.file_name()
|
||||
.unwrap_or(path.as_os_str())
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
use super::super::CheckStatus;
|
||||
use super::super::DoctorCheck;
|
||||
use super::platform::desktop_check;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::process::Output;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_OUTPUT_BYTES: usize = 256 * 1024;
|
||||
const SECURITY_LOG_PREDICATE: &str = concat!(
|
||||
"(process == 'syspolicyd' OR process == 'AppleSystemPolicy' ",
|
||||
"OR process BEGINSWITH 'XProtect' OR subsystem BEGINSWITH 'com.apple.syspolicy' ",
|
||||
"OR subsystem CONTAINS[c] 'XProtect' ",
|
||||
"OR subsystem == 'com.apple.security.assessment') AND ",
|
||||
"(eventMessage CONTAINS[c] 'codex' OR eventMessage CONTAINS[c] 'chatgpt' ",
|
||||
"OR eventMessage CONTAINS[c] '.plugin-appserver' ",
|
||||
"OR eventMessage CONTAINS[c] '100024' OR eventMessage CONTAINS[c] 'EMFILE' ",
|
||||
"OR eventMessage CONTAINS[c] 'ENFILE' ",
|
||||
"OR eventMessage CONTAINS[c] 'too many open files' ",
|
||||
"OR eventMessage CONTAINS[c] 'Unexpected Xprotect assessment')"
|
||||
);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
enum Evidence {
|
||||
Clear,
|
||||
Audit,
|
||||
Exhausted,
|
||||
Blocked,
|
||||
Malware,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
pub(super) async fn collect(bundle: &Path) -> DoctorCheck {
|
||||
let (gatekeeper, events) = tokio::join!(inspect_gatekeeper(bundle), inspect_security_events());
|
||||
enforcement_check(gatekeeper, events)
|
||||
}
|
||||
|
||||
async fn inspect_gatekeeper(bundle: &Path) -> Evidence {
|
||||
let mut command = Command::new("/usr/sbin/spctl");
|
||||
command
|
||||
.args(["--assess", "--type", "execute", "--verbose=2"])
|
||||
.arg(bundle);
|
||||
classify_gatekeeper(run_command(&mut command).await.as_ref())
|
||||
}
|
||||
|
||||
fn classify_gatekeeper(output: Option<&Output>) -> Evidence {
|
||||
let Some(output) = output.filter(|output| !is_truncated(output)) else {
|
||||
return Evidence::Unavailable;
|
||||
};
|
||||
if output.status.success() {
|
||||
return Evidence::Clear;
|
||||
}
|
||||
let error = String::from_utf8_lossy(&output.stderr).to_ascii_lowercase();
|
||||
if error.contains("rejected") || error.contains("no usable signature") {
|
||||
Evidence::Blocked
|
||||
} else {
|
||||
Evidence::Unavailable
|
||||
}
|
||||
}
|
||||
|
||||
async fn inspect_security_events() -> Evidence {
|
||||
let mut command = Command::new("/usr/bin/log");
|
||||
command.args([
|
||||
"show",
|
||||
"--last",
|
||||
"30m",
|
||||
"--info",
|
||||
"--style",
|
||||
"compact",
|
||||
"--predicate",
|
||||
SECURITY_LOG_PREDICATE,
|
||||
]);
|
||||
let Some(output) = run_command(&mut command)
|
||||
.await
|
||||
.filter(|output| output.status.success())
|
||||
else {
|
||||
return Evidence::Unavailable;
|
||||
};
|
||||
let evidence = classify_security_events(&String::from_utf8_lossy(&output.stdout));
|
||||
if is_truncated(&output) && evidence < Evidence::Exhausted {
|
||||
Evidence::Unavailable
|
||||
} else {
|
||||
evidence
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_security_events(output: &str) -> Evidence {
|
||||
let mut evidence = Evidence::Clear;
|
||||
for line in output.lines().map(str::to_ascii_lowercase) {
|
||||
let contains = |values: &[&str]| values.iter().any(|value| line.contains(value));
|
||||
if !contains(&[
|
||||
"com.openai.codex",
|
||||
"codex.app",
|
||||
"chatgpt.app",
|
||||
".plugin-appserver",
|
||||
"akode-command-runner",
|
||||
]) || contains(&["not blocked", "not denied"])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let event = if contains(&["100024", "emfile", "enfile", "too many open files"]) {
|
||||
Evidence::Exhausted
|
||||
} else if contains(&["would block", "would deny"]) {
|
||||
Evidence::Audit
|
||||
} else if contains(&[
|
||||
"xp_malware_detected",
|
||||
"xp_malware_remediated",
|
||||
"malware detected",
|
||||
"malware blocked",
|
||||
"malware removed",
|
||||
"remediat",
|
||||
]) {
|
||||
Evidence::Malware
|
||||
} else if contains(&[
|
||||
"blocked",
|
||||
"denied",
|
||||
"rejected",
|
||||
"notarization failed",
|
||||
"signature invalid",
|
||||
"execution prevented",
|
||||
"unexpected xprotect assessment",
|
||||
"damaged and",
|
||||
]) {
|
||||
Evidence::Blocked
|
||||
} else if contains(&["audit"]) {
|
||||
Evidence::Audit
|
||||
} else {
|
||||
Evidence::Clear
|
||||
};
|
||||
evidence = evidence.max(event);
|
||||
}
|
||||
evidence
|
||||
}
|
||||
|
||||
fn enforcement_check(gatekeeper: Evidence, events: Evidence) -> DoctorCheck {
|
||||
let id = "desktop.security.enforcement";
|
||||
let (status, summary, remedy) = if events == Evidence::Malware {
|
||||
(
|
||||
CheckStatus::Fail,
|
||||
"macos XProtect blocked or remediated the desktop application",
|
||||
"collect the XProtect detection and ask your security administrator to review the official aKode installation",
|
||||
)
|
||||
} else if gatekeeper == Evidence::Blocked {
|
||||
(
|
||||
CheckStatus::Fail,
|
||||
"macos gatekeeper rejected the desktop application",
|
||||
"ask your security administrator to review the application policy",
|
||||
)
|
||||
} else if events == Evidence::Blocked {
|
||||
(
|
||||
CheckStatus::Fail,
|
||||
"a recent macos security event blocked the desktop application",
|
||||
"ask your security administrator to review the matching prevention event",
|
||||
)
|
||||
} else if events == Evidence::Exhausted {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"macos system-policy diagnostics indicate file descriptor exhaustion",
|
||||
"restart your Mac, retry aKode once, and contact support if the problem returns",
|
||||
)
|
||||
} else if events == Evidence::Audit {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"recent desktop security events are audit-only",
|
||||
"ask your security administrator to verify the application policy",
|
||||
)
|
||||
} else if gatekeeper == Evidence::Unavailable {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"the desktop security assessment was unavailable",
|
||||
"check access to macos gatekeeper diagnostics",
|
||||
)
|
||||
} else if events == Evidence::Unavailable {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"recent macos security enforcement history was unavailable",
|
||||
"check access to macos unified security logs and rerun akode doctor",
|
||||
)
|
||||
} else {
|
||||
return desktop_check(
|
||||
id,
|
||||
CheckStatus::Ok,
|
||||
"the desktop application passed available macos security assessments",
|
||||
)
|
||||
.detail("gatekeeper: accepted");
|
||||
};
|
||||
desktop_check(id, status, summary).remediation(remedy)
|
||||
}
|
||||
|
||||
fn is_truncated(output: &Output) -> bool {
|
||||
output.stdout.len() > MAX_OUTPUT_BYTES || output.stderr.len() > MAX_OUTPUT_BYTES
|
||||
}
|
||||
|
||||
async fn run_command(command: &mut Command) -> Option<Output> {
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
let mut child = command.spawn().ok()?;
|
||||
let (stdout, stderr) = (child.stdout.take()?, child.stderr.take()?);
|
||||
timeout(PROBE_TIMEOUT, async {
|
||||
let (stdout, stderr, status) =
|
||||
tokio::join!(read_bounded(stdout), read_bounded(stderr), child.wait());
|
||||
Some(Output {
|
||||
status: status.ok()?,
|
||||
stdout: stdout.ok()?,
|
||||
stderr: stderr.ok()?,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
async fn read_bounded<R: AsyncRead + Unpin>(mut reader: R) -> io::Result<Vec<u8>> {
|
||||
let mut bytes = Vec::new();
|
||||
(&mut reader)
|
||||
.take(MAX_OUTPUT_BYTES as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.await?;
|
||||
if bytes.len() > MAX_OUTPUT_BYTES {
|
||||
tokio::io::copy(&mut reader, &mut tokio::io::sink()).await?;
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "macos_security_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,67 +0,0 @@
|
||||
use super::CheckStatus;
|
||||
use super::Evidence;
|
||||
use super::classify_gatekeeper;
|
||||
use super::classify_security_events;
|
||||
use super::enforcement_check;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
use std::process::ExitStatus;
|
||||
use std::process::Output;
|
||||
|
||||
#[test]
|
||||
fn only_matching_enforced_apple_security_events_are_failures() {
|
||||
for (event, expected) in [
|
||||
("denied com.openai.codex", Evidence::Blocked),
|
||||
(
|
||||
"denied /Applications/Codex.app/Contents/MacOS/Codex",
|
||||
Evidence::Blocked,
|
||||
),
|
||||
("malware detected ChatGPT.app", Evidence::Malware),
|
||||
("audit token blocked ChatGPT.app", Evidence::Blocked),
|
||||
(
|
||||
"audit token XP_MALWARE_DETECTED ChatGPT.app",
|
||||
Evidence::Malware,
|
||||
),
|
||||
("XP_MALWARE_REMEDIATED ChatGPT.app", Evidence::Malware),
|
||||
("denied .plugin-appserver", Evidence::Blocked),
|
||||
("audit would block ChatGPT.app", Evidence::Audit),
|
||||
("OSStatus 100024 ChatGPT.app", Evidence::Exhausted),
|
||||
("not blocked ChatGPT.app", Evidence::Clear),
|
||||
("denied EMFILE com.example.other", Evidence::Clear),
|
||||
("EMFILE\nmalware detected ChatGPT.app", Evidence::Malware),
|
||||
] {
|
||||
assert_eq!(classify_security_events(event), expected, "{event}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gatekeeper_failures_require_actionable_security_evidence() {
|
||||
for (message, expected) in [
|
||||
("ChatGPT.app: rejected", Evidence::Blocked),
|
||||
("operation not permitted", Evidence::Unavailable),
|
||||
] {
|
||||
let output = Output {
|
||||
status: ExitStatus::from_raw(1 << 8),
|
||||
stdout: Vec::new(),
|
||||
stderr: message.as_bytes().to_vec(),
|
||||
};
|
||||
assert_eq!(classify_gatekeeper(Some(&output)), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exhaustion_and_unavailable_history_have_actionable_warnings() {
|
||||
for (events, remedy) in [
|
||||
(Evidence::Exhausted, "restart"),
|
||||
(Evidence::Unavailable, "unified security logs"),
|
||||
] {
|
||||
let check = enforcement_check(Evidence::Clear, events);
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert!(
|
||||
check
|
||||
.remediation
|
||||
.as_deref()
|
||||
.is_some_and(|value| value.contains(remedy))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::ffi::CStr;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::ffi::OsStr;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::fs;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::Path;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::PathBuf;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::process::Stdio;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use serde_json::Value;
|
||||
#[cfg(target_os = "macos")]
|
||||
use tokio::process::Command;
|
||||
#[cfg(target_os = "macos")]
|
||||
use tokio::time::timeout;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Storage::Packaging::Appx::FindPackagesByPackageFamily;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Storage::Packaging::Appx::GetPackageFamilyName;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Storage::Packaging::Appx::PACKAGE_FILTER_HEAD;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::System::Threading::OpenProcess;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
|
||||
|
||||
use super::super::CheckStatus;
|
||||
use super::super::DoctorCheck;
|
||||
|
||||
pub(in crate::doctor) struct InstalledApp {
|
||||
pub(in crate::doctor) identity: &'static str,
|
||||
pub(in crate::doctor) version: String,
|
||||
#[cfg(target_os = "windows")]
|
||||
package_family: &'static str,
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::doctor) bundle: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(in crate::doctor) struct DiscoveryError;
|
||||
|
||||
pub(super) async fn installed_app() -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
installed_windows_app()
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
installed_macos_app().await
|
||||
}
|
||||
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(super) fn application_running(application: &InstalledApp, candidate_pid: u32) -> bool {
|
||||
process_executable_path(candidate_pid)
|
||||
.is_some_and(|path| path.starts_with(application.bundle.join("Contents/MacOS")))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn process_executable_path(pid: u32) -> Option<PathBuf> {
|
||||
let pid = i32::try_from(pid).ok()?;
|
||||
let mut buffer = [0_u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
|
||||
let result =
|
||||
unsafe { libc::proc_pidpath(pid, buffer.as_mut_ptr().cast(), buffer.len() as u32) };
|
||||
if result <= 0 {
|
||||
return None;
|
||||
}
|
||||
let executable = CStr::from_bytes_until_nul(&buffer).ok()?;
|
||||
Some(PathBuf::from(OsStr::from_bytes(executable.to_bytes())))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(super) fn application_running(application: &InstalledApp, candidate_pid: u32) -> bool {
|
||||
process_package_family(candidate_pid).as_deref() == Some(application.package_family)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn process_package_family(pid: u32) -> Option<String> {
|
||||
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
|
||||
if handle.is_null() {
|
||||
return None;
|
||||
}
|
||||
let process = unsafe { OwnedHandle::from_raw_handle(handle) };
|
||||
|
||||
let mut family_length = 0;
|
||||
let result = unsafe {
|
||||
GetPackageFamilyName(
|
||||
process.as_raw_handle(),
|
||||
&mut family_length,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if result != ERROR_INSUFFICIENT_BUFFER || family_length == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut family = vec![0_u16; family_length as usize];
|
||||
let result = unsafe {
|
||||
GetPackageFamilyName(
|
||||
process.as_raw_handle(),
|
||||
&mut family_length,
|
||||
family.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
if result != ERROR_SUCCESS {
|
||||
return None;
|
||||
}
|
||||
|
||||
let end = family.iter().position(|value| *value == 0)?;
|
||||
String::from_utf16(&family[..end]).ok()
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
|
||||
pub(super) fn application_running(_application: &InstalledApp, _candidate_pid: u32) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(super) fn desktop_check(
|
||||
id: impl Into<String>,
|
||||
status: CheckStatus,
|
||||
summary: impl Into<String>,
|
||||
) -> DoctorCheck {
|
||||
DoctorCheck::new(id, "desktop", status, summary)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn installed_windows_app() -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
const PACKAGE_FAMILY: &str = "OpenAI.Codex_2p2nqsd0c76g0";
|
||||
|
||||
let family = PACKAGE_FAMILY
|
||||
.encode_utf16()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
let mut count = 0;
|
||||
let mut length = 0;
|
||||
let result = unsafe {
|
||||
FindPackagesByPackageFamily(
|
||||
family.as_ptr(),
|
||||
PACKAGE_FILTER_HEAD,
|
||||
&mut count,
|
||||
std::ptr::null_mut(),
|
||||
&mut length,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if result == ERROR_SUCCESS && count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
if result != ERROR_INSUFFICIENT_BUFFER {
|
||||
return Err(DiscoveryError);
|
||||
}
|
||||
|
||||
let mut names = vec![std::ptr::null_mut(); count as usize];
|
||||
let mut buffer = vec![0_u16; length as usize];
|
||||
let result = unsafe {
|
||||
FindPackagesByPackageFamily(
|
||||
family.as_ptr(),
|
||||
PACKAGE_FILTER_HEAD,
|
||||
&mut count,
|
||||
names.as_mut_ptr(),
|
||||
&mut length,
|
||||
buffer.as_mut_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if result != ERROR_SUCCESS {
|
||||
return Err(DiscoveryError);
|
||||
}
|
||||
if count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let end = buffer
|
||||
.iter()
|
||||
.position(|value| *value == 0)
|
||||
.ok_or(DiscoveryError)?;
|
||||
let package = String::from_utf16(&buffer[..end]).map_err(|_| DiscoveryError)?;
|
||||
let version = package
|
||||
.strip_prefix("OpenAI.Codex_")
|
||||
.and_then(|name| name.split('_').next())
|
||||
.filter(|version| {
|
||||
version
|
||||
.split('.')
|
||||
.all(|part| !part.is_empty() && part.bytes().all(|digit| digit.is_ascii_digit()))
|
||||
})
|
||||
.ok_or(DiscoveryError)?;
|
||||
|
||||
Ok(Some(InstalledApp {
|
||||
identity: "OpenAI.Codex",
|
||||
version: version.to_string(),
|
||||
package_family: PACKAGE_FAMILY,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
async fn installed_macos_app() -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
let applications = std::iter::once(PathBuf::from("/Applications"))
|
||||
.chain(std::env::var_os("HOME").map(|home| PathBuf::from(home).join("Applications")))
|
||||
.flat_map(|directory| {
|
||||
["ChatGPT.app", "Codex.app"]
|
||||
.into_iter()
|
||||
.map(move |application| directory.join(application))
|
||||
});
|
||||
|
||||
for bundle in applications {
|
||||
match fs::metadata(&bundle) {
|
||||
Ok(metadata) if metadata.is_dir() => {}
|
||||
Ok(_) => continue,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
|
||||
Err(_) => return Err(DiscoveryError),
|
||||
}
|
||||
if let Some(application) = inspect_macos_bundle(&bundle).await? {
|
||||
return Ok(Some(application));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::doctor) async fn inspect_macos_bundle(
|
||||
bundle: &Path,
|
||||
) -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
let mut command = Command::new("/usr/bin/plutil");
|
||||
command
|
||||
.args(["-convert", "json", "-o", "-"])
|
||||
.arg(bundle.join("Contents/Info.plist"))
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true);
|
||||
let output = timeout(Duration::from_secs(5), command.output())
|
||||
.await
|
||||
.map_err(|_| DiscoveryError)?
|
||||
.map_err(|_| DiscoveryError)?;
|
||||
if !output.status.success() || output.stdout.len() > 64 * 1024 {
|
||||
return Err(DiscoveryError);
|
||||
}
|
||||
let metadata: Value = serde_json::from_slice(&output.stdout).map_err(|_| DiscoveryError)?;
|
||||
if metadata.get("CFBundleIdentifier").and_then(Value::as_str) != Some("com.openai.codex") {
|
||||
return Ok(None);
|
||||
}
|
||||
let version = metadata
|
||||
.get("CFBundleShortVersionString")
|
||||
.or_else(|| metadata.get("CFBundleVersion"))
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(DiscoveryError)?;
|
||||
|
||||
Ok(Some(InstalledApp {
|
||||
identity: "com.openai.codex",
|
||||
version: version.to_string(),
|
||||
bundle: bundle.to_path_buf(),
|
||||
}))
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
use std::env;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::super::CheckStatus;
|
||||
use super::super::DoctorCheck;
|
||||
use super::platform::desktop_check;
|
||||
|
||||
const MAX_EVENTS_PER_CHANNEL: usize = 256;
|
||||
const MAX_RENDERED_EVENTS: usize = 16;
|
||||
const MAX_EVENT_OUTPUT_BYTES: usize = 2 * 1024 * 1024;
|
||||
type Channel = (&'static str, &'static str, &'static [u32]);
|
||||
type Evidence = (CheckStatus, String);
|
||||
|
||||
const CHANNELS: [Channel; 5] = [
|
||||
(
|
||||
"microsoft_defender",
|
||||
"Microsoft-Windows-Windows Defender/Operational",
|
||||
&[
|
||||
1006, 1007, 1116, 1117, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128,
|
||||
],
|
||||
),
|
||||
(
|
||||
"applocker",
|
||||
"Microsoft-Windows-AppLocker/EXE and DLL",
|
||||
&[8003, 8004],
|
||||
),
|
||||
(
|
||||
"applocker",
|
||||
"Microsoft-Windows-AppLocker/Packaged app-Execution",
|
||||
&[8021, 8022],
|
||||
),
|
||||
(
|
||||
"applocker",
|
||||
"Microsoft-Windows-AppLocker/MSI and Script",
|
||||
&[8006, 8007],
|
||||
),
|
||||
(
|
||||
"windows_app_control",
|
||||
"Microsoft-Windows-CodeIntegrity/Operational",
|
||||
&[3076, 3077],
|
||||
),
|
||||
];
|
||||
|
||||
pub(super) async fn collect() -> DoctorCheck {
|
||||
let Some(system_root) = env::var_os("SystemRoot") else {
|
||||
return classify(&[]);
|
||||
};
|
||||
let wevtutil = Path::new(&system_root).join("System32/wevtutil.exe");
|
||||
let mut channels = Vec::with_capacity(CHANNELS.len());
|
||||
for pair in CHANNELS.chunks(/*chunk_size*/ 2) {
|
||||
let first = query_channel(&wevtutil, pair[0]);
|
||||
if let Some(second) = pair.get(/*index*/ 1) {
|
||||
let (first, second) = tokio::join!(first, query_channel(&wevtutil, *second));
|
||||
channels.extend([first, second]);
|
||||
} else {
|
||||
channels.push(first.await);
|
||||
}
|
||||
}
|
||||
classify(&channels)
|
||||
}
|
||||
|
||||
async fn query_channel(wevtutil: &Path, channel: Channel) -> Option<Vec<Evidence>> {
|
||||
let events = channel
|
||||
.2
|
||||
.iter()
|
||||
.map(|id| format!("EventID={id}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" or ");
|
||||
let mut child = Command::from(akode_utils_process::background_command(wevtutil))
|
||||
.args(["qe", channel.1])
|
||||
.arg(format!(
|
||||
"/q:*[System[({events}) and TimeCreated[timediff(@SystemTime) <= 604800000]]]"
|
||||
))
|
||||
.arg(format!("/c:{MAX_EVENTS_PER_CHANNEL}"))
|
||||
.args(["/rd:true", "/f:xml"])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let mut output = Vec::new();
|
||||
let status = timeout(Duration::from_secs(10), async {
|
||||
let mut reader = child.stdout.take()?.take(MAX_EVENT_OUTPUT_BYTES as u64 + 1);
|
||||
reader.read_to_end(&mut output).await.ok()?;
|
||||
if output.len() > MAX_EVENT_OUTPUT_BYTES {
|
||||
return None;
|
||||
}
|
||||
child.wait().await.ok()
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()?;
|
||||
status
|
||||
.success()
|
||||
.then(|| parse_events(&String::from_utf8_lossy(&output), channel))
|
||||
}
|
||||
|
||||
fn parse_events(xml: &str, (source, _, ids): Channel) -> Vec<Evidence> {
|
||||
xml.split("</Event>")
|
||||
.take(MAX_EVENTS_PER_CHANNEL)
|
||||
.filter_map(|event| {
|
||||
let id = element(event, "EventID")?.parse().ok()?;
|
||||
if !ids.contains(&id) {
|
||||
return None;
|
||||
}
|
||||
let target = event
|
||||
.split("<Data")
|
||||
.skip(/*n*/ 1)
|
||||
.filter_map(|data| data.split_once('>')?.1.split_once("</Data>").map(|v| v.0))
|
||||
.chain(
|
||||
["FilePath", "FileName", "Image", "PackageName", "PackageFamilyName"]
|
||||
.into_iter()
|
||||
.filter_map(|name| element(event, name)),
|
||||
)
|
||||
.find_map(event_target)?;
|
||||
let timestamp = event.split_once("SystemTime=\"")?.1.split_once('"')?.0;
|
||||
let (status, action) = match id {
|
||||
1121 | 1123 | 1126 | 1127 | 8004 | 8007 | 8022 | 3077 => {
|
||||
(CheckStatus::Fail, "blocked")
|
||||
}
|
||||
1122 | 1124 | 1125 | 1128 | 8003 | 8006 | 8021 | 3076 => {
|
||||
(CheckStatus::Warning, "audited")
|
||||
}
|
||||
1006 | 1116 => (CheckStatus::Warning, "detected"),
|
||||
1007 | 1117 => defender_action(event),
|
||||
_ => return None,
|
||||
};
|
||||
Some((
|
||||
status,
|
||||
format!(
|
||||
"source: {source}; event: {id}; target: {target}; action: {action}; time: {timestamp}"
|
||||
),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn event_target(value: &str) -> Option<&'static str> {
|
||||
let value = value.to_ascii_lowercase();
|
||||
let parts = value.split(['\\', '/']).map(str::trim).collect::<Vec<_>>();
|
||||
let name = *parts.last()?;
|
||||
let package = parts.iter().any(|part| part.starts_with("openai.codex_"));
|
||||
let trusted = package || parts.windows(2).any(|pair| pair == ["openai", "codex"]);
|
||||
match name {
|
||||
"akode-windows-sandbox-setup.exe" => Some("sandbox_setup"),
|
||||
"akode-command-runner.exe" => Some("command_runner"),
|
||||
"akode.exe" => Some("codex"),
|
||||
"codex-desktop.exe" => Some("codex_desktop"),
|
||||
"chatgpt.exe" | "electron.exe" if trusted => Some("codex_desktop"),
|
||||
"rg.exe" if trusted => Some("ripgrep"),
|
||||
_ if package => Some("codex_desktop_package"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn defender_action(event: &str) -> (CheckStatus, &'static str) {
|
||||
let action = [
|
||||
"Action Name",
|
||||
"ActionName",
|
||||
"Action",
|
||||
"Action ID",
|
||||
"ActionID",
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|name| data_value(event, name))
|
||||
.or_else(|| element(event, "ActionName"))
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
match action.as_str() {
|
||||
"quarantine" | "2" => (CheckStatus::Fail, "quarantined"),
|
||||
"clean" | "remove" | "block" | "1" | "3" | "10" => (CheckStatus::Fail, "blocked"),
|
||||
"allow" | "ignore" | "none" | "no action" | "user defined" | "6" | "8" | "9" | "11" => {
|
||||
(CheckStatus::Ok, "allowed")
|
||||
}
|
||||
_ => (CheckStatus::Warning, "detected"),
|
||||
}
|
||||
}
|
||||
|
||||
fn classify(channels: &[Option<Vec<Evidence>>]) -> DoctorCheck {
|
||||
let visible = channels.iter().any(Option::is_some);
|
||||
let mut status = if visible {
|
||||
CheckStatus::Ok
|
||||
} else {
|
||||
CheckStatus::Warning
|
||||
};
|
||||
let mut details = Vec::new();
|
||||
for (event_status, detail) in channels.iter().flatten().flatten() {
|
||||
status = status.max(*event_status);
|
||||
if details.len() < MAX_RENDERED_EVENTS {
|
||||
details.push(detail.clone());
|
||||
}
|
||||
}
|
||||
let summary = match (status, visible) {
|
||||
(CheckStatus::Ok, _) if channels.contains(&None) => "security event coverage is incomplete",
|
||||
(CheckStatus::Ok, _) => "no locally visible recent aKode security enforcement was found",
|
||||
(CheckStatus::Warning, false) => "security event channels could not be inspected",
|
||||
(CheckStatus::Warning, true) => "recent aKode security audit or detection requires review",
|
||||
(CheckStatus::Fail, _) => "endpoint security blocked or quarantined a Codex executable",
|
||||
};
|
||||
let mut check = desktop_check("desktop.security.enforcement", status, summary).details(details);
|
||||
if status != CheckStatus::Ok {
|
||||
check = check.remediation(
|
||||
"ask your organization's security administrator to review endpoint security events and the approved aKode application policy",
|
||||
);
|
||||
}
|
||||
check
|
||||
}
|
||||
|
||||
fn element<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
|
||||
let body = xml.split_once(&format!("<{name}"))?.1.split_once('>')?.1;
|
||||
Some(body.split_once(&format!("</{name}>"))?.0.trim())
|
||||
}
|
||||
|
||||
fn data_value<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
|
||||
let body = xml
|
||||
.split_once(&format!("Name=\"{name}\""))?
|
||||
.1
|
||||
.split_once('>')?
|
||||
.1;
|
||||
Some(body.split_once("</Data>")?.0.trim())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "windows_security_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,85 +0,0 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::CHANNELS;
|
||||
use super::CheckStatus;
|
||||
use super::MAX_RENDERED_EVENTS;
|
||||
use super::classify;
|
||||
use super::parse_events;
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[tokio::test]
|
||||
async fn an_unavailable_reader_is_not_reported_as_clean() {
|
||||
assert_eq!(super::collect().await.status, CheckStatus::Warning);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_source_distinguishes_audits_from_blocks() {
|
||||
for (channel, audit, block) in [
|
||||
(0, 1122, 1121),
|
||||
(0, 1125, 1126),
|
||||
(1, 8003, 8004),
|
||||
(2, 8021, 8022),
|
||||
(3, 8006, 8007),
|
||||
(4, 3076, 3077),
|
||||
] {
|
||||
for (id, expected) in [(audit, CheckStatus::Warning), (block, CheckStatus::Fail)] {
|
||||
let events = parse_events(&fixture(id, "akode.exe", &[]), CHANNELS[channel]);
|
||||
assert_eq!(events[0].0, expected, "misclassified event {id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defender_distinguishes_detection_and_remediation() {
|
||||
for (id, action, expected) in [
|
||||
(1116, "", CheckStatus::Warning),
|
||||
(1117, "Allow", CheckStatus::Ok),
|
||||
(1117, "Quarantine", CheckStatus::Fail),
|
||||
(1117, "Remove", CheckStatus::Fail),
|
||||
] {
|
||||
let events = parse_events(
|
||||
&fixture(id, "akode.exe", &[("Action Name", action)]),
|
||||
CHANNELS[0],
|
||||
);
|
||||
assert_eq!(classify(&[Some(events)]).status, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_trusted_codex_executables_are_reported() {
|
||||
for (path, expected) in [
|
||||
("akode.exe", true),
|
||||
(r"OpenAI.Codex_2p2nqsd0c76g0\ChatGPT.exe", true),
|
||||
("evil-codex.exe", false),
|
||||
(r"C:\Other\ChatGPT.exe", false),
|
||||
(r"OpenAI.CodexEvil_1\ChatGPT.exe", false),
|
||||
] {
|
||||
let events = parse_events(&fixture(/*id*/ 1121, path, &[]), CHANNELS[0]);
|
||||
assert_eq!(!events.is_empty(), expected, "misclassified {path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evidence_is_bounded_redacted_and_correctly_classified() {
|
||||
assert_eq!(classify(&[None]).status, CheckStatus::Warning);
|
||||
assert_eq!(classify(&[Some(Vec::new()), None]).status, CheckStatus::Ok);
|
||||
let audits = fixture(/*id*/ 1122, "akode.exe", &[]).repeat(MAX_RENDERED_EVENTS);
|
||||
let secret = "private-customer-secret";
|
||||
let block = fixture(/*id*/ 1121, "akode.exe", &[("User", secret)]);
|
||||
let events = parse_events(&format!("{audits}{block}"), CHANNELS[0]);
|
||||
let check = classify(&[Some(events)]);
|
||||
assert_eq!(check.id, "desktop.security.enforcement");
|
||||
assert_eq!(check.status, CheckStatus::Fail);
|
||||
assert_eq!(check.details.len(), MAX_RENDERED_EVENTS);
|
||||
assert!(!serde_json::to_string(&check).unwrap().contains(secret));
|
||||
}
|
||||
|
||||
fn fixture(id: u32, path: &str, fields: &[(&str, &str)]) -> String {
|
||||
let data = fields
|
||||
.iter()
|
||||
.map(|(name, value)| format!("<Data Name=\"{name}\">{value}</Data>"))
|
||||
.collect::<String>();
|
||||
format!(
|
||||
"<Event><System><EventID>{id}</EventID><TimeCreated SystemTime=\"2026-01-01T00:00:00Z\"/></System><EventData><Data Name=\"Path\">{path}</Data>{data}</EventData></Event>"
|
||||
)
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::desktop::inspect_desktop_session;
|
||||
|
||||
const CURRENT_SESSION: &str = "12345678-1234-1234-1234-123456789abc";
|
||||
const CURRENT_PROCESS: u32 = 12345;
|
||||
|
||||
#[test]
|
||||
fn current_desktop_session_reports_the_latest_local_handshake() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
write_log(
|
||||
directory.path(),
|
||||
concat!(
|
||||
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n",
|
||||
"2026-08-07T12:01:00.000Z info [AppServerConnection] Starting app-server connection hostId=local transport=websocket\n",
|
||||
"2026-08-07T12:02:00.000Z info [AppServerConnection] initialize_handshake_result outcome=success transportKind=websocket\n",
|
||||
"2026-08-07T12:03:00.000Z info [AppServerConnection] app_server_connection.state_changed hostId=remote transport=websocket\n",
|
||||
"2026-08-07T12:04:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=websocket\n",
|
||||
),
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |pid| pid == CURRENT_PROCESS);
|
||||
|
||||
assert!(running);
|
||||
assert_eq!(check.id, "desktop.app_server.handshake");
|
||||
assert_eq!(check.status, CheckStatus::Ok);
|
||||
assert_eq!(
|
||||
check.summary,
|
||||
"the desktop app-server initialized successfully"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_handshake_does_not_expose_sensitive_log_fields() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
write_log(
|
||||
directory.path(),
|
||||
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result errorMessage=\"desktop-secret outcome=success\" outcome=failure transportKind=stdio\n",
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |_| true);
|
||||
|
||||
assert!(running);
|
||||
assert_eq!(check.status, CheckStatus::Fail);
|
||||
assert_eq!(check.summary, "the desktop app-server failed to initialize");
|
||||
assert!(
|
||||
!serde_json::to_string(&check)
|
||||
.unwrap()
|
||||
.contains("desktop-secret")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_failure_in_the_middle_of_a_log_segment_is_detected() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
let padding = "x".repeat(96 * 1024);
|
||||
write_log(
|
||||
directory.path(),
|
||||
&format!(
|
||||
"{padding}\n2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n{padding}"
|
||||
),
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |_| true);
|
||||
|
||||
assert!(running);
|
||||
assert_eq!(check.status, CheckStatus::Fail);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopped_desktop_does_not_report_a_failure() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
write_log(
|
||||
directory.path(),
|
||||
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n",
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |_| false);
|
||||
|
||||
assert!(!running);
|
||||
assert_eq!(check.status, CheckStatus::Ok);
|
||||
assert_eq!(check.summary, "the desktop application is not running");
|
||||
}
|
||||
|
||||
fn write_log(directory: &Path, contents: &str) {
|
||||
fs::write(
|
||||
directory.join(format!(
|
||||
"codex-desktop-{CURRENT_SESSION}-{CURRENT_PROCESS}-t0-i0-120000-0.log"
|
||||
)),
|
||||
contents,
|
||||
)
|
||||
.expect("desktop log fixture should be created");
|
||||
}
|
||||
@@ -34,10 +34,6 @@ const GROUPS: &[OutputGroup] = &[
|
||||
title: "Configuration",
|
||||
keys: &["config", "auth", "mcp", "sandbox"],
|
||||
},
|
||||
OutputGroup {
|
||||
title: "Desktop App",
|
||||
keys: &["desktop"],
|
||||
},
|
||||
OutputGroup {
|
||||
title: "Updates",
|
||||
keys: &["updates"],
|
||||
@@ -504,9 +500,6 @@ fn notes_for_report(report: &DoctorReport) -> Vec<DoctorNote> {
|
||||
update_note(check, report)
|
||||
.into_iter()
|
||||
.for_each(|note| notes.push(note));
|
||||
desktop_update_note(check)
|
||||
.into_iter()
|
||||
.for_each(|note| notes.push(note));
|
||||
}
|
||||
if let Some(check) = find_check(report, "state") {
|
||||
rollout_note(check)
|
||||
@@ -556,21 +549,6 @@ fn update_note(check: &DoctorCheck, report: &DoctorReport) -> Option<DoctorNote>
|
||||
})
|
||||
}
|
||||
|
||||
fn desktop_update_note(check: &DoctorCheck) -> Option<DoctorNote> {
|
||||
let status = detail::detail_value(check, "desktop update status")?;
|
||||
let build = detail::detail_value(check, "desktop latest build")?;
|
||||
let summary = match status.as_str() {
|
||||
"ready to install" => format!("build {build} available (ready to install)"),
|
||||
"available" => format!("build {build} available"),
|
||||
_ => return None,
|
||||
};
|
||||
Some(DoctorNote {
|
||||
status: DisplayStatus::Update,
|
||||
name: "desktop".to_string(),
|
||||
summary,
|
||||
})
|
||||
}
|
||||
|
||||
fn rollout_note(check: &DoctorCheck) -> Option<DoctorNote> {
|
||||
let active = detail::detail_value(check, "active rollout files")?;
|
||||
let (files, bytes) = detail::rollout_files_and_bytes(&active)?;
|
||||
@@ -1453,40 +1431,8 @@ Background Server
|
||||
.iter_mut()
|
||||
.find(|detail| detail.starts_with("exclusion targets: "))
|
||||
.expect("endpoint security check should include exclusion targets");
|
||||
*targets = "exclusion targets: verified Codex app and required helpers".into();
|
||||
*targets = "exclusion targets: verified akode binary and required helpers".into();
|
||||
report.checks.push(security);
|
||||
report.checks.extend([
|
||||
DoctorCheck::new(
|
||||
"desktop.app.version",
|
||||
"desktop",
|
||||
CheckStatus::Ok,
|
||||
"the desktop application is installed",
|
||||
)
|
||||
.detail("version: 1.2.3")
|
||||
.detail("running: true")
|
||||
.detail("log directory: $HOME/Library/Logs/com.openai.codex"),
|
||||
DoctorCheck::new(
|
||||
"desktop.app_server.handshake",
|
||||
"desktop",
|
||||
CheckStatus::Ok,
|
||||
"the desktop app-server initialized successfully",
|
||||
),
|
||||
]);
|
||||
let update = report
|
||||
.checks
|
||||
.iter_mut()
|
||||
.find(|check| check.category == "updates")
|
||||
.unwrap();
|
||||
for (status, expected) in [
|
||||
("available", "build 123 available"),
|
||||
("ready to install", "build 123 available (ready to install)"),
|
||||
] {
|
||||
update.details = vec![
|
||||
format!("desktop update status: {status}"),
|
||||
"desktop latest build: 123".to_string(),
|
||||
];
|
||||
assert_eq!(desktop_update_note(update).unwrap().summary, expected);
|
||||
}
|
||||
insta::assert_snapshot!(
|
||||
"doctor_human_report_environment_rows",
|
||||
render_human_report(&report, detailed_no_color_unicode_options())
|
||||
|
||||
@@ -66,11 +66,11 @@ pub(super) fn endpoint_check(inspection: EndpointInspection) -> DoctorCheck {
|
||||
}
|
||||
|
||||
let targets = if cfg!(target_os = "windows") {
|
||||
"signed Codex app; codex.exe; akode-windows-sandbox-setup.exe; akode-command-runner.exe; akode-code-mode-host.exe"
|
||||
"akode.exe; akode-windows-sandbox-setup.exe; akode-command-runner.exe; akode-code-mode-host.exe"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"signing team 2DC432GLL2 plus the installed Codex app identity, signed codex agent, and required helpers"
|
||||
"the akode binary and required helpers"
|
||||
} else {
|
||||
"verified Codex app, codex agent, and required helpers"
|
||||
"verified akode binary and required helpers"
|
||||
};
|
||||
let mut check = DoctorCheck::new(
|
||||
"security.endpoint",
|
||||
|
||||
@@ -5,7 +5,6 @@ expression: "render_human_report(&report, detailed_no_color_unicode_options())"
|
||||
aKode Doctor v0.0.0
|
||||
|
||||
Notes
|
||||
↑ desktop build 123 available (ready to install)
|
||||
⚠ terminal narrow terminal
|
||||
✗ auth token expired - Run `akode login`.
|
||||
✗ network provider is unreachable - A macOS system proxy is configured but unused. If your organization requires it, ask your administrator whether to enable the experimental System proxy setting in `/experimental` or with `akode features enable respect_system_proxy`. Restart aKode after changing this setting.
|
||||
@@ -26,7 +25,7 @@ Environment
|
||||
✓ disk sufficient free disk space (42.0 GiB)
|
||||
⚠ security Microsoft Defender can interfere with aKode. Verify aKode exclusions.
|
||||
endpoint products Microsoft Defender
|
||||
exclusion targets verified aKode app and required helpers
|
||||
exclusion targets verified akode binary and required helpers
|
||||
▸ aKode exclusions not verified (expected aKode application and helper exclusions)
|
||||
→ Microsoft Defender: Add a certificate or executable-path exclusion for aKode and its helpers. If Attack Surface Reduction blocks aKode, add a rule exclusion. If Controlled Folder Access blocks aKode, allow the app.
|
||||
✓ runtime running local build on darwin-arm64
|
||||
@@ -39,10 +38,10 @@ Environment
|
||||
repo detected true
|
||||
⚠ git this worktree is not on a Windows Dev Drive — create a trusted Windows Dev Drive: https://learn.microsoft.com/en-us/windows/dev-drive/
|
||||
⚠ terminal narrow terminal
|
||||
✓ title default · project akode
|
||||
✓ title default · project codex
|
||||
title source default
|
||||
title items activity, project-name
|
||||
project value akode
|
||||
project value codex
|
||||
✓ state state paths inspectable
|
||||
|
||||
Configuration
|
||||
@@ -52,17 +51,8 @@ Configuration
|
||||
✗ auth token expired — Run `akode login`.
|
||||
OPENAI_API_KEY present
|
||||
|
||||
Desktop App
|
||||
✓ desktop the desktop application is installed
|
||||
version 1.2.3
|
||||
running true
|
||||
log directory $HOME/Library/Logs/com.openai.akode
|
||||
✓ desktop the desktop app-server initialized successfully
|
||||
|
||||
Updates
|
||||
✓ updates update configuration is locally consistent
|
||||
desktop update status ready to install
|
||||
desktop latest build 123
|
||||
|
||||
Connectivity
|
||||
✓ network network environment readable
|
||||
@@ -74,7 +64,7 @@ Background Server
|
||||
✓ app-server background server is not running
|
||||
|
||||
─────────────────────────────────────────────────────────────
|
||||
16 ok · 6 notes · 3 warn · 2 fail failed
|
||||
14 ok · 5 notes · 3 warn · 2 fail failed
|
||||
|
||||
--summary compact output --all expand truncated lists
|
||||
--json redacted report
|
||||
|
||||
@@ -1554,9 +1554,6 @@ impl App {
|
||||
AppEvent::OpenUrlInBrowser { url } => {
|
||||
self.open_url_in_browser(url);
|
||||
}
|
||||
AppEvent::OpenDesktopThread { thread_id } => {
|
||||
self.open_desktop_thread(thread_id);
|
||||
}
|
||||
AppEvent::PetSelected { pet_id } => {
|
||||
self.handle_pet_selected(tui, pet_id);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Terminal history, desktop handoff, and clear-screen UI helpers for the TUI app.
|
||||
//! Terminal history and clear-screen UI helpers for the TUI app.
|
||||
//!
|
||||
//! This module owns rendering the fresh session header, clearing inline or alternate-screen UI
|
||||
//! state, and resetting transcript-related app state after `/clear` or Ctrl-L. Owned-screen sessions
|
||||
@@ -7,8 +7,6 @@
|
||||
use super::*;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
|
||||
const DESKTOP_THREAD_OPENED_MESSAGE: &str = "Opened this session in the Desktop app.";
|
||||
|
||||
/// Lines of the most recently committed history cell, kept so reflow and restore can be verified.
|
||||
pub(super) struct RenderedHistoryTail {
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
@@ -119,20 +117,6 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn open_desktop_thread(&mut self, thread_id: ThreadId) {
|
||||
let url = format!("codex://threads/{thread_id}");
|
||||
if let Err(err) = open_desktop_thread_url(&url) {
|
||||
self.chat_widget
|
||||
.add_error_message(desktop_thread_open_error_message(&err));
|
||||
return;
|
||||
}
|
||||
|
||||
self.chat_widget.add_info_message(
|
||||
DESKTOP_THREAD_OPENED_MESSAGE.to_string(),
|
||||
/*hint*/ None,
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn clear_ui_header_lines_with_version(
|
||||
&self,
|
||||
width: u16,
|
||||
@@ -258,107 +242,6 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
fn desktop_thread_open_error_message(err: &str) -> String {
|
||||
format!(
|
||||
"Failed to open this session in the Desktop app: {err}. Install or launch the Desktop app and try again."
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn open_desktop_thread_url(url: &str) -> Result<(), String> {
|
||||
let status = std::process::Command::new("open")
|
||||
.arg(url)
|
||||
.status()
|
||||
.map_err(|err| format!("failed to invoke `open`: {err}"))?;
|
||||
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("`open {url}` exited with {status}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn open_desktop_thread_url(url: &str) -> Result<(), String> {
|
||||
let script = windows_desktop_app_launch_script(url);
|
||||
let output = std::process::Command::new("powershell.exe")
|
||||
.arg("-NoProfile")
|
||||
.arg("-Command")
|
||||
.arg(&script)
|
||||
.output()
|
||||
.map_err(|err| format!("failed to launch the Desktop app through PowerShell: {err}"))?;
|
||||
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
if stderr.is_empty() {
|
||||
Err(format!(
|
||||
"failed to launch the Desktop app through PowerShell with {}",
|
||||
output.status
|
||||
))
|
||||
} else {
|
||||
Err(stderr)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn windows_desktop_app_launch_script(url: &str) -> String {
|
||||
let url = powershell_single_quoted_string(url);
|
||||
format!(
|
||||
r#"
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$url = {url}
|
||||
|
||||
$package = Get-AppxPackage -Name OpenAI.Codex -ErrorAction SilentlyContinue
|
||||
if ($null -eq $package) {{
|
||||
Write-Error 'Desktop app package is not installed'
|
||||
exit 1
|
||||
}}
|
||||
|
||||
$manifest = Get-AppxPackageManifest -Package $package.PackageFullName
|
||||
$application = $manifest.Package.Applications.Application |
|
||||
Where-Object {{
|
||||
@($_.Extensions.Extension) | Where-Object {{
|
||||
$_.Category -eq 'windows.protocol' -and $_.Protocol.Name -eq 'codex'
|
||||
}}
|
||||
}} |
|
||||
Select-Object -First 1
|
||||
if ($null -eq $application -or [string]::IsNullOrWhiteSpace($application.Executable)) {{
|
||||
Write-Error 'Desktop app package does not declare a codex protocol executable'
|
||||
exit 1
|
||||
}}
|
||||
|
||||
# Launch the package-declared protocol executable rather than an internal Electron shim.
|
||||
# Windows can deny direct starts of internal executables under WindowsApps.
|
||||
$exe = Join-Path $package.InstallLocation $application.Executable
|
||||
$appDir = Split-Path -Parent $exe
|
||||
$app = Join-Path $appDir 'resources\app.asar'
|
||||
if (-not (Test-Path $exe)) {{
|
||||
Write-Error "Desktop app executable not found at $exe"
|
||||
exit 1
|
||||
}}
|
||||
if (-not (Test-Path $app)) {{
|
||||
Write-Error "Desktop app bundle not found at $app"
|
||||
exit 1
|
||||
}}
|
||||
|
||||
Start-Process -FilePath $exe -WorkingDirectory $appDir -ArgumentList @('resources\app.asar', $url)
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn powershell_single_quoted_string(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "''"))
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
fn open_desktop_thread_url(_url: &str) -> Result<(), String> {
|
||||
Err("The Desktop app is only available on macOS and Windows".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "history_ui_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -1,38 +1,11 @@
|
||||
//! Desktop handoff output and clear-screen history reset behavior.
|
||||
//! Clear-screen history reset behavior.
|
||||
|
||||
use super::*;
|
||||
use crate::app::tests::make_test_app_with_channels;
|
||||
use crate::history_cell;
|
||||
use crate::history_cell::HistoryCell;
|
||||
use crate::history_cell::PlainHistoryCell;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn desktop_thread_opened_history_snapshot() {
|
||||
let cell = history_cell::new_info_event(
|
||||
DESKTOP_THREAD_OPENED_MESSAGE.to_string(),
|
||||
/*hint*/ None,
|
||||
);
|
||||
|
||||
insta::assert_snapshot!("desktop_thread_opened_history", render_cell(&cell));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_thread_open_error_history_snapshot() {
|
||||
let cell = history_cell::new_error_event(desktop_thread_open_error_message("launch failed"));
|
||||
|
||||
insta::assert_snapshot!("desktop_thread_open_error_history", render_cell(&cell));
|
||||
}
|
||||
|
||||
fn render_cell(cell: &impl HistoryCell) -> String {
|
||||
let lines = cell.display_lines(/*width*/ 80);
|
||||
lines
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn viewed_image_links_follow_workspace_locality() -> Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
source: tui/src/app/history_ui_tests.rs
|
||||
expression: render_cell(&cell)
|
||||
---
|
||||
■ Failed to open this session in the Desktop app: launch failed. Install or launch the Desktop app and try again.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
source: tui/src/app/history_ui_tests.rs
|
||||
expression: render_cell(&cell)
|
||||
---
|
||||
• Opened this session in the Desktop app.
|
||||
@@ -847,11 +847,6 @@ pub(crate) enum AppEvent {
|
||||
url: String,
|
||||
},
|
||||
|
||||
/// Open the current thread in Codex Desktop.
|
||||
OpenDesktopThread {
|
||||
thread_id: ThreadId,
|
||||
},
|
||||
|
||||
/// Persist a pet selection and reload the ambient pet.
|
||||
PetSelected {
|
||||
pet_id: String,
|
||||
|
||||
@@ -526,7 +526,6 @@ fn parent_owned_command_is_allowed(command: SlashCommand, args: &str) -> bool {
|
||||
| SlashCommand::New
|
||||
| SlashCommand::Clear
|
||||
| SlashCommand::Resume
|
||||
| SlashCommand::App
|
||||
| SlashCommand::Side
|
||||
| SlashCommand::Btw
|
||||
| SlashCommand::Agents
|
||||
|
||||
@@ -510,25 +510,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
#[test]
|
||||
fn app_command_popup_snapshot() {
|
||||
let mut popup = CommandPopup::new(CommandPopupFlags::default(), Vec::new());
|
||||
popup.on_composer_text_change("/app".to_string());
|
||||
|
||||
let width = 72;
|
||||
let area = Rect::new(
|
||||
/*x*/ 0,
|
||||
/*y*/ 0,
|
||||
width,
|
||||
popup.calculate_required_height(width),
|
||||
);
|
||||
let mut buf = Buffer::empty(area);
|
||||
popup.render_ref(area, &mut buf);
|
||||
|
||||
insta::assert_snapshot!("command_popup_app", format!("{buf:?}"));
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
#[test]
|
||||
fn voice_command_popup_snapshot() {
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
---
|
||||
source: tui/src/bottom_pane/command_popup.rs
|
||||
expression: "format!(\"{buf:?}\")"
|
||||
---
|
||||
Buffer {
|
||||
area: Rect { x: 0, y: 0, width: 72, height: 2 },
|
||||
content: [
|
||||
"› /app continue this session in the Desktop app ",
|
||||
" /approve approve one retry of a recent auto-review denial ",
|
||||
],
|
||||
styles: [
|
||||
x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED,
|
||||
x: 12, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: REVERSED,
|
||||
x: 52, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED,
|
||||
x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 3, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
|
||||
x: 6, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 12, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
|
||||
x: 60, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
]
|
||||
}
|
||||
@@ -293,16 +293,6 @@ impl ChatWidget {
|
||||
SlashCommand::Worktree => {
|
||||
self.show_managed_worktree_picker();
|
||||
}
|
||||
SlashCommand::App => {
|
||||
let Some(thread_id) = self.thread_id else {
|
||||
self.add_error_message(
|
||||
"Session is still starting; try /app again in a moment.".to_string(),
|
||||
);
|
||||
return;
|
||||
};
|
||||
self.app_event_tx
|
||||
.send(AppEvent::OpenDesktopThread { thread_id });
|
||||
}
|
||||
SlashCommand::Init => {
|
||||
const INIT_PROMPT: &str = include_str!("../../assets/prompt_for_init_command.md");
|
||||
self.submit_user_message(INIT_PROMPT.to_string().into());
|
||||
@@ -1237,7 +1227,6 @@ impl ChatWidget {
|
||||
| SlashCommand::Raw
|
||||
| SlashCommand::Vim
|
||||
| SlashCommand::Diff
|
||||
| SlashCommand::App
|
||||
| SlashCommand::Rename
|
||||
| SlashCommand::Voice
|
||||
| SlashCommand::Recap
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests/slash_commands.rs
|
||||
expression: "lines_to_single_string(&cells[0])"
|
||||
---
|
||||
■ Session is still starting; try /app again in a moment.
|
||||
@@ -3072,36 +3072,6 @@ async fn slash_fork_with_name_requests_named_fork() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slash_app_requests_desktop_handoff() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
let thread_id = ThreadId::new();
|
||||
chat.thread_id = Some(thread_id);
|
||||
|
||||
chat.dispatch_command(SlashCommand::App);
|
||||
|
||||
assert_matches!(
|
||||
rx.try_recv(),
|
||||
Ok(AppEvent::OpenDesktopThread {
|
||||
thread_id: actual_thread_id,
|
||||
}) if actual_thread_id == thread_id
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slash_app_without_thread_id_shows_starting_error() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
|
||||
chat.dispatch_command(SlashCommand::App);
|
||||
|
||||
let cells = drain_insert_history(&mut rx);
|
||||
assert_eq!(cells.len(), 1, "expected app startup error");
|
||||
assert_chatwidget_snapshot!(
|
||||
"slash_app_without_thread_id_shows_starting_error",
|
||||
lines_to_single_string(&cells[0])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slash_pwd_and_cwd_alias_display_current_working_directory_from_composer() {
|
||||
let mut output = Vec::new();
|
||||
|
||||
@@ -35,7 +35,6 @@ pub enum SlashCommand {
|
||||
Resume,
|
||||
Fork,
|
||||
Worktree,
|
||||
App,
|
||||
Init,
|
||||
Compact,
|
||||
Config,
|
||||
@@ -103,7 +102,6 @@ impl SlashCommand {
|
||||
SlashCommand::Clear => "clear the terminal and start a new chat",
|
||||
SlashCommand::Fork => "fork the current chat",
|
||||
SlashCommand::Worktree => "start or continue a conversation in a new worktree",
|
||||
SlashCommand::App => "continue this session in the Desktop app",
|
||||
SlashCommand::Quit | SlashCommand::Exit => "exit aKode",
|
||||
SlashCommand::Copy => "copy the last response or part of it",
|
||||
SlashCommand::Export => "export the conversation as markdown",
|
||||
@@ -280,7 +278,6 @@ impl SlashCommand {
|
||||
| SlashCommand::DebugConfig
|
||||
| SlashCommand::Ps
|
||||
| SlashCommand::Stop
|
||||
| SlashCommand::App
|
||||
| SlashCommand::Goal
|
||||
| SlashCommand::Voice
|
||||
| SlashCommand::Mcp
|
||||
@@ -304,7 +301,6 @@ impl SlashCommand {
|
||||
fn is_visible(self) -> bool {
|
||||
match self {
|
||||
SlashCommand::Copy => !cfg!(target_os = "android"),
|
||||
SlashCommand::App => cfg!(any(target_os = "macos", target_os = "windows")),
|
||||
SlashCommand::Voice => true,
|
||||
SlashCommand::Rollout | SlashCommand::TestApproval => cfg!(debug_assertions),
|
||||
_ => true,
|
||||
@@ -352,7 +348,6 @@ mod tests {
|
||||
assert!(SlashCommand::Raw.available_during_task());
|
||||
assert!(SlashCommand::Raw.available_in_side_conversation());
|
||||
assert!(SlashCommand::Raw.supports_inline_args());
|
||||
assert!(SlashCommand::App.available_during_task());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user