Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(app): close-to-tray setting for Windows and Linux (#9666) (#9670)
Thinh Le6a1214c2bc0f
diff --git a/docs/src/pages/docs/desktop/settings.mdx b/docs/src/pages/docs/desktop/settings.mdxindex 1884b0ead..4c45eeba6 100644--- a/docs/src/pages/docs/desktop/settings.mdx+++ b/docs/src/pages/docs/desktop/settings.mdx@@ -91,6 +91,15 @@ Jan includes a built-in spell check feature to help catch typing errors in your+### Close Button and System Tray (Windows and Linux)+By default, closing Jan's window quits Jan. In **Settings > General**, turn on **Close button minimizes to the system tray** to keep Jan running in the system tray instead. To open Jan again, click the tray icon, or choose **Open Jan** from its menu (on Linux, the icon opens the menu). Choose **Quit** from the menu to exit.++Closing the window also hides Jan to the tray while the Local API Server is running and **Settings > Local API Server > Run in background** is on. macOS always keeps Jan running when you close the window; quit with Cmd+Q.++<Callout type="warning">+Some Linux desktops, including stock GNOME, do not show tray icons unless an AppIndicator extension is installed. If you cannot see the tray icon, launch Jan again to bring the hidden window back.+</Callout>+### Jan Data FolderJan stores your data locally in your own filesystem in a universal file format. See detailed [Jan Folder Structure](/docs/desktop/data-folder#directory-structure).diff --git a/src-tauri/src/core/setup.rs b/src-tauri/src/core/setup.rsindex 88942aacc..feb1399a3 100644--- a/src-tauri/src/core/setup.rs+++ b/src-tauri/src/core/setup.rs@@ -395,11 +395,19 @@ pub fn show_tray<R: Runtime>(app: &AppHandle<R>) {#[cfg(feature = "desktop")]pub fn remove_tray<R: Runtime>(app: &AppHandle<R>) {- if tray_always_visible() {- return;- }let handle = app.clone();+ // Decided on the main thread, where creation also happens, so a removal+ // queued before the Local API Server started cannot run after the server's+ // own `show_tray` and take away the icon the server needs.let _ = app.run_on_main_thread(move || {+ // The tray is also the way back to a window hidden by close-to-tray.+ if tray_always_visible()+ || crate::core::system::commands::CLOSE_TO_TRAY+ .load(std::sync::atomic::Ordering::SeqCst)+ || proxy_server_running(&handle)+ {+ return;+ }let _ = handle.remove_tray_by_id(TRAY_ID);});}@@ -436,6 +444,15 @@ pub fn setup_app_menu_quit<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()>Ok(())}+/// A held lock means a start or stop is in flight, which counts as running:+/// keeping the icon is the safe answer when the state cannot be read.+#[cfg(feature = "desktop")]+fn proxy_server_running<R: Runtime>(app: &AppHandle<R>) -> bool {+ app.try_state::<AppState>()+ .map(|s| s.server_handle.try_lock().map_or(true, |g| g.is_some()))+ .unwrap_or(false)+}+#[cfg(feature = "desktop")]pub fn setup_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<TrayIcon<R>> {let show_i = MenuItem::with_id(app, "open", "Open Jan", true, None::<&str>)?;diff --git a/src-tauri/src/core/system/commands.rs b/src-tauri/src/core/system/commands.rsindex 253406da1..aa995194a 100644--- a/src-tauri/src/core/system/commands.rs+++ b/src-tauri/src/core/system/commands.rs@@ -740,6 +740,37 @@ pub fn exit_blocked_by_reset(reset_in_progress: bool, code: Option<i32>) -> boolreset_in_progress && code != Some(tauri::RESTART_EXIT_CODE)}+/// The "Close button minimizes to the system tray" setting (Windows/Linux; off+/// by default). macOS always hides on close, so it ignores this.+pub static CLOSE_TO_TRAY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++/// Whether a close of the main window hides it on Windows/Linux instead of+/// quitting: when the user chose close-to-tray, or while the Local API Server+/// runs with "Run in background" on.+pub fn close_hides_window(+ close_to_tray: bool,+ server_running: bool,+ server_run_in_background: bool,+) -> bool {+ close_to_tray || (server_running && server_run_in_background)+}++/// Applies the close-to-tray setting. A window hidden on close is only+/// reachable through the tray icon, so the icon is created here rather than+/// left to the Local API Server, and kept while the server still needs it.+#[tauri::command]+pub fn set_close_to_tray<R: Runtime>(app_handle: AppHandle<R>, enabled: bool) {+ CLOSE_TO_TRAY.store(enabled, std::sync::atomic::Ordering::SeqCst);+ #[cfg(feature = "desktop")]+ if enabled {+ crate::core::setup::show_tray(&app_handle);+ } else {+ crate::core::setup::remove_tray(&app_handle);+ }+ #[cfg(not(feature = "desktop"))]+ let _ = app_handle;+}+/// Wipe the selected data categories and restart the app.////// Async so it runs on the async runtime: as a sync command it ran on the main@@ -1158,6 +1189,20 @@ mod tests {assert!(!exit_blocked_by_reset(false, None));}+ #[test]+ fn close_hides_the_window_for_the_tray_setting_or_a_background_server() {+ // Nothing asks Jan to stay resident: closing quits.+ assert!(!close_hides_window(false, false, true));+ // A running server only counts while "Run in background" is on.+ assert!(close_hides_window(false, true, true));+ assert!(!close_hides_window(false, true, false));+ // Close-to-tray hides with no server running, and does not depend on+ // the server's own toggle.+ assert!(close_hides_window(true, false, true));+ assert!(close_hides_window(true, false, false));+ assert!(close_hides_window(true, true, false));+ }+fn create_all_data(dir: &std::path::Path) {for subdir in JAN_DATA_SUBDIRS {fs::create_dir_all(dir.join(subdir)).unwrap();diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex b1f32655a..74f5a4f04 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -83,6 +83,7 @@ macro_rules! invoke_commands_with_extras {core::server::commands::stop_server,core::server::commands::get_server_status,core::server::commands::set_server_run_in_background,+ core::system::commands::set_close_to_tray,// Agent commandscore::agent::commands::agent_skill_list,core::agent::commands::agent_skill_read,@@ -204,10 +205,11 @@ fn is_proxy_server_running<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> bool#[cfg(not(feature = "cli"))]/// Whether closing the main window only hides it, keeping the app running:-/// always on macOS (quit is Cmd+Q / dock / tray), and on Windows/Linux while-/// the Local API Server runs with "keep running in background" on. Never once-/// a shutdown has started. The window-event handler below and the web app's-/// close handler both ask this, so they agree on whether a close is a quit.+/// always on macOS (quit is Cmd+Q / dock / tray), and on Windows/Linux when+/// close-to-tray is on or the Local API Server runs with "keep running in+/// background" on. Never once a shutdown has started. The window-event handler+/// below and the web app's close handler both ask this, so they agree on+/// whether a close is a quit.fn hides_main_window_on_close<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> bool {use std::sync::atomic::Ordering;if SHUTTING_DOWN.load(Ordering::SeqCst) {@@ -220,8 +222,11 @@ fn hides_main_window_on_close<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> b}#[cfg(not(target_os = "macos"))]{- is_proxy_server_running(app)- && core::server::commands::SERVER_RUN_IN_BACKGROUND.load(Ordering::SeqCst)+ core::system::commands::close_hides_window(+ core::system::commands::CLOSE_TO_TRAY.load(Ordering::SeqCst),+ is_proxy_server_running(app),+ core::server::commands::SERVER_RUN_IN_BACKGROUND.load(Ordering::SeqCst),+ )}}@@ -427,8 +432,12 @@ pub fn run() {// test binary would hand over its argv and exit before the embedded// WebDriver server ever bound.#[cfg(all(desktop, not(feature = "e2e")))]- let builder = builder.plugin(tauri_plugin_single_instance::init(|_app, argv, _cwd| {+ let builder = builder.plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {println!("a new app instance was opened with {argv:?} and the deep link event was already triggered");+ // The second process exits right after this runs, so whatever the user+ // expected from launching Jan again has to happen here: bring the+ // running window back, even when it was minimized or hidden to the tray.+ core::system::commands::show_main_window(app);// when defining deep link schemes at runtime, you must also check `argv` here}));diff --git a/web-app/src/hooks/useGeneralSetting.ts b/web-app/src/hooks/useGeneralSetting.tsindex 5005fd9c2..2633ef7d6 100644--- a/web-app/src/hooks/useGeneralSetting.ts+++ b/web-app/src/hooks/useGeneralSetting.ts@@ -9,11 +9,13 @@ type GeneralSettingState = {currentLanguage: LanguagespellCheckChatInput: booleanautoUpdateCheck: boolean+ closeToTray: booleanstripReasoningFromContext: booleanhuggingfaceToken?: stringsetHuggingfaceToken: (token: string) => voidsetSpellCheckChatInput: (value: boolean) => voidsetAutoUpdateCheck: (value: boolean) => void+ setCloseToTray: (value: boolean) => voidsetStripReasoningFromContext: (value: boolean) => voidsetCurrentLanguage: (value: Language) => void}@@ -24,10 +26,12 @@ export const useGeneralSetting = create<GeneralSettingState>()(currentLanguage: 'en',spellCheckChatInput: true,autoUpdateCheck: true,+ closeToTray: false,stripReasoningFromContext: false,huggingfaceToken: undefined,setSpellCheckChatInput: (value) => set({ spellCheckChatInput: value }),setAutoUpdateCheck: (value) => set({ autoUpdateCheck: value }),+ setCloseToTray: (value) => set({ closeToTray: value }),setStripReasoningFromContext: (value) =>set({ stripReasoningFromContext: value }),setCurrentLanguage: (value) => set({ currentLanguage: value }),@@ -54,6 +58,7 @@ export const useGeneralSetting = create<GeneralSettingState>()(currentLanguage: state.currentLanguage,spellCheckChatInput: state.spellCheckChatInput,autoUpdateCheck: state.autoUpdateCheck,+ closeToTray: state.closeToTray,stripReasoningFromContext: state.stripReasoningFromContext,}),}diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex 027ea1d37..264421e60 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -302,6 +302,8 @@"checkingForUpdates": "Checking for updates...","autoUpdateCheck": "Automatic Update Check","autoUpdateCheckDesc": "Automatically check for updates on startup and periodically.",+ "closeToTray": "Close button minimizes to the system tray",+ "closeToTrayDesc": "Keep Jan running in the system tray when you close the window, instead of quitting. Open or quit Jan from the tray icon. If your desktop does not show tray icons (for example GNOME without an AppIndicator extension), launch Jan again to bring the window back.","copied": "Copied","copyPath": "Copy Path","changeLocation": "Change Location",diff --git a/web-app/src/providers/DataProvider.tsx b/web-app/src/providers/DataProvider.tsxindex 3f9506cda..d8c651cd7 100644--- a/web-app/src/providers/DataProvider.tsx+++ b/web-app/src/providers/DataProvider.tsx@@ -186,6 +186,7 @@ export function DataProvider() {const { checkForUpdate } = useAppUpdater()const autoUpdateCheck = useGeneralSetting((s) => s.autoUpdateCheck)+ const closeToTray = useGeneralSetting((s) => s.closeToTray)const { setServers, setSettings } = useMCPServers()const { setAssistants } = useAssistant()const { setThreads } = useThreads()@@ -414,6 +415,16 @@ export function DataProvider() {)}, [serviceHub, runInBackground])+ // Keep the backend's hide-to-tray-on-close flag in sync with the setting+ useEffect(() => {+ serviceHub+ .app()+ .setCloseToTray(closeToTray)+ .catch((error) =>+ console.error('Failed to sync close-to-tray setting:', error)+ )+ }, [serviceHub, closeToTray])+// Reconcile the UI with the backend server on every webview boot (the Rust// server outlives the webview, e.g. across a hide-to-tray reload), then// auto-start it only if enabled and not already running.diff --git a/web-app/src/providers/__tests__/DataProvider.test.tsx b/web-app/src/providers/__tests__/DataProvider.test.tsxindex 20c396f58..024cd8e22 100644--- a/web-app/src/providers/__tests__/DataProvider.test.tsx+++ b/web-app/src/providers/__tests__/DataProvider.test.tsx@@ -163,6 +163,7 @@ const hubState = vi.hoisted(() => ({fetchThreads: vi.fn().mockResolvedValue([]),getServerStatus: vi.fn().mockResolvedValue(false),setServerRunInBackground: vi.fn().mockResolvedValue(undefined),+ setCloseToTray: vi.fn().mockResolvedValue(undefined),startModel: vi.fn().mockResolvedValue(undefined),getActiveModels: vi.fn().mockResolvedValue([]),startServer: vi.fn().mockResolvedValue(1337),@@ -187,6 +188,7 @@ vi.mock('@/hooks/useServiceHub', () => {app: () => ({getServerStatus: hubState.getServerStatus,setServerRunInBackground: hubState.setServerRunInBackground,+ setCloseToTray: hubState.setCloseToTray,}),models: () => ({startModel: hubState.startModel,diff --git a/web-app/src/routes/settings/general.tsx b/web-app/src/routes/settings/general.tsxindex 20ac9947d..c070f6c15 100644--- a/web-app/src/routes/settings/general.tsx+++ b/web-app/src/routes/settings/general.tsx@@ -44,6 +44,8 @@ function General() {setSpellCheckChatInput,autoUpdateCheck,setAutoUpdateCheck,+ closeToTray,+ setCloseToTray,huggingfaceToken,setHuggingfaceToken,} = useGeneralSetting()@@ -235,6 +237,19 @@ function General() {/></>)}+ {IS_TAURI && !IS_MACOS && (+ <CardItem+ title={t('settings:general.closeToTray')}+ description={t('settings:general.closeToTrayDesc')}+ className="items-center flex-row gap-y-2"+ actions={+ <Switch+ checked={closeToTray}+ onCheckedChange={(e) => setCloseToTray(e)}+ />+ }+ />+ )}<CardItemtitle={t('common:language')}actions={<LanguageSwitcher />}diff --git a/web-app/src/services/app/default.ts b/web-app/src/services/app/default.tsindex b299a9e3e..8e8ba4af5 100644--- a/web-app/src/services/app/default.ts+++ b/web-app/src/services/app/default.ts@@ -41,6 +41,11 @@ export class DefaultAppService implements AppService {void enabled}+ async setCloseToTray(enabled: boolean): Promise<void> {+ // No-op - the tray only exists in the desktop app+ void enabled+ }+async readYaml<T = unknown>(path: string): Promise<T> {console.log('readYaml called with path:', path)throw new Error('readYaml not implemented in default app service')diff --git a/web-app/src/services/app/tauri.ts b/web-app/src/services/app/tauri.tsindex a3311ba4e..7edf84786 100644--- a/web-app/src/services/app/tauri.ts+++ b/web-app/src/services/app/tauri.ts@@ -101,6 +101,10 @@ export class TauriAppService extends DefaultAppService {await invoke('set_server_run_in_background', { enabled })}+ async setCloseToTray(enabled: boolean): Promise<void> {+ await invoke('set_close_to_tray', { enabled })+ }+async readYaml<T = unknown>(path: string): Promise<T> {return await invoke<T>('read_yaml', { path })}diff --git a/web-app/src/services/app/types.ts b/web-app/src/services/app/types.tsindex 97eb21e27..c7753f79b 100644--- a/web-app/src/services/app/types.ts+++ b/web-app/src/services/app/types.ts@@ -23,5 +23,6 @@ export interface AppService {relocateJanDataFolder(path: string): Promise<void>getServerStatus(): Promise<boolean>setServerRunInBackground(enabled: boolean): Promise<void>+ setCloseToTray(enabled: boolean): Promise<void>readYaml<T = unknown>(path: string): Promise<T>}