diff --git a/desktop/src-tauri/src/dock.rs b/desktop/src-tauri/src/dock.rs new file mode 100644 index 00000000000..522526ef0a1 --- /dev/null +++ b/desktop/src-tauri/src/dock.rs @@ -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, + enabled: AtomicBool, +} + +impl Preference { + fn load(directory: Option) -> 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) { + let preference = app.state::(); + // 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()); + } +} diff --git a/desktop/src-tauri/src/exit.rs b/desktop/src-tauri/src/exit.rs index 9c3d0040881..b5aca20f664 100644 --- a/desktop/src-tauri/src/exit.rs +++ b/desktop/src-tauri/src/exit.rs @@ -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 } } diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index 5966f2fc594..492e3c2877a 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -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; @@ -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, @@ -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()); @@ -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); + } + }); } diff --git a/desktop/src-tauri/src/tray.rs b/desktop/src-tauri/src/tray.rs index e12f97f44fe..5171fe1f211 100644 --- a/desktop/src-tauri/src/tray.rs +++ b/desktop/src-tauri/src/tray.rs @@ -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::().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 @@ -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, @@ -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. diff --git a/desktop/src-tauri/src/window.rs b/desktop/src-tauri/src/window.rs index 7b71614c64a..131549ae0f1 100644 --- a/desktop/src-tauri/src/window.rs +++ b/desktop/src-tauri/src/window.rs @@ -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::() + .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. @@ -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::().enabled(); + let has_tray = handle + .state::() + .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 { diff --git a/docs-site/src/content/docs/es/guides/desktop-app.md b/docs-site/src/content/docs/es/guides/desktop-app.md index 22a918cd378..ec6b5eee181 100644 --- a/docs-site/src/content/docs/es/guides/desktop-app.md +++ b/docs-site/src/content/docs/es/guides/desktop-app.md @@ -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. diff --git a/docs-site/src/content/docs/fr/guides/desktop-app.md b/docs-site/src/content/docs/fr/guides/desktop-app.md index 88056153260..d872f3ed407 100644 --- a/docs-site/src/content/docs/fr/guides/desktop-app.md +++ b/docs-site/src/content/docs/fr/guides/desktop-app.md @@ -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 diff --git a/docs-site/src/content/docs/guides/desktop-app.md b/docs-site/src/content/docs/guides/desktop-app.md index 731c7c26044..4d88b3168b3 100644 --- a/docs-site/src/content/docs/guides/desktop-app.md +++ b/docs-site/src/content/docs/guides/desktop-app.md @@ -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 diff --git a/docs-site/src/content/docs/guides/macos-menu-bar.md b/docs-site/src/content/docs/guides/macos-menu-bar.md index 89ab7089dbd..d205d98f403 100644 --- a/docs-site/src/content/docs/guides/macos-menu-bar.md +++ b/docs-site/src/content/docs/guides/macos-menu-bar.md @@ -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. diff --git a/docs-site/src/content/docs/ja/guides/desktop-app.md b/docs-site/src/content/docs/ja/guides/desktop-app.md index 67a743a2ac8..d1bbe96efe9 100644 --- a/docs-site/src/content/docs/ja/guides/desktop-app.md +++ b/docs-site/src/content/docs/ja/guides/desktop-app.md @@ -57,7 +57,7 @@ sudo apt install ./OpenCodex--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` を追加してください。 diff --git a/docs-site/src/content/docs/ko/guides/desktop-app.md b/docs-site/src/content/docs/ko/guides/desktop-app.md index c1aff82a522..f12dc886085 100644 --- a/docs-site/src/content/docs/ko/guides/desktop-app.md +++ b/docs-site/src/content/docs/ko/guides/desktop-app.md @@ -57,7 +57,7 @@ sudo apt install ./OpenCodex--linux-amd64.deb 트레이의 **Open dashboard** 또는 **Open in browser**를 사용하면 내장 대시보드와 일반 브라우저를 오갈 수 있습니다. 트레이에서는 업데이트도 확인할 수 있습니다. -macOS에서는 대시보드를 닫아도 앱이 메뉴 막대에서 계속 실행됩니다. Dock 또는 Finder에서 OpenCodex를 다시 열면 프록시를 재시작하지 않고 대시보드가 다시 표시됩니다. +macOS에서는 대시보드를 닫아도 앱이 메뉴 막대에서 계속 실행됩니다. 메뉴 막대에서 **Open Dashboard**를 선택하거나 Finder에서 OpenCodex를 다시 열면 프록시를 재시작하지 않고 대시보드를 표시할 수 있습니다. 같은 메뉴에서 **Hide Dock icon**을 켜면 대시보드가 열려 있어도 Dock 아이콘이 숨겨집니다. ## 데스크톱 앱과 ocx CLI 함께 사용하기 diff --git a/docs-site/src/content/docs/ru/guides/desktop-app.md b/docs-site/src/content/docs/ru/guides/desktop-app.md index 308553489c5..c8c6efc2965 100644 --- a/docs-site/src/content/docs/ru/guides/desktop-app.md +++ b/docs-site/src/content/docs/ru/guides/desktop-app.md @@ -73,7 +73,7 @@ CLI подтвердил отсутствие прокси; неопределё Используйте действия **Open dashboard** или **Open in browser** в системной панели, чтобы переключаться между встроенным дашбордом и обычным браузером. Там же доступны проверки обновлений. -В macOS после закрытия дашборда приложение продолжает работать в строке меню. Откройте OpenCodex снова через Dock или Finder, чтобы вернуть дашборд без перезапуска прокси. +В macOS после закрытия дашборда приложение продолжает работать в строке меню. Выберите **Open Dashboard** в строке меню или снова откройте OpenCodex через Finder, чтобы вернуть дашборд без перезапуска прокси. Включите **Hide Dock icon** в том же меню, чтобы скрыть значок в Dock даже при открытом дашборде. Если при запуске Codex прокси не найден, встроенный CLI ждёт независимо подтверждённого восстановления Desktop — в том числе когда у Desktop нет записанного заявления о владении. Совпавший Desktop, который остановил свой прокси или чьё восстановление невозможно проверить, даёт ошибку; исключение — на платформе без проверки живого образа записанное заявление о владении при работающем приложении сохраняет существующее ограниченное ожидание. Одного имени процесса или файла-локатора недостаточно, чтобы блокировать обычный запуск CLI. Shim открывает OpenCodex в macOS, если приложение завершено и записанное владение совпадает с действительной регистрацией **Start at Login**. При автоматическом повторном открытии выбирается путь bundle приложения из этой регистрации и проверяется, что объявленный основной исполняемый файл совпадает с зарегистрированным исполняемым файлом Desktop. Если регистрация отсутствует, устарела или не согласована, откройте OpenCodex вручную: другая копия с тем же идентификатором bundle не выбирается как запасная. Если shim сообщает «activation not confirmed», добавьте `. ~/.opencodex/codex-shell-env.sh` в файл инициализации shell после остальных настроек PATH. diff --git a/docs-site/src/content/docs/tr/guides/desktop-app.md b/docs-site/src/content/docs/tr/guides/desktop-app.md index 98d09f07051..62447cb8266 100644 --- a/docs-site/src/content/docs/tr/guides/desktop-app.md +++ b/docs-site/src/content/docs/tr/guides/desktop-app.md @@ -57,7 +57,7 @@ Uygulama, paketindeki CLI'dan `ocx resolve --json` çalıştırmasını ister ve Gömülü kontrol paneli ile normal tarayıcınız arasında geçmek için tepsideki **Open dashboard** veya **Open in browser** eylemini kullanın. Tepsi, güncelleme denetimlerini de sunar. -macOS’te kontrol panelini kapattığınızda uygulama menü çubuğunda çalışmaya devam eder. Proxy’yi yeniden başlatmadan kontrol panelini geri getirmek için OpenCodex’i Dock veya Finder üzerinden yeniden açın. +macOS’te kontrol panelini kapattığınızda uygulama menü çubuğunda çalışmaya devam eder. Proxy’yi yeniden başlatmadan kontrol panelini açmak için menü çubuğunda **Open Dashboard** öğesini seçin veya OpenCodex’i Finder’dan yeniden açın. Kontrol paneli açıkken de Dock simgesini gizlemek için aynı menüde **Hide Dock icon** seçeneğini işaretleyin. ## Tepside kullanım diff --git a/docs-site/src/content/docs/zh-cn/guides/desktop-app.md b/docs-site/src/content/docs/zh-cn/guides/desktop-app.md index 432e8fc90eb..907d57c4e3d 100644 --- a/docs-site/src/content/docs/zh-cn/guides/desktop-app.md +++ b/docs-site/src/content/docs/zh-cn/guides/desktop-app.md @@ -57,7 +57,7 @@ sudo apt install ./OpenCodex--linux-amd64.deb 使用托盘中的 **Open dashboard** 或 **Open in browser**,可在内嵌仪表盘与常用浏览器之间切换。托盘也提供更新检查。 -在 macOS 上,关闭仪表盘后,应用会继续在菜单栏中运行。从 Dock 或 Finder 再次打开 OpenCodex 即可恢复仪表盘,无需重启代理。 +在 macOS 上,关闭仪表盘后,应用会继续在菜单栏中运行。在菜单栏选择 **Open Dashboard**,或从访达重新打开 OpenCodex,即可恢复仪表盘,无需重启代理。在同一菜单中启用 **Hide Dock icon**,即可在仪表盘打开时继续隐藏程序坞图标。 当 Codex 启动找不到 proxy 时,内置 CLI 会等待经过独立验证的 Desktop 恢复——即使 Desktop 没有记录在案的所有权声明也不例外。匹配到的 Desktop 已停止其 proxy,或其恢复无法验证时,会报错;但在不支持运行镜像验证的平台上,若有记录在案的所有权声明且应用仍在运行,则保留现有的有界等待。仅凭进程名或定位文件不会阻止普通的 CLI 启动。在 macOS 上,如果 shim 发现 OpenCodex 已退出且记录的所有权与有效的 **Start at Login** 注册一致,就会打开它。自动重新打开时,会选择该注册记录中的应用 bundle 路径,并检查其声明的主可执行文件是否与已注册的 Desktop 可执行文件一致。注册缺失、过期或不一致时,请手动打开 OpenCodex;具有相同 bundle 标识符的其他副本不会作为回退被选中。如果 shim 显示“activation not confirmed”,请在 shell 启动文件中的其他 PATH 设置之后添加 `. ~/.opencodex/codex-shell-env.sh`。 diff --git a/docs-site/src/content/docs/zh-tw/guides/desktop-app.md b/docs-site/src/content/docs/zh-tw/guides/desktop-app.md index 229fc0c4946..7b8eafcf37b 100644 --- a/docs-site/src/content/docs/zh-tw/guides/desktop-app.md +++ b/docs-site/src/content/docs/zh-tw/guides/desktop-app.md @@ -57,7 +57,7 @@ sudo apt install ./OpenCodex--linux-amd64.deb 透過系統匣的 **Open dashboard** 或 **Open in browser**,可以在內嵌儀表板與一般瀏覽器間切換。系統匣也提供更新檢查。 -在 macOS 上,關閉儀表板後,應用程式會繼續在選單列中執行。從 Dock 或 Finder 再次開啟 OpenCodex 即可恢復儀表板,無須重新啟動代理。 +在 macOS 上,關閉儀表板後,應用程式會繼續在選單列中執行。在選單列選擇 **Open Dashboard**,或從 Finder 重新開啟 OpenCodex,即可恢復儀表板,無須重新啟動代理。在同一選單中啟用 **Hide Dock icon**,便可在儀表板開啟時繼續隱藏 Dock 圖示。 ## 系統匣中的用量資訊 diff --git a/structure/desktop-shell.md b/structure/desktop-shell.md index 1e2c84faf57..c9bdc6c3a4f 100644 --- a/structure/desktop-shell.md +++ b/structure/desktop-shell.md @@ -137,6 +137,16 @@ window, closes the usage popup if it is open, and loads the dashboard if a hidde it. This is separate from the single-instance callback, which handles a second process notifying the existing one. +The macOS tray's **Hide Dock icon** checkbox is a local desktop preference. The +`desktop/src-tauri/src/dock.rs` marker in the desktop app configuration directory +is loaded before AppKit launches and updated before the live preference changes. +When the preference is enabled, showing the dashboard keeps the app in accessory +mode while the window can still take focus. A failed tray installation restores +Dock access when startup shows the dashboard. The shell reads the current +dashboard visibility, preference, and tray verdict in the same main-thread +turn that applies both native policies. The preference and its tray item are +macOS-only and do not depend on the proxy. + The host window also answers whether the dashboard is visible at all. Windows WebView2 is reported to keep `document.visibilityState === "visible"` while the Tauri window sits hidden in the tray (tauri issues #10592 and #6864; macOS WKWebView does flip it, measured), so a hidden dashboard went