Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions desktop/src-tauri/src/dock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
use std::{
fs, io,
path::PathBuf,
sync::atomic::{AtomicBool, Ordering},
};
use tauri::{menu::CheckMenuItem, ActivationPolicy, App, AppHandle, Manager, Wry};

const MARKER: &str = "hide-dock-icon";

pub struct Preference {
marker: Option<PathBuf>,
enabled: AtomicBool,
}

impl Preference {
fn load(directory: Option<PathBuf>) -> Self {
let marker = directory.map(|dir| dir.join(MARKER));
let enabled = marker.as_ref().is_some_and(|path| path.is_file());
Self {
marker,
enabled: AtomicBool::new(enabled),
}
}

pub fn enabled(&self) -> bool {
self.enabled.load(Ordering::Acquire)
}

fn set(&self, enabled: bool) -> io::Result<()> {
let marker = self.marker.as_ref().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"desktop configuration directory unavailable",
)
})?;
if enabled {
if let Some(directory) = marker.parent() {
fs::create_dir_all(directory)?;
}
match fs::File::create_new(marker) {
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists && marker.is_file() => {}
Err(error) => return Err(error),
}
} else if let Err(error) = fs::remove_file(marker) {
if error.kind() != io::ErrorKind::NotFound {
return Err(error);
}
}
self.enabled.store(enabled, Ordering::Release);
Ok(())
}
}

pub fn prepare_launch(mut app: App) -> App {
let preference = Preference::load(app.path().app_config_dir().ok());
if preference.enabled() {
// Stage this before the event loop starts so a saved preference applies at launch.
app.set_activation_policy(ActivationPolicy::Accessory);
app.set_dock_visibility(false);
}
app.manage(preference);
app
}

pub fn show_in_dock(window_visible: bool, hide_dock: bool, tray_available: bool) -> bool {
window_visible && (!hide_dock || !tray_available)
}

pub fn toggle(app: &AppHandle, item: &CheckMenuItem<Wry>) {
let preference = app.state::<Preference>();
// The native menu flips the checkmark before dispatching the event.
if let Err(error) = preference.set(!preference.enabled()) {
crate::logging::log_once("could not save Hide Dock icon", &error.to_string());
}
let _ = item.set_checked(preference.enabled());

crate::window::refresh_tray_policy(app);
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn dock_visibility_tracks_the_window_unless_menu_bar_mode_is_available() {
for hide_dock in [false, true] {
for tray_available in [false, true] {
assert!(!show_in_dock(false, hide_dock, tray_available));
}
}
assert!(show_in_dock(true, false, true));
assert!(!show_in_dock(true, true, true));
assert!(show_in_dock(true, true, false));
}

#[test]
fn preference_survives_reloads_and_restores_the_default_when_disabled() {
let directory = std::env::temp_dir().join(format!("ocx-dock-{}", uuid::Uuid::new_v4()));
let load = || Preference::load(Some(directory.clone()));
let preference = load();
assert!(!preference.enabled());
preference.set(true).unwrap();
assert!(load().enabled());
preference.set(false).unwrap();
assert!(!load().enabled());
fs::remove_dir(directory).unwrap();
}

#[test]
fn failed_save_keeps_the_current_preference() {
let preference = Preference::load(None);
assert!(preference.set(true).is_err());
assert!(!preference.enabled());
}
}
4 changes: 2 additions & 2 deletions desktop/src-tauri/src/exit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,8 +398,8 @@ impl ExitCoordinator {
self.inner().phase
}

