From df91a7cc8b5c64c24f541ab8d70b21d012ee4e86 Mon Sep 17 00:00:00 2001 From: knqiufan Date: Sun, 6 Dec 2026 16:21:34 +0800 Subject: [PATCH 1/2] fix(desktop): sync login state with macOS BTM and add retry recovery --- desktop/src-tauri/Cargo.lock | 1 + desktop/src-tauri/Cargo.toml | 3 +- desktop/src-tauri/src/desktop_preferences.rs | 49 ++- .../src/desktop_preferences/launch_agent.rs | 320 ++++++++++++++++-- desktop/ui/src/app/SettingsPage.tsx | 136 ++++++-- desktop/ui/tests/settings.test.tsx | 82 +++++ 6 files changed, 526 insertions(+), 65 deletions(-) diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index a84f8f7640..f1b332d961 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -3118,6 +3118,7 @@ dependencies = [ "keyring", "libc", "native-tls", + "objc2", "objc2-foundation", "plist", "rcgen", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 7af66f655c..f979b4149b 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -54,7 +54,8 @@ tauri-plugin-autostart = "=2.5.1" [target.'cfg(target_os = "macos")'.dependencies] keyring = { version = "=3.6.3", default-features = false, features = ["apple-native"] } -objc2-foundation = { version = "=0.3.2", default-features = false, features = ["NSProcessInfo", "NSString"] } +objc2 = "=0.6.4" +objc2-foundation = { version = "=0.3.2", default-features = false, features = ["NSProcessInfo", "NSString", "NSURL"] } plist = "=1.10.1" [target.'cfg(unix)'.dependencies] diff --git a/desktop/src-tauri/src/desktop_preferences.rs b/desktop/src-tauri/src/desktop_preferences.rs index 69e50d3935..aa36ec0bc7 100644 --- a/desktop/src-tauri/src/desktop_preferences.rs +++ b/desktop/src-tauri/src/desktop_preferences.rs @@ -20,7 +20,7 @@ use crate::{error::SafeError, ipc::authorize_window}; mod launch_agent; #[tauri::command] -pub fn desktop_login( +pub async fn desktop_login( window: tauri::WebviewWindow, enabled: Option, ) -> Result { @@ -29,27 +29,42 @@ pub fn desktop_login( { use tauri::Manager; - let home = window.path().home_dir().map_err(|_| SafeError::Storage)?; - let executable = tauri::utils::platform::current_exe() - .and_then(std::fs::canonicalize) - .map_err(|_| SafeError::Storage)?; - launch_agent::configure(&home, &executable, enabled).map_err(|_| SafeError::Storage) + tauri::async_runtime::spawn_blocking(move || { + let home = window.path().home_dir().map_err(|_| SafeError::Storage)?; + let executable = tauri::utils::platform::current_exe() + .and_then(std::fs::canonicalize) + .map_err(|_| SafeError::Storage)?; + launch_agent::configure(&home, &executable, enabled).map_err(|error| { + if error.kind() == std::io::ErrorKind::PermissionDenied { + SafeError::Forbidden + } else { + SafeError::Storage + } + }) + }) + .await + .map_err(|_| SafeError::ProcessFailure)? } #[cfg(target_os = "windows")] { use tauri_plugin_autostart::ManagerExt; - let login = window.autolaunch(); - let current = login.is_enabled().map_err(|_| SafeError::Storage)?; - if let Some(enabled) = enabled.filter(|enabled| *enabled != current) { - if enabled { - login.enable() - } else { - login.disable() + + tauri::async_runtime::spawn_blocking(move || { + let login = window.autolaunch(); + let current = login.is_enabled().map_err(|_| SafeError::Storage)?; + if let Some(enabled) = enabled.filter(|enabled| *enabled != current) { + if enabled { + login.enable() + } else { + login.disable() + } + .map_err(|_| SafeError::Storage)?; + return login.is_enabled().map_err(|_| SafeError::Storage); } - .map_err(|_| SafeError::Storage)?; - return login.is_enabled().map_err(|_| SafeError::Storage); - } - Ok(current) + Ok(current) + }) + .await + .map_err(|_| SafeError::ProcessFailure)? } #[cfg(not(any(target_os = "macos", target_os = "windows")))] { diff --git a/desktop/src-tauri/src/desktop_preferences/launch_agent.rs b/desktop/src-tauri/src/desktop_preferences/launch_agent.rs index 2081b6cf11..0ce80266bd 100644 --- a/desktop/src-tauri/src/desktop_preferences/launch_agent.rs +++ b/desktop/src-tauri/src/desktop_preferences/launch_agent.rs @@ -19,9 +19,24 @@ use std::{ fs, io::{self, ErrorKind, Write}, path::Path, + time::Duration, }; const LABEL: &str = "PowerContext Desktop"; +const BTM_POLL_ATTEMPTS: usize = 40; +const BTM_POLL_INTERVAL: Duration = Duration::from_millis(50); + +#[cfg(target_os = "macos")] +#[link(name = "ServiceManagement", kind = "framework")] +unsafe extern "C" {} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum BtmStatus { + NotRegistered, + Enabled, + RequiresApproval, + NotFound, +} #[derive(Deserialize, Serialize, PartialEq, Eq)] #[serde(rename_all = "PascalCase")] @@ -31,7 +46,51 @@ struct LaunchAgent { run_at_load: bool, } +#[cfg(target_os = "macos")] pub(super) fn configure(home: &Path, executable: &Path, enabled: Option) -> io::Result { + configure_with( + home, + executable, + enabled, + legacy_btm_status, + std::thread::sleep, + ) +} + +#[cfg(target_os = "macos")] +fn legacy_btm_status(path: &Path) -> BtmStatus { + use objc2::{msg_send, runtime::AnyClass}; + use objc2_foundation::{NSString, NSURL}; + + let Some(path) = path.to_str() else { + return BtmStatus::NotFound; + }; + let Some(service_class) = AnyClass::get(c"SMAppService") else { + // Pre-macOS 13 has no Background Task Management approval gate. + return BtmStatus::Enabled; + }; + let url = NSURL::fileURLWithPath(&NSString::from_str(path)); + // SAFETY: `SMAppService +statusForLegacyURL:` takes a non-null `NSURL *` and returns `NSInteger`. + let status: isize = unsafe { msg_send![service_class, statusForLegacyURL: &*url] }; + match status { + 0 => BtmStatus::NotRegistered, + 1 => BtmStatus::Enabled, + 2 => BtmStatus::RequiresApproval, + _ => BtmStatus::NotFound, + } +} + +fn configure_with( + home: &Path, + executable: &Path, + enabled: Option, + mut btm_status: F, + mut sleep: S, +) -> io::Result +where + F: FnMut(&Path) -> BtmStatus, + S: FnMut(Duration), +{ let executable = executable .to_str() .ok_or_else(|| io::Error::new(ErrorKind::InvalidInput, "invalid executable path"))?; @@ -43,20 +102,11 @@ pub(super) fn configure(home: &Path, executable: &Path, enabled: Option) - // Keep the registration used by builds that wrote the plist through the autostart plugin. let directory = home.join("Library/LaunchAgents"); let path = directory.join(format!("{LABEL}.plist")); + let mut wrote_plist = false; match enabled { - Some(true) if !is_enabled(&path, &agent)? => { - let mut contents = Vec::new(); - plist::to_writer_xml(&mut contents, &agent).map_err(io::Error::other)?; - if !plist::from_bytes::(&contents).is_ok_and(|saved| saved == agent) { - return Err(io::Error::new( - ErrorKind::InvalidData, - "invalid LaunchAgent", - )); - } - fs::create_dir_all(&directory)?; - let mut file = tempfile::NamedTempFile::new_in(&directory)?; - file.write_all(&contents)?; - file.persist(&path)?; + Some(true) if !plist_matches(&path, &agent)? => { + write_plist(&directory, &path, &agent)?; + wrote_plist = true; } Some(false) => match fs::remove_file(&path) { Ok(()) => {} @@ -65,10 +115,47 @@ pub(super) fn configure(home: &Path, executable: &Path, enabled: Option) - }, _ => {} } - is_enabled(&path, &agent) + + if !plist_matches(&path, &agent)? { + return Ok(false); + } + + let mut status = btm_status(&path); + if wrote_plist { + for _ in 0..BTM_POLL_ATTEMPTS { + if !matches!(status, BtmStatus::NotRegistered | BtmStatus::NotFound) { + break; + } + sleep(BTM_POLL_INTERVAL); + status = btm_status(&path); + } + } + if enabled == Some(true) && status == BtmStatus::RequiresApproval { + return Err(io::Error::new( + ErrorKind::PermissionDenied, + "login item requires approval in System Settings", + )); + } + Ok(status == BtmStatus::Enabled) } -fn is_enabled(path: &Path, expected: &LaunchAgent) -> io::Result { +fn write_plist(directory: &Path, path: &Path, agent: &LaunchAgent) -> io::Result<()> { + let mut contents = Vec::new(); + plist::to_writer_xml(&mut contents, agent).map_err(io::Error::other)?; + if !plist::from_bytes::(&contents).is_ok_and(|saved| &saved == agent) { + return Err(io::Error::new( + ErrorKind::InvalidData, + "invalid LaunchAgent", + )); + } + fs::create_dir_all(directory)?; + let mut file = tempfile::NamedTempFile::new_in(directory)?; + file.write_all(&contents)?; + file.persist(path)?; + Ok(()) +} + +fn plist_matches(path: &Path, expected: &LaunchAgent) -> io::Result { match fs::read(path) { Ok(contents) => { Ok(plist::from_bytes::(&contents).is_ok_and(|agent| &agent == expected)) @@ -82,6 +169,13 @@ fn is_enabled(path: &Path, expected: &LaunchAgent) -> io::Result { mod tests { use super::*; use plist::Value; + use std::cell::Cell; + + fn always_enabled(_: &Path) -> BtmStatus { + BtmStatus::Enabled + } + + fn no_sleep(_: Duration) {} #[test] fn registers_and_removes_an_executable_with_xml_characters() { @@ -93,8 +187,17 @@ mod tests { "/Applications/Apps & Tools /PowerContext Desktop.app/Contents/MacOS/powercontext-desktop", ); - assert!(!configure(home.path(), executable, None).unwrap()); - assert!(configure(home.path(), executable, Some(true)).unwrap()); + assert!(!configure_with(home.path(), executable, None, always_enabled, no_sleep).unwrap()); + assert!( + configure_with( + home.path(), + executable, + Some(true), + always_enabled, + no_sleep + ) + .unwrap() + ); let registration = Value::from_file(&path).unwrap(); let registration = registration.as_dictionary().unwrap(); @@ -107,9 +210,18 @@ mod tests { Some("PowerContext Desktop") ); assert_eq!(registration["RunAtLoad"].as_boolean(), Some(true)); - assert!(configure(home.path(), executable, None).unwrap()); + assert!(configure_with(home.path(), executable, None, always_enabled, no_sleep).unwrap()); - assert!(!configure(home.path(), executable, Some(false)).unwrap()); + assert!( + !configure_with( + home.path(), + executable, + Some(false), + always_enabled, + no_sleep + ) + .unwrap() + ); assert!(!path.exists()); } @@ -132,8 +244,172 @@ mod tests { ) .unwrap(); - assert!(!configure(home.path(), executable, None).unwrap()); - assert!(configure(home.path(), executable, Some(true)).unwrap()); - assert!(configure(home.path(), executable, None).unwrap()); + assert!(!configure_with(home.path(), executable, None, always_enabled, no_sleep).unwrap()); + assert!( + configure_with( + home.path(), + executable, + Some(true), + always_enabled, + no_sleep + ) + .unwrap() + ); + assert!(configure_with(home.path(), executable, None, always_enabled, no_sleep).unwrap()); + } + + #[test] + fn reflects_btm_disabled_state_even_when_plist_exists() { + let home = tempfile::tempdir().unwrap(); + let path = home + .path() + .join("Library/LaunchAgents/PowerContext Desktop.plist"); + let executable = Path::new("/Applications/PowerContext Desktop.app/Contents/MacOS/app"); + + assert!( + configure_with( + home.path(), + executable, + Some(true), + always_enabled, + no_sleep + ) + .unwrap() + ); + assert!(path.exists()); + + // When System Settings disables the LaunchAgent, the plist remains on disk + // while BTM reports RequiresApproval. + let disabled_in_btm = |_: &Path| BtmStatus::RequiresApproval; + assert!(!configure_with(home.path(), executable, None, disabled_in_btm, no_sleep).unwrap()); + + let mtime_before = fs::metadata(&path).unwrap().modified().unwrap(); + let error = configure_with( + home.path(), + executable, + Some(true), + disabled_in_btm, + no_sleep, + ) + .unwrap_err(); + assert_eq!(error.kind(), ErrorKind::PermissionDenied); + assert_eq!( + fs::metadata(&path).unwrap().modified().unwrap(), + mtime_before + ); + + assert!( + !configure_with( + home.path(), + executable, + Some(false), + disabled_in_btm, + no_sleep + ) + .unwrap() + ); + assert!(!path.exists()); + } + + #[test] + fn waits_briefly_for_btm_indexing_after_writing_plist() { + let home = tempfile::tempdir().unwrap(); + let executable = Path::new("/Applications/PowerContext Desktop.app/Contents/MacOS/app"); + let polls = Cell::new(0); + let delayed_enabled = |_: &Path| { + let count = polls.get(); + polls.set(count + 1); + if count < 2 { + BtmStatus::NotFound + } else { + BtmStatus::Enabled + } + }; + + assert!( + configure_with( + home.path(), + executable, + Some(true), + delayed_enabled, + no_sleep + ) + .unwrap() + ); + assert_eq!(polls.get(), 3); + } + + #[test] + fn returns_false_when_btm_never_confirms_registration() { + let home = tempfile::tempdir().unwrap(); + let executable = Path::new("/Applications/PowerContext Desktop.app/Contents/MacOS/app"); + let polls = Cell::new(0); + let sleeps = Cell::new(0); + let never_indexed = |_: &Path| { + polls.set(polls.get() + 1); + BtmStatus::NotFound + }; + let count_sleep = |_: Duration| { + sleeps.set(sleeps.get() + 1); + }; + + assert!( + !configure_with( + home.path(), + executable, + Some(true), + never_indexed, + count_sleep + ) + .unwrap() + ); + assert_eq!(sleeps.get(), BTM_POLL_ATTEMPTS); + assert_eq!(polls.get(), BTM_POLL_ATTEMPTS + 1); + } + + #[test] + fn skips_rewriting_or_polling_when_matching_plist_is_already_on_disk() { + let home = tempfile::tempdir().unwrap(); + let path = home + .path() + .join("Library/LaunchAgents/PowerContext Desktop.plist"); + let executable = Path::new("/Applications/PowerContext Desktop.app/Contents/MacOS/app"); + assert!( + configure_with( + home.path(), + executable, + Some(true), + always_enabled, + no_sleep + ) + .unwrap() + ); + let mtime_before = fs::metadata(&path).unwrap().modified().unwrap(); + let sleeps = Cell::new(0); + let count_sleep = |_: Duration| sleeps.set(sleeps.get() + 1); + + assert!( + !configure_with( + home.path(), + executable, + Some(true), + |_| BtmStatus::NotFound, + count_sleep + ) + .unwrap() + ); + assert_eq!(sleeps.get(), 0); + assert_eq!( + fs::metadata(&path).unwrap().modified().unwrap(), + mtime_before + ); + } + + #[cfg(target_os = "macos")] + #[test] + fn queries_legacy_btm_status_for_absent_launch_agent() { + let missing = + Path::new("/Users/nonexistent/Library/LaunchAgents/PowerContext Desktop Missing.plist"); + assert_eq!(legacy_btm_status(missing), BtmStatus::NotRegistered); } } diff --git a/desktop/ui/src/app/SettingsPage.tsx b/desktop/ui/src/app/SettingsPage.tsx index f774f40813..5ce0f1aa45 100644 --- a/desktop/ui/src/app/SettingsPage.tsx +++ b/desktop/ui/src/app/SettingsPage.tsx @@ -22,9 +22,16 @@ */ import { ArrowUpRight } from "lucide-react"; -import { useEffect, useState, type MouseEvent } from "react"; +import { + useCallback, + useEffect, + useRef, + useState, + type MouseEvent, +} from "react"; import { invoke, isTauri } from "@tauri-apps/api/core"; import { openUrl } from "@tauri-apps/plugin-opener"; +import { Button } from "../components/ui/button"; import { Select, SelectContent, @@ -34,12 +41,14 @@ import { } from "../components/ui/select"; import { Switch } from "../components/ui/switch"; import { PageFeedback } from "../components/ui/feedback"; +import { connectionErrorCode } from "./connection-messages"; import { desktopZoomLevels, supportsNativeDesktopPreferences, type useServiceNotifications, type DesktopPreferences, } from "./desktop-preferences"; +import { messages } from "./messages"; const docs = { zh: "https://github.com/oceanbase/powercontext/blob/master/desktop/README.zh.md", @@ -75,35 +84,82 @@ export function SettingsPage({ const nativeSettings = !preview && supportsNativeDesktopPreferences(); const [nativeLogin, setNativeLogin] = useState(null); const [loginBusy, setLoginBusy] = useState(false); - const [loginFailed, setLoginFailed] = useState(false); + const [loginError, setLoginError] = useState< + "verification" | "approval" | null + >(null); + const mountedRef = useRef(true); + const loginRequestRef = useRef(0); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; + }, []); + + const runLoginRequest = useCallback( + async ( + request: () => Promise, + onSuccess: (actual: boolean) => void, + { showBusy = true }: { showBusy?: boolean } = {}, + ) => { + const requestId = ++loginRequestRef.current; + if (showBusy) setLoginBusy(true); + setLoginError(null); + try { + const actual = await request(); + if (!mountedRef.current || loginRequestRef.current !== requestId) + return; + onSuccess(actual); + } catch (error) { + if (!mountedRef.current || loginRequestRef.current !== requestId) + return; + setLoginError( + connectionErrorCode(error) === "forbidden" + ? "approval" + : "verification", + ); + } finally { + if ( + showBusy && + mountedRef.current && + loginRequestRef.current === requestId + ) { + setLoginBusy(false); + } + } + }, + [], + ); useEffect(() => { if (!nativeSettings) return; - let cancelled = false; - void desktopLogin() - .then((enabled) => { - if (!cancelled) setNativeLogin(enabled); - }) - .catch(() => { - if (!cancelled) setLoginFailed(true); - }); + void runLoginRequest( + () => desktopLogin(), + (enabled) => setNativeLogin(enabled), + { showBusy: false }, + ); return () => { - cancelled = true; + loginRequestRef.current += 1; }; - }, [nativeSettings]); + }, [nativeSettings, runLoginRequest]); - async function updateLogin(enabled: boolean) { - setLoginBusy(true); - setLoginFailed(false); - try { - const actual = await desktopLogin(enabled); - setNativeLogin(actual); - setLoginFailed(actual !== enabled); - } catch { - setLoginFailed(true); - } finally { - setLoginBusy(false); - } + function retryLoginRead() { + if (loginBusy) return; + return runLoginRequest( + () => desktopLogin(), + (enabled) => setNativeLogin(enabled), + ); + } + + function updateLogin(enabled: boolean) { + return runLoginRequest( + () => desktopLogin(enabled), + (actual) => { + setNativeLogin(actual); + setLoginError(actual === enabled ? null : "verification"); + }, + ); } function openSupportLink(event: MouseEvent) { @@ -270,7 +326,24 @@ export function SettingsPage({ /> - {loginFailed && ( + {loginError === "approval" && ( + +

+ {zh + ? "请在“系统设置 → 通用 → 登录项与扩展”中允许 PowerContext Desktop。" + : "Enable PowerContext Desktop in System Settings → General → Login Items & Extensions."} +

+
+ )} + {loginError === "verification" && ( void retryLoginRead()} + > + {messages[language].retryRead} + + ) : undefined + } /> )} diff --git a/desktop/ui/tests/settings.test.tsx b/desktop/ui/tests/settings.test.tsx index 27627c9a2d..350e549dff 100644 --- a/desktop/ui/tests/settings.test.tsx +++ b/desktop/ui/tests/settings.test.tsx @@ -70,6 +70,88 @@ test("shows the operating system login setting on open and after a rejected chan expect(launch.getAttribute("aria-checked")).toBe("true"); }); +test("allows retrying the initial operating system login check after failure", async () => { + vi.mocked(isTauri).mockReturnValue(true); + vi.spyOn(navigator, "userAgent", "get").mockReturnValue("Macintosh"); + vi.mocked(invoke) + .mockRejectedValueOnce(new Error("transient read failure")) + .mockRejectedValueOnce(new Error("still unavailable")) + .mockResolvedValueOnce(true); + const user = userEvent.setup(); + render( + {}} + />, + ); + + const launch = screen.getByRole("switch", { + name: "Open Desktop at login", + }); + expect( + await screen.findByText("Could not verify the system login setting"), + ).toBeTruthy(); + expect(launch.disabled).toBe(true); + + const retry = screen.getByRole("button", { name: "Retry read" }); + await user.click(retry); + expect( + await screen.findByText("Could not verify the system login setting"), + ).toBeTruthy(); + expect(launch.disabled).toBe(true); + + await user.click(screen.getByRole("button", { name: "Retry read" })); + await waitFor(() => expect(launch.disabled).toBe(false)); + expect(launch.getAttribute("aria-checked")).toBe("true"); + expect(screen.queryByText("Could not verify the system login setting")).toBe( + null, + ); + expect(invoke).toHaveBeenCalledTimes(3); + expect(invoke).toHaveBeenNthCalledWith(3, "desktop_login", { + enabled: null, + }); +}); + +test("guides the user to System Settings when login startup requires approval", async () => { + vi.mocked(isTauri).mockReturnValue(true); + vi.spyOn(navigator, "userAgent", "get").mockReturnValue("Macintosh"); + vi.mocked(invoke) + .mockResolvedValueOnce(false) + .mockRejectedValueOnce("forbidden"); + const user = userEvent.setup(); + render( + {}} + />, + ); + + const launch = screen.getByRole("switch", { + name: "Open Desktop at login", + }); + await waitFor(() => expect(launch.disabled).toBe(false)); + expect(launch.getAttribute("aria-checked")).toBe("false"); + + await user.click(launch); + expect( + await screen.findByText("Allow login startup in System Settings"), + ).toBeTruthy(); + expect( + screen.getByText( + "Enable PowerContext Desktop in System Settings → General → Login Items & Extensions.", + ), + ).toBeTruthy(); + expect(launch.getAttribute("aria-checked")).toBe("false"); +}); + function SettingsHarness({ initial = defaultDesktopPreferences }) { const [preferences, setPreferences] = useState(initial); return ( From 0f6f565a05f70c198e84252bea4d687e2b3db964 Mon Sep 17 00:00:00 2001 From: knqiufan Date: Sun, 6 Dec 2026 20:16:32 +0800 Subject: [PATCH 2/2] test(desktop): cover BTM not-registered polling --- desktop/src-tauri/src/desktop_preferences/launch_agent.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/desktop/src-tauri/src/desktop_preferences/launch_agent.rs b/desktop/src-tauri/src/desktop_preferences/launch_agent.rs index 0ce80266bd..481534a26c 100644 --- a/desktop/src-tauri/src/desktop_preferences/launch_agent.rs +++ b/desktop/src-tauri/src/desktop_preferences/launch_agent.rs @@ -319,10 +319,10 @@ mod tests { let delayed_enabled = |_: &Path| { let count = polls.get(); polls.set(count + 1); - if count < 2 { - BtmStatus::NotFound - } else { - BtmStatus::Enabled + match count { + 0 => BtmStatus::NotRegistered, + 1 => BtmStatus::NotFound, + _ => BtmStatus::Enabled, } };