Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat(enterprise): add admin-enforced tray suppression

louisccfc7ade8114
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/enterprise/policy.rs b/apps/screenpipe-app-tauri/src-tauri/src/enterprise/policy.rs
index 6caad27ca..c3375b1bf 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/enterprise/policy.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/enterprise/policy.rs
@@ -24,6 +24,22 @@ static RECORDING_AUTHORIZED: AtomicBool = AtomicBool::new(false);
static IMMUTABLE_DEPLOYMENT_APP_UI_HIDDEN: Lazy<bool> =
Lazy::new(|| env_hides_app_ui() || bundled_enterprise_config_hides_app_ui());
static PERSISTED_APP_UI_HIDDEN: Lazy<bool> = Lazy::new(user_enterprise_config_hides_app_ui);
+// Tray suppression is a SEPARATE axis from `is_app_ui_hidden()`.
+//
+// Hiding the app UI tears down windows and drops the dock icon but deliberately
+// keeps the menu-bar item, because that tray is the employee's only in-app
+// affordance: it is where pause lives, and it is the only signal that capture is
+// running. An org that also removes the tray gets an app with no UI at all, so
+// this is gated behind an explicit admin decision rather than being implied by
+// the existing hidden-UI policy — a silent change to existing deployments would
+// strip their pause control without anyone asking for it.
+//
+// This is an app-surface policy only. It does not touch, and cannot touch, the
+// macOS screen-recording and microphone indicators: those are drawn by the OS
+// for any capture session and are not suppressible by the app.
+static IMMUTABLE_DEPLOYMENT_TRAY_HIDDEN: Lazy<bool> =
+ Lazy::new(|| env_hides_tray() || bundled_enterprise_config_hides_tray());
+static PERSISTED_TRAY_HIDDEN: Lazy<bool> = Lazy::new(user_enterprise_config_hides_tray);
static ENFORCE_AUTO_START: Lazy<AtomicBool> =
Lazy::new(|| AtomicBool::new(read_persisted_enforce_auto_start()));
static POLICY_UPDATE_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
@@ -140,6 +156,27 @@ const APP_UI_HIDDEN_SECTIONS: &[&str] = &[
"tray_open_app",
];
+/// Control-plane section ids that additionally suppress the tray icon.
+///
+/// These ride the existing `hidden_sections` channel rather than a new command
+/// argument, so an admin enabling tray suppression needs no client change and no
+/// binding regeneration. Deliberately NOT part of `APP_UI_HIDDEN_SECTIONS`: a
+/// tray-only policy must not imply the app UI is hidden, or the two axes could
+/// never be reasoned about independently.
+///
+/// # Control-plane contract
+///
+/// The producer of `hidden_sections` is the hosted `/api/enterprise/policy`
+/// endpoint, which is NOT in this repository. Adding a value here does not make
+/// it selectable in the admin UI; that requires a matching change server-side.
+/// This client treats any of the three ids below as equivalent and is a no-op
+/// until the server emits one, so the two sides can ship in any order.
+///
+/// Precedence is unchanged by this axis: an immutable deployment env
+/// (`SCREENPIPE_ENTERPRISE_HIDE_TRAY`) or bundled `hide_tray` still wins over
+/// the server, matching how `app_ui` suppression is enforced.
+const TRAY_HIDDEN_SECTIONS: &[&str] = &["tray", "hide_tray", "tray_icon"];
+
fn truthy(value: &str) -> bool {
matches!(
value.trim().to_ascii_lowercase().as_str(),
@@ -165,6 +202,18 @@ fn env_hides_app_ui() -> bool {
.unwrap_or(false)
}
+/// Managed-deployment escape hatch for suppressing the tray. Separate from
+/// `SCREENPIPE_ENTERPRISE_HIDE_APP` so an org can run the app with no windows
+/// but keep the tray (the existing hidden-UI contract), or go fully
+/// surface-free without changing the other variable's meaning.
+fn env_hides_tray() -> bool {
+ std::env::var("SCREENPIPE_ENTERPRISE_HIDE_TRAY")
+ .ok()
+ .as_deref()
+ .map(truthy)
+ .unwrap_or(false)
+}
+
fn bundled_enterprise_config_path() -> Option<std::path::PathBuf> {
let exe = std::env::current_exe().ok()?;
let exe_dir = exe.parent()?;
@@ -293,12 +342,47 @@ fn user_enterprise_config_hides_app_ui() -> bool {
enterprise_config_hides_app_ui(&user_enterprise_config_path())
}
+/// Read the tray-suppression flag from a deployment or user enterprise config.
+///
+/// Mirrors `enterprise_config_hides_app_ui`: an explicit boolean `hide_tray` on
+/// the bundled (immutable, MDM-pushed) config or the user file. Absence stays
+/// false, so existing deployments keep their tray.
+fn enterprise_config_hides_tray(path: &std::path::Path) -> bool {
+ let Ok(raw) = std::fs::read_to_string(path) else {
+ return false;
+ };
+ let Ok(json) = serde_json::from_str::<serde_json::Value>(&raw) else {
+ return false;
+ };
+
+ json.get("hide_tray")
+ .and_then(|value| value.as_bool())
+ .unwrap_or(false)
+}
+
+fn bundled_enterprise_config_hides_tray() -> bool {
+ bundled_enterprise_config_path()
+ .as_deref()
+ .map(enterprise_config_hides_tray)
+ .unwrap_or(false)
+}
+
+fn user_enterprise_config_hides_tray() -> bool {
+ enterprise_config_hides_tray(&user_enterprise_config_path())
+}
+
fn hidden_sections_hide_app_ui(hidden_sections: &HashSet<String>) -> bool {
APP_UI_HIDDEN_SECTIONS
.iter()
.any(|section| hidden_sections.contains(*section))
}
+fn hidden_sections_hide_tray(hidden_sections: &HashSet<String>) -> bool {
+ TRAY_HIDDEN_SECTIONS
+ .iter()
+ .any(|section| hidden_sections.contains(*section))
+}
+
fn resolve_app_ui_hidden(
immutable_deployment_hidden: bool,
server_policy_hidden: Option<bool>,
@@ -307,6 +391,17 @@ fn resolve_app_ui_hidden(
immutable_deployment_hidden || server_policy_hidden.unwrap_or(persisted_hidden)
}
+/// Same precedence as `resolve_app_ui_hidden`: an immutable deployment override
+/// (env var / MDM-pushed bundled config) always wins; otherwise the server's
+/// last answer supersedes the user-file snapshot, including a server `false`.
+fn resolve_tray_hidden(
+ immutable_deployment_hidden: bool,
+ server_policy_hidden: Option<bool>,
+ persisted_hidden: bool,
+) -> bool {
+ immutable_deployment_hidden || server_policy_hidden.unwrap_or(persisted_hidden)
+}
+
/// Called by the frontend after fetching the enterprise policy.
#[tauri::command]
#[specta::specta]
@@ -481,6 +576,29 @@ pub fn is_app_ui_hidden() -> bool {
)
}
+/// True when the admin has suppressed the menu-bar tray icon.
+///
+/// Independent of [`is_app_ui_hidden`], and intentionally narrower than "hide
+/// everything": this only removes the app's own menu-bar surface. It does not
+/// and cannot suppress the macOS screen-recording or microphone indicators,
+/// which the OS draws for any capture session, and it never disables the
+/// recording pause control — see `initialize_recording_control_shortcuts` for
+/// the affordance that replaces the tray's Pause item.
+pub fn is_tray_hidden() -> bool {
+ let server_policy_hidden = SERVER_POLICY_RECEIVED.load(Ordering::SeqCst).then(|| {
+ HIDDEN_SECTIONS
+ .read()
+ .map(|guard| hidden_sections_hide_tray(&guard))
+ .unwrap_or(false)
+ });
+
+ resolve_tray_hidden(
+ *IMMUTABLE_DEPLOYMENT_TRAY_HIDDEN,
+ server_policy_hidden,
+ *PERSISTED_TRAY_HIDDEN,
+ )
+}
+
/// Serializes any test that mutates `SYNC_STREAMS`. Cargo runs tests in
/// parallel within a binary by default, and the static here is shared with the
/// `enterprise_sync::run_one_sync` test mod — two tests racing on a global
@@ -526,6 +644,55 @@ mod tests {
assert!(resolve_app_ui_hidden(true, Some(false), false));
}
+ #[test]
+ fn tray_and_app_ui_axes_are_independent() {
+ // A tray-only policy must not imply the app UI is hidden, and hiding the
+ // app UI must not implicitly strip the tray. Existing deployments rely on
+ // the second half: hidden UI has always kept the tray.
+ for section in TRAY_HIDDEN_SECTIONS {
+ let hidden = HashSet::from([(*section).to_string()]);
+ assert!(hidden_sections_hide_tray(&hidden), "{section}");
+ assert!(!hidden_sections_hide_app_ui(&hidden), "{section}");
+ }
+
+ for section in APP_UI_HIDDEN_SECTIONS {
+ let hidden = HashSet::from([(*section).to_string()]);
+ assert!(hidden_sections_hide_app_ui(&hidden), "{section}");
+ assert!(!hidden_sections_hide_tray(&hidden), "{section}");
+ }
+ }
+
+ #[test]
+ fn fresh_server_policy_supersedes_persisted_tray_snapshot() {
+ assert!(resolve_tray_hidden(false, None, true));
+ assert!(!resolve_tray_hidden(false, Some(false), true));
+ assert!(resolve_tray_hidden(false, Some(true), false));
+ }
+
+ #[test]
+ fn immutable_deployment_override_keeps_tray_authoritative() {
+ assert!(resolve_tray_hidden(true, Some(false), false));
+ }
+
+ #[test]
+ fn tray_config_requires_explicit_boolean_true() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("enterprise.json");
+
+ for body in [
+ r#"{}"#,
+ r#"{"hide_tray":false}"#,
+ r#"{"hide_tray":"true"}"#,
+ r#"{"hide_app":true}"#,
+ ] {
+ std::fs::write(&path, body).unwrap();
+ assert!(!enterprise_config_hides_tray(&path), "body={body}");
+ }
+
+ std::fs::write(&path, r#"{"hide_tray":true}"#).unwrap();
+ assert!(enterprise_config_hides_tray(&path));
+ }
+
#[test]
fn persisted_auto_start_requires_explicit_boolean_true() {
let dir = tempfile::tempdir().unwrap();
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index bfe462a4f..a3b14a4c4 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -2313,7 +2313,25 @@ async fn main() {
// 1. Collect per-shortcut failures instead of aborting on the first one
// 2. Emit a user-visible notification listing the conflicting shortcuts
if app_ui_hidden {
- info!("enterprise: hidden UI mode active, skipping global app shortcuts");
+ // With windows torn down, the tray is the only pause affordance.
+ // Only when the admin ALSO suppresses the tray does the app have
+ // no way to stop capture at all — and then the start/stop hotkeys
+ // are registered and routed natively, because the usual
+ // `shortcut-*-recording` emits have no webview listener here.
+ if crate::enterprise_policy::is_tray_hidden() {
+ info!("enterprise: hidden UI and tray suppressed, registering recording control shortcuts only");
+ let app_handle_clone = app_handle.clone();
+ tauri::async_runtime::spawn(async move {
+ crate::shortcuts::reconcile_with_enterprise_policy(
+ &app_handle_clone,
+ true,
+ true,
+ )
+ .await;
+ });
+ } else {
+ info!("enterprise: hidden UI mode active, skipping global app shortcuts");
+ }
} else if headless_startup {
info!("headless: skipping global shortcuts while UI is dormant");
} else {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/shortcuts.rs b/apps/screenpipe-app-tauri/src-tauri/src/shortcuts.rs
index e14710b57..0958fc9a4 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/shortcuts.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/shortcuts.rs
@@ -210,6 +210,77 @@ pub async fn initialize_global_shortcuts(app: &AppHandle) -> Result<(), String>
apply_shortcuts(app, &config).await
}
+/// Register ONLY the start/stop capture shortcuts, and route them through the
+/// native recording path rather than the normal `shortcut-*-recording` webview
+/// events.
+///
+/// Enterprise policy can leave the app with no tray and no windows. In that state
+/// the regular handlers are dead: `shortcut-start-recording` / `-stop-recording`
+/// are consumed by `deeplink-handler` and the home page, and every webview is
+/// destroyed, so the emit lands on nothing and the user cannot pause capture.
+/// The native path is authoritative and needs no webview, which keeps a working
+/// pause control in a fully surface-free deployment.
+pub async fn initialize_recording_control_shortcuts(app: &AppHandle) -> Result<(), String> {
+ let config = ShortcutConfig::from_store(app).await?;
+ let global_shortcut = app.global_shortcut();
+ if let Err(e) = global_shortcut.unregister_all() {
+ error!("failed to unregister all shortcuts for recording-only setup: {}", e);
+ }
+
+ register_shortcut(
+ app,
+ &config.start,
+ config.is_disabled("start_recording"),
+ |app| {
+ track_shortcut_used(app, "start_recording");
+ crate::tray::start_recording_native(app);
+ },
+ )
+ .await?;
+
+ register_shortcut(
+ app,
+ &config.stop,
+ config.is_disabled("stop_recording"),
+ |app| {
+ track_shortcut_used(app, "stop_recording");
+ crate::tray::stop_recording_native(app);
+ },
+ )
+ .await?;
+
+ info!("registered recording control shortcuts only (hidden UI mode)");
+ Ok(())
+}
+
+/// Reconcile the global shortcut set against enterprise policy.
+///
+/// Called at startup and on every enterprise-policy transition, so a policy that
+/// arrives after launch (or is later relaxed) converges on the same state.
+///
+/// - normal mode: the full shortcut set.
+/// - hidden UI, tray visible: nothing registered. The tray carries Pause, and
+/// registering hotkeys here would change behavior for existing deployments and
+/// risk colliding with another app's shortcut.
+/// - hidden UI, tray also suppressed: start/stop capture only, routed natively.
+/// This is the one state with no visible pause affordance at all, so it must
+/// not be left without one.
+pub async fn reconcile_with_enterprise_policy(app: &AppHandle, ui_hidden: bool, tray_hidden: bool) {
+ let result = if ui_hidden && tray_hidden {
+ info!("shortcuts: hidden UI with suppressed tray, recording controls only");
+ initialize_recording_control_shortcuts(app).await
+ } else if ui_hidden {
+ info!("shortcuts: hidden UI, tray retains pause, registering none");
+ Ok(())
+ } else {
+ initialize_global_shortcuts(app).await
+ };
+
+ if let Err(e) = result {
+ error!("failed to reconcile global shortcuts: {}", e);
+ }
+}
+
async fn apply_shortcuts(app: &AppHandle, config: &ShortcutConfig) -> Result<(), String> {
let global_shortcut = app.global_shortcut();
if let Err(e) = global_shortcut.unregister_all() {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
index 4a63b384f..05671ec7e 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
@@ -482,6 +482,18 @@ async fn tray_recording_action(app: &AppHandle) -> TrayRecordingAction {
}
fn toggle_recording_from_tray(app: &AppHandle) {
+ toggle_recording_native(app);
+}
+
+/// Toggle capture through the native path, independent of the tray icon and of
+/// any webview.
+///
+/// This is what keeps a pause control reachable when enterprise policy suppresses
+/// the tray. The tray's own Pause item routes to this same function, so removing
+/// the icon removes a menu entry — not the ability to stop recording. Safe to
+/// call with no tray present: the post-action tray rebuild is already a no-op
+/// when `tray_by_id` returns `None`.
+pub fn toggle_recording_native(app: &AppHandle) {
cancel_pause_timer();
let app = app.clone();
tauri::async_runtime::spawn(async move {
@@ -490,6 +502,28 @@ fn toggle_recording_from_tray(app: &AppHandle) {
});
}
+/// Resume capture natively. Used by the hidden-UI shortcut path, where the
+/// `shortcut-start-recording` webview event has no listener to consume it.
+pub fn start_recording_native(app: &AppHandle) {
+ cancel_pause_timer();
+ dispatch_tray_recording_action(
+ app.clone(),
+ TrayRecordingAction::Start,
+ Some(("recording started", "screen recording has been initiated")),
+ );
+}
+
+/// Pause capture natively. This is the user-facing pause control when no tray
+/// icon and no window exists, so it must work with every webview destroyed.
+pub fn stop_recording_native(app: &AppHandle) {
+ cancel_pause_timer();
+ dispatch_tray_recording_action(
+ app.clone(),
+ TrayRecordingAction::Stop,
+ Some(("recording paused", "capture paused — pipes and search still available")),
+ );
+}
+
#[cfg(feature = "e2e")]
pub(crate) async fn toggle_recording_from_harness(app: AppHandle) -> Result<(), String> {
cancel_pause_timer();
@@ -502,6 +536,13 @@ pub(crate) async fn toggle_recording_from_harness(app: AppHandle) -> Result<(),
/// Immediately rebuild the tray menu (called from main thread after optimistic status set).
pub(crate) fn force_tray_rebuild(app: &AppHandle) -> Result<()> {
+ // Reachable from the native recording path, which still runs when the tray is
+ // suppressed. Bail before prefetching menu data (a DB read) to build a menu
+ // that would be discarded by the `tray_by_id` check at the end anyway.
+ if tray_suppressed_by_policy() {
+ return Ok(());
+ }
+
let update_item = UPDATE_MENU_ITEM
.lock()
.unwrap_or_else(|e| e.into_inner())
@@ -1035,12 +1076,134 @@ struct MenuState {
all_capture_disabled: bool,
}
+/// True when enterprise policy forbids the tray icon from existing at all.
+///
+/// The tray is created by Tauri config at launch, so suppressing it is an active
+/// removal rather than simply declining to build one — see [`remove_tray`].
+pub fn tray_suppressed_by_policy() -> bool {
+ crate::enterprise_policy::is_tray_hidden()
+}
+
+/// Remove the tray icon without recreating it.
+///
+/// Must run on the main thread: dropping an `NSStatusItem` from a tokio thread
+/// fires `NSStatusBar _removeStatusItem` off-thread and crashes, which is the
+/// same hazard `recreate_tray` guards against.
+pub fn remove_tray(app: &AppHandle) {
+ let app_for_thread = app.clone();
+ let _ = app.run_on_main_thread(move || {
+ if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ crate::window::with_autorelease_pool(|| {
+ if app_for_thread.tray_by_id("screenpipe_main").is_none() {
+ return;
+ }
+ info!("tray: removing icon (suppressed by enterprise policy)");
+ let _old = app_for_thread.remove_tray_by_id("screenpipe_main");
+ drop(_old);
+ });
+ })) {
+ let panic_msg = if let Some(s) = e.downcast_ref::<&str>() {
+ s.to_string()
+ } else if let Some(s) = e.downcast_ref::<String>() {
+ s.clone()
+ } else {
+ format!("{:?}", e)
+ };
+ error!("panic caught while removing tray icon: {}", panic_msg);
+ }
+ });
+}
+
+/// Re-assert the tray against the current enterprise policy.
+///
+/// Called on every policy reconciliation. Removing the tray is the easy half;
+/// restoring it needs `setup_tray` after the icon is rebuilt, because
+/// `recreate_tray` deliberately does not re-register click handlers (it assumes
+/// they survived an icon swap) and installs no poller. A tray that was fully
+/// removed has neither.
+///
+/// When the icon is missing we rebuild and install the menu inside a single main
+/// thread hop. `recreate_tray` only *schedules* its work, so calling it and then
+/// calling `setup_tray` from this thread would let the menu install look for an
+/// icon the scheduled closure has not built yet — `tray_by_id` returns `None` and
+/// `setup_tray` returns `Ok(())` having installed nothing, leaving a live icon
+/// with no menu for a full poll interval.
+pub fn enforce_tray_visibility(app: &AppHandle) {
+ if tray_suppressed_by_policy() {
+ remove_tray(app);
+ return;
+ }
+
+ let update_item = UPDATE_MENU_ITEM
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .clone();
+
+ if app.tray_by_id("screenpipe_main").is_some() {
+ // Icon is already there; just make sure its menu and handlers are current.
+ if let Err(error) = setup_tray(app, update_item.as_ref()) {
+ error!("failed to reinstall tray menu: {error:#}");
+ }
+ return;
+ }
+
+ let app_for_thread = app.clone();
+ let _ = app.run_on_main_thread(move || {
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ // Re-check on the main thread: the policy can flip again between the
+ // caller's check and this closure actually running.
+ if tray_suppressed_by_policy() {
+ return;
+ }
+ recreate_tray_on_main_thread(&app_for_thread);
+
+ // Only install if the rebuild actually produced an icon.
+ if app_for_thread.tray_by_id("screenpipe_main").is_none() {
+ error!("tray: rebuild produced no icon, skipping menu install");
+ return;
+ }
+
+ let update_item = UPDATE_MENU_ITEM
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .clone();
+ if let Err(error) = setup_tray(&app_for_thread, update_item.as_ref()) {
+ error!("failed to reinstall tray menu: {error:#}");
+ }
+ }));
+
+ if let Err(e) = result {
+ let panic_msg = if let Some(s) = e.downcast_ref::<&str>() {
+ s.to_string()
+ } else if let Some(s) = e.downcast_ref::<String>() {
+ s.clone()
+ } else {
+ format!("{:?}", e)
+ };
+ error!("panic caught while restoring tray icon: {}", panic_msg);
+ }
+ });
+}
+
pub fn setup_tray(app: &AppHandle, update_item: Option<&tauri::menu::MenuItem<Wry>>) -> Result<()> {
- // Store update_item globally so recreate_tray can use it (None for enterprise)
+ // Store update_item globally so recreate_tray can use it (None for enterprise).
+ // Do this even when suppressed: `enforce_tray_visibility` needs the item to
+ // rebuild a full tray if the policy is later relaxed, and skipping the store
+ // would silently downgrade the restored tray.
if let Ok(mut guard) = UPDATE_MENU_ITEM.lock() {
*guard = update_item.cloned();
}
+ // An admin may suppress the tray outright. Tauri already built the icon
+ // from `tauri.conf.json`, so take it back down and install nothing: no
+ // menu, no click handlers, and no 5s poller rebuilding a menu for an icon
+ // the org removed.
+ if tray_suppressed_by_policy() {
+ info!("tray: suppressed by enterprise policy, skipping tray setup");
+ remove_tray(app);
+ return Ok(());
+ }
+
if let Some(main_tray) = app.tray_by_id("screenpipe_main") {
// Initial menu setup with empty state
let data = prefetch_tray_menu_data(app);
@@ -1100,85 +1263,109 @@ pub fn log_tray_position(app: &AppHandle) {
}
}
-#[allow(dead_code)] // called only on macOS
-pub fn recreate_tray(app: &AppHandle) {
- let app_for_thread = app.clone();
- // Wrap in catch_unwind: ObjC exceptions during tray operations can panic
- // across the FFI boundary (nounwind → abort). catch_unwind prevents this.
- let _ = app.run_on_main_thread(move || {
- if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
- crate::window::with_autorelease_pool(|| {
- let app = app_for_thread;
- let update_item = match UPDATE_MENU_ITEM.lock() {
- Ok(guard) => guard.clone(),
- Err(_) => {
- error!("failed to lock UPDATE_MENU_ITEM for tray recreation");
- return;
- }
- };
-
- // Remove the old tray icon (must be on main thread for NSStatusBar)
- debug!("recreate_tray: removing old tray icon");
+/// Body of [`recreate_tray`]. **Must run on the main thread** — dropping or
+/// building an `NSStatusItem` off-thread crashes, the same hazard the
+/// `run_on_main_thread` wrapper in `recreate_tray` exists to avoid.
+///
+/// Split out from [`recreate_tray`] so a caller that must recreate *and then*
+/// install the menu can do both in one ordered hop. `recreate_tray` schedules,
+/// so following it with a `setup_tray` on the calling thread would race: the
+/// menu install would look for an icon that the scheduled closure has not built
+/// yet and silently no-op.
+#[allow(dead_code)] // reached only via the macOS/Windows tray paths
+fn recreate_tray_on_main_thread(app: &AppHandle) {
+ crate::window::with_autorelease_pool(|| {
+ // Never resurrect a tray the admin removed. recreate_tray runs on
+ // every enterprise-policy reconciliation and from the menu-refresh
+ // path, so without this guard a suppressed icon would reappear on
+ // the next poll. Take it down instead and stop.
+ if tray_suppressed_by_policy() {
+ if app.tray_by_id("screenpipe_main").is_some() {
+ info!("recreate_tray: suppressed by enterprise policy, removing instead");
let _old = app.remove_tray_by_id("screenpipe_main");
- // Drop the old tray icon explicitly on main thread
drop(_old);
- debug!("recreate_tray: old tray removed, building new one");
+ }
+ return;
+ }
- // Create a new tray icon — macOS assigns it the rightmost position
- let icon = match app.path().resolve(
- "assets/screenpipe-logo-tray-white.png",
- tauri::path::BaseDirectory::Resource,
- ) {
- Ok(path) => tauri::image::Image::from_path(path).ok(),
- Err(_) => {
- tauri::image::Image::from_path("assets/screenpipe-logo-tray-white.png").ok()
- }
- };
+ let update_item = match UPDATE_MENU_ITEM.lock() {
+ Ok(guard) => guard.clone(),
+ Err(_) => {
+ error!("failed to lock UPDATE_MENU_ITEM for tray recreation");
+ return;
+ }
+ };
- let mut builder = TrayIconBuilder::<Wry>::with_id("screenpipe_main")
- .icon_as_template(true)
- .show_menu_on_left_click(!cfg!(target_os = "windows"));
+ // Remove the old tray icon (must be on main thread for NSStatusBar)
+ debug!("recreate_tray: removing old tray icon");
+ let _old = app.remove_tray_by_id("screenpipe_main");
+ // Drop the old tray icon explicitly on main thread
+ drop(_old);
+ debug!("recreate_tray: old tray removed, building new one");
+
+ // Create a new tray icon — macOS assigns it the rightmost position
+ let icon = match app.path().resolve(
+ "assets/screenpipe-logo-tray-white.png",
+ tauri::path::BaseDirectory::Resource,
+ ) {
+ Ok(path) => tauri::image::Image::from_path(path).ok(),
+ Err(_) => tauri::image::Image::from_path("assets/screenpipe-logo-tray-white.png").ok(),
+ };
- if let Some(ref icon) = icon {
- if icon.width() > 0 && icon.height() > 0 {
- builder = builder.icon(icon.clone());
- } else {
- error!(
- "tray icon has zero dimensions ({}x{}), skipping",
- icon.width(),
- icon.height()
- );
- }
- } else {
- error!("failed to load tray icon for recreation");
+ let mut builder = TrayIconBuilder::<Wry>::with_id("screenpipe_main")
+ .icon_as_template(true)
+ .show_menu_on_left_click(!cfg!(target_os = "windows"));
+
+ if let Some(ref icon) = icon {
+ if icon.width() > 0 && icon.height() > 0 {
+ builder = builder.icon(icon.clone());
+ } else {
+ error!(
+ "tray icon has zero dimensions ({}x{}), skipping",
+ icon.width(),
+ icon.height()
+ );
+ }
+ } else {
+ error!("failed to load tray icon for recreation");
+ }
+
+ debug!("recreate_tray: calling builder.build()");
+ match builder.build(app) {
+ Ok(new_tray) => {
+ debug!("recreate_tray: build succeeded, setting menu");
+ // Setup menu
+ let data = prefetch_tray_menu_data(app);
+ if let Ok(menu) = create_dynamic_menu(
+ app,
+ &MenuState::default(),
+ update_item.as_ref(),
+ &data,
+ ) {
+ let _ = install_tray_menu(&new_tray, menu);
+ clear_pending_tray_menu();
}
+ // NOTE: do NOT re-register click handlers here.
+ // The handler from setup_tray() is keyed by tray ID and persists
+ // across tray icon recreation. Re-registering causes double-firing.
- debug!("recreate_tray: calling builder.build()");
- match builder.build(&app) {
- Ok(new_tray) => {
- debug!("recreate_tray: build succeeded, setting menu");
- // Setup menu
- let data = prefetch_tray_menu_data(&app);
- if let Ok(menu) = create_dynamic_menu(
- &app,
- &MenuState::default(),
- update_item.as_ref(),
- &data,
- ) {
- let _ = install_tray_menu(&new_tray, menu);
- clear_pending_tray_menu();
- }
- // NOTE: do NOT re-register click handlers here.
- // The handler from setup_tray() is keyed by tray ID and persists
- // across tray icon recreation. Re-registering causes double-firing.
+ info!("tray icon recreated at rightmost position");
+ }
+ Err(e) => {
+ error!("failed to recreate tray icon: {}", e);
+ }
+ }
+ }); // with_autorelease_pool
+}
- info!("tray icon recreated at rightmost position");
- }
- Err(e) => {
- error!("failed to recreate tray icon: {}", e);
- }
- }
- }); // with_autorelease_pool
+#[allow(dead_code)] // called only on macOS
+pub fn recreate_tray(app: &AppHandle) {
+ let app_for_thread = app.clone();
+ // Wrap in catch_unwind: ObjC exceptions during tray operations can panic
+ // across the FFI boundary (nounwind → abort). catch_unwind prevents this.
+ let _ = app.run_on_main_thread(move || {
+ if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ recreate_tray_on_main_thread(&app_for_thread);
})) {
// The panic hook already sent the panic message + backtrace to Sentry
// (as a Fatal-level capture_message). Log here for local diagnostics.
@@ -2352,6 +2539,15 @@ pub(crate) async fn set_recording_status_from_harness(
}
pub fn setup_tray_menu_updater(app: AppHandle, update_item: Option<&tauri::menu::MenuItem<Wry>>) {
+ // Spawn exactly once per process. The tray can be removed and reinstalled
+ // when enterprise policy flips, and each reinstall re-enters setup_tray —
+ // without this guard every flip would leave another 5s poller running.
+ static POLLER_STARTED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
+ if POLLER_STARTED.set(()).is_err() {
+ debug!("tray menu updater already running, skipping duplicate spawn");
+ return;
+ }
+
let update_item = update_item.cloned();
tauri::async_runtime::spawn(async move {
let mut interval = tokio::time::interval(std::time::Duration::from_secs(5));
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/window/mod.rs b/apps/screenpipe-app-tauri/src-tauri/src/window/mod.rs
index 40a92901d..cc9e2bc31 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/window/mod.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/window/mod.rs
@@ -459,13 +459,18 @@ pub fn webview_renderer_heartbeat(window: tauri::WebviewWindow) {
/// later policy reversal.
pub fn enforce_enterprise_ui_visibility(app: &tauri::AppHandle) {
let hidden = crate::enterprise_policy::is_app_ui_hidden();
+ let tray_hidden = crate::enterprise_policy::is_tray_hidden();
// The enterprise policy hook calls this on every 5-min poll. Only do work
// on an actual transition — otherwise we'd tear down an already-dormant UI
// and (worse) rebuild the tray every poll, flickering the menu-bar icon.
- // -1 = unknown (first call), 0 = visible, 1 = hidden.
+ //
+ // Both axes are packed into the key: the admin can suppress the tray while
+ // leaving windows visible, so keying only on `hidden` would miss a tray-only
+ // flip entirely. 0 = both visible, 1 = app UI hidden, 2 = tray hidden,
+ // 3 = both hidden. -1 = unknown (first call).
static LAST_APPLIED: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
- let next = if hidden { 1 } else { 0 };
+ let next = (if hidden { 1 } else { 0 }) | (if tray_hidden { 2 } else { 0 });
if LAST_APPLIED.swap(next, std::sync::atomic::Ordering::SeqCst) == next {
return;
}
@@ -504,11 +509,27 @@ pub fn enforce_enterprise_ui_visibility(app: &tauri::AppHandle) {
// Always re-apply the activation policy + tray so a policy change in EITHER
// direction is reflected immediately (Accessory+minimal tray when hidden,
- // Regular+full tray when not).
+ // Regular+full tray when not). enforce_tray_visibility also handles the
+ // tray-suppressed case, where the correct end state is no icon at all.
#[cfg(target_os = "macos")]
panel::reset_to_regular_and_refresh_tray(app);
#[cfg(any(target_os = "macos", target_os = "windows"))]
- crate::tray::recreate_tray(app);
+ crate::tray::enforce_tray_visibility(app);
+
+ // Reached only on an actual transition, so this re-registers shortcuts just
+ // when the pause affordance changed: a policy that suppresses the tray after
+ // launch must still leave a working pause control, and relaxing it must put
+ // the normal shortcut set back.
+ let app_for_shortcuts = app.clone();
+ let (ui_hidden, tray_hidden) = (hidden, tray_hidden);
+ tauri::async_runtime::spawn(async move {
+ crate::shortcuts::reconcile_with_enterprise_policy(
+ &app_for_shortcuts,
+ ui_hidden,
+ tray_hidden,
+ )
+ .await;
+ });
}
// These re-exports preserve the original public API surface. Some are only
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/window/panel.rs b/apps/screenpipe-app-tauri/src-tauri/src/window/panel.rs
index 0149095da..20337d2a3 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/window/panel.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/window/panel.rs
@@ -86,10 +86,14 @@ pub fn main_label_for_mode(mode: &str) -> &'static str {
/// 2. Headless mode has torn down every webview, or
/// 3. the user opted into `hideDockIcon` in Settings → Display.
///
-/// The tray icon is unaffected in every case, so the app stays reachable. This
-/// is a single explicit call (on startup, window close, and when the user
-/// toggles the setting) — NOT the per-tick watchdog toggling that was removed
-/// for causing crashes; setting the policy once on a real event is safe.
+/// This function only sets the activation policy; it never creates a tray, so
+/// it cannot resurrect one. The tray stays reachable in the cases above because
+/// `tray::enforce_tray_visibility` keeps it unless enterprise tray suppression
+/// is explicitly on — see `is_tray_hidden` for why that is a separate, opt-in
+/// decision rather than a consequence of hidden UI. This is a single explicit
+/// call (on startup, window close, and when the user toggles the setting) — NOT
+/// the per-tick watchdog toggling that was removed for causing crashes; setting
+/// the policy once on a real event is safe.
#[cfg(target_os = "macos")]
pub fn reset_to_regular_and_refresh_tray(app: &AppHandle) {
if !super::window_activation_allowed() {