mirror of
https://github.com/openai/codex.git
synced 2026-11-16 22:00:36 +00:00
WIP
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "codex-notifier"
|
||||
version = { workspace = true }
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1.0"
|
||||
Binary file not shown.
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>codex-notifier</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.openai.codex.notifier</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>Codex Notifier</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>0.1.0</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>14.0</string>
|
||||
<key>LSUIElement</key>
|
||||
<true/>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>Codex</string>
|
||||
<key>NSUserNotificationUsageDescription</key>
|
||||
<string>Codex CLI uses notifications to tell you when a turn completes.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,21 @@
|
||||
fn main() {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
use std::path::PathBuf;
|
||||
|
||||
let source = PathBuf::from("src/macos/notification.mm");
|
||||
println!("cargo:rerun-if-changed={}", source.display());
|
||||
|
||||
let mut build = cc::Build::new();
|
||||
build
|
||||
.cpp(true)
|
||||
.flag("-fobjc-arc")
|
||||
.flag("-fmodules")
|
||||
.file(&source);
|
||||
build.compile("codex_macos_notification");
|
||||
|
||||
println!("cargo:rustc-link-lib=framework=UserNotifications");
|
||||
println!("cargo:rustc-link-lib=framework=Foundation");
|
||||
println!("cargo:rustc-link-lib=framework=AppKit");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
#include <AppKit/AppKit.h>
|
||||
#include <UserNotifications/UserNotifications.h>
|
||||
#include <dispatch/dispatch.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
@interface CodexNotificationDelegate : NSObject <UNUserNotificationCenterDelegate>
|
||||
@end
|
||||
|
||||
@implementation CodexNotificationDelegate
|
||||
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
|
||||
willPresentNotification:(UNNotification *)notification
|
||||
withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
|
||||
completionHandler(UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionSound);
|
||||
}
|
||||
|
||||
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
|
||||
didReceiveNotificationResponse:(UNNotificationResponse *)response
|
||||
withCompletionHandler:(void (^)(void))completionHandler {
|
||||
completionHandler();
|
||||
}
|
||||
@end
|
||||
|
||||
static void install_delegate(UNUserNotificationCenter *center) {
|
||||
static dispatch_once_t onceToken;
|
||||
static CodexNotificationDelegate *delegate = nil;
|
||||
dispatch_once(&onceToken, ^{
|
||||
delegate = [CodexNotificationDelegate new];
|
||||
center.delegate = delegate;
|
||||
});
|
||||
}
|
||||
|
||||
static BOOL ensure_authorization(UNUserNotificationCenter *center) {
|
||||
dispatch_semaphore_t settings_wait = dispatch_semaphore_create(0);
|
||||
__block UNAuthorizationStatus status = UNAuthorizationStatusNotDetermined;
|
||||
|
||||
[center
|
||||
getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
|
||||
status = settings.authorizationStatus;
|
||||
dispatch_semaphore_signal(settings_wait);
|
||||
}];
|
||||
|
||||
dispatch_semaphore_wait(settings_wait, DISPATCH_TIME_FOREVER);
|
||||
|
||||
if (status == UNAuthorizationStatusDenied) {
|
||||
fprintf(stderr, "[codex-notifier] notification authorization currently denied\n");
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (status == UNAuthorizationStatusAuthorized ||
|
||||
status == UNAuthorizationStatusProvisional) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
dispatch_semaphore_t request_wait = dispatch_semaphore_create(0);
|
||||
__block BOOL granted = NO;
|
||||
|
||||
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound |
|
||||
UNAuthorizationOptionBadge)
|
||||
completionHandler:^(BOOL success, NSError *error) {
|
||||
granted = success;
|
||||
if (error) {
|
||||
fprintf(stderr, "[codex-notifier] authorization request error: %s\n",
|
||||
error.localizedDescription.UTF8String);
|
||||
}
|
||||
dispatch_semaphore_signal(request_wait);
|
||||
}];
|
||||
|
||||
dispatch_semaphore_wait(request_wait, DISPATCH_TIME_FOREVER);
|
||||
return granted;
|
||||
}
|
||||
|
||||
extern "C" int codex_post_user_notification(const char *title_c,
|
||||
const char *subtitle_c,
|
||||
const char *body_c,
|
||||
const char *icon_path_c) {
|
||||
setenv("__CFBundleIdentifier", "com.openai.codex.notifier", 0);
|
||||
|
||||
@autoreleasepool {
|
||||
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
|
||||
if (!center) {
|
||||
fprintf(stderr, "[codex-notifier] UNUserNotificationCenter unavailable\n");
|
||||
return -10;
|
||||
}
|
||||
|
||||
install_delegate(center);
|
||||
|
||||
if (!ensure_authorization(center)) {
|
||||
return -11;
|
||||
}
|
||||
|
||||
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
|
||||
if (!content) {
|
||||
fprintf(stderr, "[codex-notifier] failed to allocate notification content\n");
|
||||
return -12;
|
||||
}
|
||||
|
||||
if (title_c && title_c[0] != '\0') {
|
||||
content.title = [NSString stringWithUTF8String:title_c];
|
||||
} else {
|
||||
content.title = @"Codex CLI";
|
||||
}
|
||||
|
||||
if (subtitle_c && subtitle_c[0] != '\0') {
|
||||
content.subtitle = [NSString stringWithUTF8String:subtitle_c];
|
||||
}
|
||||
|
||||
if (body_c && body_c[0] != '\0') {
|
||||
content.body = [NSString stringWithUTF8String:body_c];
|
||||
}
|
||||
|
||||
if (icon_path_c && icon_path_c[0] != '\0') {
|
||||
NSError *attachmentError = nil;
|
||||
NSString *path = [NSString stringWithUTF8String:icon_path_c];
|
||||
UNNotificationAttachment *attachment =
|
||||
[UNNotificationAttachment attachmentWithIdentifier:@"codex-icon"
|
||||
URL:[NSURL fileURLWithPath:path]
|
||||
options:nil
|
||||
error:&attachmentError];
|
||||
if (attachment) {
|
||||
content.attachments = @[attachment];
|
||||
} else if (attachmentError) {
|
||||
fprintf(stderr, "[codex-notifier] attachment error: %s\n",
|
||||
attachmentError.localizedDescription.UTF8String);
|
||||
}
|
||||
}
|
||||
|
||||
UNTimeIntervalNotificationTrigger *trigger =
|
||||
[UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1 repeats:NO];
|
||||
NSString *identifier =
|
||||
[NSString stringWithFormat:@"com.openai.codex.notifier.%@", [[NSUUID UUID] UUIDString]];
|
||||
UNNotificationRequest *request =
|
||||
[UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
|
||||
|
||||
dispatch_semaphore_t submit_wait = dispatch_semaphore_create(0);
|
||||
__block NSError *submit_error = nil;
|
||||
[center addNotificationRequest:request
|
||||
withCompletionHandler:^(NSError *error) {
|
||||
submit_error = error;
|
||||
dispatch_semaphore_signal(submit_wait);
|
||||
}];
|
||||
|
||||
dispatch_semaphore_wait(submit_wait, DISPATCH_TIME_FOREVER);
|
||||
|
||||
if (submit_error) {
|
||||
fprintf(stderr, "[codex-notifier] addNotificationRequest error: %s\n",
|
||||
submit_error.localizedDescription.UTF8String);
|
||||
return -13;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
#![cfg_attr(not(target_os = "macos"), allow(unused))]
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use serde::Deserialize;
|
||||
use std::env;
|
||||
use std::ffi::CString;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::io::{self};
|
||||
use std::os::raw::c_char;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "kebab-case")]
|
||||
enum NotificationPayload {
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
AgentTurnComplete {
|
||||
thread_id: String,
|
||||
turn_id: String,
|
||||
cwd: String,
|
||||
#[serde(default)]
|
||||
input_messages: Vec<String>,
|
||||
#[serde(default)]
|
||||
last_assistant_message: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe extern "C" {
|
||||
fn codex_post_user_notification(
|
||||
title: *const c_char,
|
||||
subtitle: *const c_char,
|
||||
body: *const c_char,
|
||||
icon_path: *const c_char,
|
||||
) -> i32;
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
real_main()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn real_main() -> Result<()> {
|
||||
let payload = read_payload()?;
|
||||
let (title, subtitle, body) = render_notification(&payload)?;
|
||||
dispatch_notification(&title, subtitle.as_deref(), &body)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn real_main() -> Result<()> {
|
||||
bail!("codex-notifier is only supported on macOS");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn read_payload() -> Result<NotificationPayload> {
|
||||
let mut args = env::args().skip(1);
|
||||
let mut payload_json: Option<String> = None;
|
||||
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--payload" => {
|
||||
let Some(value) = args.next() else {
|
||||
bail!("missing value for --payload");
|
||||
};
|
||||
payload_json = Some(value);
|
||||
break;
|
||||
}
|
||||
"--payload-file" => {
|
||||
let Some(path) = args.next() else {
|
||||
bail!("missing value for --payload-file");
|
||||
};
|
||||
payload_json = Some(
|
||||
fs::read_to_string(Path::new(&path))
|
||||
.with_context(|| format!("failed to read payload file at {path}"))?,
|
||||
);
|
||||
// Best-effort cleanup to avoid cluttering temp directories.
|
||||
let _ = fs::remove_file(path);
|
||||
break;
|
||||
}
|
||||
// Ignore arguments injected by `open -a`.
|
||||
arg if arg.starts_with("-Apple") || arg == "-NSDocumentRevisionsDebugMode" => {
|
||||
let _ = args.next(); // consume companion value if present
|
||||
}
|
||||
_ => {
|
||||
// Unrecognised argument – continue scanning in case the payload flag appears later.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let json = if let Some(payload) = payload_json {
|
||||
payload
|
||||
} else {
|
||||
let mut buf = String::new();
|
||||
io::stdin()
|
||||
.read_to_string(&mut buf)
|
||||
.context("failed to read payload from stdin")?;
|
||||
buf
|
||||
};
|
||||
|
||||
serde_json::from_str(&json).context("failed to parse notification payload JSON")
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn render_notification(payload: &NotificationPayload) -> Result<(String, Option<String>, String)> {
|
||||
match payload {
|
||||
NotificationPayload::AgentTurnComplete {
|
||||
input_messages,
|
||||
last_assistant_message,
|
||||
cwd,
|
||||
..
|
||||
} => {
|
||||
let title = "Codex CLI".to_string();
|
||||
let subtitle = last_assistant_message
|
||||
.as_ref()
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.or_else(|| Some("Turn complete".to_string()));
|
||||
|
||||
let mut body = String::new();
|
||||
if !input_messages.is_empty() {
|
||||
body.push_str(&input_messages.join(" "));
|
||||
}
|
||||
if body.is_empty() {
|
||||
body.push_str("Agent turn finished");
|
||||
}
|
||||
body.push_str("\n");
|
||||
body.push_str(cwd);
|
||||
|
||||
Ok((title, subtitle, body))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn dispatch_notification(title: &str, subtitle: Option<&str>, body: &str) -> Result<()> {
|
||||
let title_c = CString::new(title)?;
|
||||
let subtitle_c = subtitle
|
||||
.map(|s| CString::new(s))
|
||||
.transpose()
|
||||
.context("invalid subtitle string")?;
|
||||
let body_c = CString::new(body)?;
|
||||
|
||||
let icon_ptr = std::ptr::null();
|
||||
|
||||
let code = unsafe {
|
||||
codex_post_user_notification(
|
||||
title_c.as_ptr(),
|
||||
subtitle_c.as_ref().map_or(std::ptr::null(), |c| c.as_ptr()),
|
||||
body_c.as_ptr(),
|
||||
icon_ptr,
|
||||
)
|
||||
};
|
||||
|
||||
if code != 0 {
|
||||
bail!("codex_post_user_notification returned error code {code}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user