#[cfg(test)]
fn hides_to_tray(&self) -> bool {
#[cfg(any(target_os = "macos", test))]
pub fn hides_to_tray(&self) -> bool {
self.inner().hides_to_tray
}
}
Expand Down
36 changes: 20 additions & 16 deletions desktop/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ mod cli_command_windows;
#[cfg(target_os = "macos")]
mod companion_query;
mod companion_usage;
#[cfg(target_os = "macos")]
mod dock;
mod endpoint;
mod exit;
mod first_run;
Expand Down Expand Up @@ -337,7 +339,7 @@ pub fn run() {
.menu(menu::build)
.on_menu_event(|app, event| menu::on_event(app, event.id().as_ref()));

builder
let app = builder
.invoke_handler(tauri::generate_handler![
show_dashboard,
hide_dashboard,
Expand Down Expand Up @@ -424,7 +426,7 @@ pub fn run() {
if startup::LaunchOrigin::detect() == startup::LaunchOrigin::User {
window::show(&window);
} else {
window::set_tray_policy(app.handle(), false);
window::refresh_tray_policy(app.handle());
}

recovery::register(app.handle());
Expand All @@ -436,18 +438,20 @@ pub fn run() {
Ok(())
})
.build(tauri::generate_context!())
.expect("error while building OpenCodex desktop shell")
.run(|app, event| {
// Dock/Finder reopening an existing macOS app does not launch a second instance.
#[cfg(target_os = "macos")]
if let tauri::RunEvent::Reopen { .. } = event {
show_dashboard(app.clone());
}
// Window close and the platform quit gesture arrive here as an exit request, and until
// this handler existed they went straight through to a SIGKILL of the runtime. D2 makes
// them hide; only the tray's Quit, and an update's coordinated restart, get past.
if let tauri::RunEvent::ExitRequested { code, api, .. } = event {
exit::on_exit_requested(app, code, &api);
}
});
.expect("error while building OpenCodex desktop shell");
#[cfg(target_os = "macos")]
let app = dock::prepare_launch(app);
app.run(|app, event| {
// Dock/Finder reopening an existing macOS app does not launch a second instance.
#[cfg(target_os = "macos")]
if let tauri::RunEvent::Reopen { .. } = event {
show_dashboard(app.clone());
}
// Window close and the platform quit gesture arrive here as an exit request, and until
// this handler existed they went straight through to a SIGKILL of the runtime. D2 makes
// them hide; only the tray's Quit, and an update's coordinated restart, get past.
if let tauri::RunEvent::ExitRequested { code, api, .. } = event {
exit::on_exit_requested(app, code, &api);
}
});
}
13 changes: 13 additions & 0 deletions desktop/src-tauri/src/tray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ pub fn install(app: &AppHandle) -> tauri::Result<()> {
app.autolaunch().is_enabled().unwrap_or(false),
None::<&str>,
)?;
#[cfg(target_os = "macos")]
let hide_dock = CheckMenuItem::with_id(
app,
"hide-dock-icon",
"Hide Dock icon",
true,
app.state::<crate::dock::Preference>().enabled(),
None::<&str>,
)?;
// The tray is built before the startup sequence has decided anything, so nothing owns a
// runtime yet. Ownership arrives later and reaches this item through [`set_owned`].
let owned = app
Expand Down Expand Up @@ -127,6 +136,8 @@ pub fn install(app: &AppHandle) -> tauri::Result<()> {
&cli_command,
&PredefinedMenuItem::separator(app)?,
&login,
#[cfg(target_os = "macos")]
&hide_dock,
&stop,
&PredefinedMenuItem::separator(app)?,
&check_updates,
Expand Down Expand Up @@ -242,6 +253,8 @@ pub fn install(app: &AppHandle) -> tauri::Result<()> {
}
}
}
#[cfg(target_os = "macos")]
"hide-dock-icon" => crate::dock::toggle(app, &hide_dock),
"stop-proxy" => {
// Through the coordinator, not beside it: Stop pressed twice, Stop then Quit, and
// Stop during an update all have to be one execution over one child.
Expand Down
48 changes: 33 additions & 15 deletions desktop/src-tauri/src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,16 +170,25 @@ pub fn shows_update_page(window: &WebviewWindow) -> bool {
}

pub fn show(window: &WebviewWindow) {
#[cfg(target_os = "macos")]
if window
.app_handle()
.state::<crate::dock::Preference>()
.enabled()
{
// The status menu must also restore a minimized dashboard in menu bar mode.
let _ = window.unminimize();
}
let _ = window.show();
let _ = window.set_focus();
report_visibility(window, true);
apply_tray_policy(window.app_handle(), true);
refresh_tray_policy(window.app_handle());
}

pub fn hide(window: &WebviewWindow) {
let _ = window.hide();
report_visibility(window, false);
apply_tray_policy(window.app_handle(), false);
refresh_tray_policy(window.app_handle());
}

/// Tell the main window's page whether its host window is visible.
Expand All @@ -204,22 +213,31 @@ pub fn report_visibility(window: &WebviewWindow, visible: bool) {
}

#[cfg(target_os = "macos")]
fn apply_tray_policy(app: &AppHandle, visible: bool) {
let policy = if visible {
tauri::ActivationPolicy::Regular
} else {
tauri::ActivationPolicy::Accessory
};
let _ = app.set_dock_visibility(visible);
let _ = app.set_activation_policy(policy);
pub fn refresh_tray_policy(app: &AppHandle) {
let handle = app.clone();
// Read live state in the same main-thread turn as both native updates. Startup can
// queue this refresh from another thread while the user toggles the menu item.
let _ = app.run_on_main_thread(move || {
let visible = handle
.get_webview_window("main")
.is_some_and(|window| window.is_visible().unwrap_or(false));
let hide_dock = handle.state::<crate::dock::Preference>().enabled();
let has_tray = handle
.state::<crate::exit::ExitCoordinator>()
.hides_to_tray();
let show_dock = crate::dock::show_in_dock(visible, hide_dock, has_tray);
let policy = if show_dock {
tauri::ActivationPolicy::Regular
} else {
tauri::ActivationPolicy::Accessory
};
let _ = handle.set_dock_visibility(show_dock);
let _ = handle.set_activation_policy(policy);
});
}

#[cfg(not(target_os = "macos"))]
fn apply_tray_policy(_app: &AppHandle, _visible: bool) {}

pub fn set_tray_policy(app: &AppHandle, visible: bool) {
apply_tray_policy(app, visible);
}
pub fn refresh_tray_policy(_app: &AppHandle) {}

#[cfg(test)]
mod tests {
Expand Down
2 changes: 1 addition & 1 deletion docs-site/src/content/docs/es/guides/desktop-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ Usa **Open dashboard** (abrir dashboard) u **Open in browser** (abrir en el nave

En Windows, aceptar **Take over** (tomar el control) permite hasta 90 segundos para detener de forma segura el entorno de ejecución existente, transferir su control e iniciar el que incluye la aplicación. El tiempo que tardes en decidir no cuenta para ese límite. Mantén la aplicación abierta mientras termina; si falla, usa **Retry** (reintentar) para volver a buscar el entorno de ejecución actual.

En macOS, cerrar el dashboard mantiene la aplicación en la barra de menús. Vuelve a abrir OpenCodex desde el Dock o Finder para recuperar el dashboard sin reiniciar el proxy.
En macOS, cerrar el dashboard mantiene la aplicación en la barra de menús. Elige **Open Dashboard** en la barra de menús o vuelve a abrir OpenCodex desde Finder para recuperar el dashboard sin reiniciar el proxy. Activa **Hide Dock icon** en el mismo menú si quieres ocultar el icono del Dock incluso con el dashboard abierto.

En Windows, **Start at Login** (iniciar al abrir sesión) registra la ruta del ejecutable entre comillas para el usuario actual, incluidas las instalaciones en `Program Files`. Los registros habilitados se actualizan una vez al iniciar la aplicación. Las entradas que hayas deshabilitado desde la bandeja o el Administrador de tareas permanecen deshabilitadas.

Expand Down
2 changes: 1 addition & 1 deletion docs-site/src/content/docs/fr/guides/desktop-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ L’application demande à son CLI intégré d’exécuter `ocx resolve --json`

Utilisez l’action **Open dashboard** ou **Open in browser** de la zone de notification pour passer du tableau de bord intégré à votre navigateur habituel. Le menu permet aussi de rechercher les mises à jour.

Sur macOS, fermer le tableau de bord laisse l’application active dans la barre des menus. Ouvrez à nouveau OpenCodex depuis le Dock ou le Finder pour réafficher le tableau de bord sans redémarrer le proxy.
Sur macOS, fermer le tableau de bord laisse l’application active dans la barre des menus. Choisissez **Open Dashboard** dans la barre des menus ou rouvrez OpenCodex depuis le Finder pour réafficher le tableau de bord sans redémarrer le proxy. Activez **Hide Dock icon** dans le même menu pour masquer l’icône du Dock même lorsque le tableau de bord est ouvert.

## Utilisation dans la zone de notification

Expand Down
2 changes: 1 addition & 1 deletion docs-site/src/content/docs/guides/desktop-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ runtime to stop safely, ownership to transfer, and the bundled runtime to start.
deciding at the prompt does not count toward this limit. Keep the app open while it finishes;
if it fails, use **Retry** to resolve the current runtime again.

On macOS, closing the dashboard keeps the app running in the menu bar. Open OpenCodex again from Dock or Finder to restore the dashboard without restarting the proxy.
On macOS, closing the dashboard keeps the app running in the menu bar. Use **Open Dashboard** from the menu bar or reopen OpenCodex from Finder to restore the dashboard without restarting the proxy. The Dock icon appears while the dashboard is open by default. Enable [**Hide Dock icon**](/guides/macos-menu-bar/#menu-bar-and-usage-panel) from the menu bar to keep it hidden.

On Windows, **Start at Login** quotes the executable path in the current-user startup
registration, including installations under `Program Files`. Previously enabled
Expand Down
2 changes: 2 additions & 0 deletions docs-site/src/content/docs/guides/macos-menu-bar.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ Use **Show Usage** in the tray menu to open the native panel. The panel shows to

The panel has **Refresh**, **Dashboard**, and **Settings** controls. **Dashboard** opens the usage view in the desktop window; **Settings** opens the **Menu bar & widget** tab under Usage. The tray menu also offers **Open Dashboard**, **Open in Browser**, **Start at Login**, **Stop proxy**, **Check for Updates…**, an **Install update** item when one is available, and **Quit**. **Stop proxy** is always listed but is enabled only when the app started the proxy itself; a proxy you started separately keeps running. Closing the window or using Command-Q hides the app when its tray is available; use the tray's **Quit** to exit it.

To keep OpenCodex out of the Dock even while its dashboard is open, enable **Hide Dock icon** in the OpenCodex menu bar menu. You can still use **Open Dashboard** and **Quit** from that menu. OpenCodex remembers your choice after relaunch. Uncheck **Hide Dock icon** to show the Dock icon again whenever the dashboard is open.

The desktop dashboard's update button opens the app's own update page; it checks and installs the same signed update as the tray menu.

The tray headline refreshes every 60 seconds. While the native panel is open, its data refreshes every 60 seconds; **Refresh** requests an immediate update.
Expand Down
2 changes: 1 addition & 1 deletion docs-site/src/content/docs/ja/guides/desktop-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ sudo apt install ./OpenCodex-<version>-linux-amd64.deb

トレイの **Open dashboard** または **Open in browser** で、埋め込みダッシュボードと通常のブラウザを切り替えられます。トレイから更新の確認もできます。

macOS では、ダッシュボードを閉じてもアプリはメニューバーで動作し続けます。Dock または Finder から OpenCodex を再度開くと、プロキシを再起動せずにダッシュボードが再表示されます。
macOS では、ダッシュボードを閉じてもアプリはメニューバーで動作し続けます。メニューバーの **Open Dashboard** を選ぶか、Finder から OpenCodex を再度開くと、プロキシを再起動せずにダッシュボードを表示できます。同じメニューの **Hide Dock icon** を有効にすると、ダッシュボードを開いている間も Dock アイコンを非表示にできます。

Codex の起動でプロキシが見つからない場合、同梱 CLI は独立して検証された Desktop の復旧を待ちます。Desktop に記録された所有権クレームがない場合も同様です。一致する Desktop がプロキシを停止済みか復旧を検証できないときはエラーになりますが、実行イメージ検証のないプラットフォームでは、記録された所有権クレームがありアプリが実行中なら既存の制限付き待機を維持します。プロセス名や検出ファイルだけでは通常の CLI 起動を妨げません。shim は macOS でアプリが終了しており、記録された所有権が有効な **Start at Login** 登録と一致すれば OpenCodex を開きます。自動で開き直すときはその登録の app バンドルパスを選択し、宣言されたメイン実行ファイルが登録済み Desktop の実行ファイルと一致するか確認します。登録がない・古い・不整合の場合は OpenCodex を手動で開いてください。同じバンドル識別子を持つ別コピーは代替として選択されません。shim が "activation not confirmed" と表示する場合は、シェル起動ファイルの他の PATH 設定の後に `. ~/.opencodex/codex-shell-env.sh` を追加してください。

Expand Down
2 changes: 1 addition & 1 deletion docs-site/src/content/docs/ko/guides/desktop-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ sudo apt install ./OpenCodex-<version>-linux-amd64.deb

트레이의 **Open dashboard** 또는 **Open in browser**를 사용하면 내장 대시보드와 일반 브라우저를 오갈 수 있습니다. 트레이에서는 업데이트도 확인할 수 있습니다.

macOS에서는 대시보드를 닫아도 앱이 메뉴 막대에서 계속 실행됩니다. Dock 또는 Finder에서 OpenCodex를 다시 열면 프록시를 재시작하지 않고 대시보드가 다시 표시됩니다.
macOS에서는 대시보드를 닫아도 앱이 메뉴 막대에서 계속 실행됩니다. 메뉴 막대에서 **Open Dashboard**를 선택하거나 Finder에서 OpenCodex를 다시 열면 프록시를 재시작하지 않고 대시보드를 표시할 수 있습니다. 같은 메뉴에서 **Hide Dock icon**을 켜면 대시보드가 열려 있어도 Dock 아이콘이 숨겨집니다.

## 데스크톱 앱과 ocx CLI 함께 사용하기

Expand Down
Loading
Loading