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

Restore enterprise UI when hidden policy is disabled (#5313)

Ezra Ellettebbcd5738e59c
diff --git a/TESTING.md b/TESTING.md
index e3ad2358e..012912fb5 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -88,6 +88,7 @@ commits that broke this area: `0752ea59`, `7562ec62`, `2a2bd9b5`, `f2f7f770`, `5
- [ ] **Recording toggle in tray** — Verify that the tray menu has a single toggle to start/stop recording (replacing separate items). (`cdc1d0fd9`)
- [ ] **Headless webview teardown** — Enable Headless, close Home, and verify every app webview process exits while recording, scheduled pipes, and the existing tray icon remain active. Global shortcuts must do nothing while dormant; opening screenpipe from the tray must recreate Home and restore shortcuts.
- [ ] **Headless record-only mode** — Enable Headless → Record only, close Home, and verify recording and the tray remain active while scheduled pipe occurrences are consumed as no-ops. Open screenpipe from the tray and verify pipes wait for their next future schedule without a catch-up burst.
+- [ ] **Enterprise hidden-UI policy reversal** — With enterprise hidden UI active, turn the server policy off while the app is running. Home should reopen on the next policy refresh, the dock/full tray and global shortcuts should return, and `~/.screenpipe/enterprise.json` should persist `hide_app: false`. If the user separately enabled Headless, the app should remain dormant.
### 3. monitor plug/unplug
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 634db4bf3..a3e66422b 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/enterprise/policy.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/enterprise/policy.rs
@@ -10,11 +10,14 @@
use once_cell::sync::Lazy;
use std::collections::HashSet;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::RwLock;
static HIDDEN_SECTIONS: Lazy<RwLock<HashSet<String>>> = Lazy::new(|| RwLock::new(HashSet::new()));
-static DEPLOYMENT_APP_UI_HIDDEN: Lazy<bool> =
- Lazy::new(|| env_hides_app_ui() || enterprise_json_hides_app_ui());
+static SERVER_POLICY_RECEIVED: 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);
/// Per-stream sync policy. Defaults to all-true so an unconfigured device
/// behaves exactly like before this feature shipped. The frontend pulls the
@@ -142,52 +145,70 @@ fn user_enterprise_config_path() -> std::path::PathBuf {
screenpipe_core::paths::default_screenpipe_data_dir().join("enterprise.json")
}
-fn enterprise_json_hides_app_ui() -> bool {
- let paths = [
- bundled_enterprise_config_path(),
- Some(user_enterprise_config_path()),
- ];
-
- for path in paths.into_iter().flatten() {
- let Ok(raw) = std::fs::read_to_string(&path) else {
- continue;
- };
- let Ok(json) = serde_json::from_str::<serde_json::Value>(&raw) else {
- continue;
- };
-
- let hide_app = json
- .get("hide_app")
+fn enterprise_config_hides_app_ui(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;
+ };
+
+ let hide_app = json
+ .get("hide_app")
+ .and_then(|value| value.as_bool())
+ .unwrap_or(false)
+ || json
+ .get("hide_app_ui")
.and_then(|value| value.as_bool())
- .unwrap_or(false)
- || json
- .get("hide_app_ui")
- .and_then(|value| value.as_bool())
- .unwrap_or(false);
-
- let ui_mode = json
- .get("ui_mode")
- .and_then(|value| value.as_str())
- .map(|mode| {
- matches!(
- mode.trim().to_ascii_lowercase().as_str(),
- "hidden" | "background" | "managed_background"
- )
- })
.unwrap_or(false);
- if hide_app || ui_mode {
- tracing::info!(
- "enterprise: app UI hidden by deployment config at {}",
- path.display()
- );
- return true;
- }
+ let ui_mode = json
+ .get("ui_mode")
+ .and_then(|value| value.as_str())
+ .map(|mode| {
+ matches!(
+ mode.trim().to_ascii_lowercase().as_str(),
+ "hidden" | "background" | "managed_background"
+ )
+ })
+ .unwrap_or(false);
+
+ if hide_app || ui_mode {
+ tracing::info!(
+ "enterprise: app UI hidden by deployment config at {}",
+ path.display()
+ );
+ return true;
}
false
}
+fn bundled_enterprise_config_hides_app_ui() -> bool {
+ bundled_enterprise_config_path()
+ .as_deref()
+ .map(enterprise_config_hides_app_ui)
+ .unwrap_or(false)
+}
+
+fn user_enterprise_config_hides_app_ui() -> bool {
+ enterprise_config_hides_app_ui(&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 resolve_app_ui_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]
@@ -195,6 +216,10 @@ pub fn set_enterprise_policy(hidden_sections: Vec<String>) {
if let Ok(mut guard) = HIDDEN_SECTIONS.write() {
*guard = hidden_sections.into_iter().collect();
tracing::info!("enterprise: policy updated, hidden sections: {:?}", *guard);
+ // Once the server has answered, its current policy supersedes the
+ // user-writable hide_app snapshot used only to avoid startup UI flash.
+ // Environment and bundled deployment overrides remain authoritative.
+ SERVER_POLICY_RECEIVED.store(true, Ordering::SeqCst);
}
}
@@ -266,18 +291,18 @@ pub fn is_tray_item_hidden(section_id: &str) -> bool {
/// This intentionally does not hide permission recovery: macOS may still need
/// to show the raw system permission flow even for a managed background pilot.
pub fn is_app_ui_hidden() -> bool {
- if *DEPLOYMENT_APP_UI_HIDDEN {
- return true;
- }
+ let server_policy_hidden = SERVER_POLICY_RECEIVED.load(Ordering::SeqCst).then(|| {
+ HIDDEN_SECTIONS
+ .read()
+ .map(|guard| hidden_sections_hide_app_ui(&guard))
+ .unwrap_or(false)
+ });
- HIDDEN_SECTIONS
- .read()
- .map(|guard| {
- APP_UI_HIDDEN_SECTIONS
- .iter()
- .any(|section| guard.contains(*section))
- })
- .unwrap_or(false)
+ resolve_app_ui_hidden(
+ *IMMUTABLE_DEPLOYMENT_APP_UI_HIDDEN,
+ server_policy_hidden,
+ *PERSISTED_APP_UI_HIDDEN,
+ )
}
/// Serializes any test that mutates `SYNC_STREAMS`. Cargo runs tests in
@@ -308,9 +333,21 @@ mod tests {
#[test]
fn hidden_sections_can_hide_app_ui() {
- set_enterprise_policy(vec!["app_ui".to_string()]);
- assert!(is_app_ui_hidden());
- set_enterprise_policy(vec![]);
+ let hidden = HashSet::from(["app_ui".to_string()]);
+ assert!(hidden_sections_hide_app_ui(&hidden));
+ assert!(!hidden_sections_hide_app_ui(&HashSet::new()));
+ }
+
+ #[test]
+ fn fresh_server_policy_supersedes_persisted_hidden_snapshot() {
+ assert!(resolve_app_ui_hidden(false, None, true));
+ assert!(!resolve_app_ui_hidden(false, Some(false), true));
+ assert!(resolve_app_ui_hidden(false, Some(true), false));
+ }
+
+ #[test]
+ fn immutable_deployment_override_remains_authoritative() {
+ assert!(resolve_app_ui_hidden(true, Some(false), false));
}
#[test]
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/enterprise_sync.rs b/apps/screenpipe-app-tauri/src-tauri/src/enterprise_sync.rs
index e3c17faed..088e6ad9f 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/enterprise_sync.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/enterprise_sync.rs
@@ -30,6 +30,7 @@ mod imp {
};
use serde::Deserialize;
use sha2::{Digest, Sha256};
+ use std::collections::HashMap;
use std::fmt::Write as _;
use std::sync::Arc;
use tauri::Manager;
@@ -553,6 +554,128 @@ mod imp {
.or_else(crate::commands::get_enterprise_license_key)
}
+ const DEFAULT_POLICY_URL: &str = "https://screenpipe.com/api/enterprise/policy";
+ const HIDDEN_UI_POLICY_POLL_INTERVAL: std::time::Duration =
+ std::time::Duration::from_secs(5 * 60);
+
+ #[derive(Deserialize)]
+ struct HiddenUiPolicyResponse {
+ #[serde(rename = "hiddenSections", default)]
+ hidden_sections: Vec<String>,
+ #[serde(rename = "lockedSettings", default)]
+ locked_settings: HashMap<String, serde_json::Value>,
+ }
+
+ impl HiddenUiPolicyResponse {
+ fn all_hidden_sections(mut self) -> Vec<String> {
+ // Match the frontend policy normalization: locked setting keys also
+ // hide their corresponding settings surface. `referral` is always
+ // hidden in enterprise builds but is irrelevant to UI dormancy.
+ self.hidden_sections.extend(self.locked_settings.into_keys());
+ self.hidden_sections.sort();
+ self.hidden_sections.dedup();
+ self.hidden_sections
+ }
+ }
+
+ enum EnterprisePolicyCredential {
+ LicenseKey(String),
+ AccountToken(String),
+ }
+
+ fn current_policy_credential() -> Option<EnterprisePolicyCredential> {
+ license_key_from_env_or_config()
+ .map(EnterprisePolicyCredential::LicenseKey)
+ .or_else(|| {
+ crate::commands::get_cloud_token().map(EnterprisePolicyCredential::AccountToken)
+ })
+ }
+
+ async fn fetch_hidden_ui_policy(
+ http: &reqwest::Client,
+ policy_url: &str,
+ device_id: &str,
+ credential: EnterprisePolicyCredential,
+ ) -> Result<Vec<String>, String> {
+ let request = http.get(policy_url).header("X-Device-Id", device_id);
+ let request = match credential {
+ EnterprisePolicyCredential::LicenseKey(key) => request.header("X-License-Key", key),
+ EnterprisePolicyCredential::AccountToken(token) => request.bearer_auth(token),
+ };
+ let response = request.send().await.map_err(|error| error.to_string())?;
+ if !response.status().is_success() {
+ return Err(format!("HTTP {}", response.status()));
+ }
+ response
+ .json::<HiddenUiPolicyResponse>()
+ .await
+ .map(HiddenUiPolicyResponse::all_hidden_sections)
+ .map_err(|error| error.to_string())
+ }
+
+ /// The normal enterprise policy poll lives in the Home webview. Hidden UI
+ /// mode destroys that webview, so a tiny native watcher must remain alive
+ /// to observe the one policy change that can bring the UI back. Once Home
+ /// is restored, its full policy fetch applies managed settings and pipes.
+ fn spawn_hidden_ui_policy_watcher(app: &tauri::AppHandle) {
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ let policy_url = std::env::var("SCREENPIPE_ENTERPRISE_POLICY_URL")
+ .ok()
+ .filter(|url| !url.trim().is_empty())
+ .unwrap_or_else(|| DEFAULT_POLICY_URL.to_string());
+ let http = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(30))
+ .redirect(reqwest::redirect::Policy::none())
+ .build()
+ .expect("enterprise policy HTTP client builds");
+
+ // Let startup finish before the first control-plane request. This
+ // still recovers a persisted hidden app far sooner than the normal
+ // five-minute frontend polling cadence.
+ tokio::time::sleep(std::time::Duration::from_secs(15)).await;
+ loop {
+ if crate::enterprise_policy::is_app_ui_hidden() {
+ match current_policy_credential() {
+ Some(credential) => {
+ let device_id = settings_device_id(&app)
+ .unwrap_or_else(|| "unknown".to_string());
+ match fetch_hidden_ui_policy(
+ &http,
+ &policy_url,
+ &device_id,
+ credential,
+ )
+ .await
+ {
+ Ok(hidden_sections) => {
+ crate::enterprise_policy::set_enterprise_policy(
+ hidden_sections,
+ );
+ if !crate::commands::apply_enterprise_ui_visibility(
+ app.clone(),
+ ) {
+ info!(
+ "enterprise: native policy watcher restored visible UI"
+ );
+ }
+ }
+ Err(error) => warn!(
+ "enterprise: hidden-UI policy refresh failed: {error}"
+ ),
+ }
+ }
+ None => warn!(
+ "enterprise: hidden UI is active but no policy credential is available"
+ ),
+ }
+ }
+
+ tokio::time::sleep(HIDDEN_UI_POLICY_POLL_INTERVAL).await;
+ }
+ });
+ }
+
fn enterprise_license_hash(license_key: &str) -> Option<String> {
let trimmed = license_key.trim();
if trimmed.is_empty() {
@@ -619,6 +742,11 @@ mod imp {
pub fn spawn(app: &tauri::AppHandle) -> Option<tokio::sync::watch::Sender<bool>> {
use tauri::Manager;
+ // This watcher is independent of telemetry upload configuration. An
+ // account-authenticated enterprise build may have no license key, but
+ // it still needs to recover when the server turns hidden UI off.
+ spawn_hidden_ui_policy_watcher(app);
+
let app_data_dir = app.path().app_data_dir().ok()?;
// Use the same device id the heartbeat reports under (settings `deviceId`)
// so a machine is a single enterprise_devices row, not two.
@@ -758,7 +886,9 @@ mod imp {
mod device_id_tests {
use super::{
choose_device_id, enterprise_license_hash, exact_frame_url, image_uploads_allowed,
+ HiddenUiPolicyResponse,
};
+ use std::collections::HashMap;
#[test]
fn settings_id_wins_so_sync_matches_heartbeat() {
@@ -813,6 +943,22 @@ mod imp {
"http://localhost:3030/frames/42?fallback=false"
);
}
+
+ #[test]
+ fn hidden_ui_policy_matches_frontend_section_normalization() {
+ let response = HiddenUiPolicyResponse {
+ hidden_sections: vec!["app_ui".to_string(), "app_ui".to_string()],
+ locked_settings: HashMap::from([(
+ "recording".to_string(),
+ serde_json::Value::Bool(true),
+ )]),
+ };
+
+ assert_eq!(
+ response.all_hidden_sections(),
+ vec!["app_ui".to_string(), "recording".to_string()]
+ );
+ }
}
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/headless.rs b/apps/screenpipe-app-tauri/src-tauri/src/headless.rs
index 22ec5aba9..fce02b433 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/headless.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/headless.rs
@@ -35,14 +35,13 @@ fn preserve_window_during_dormancy(label: &str, onboarding_completed: bool) -> b
}
/// Sync dormant/record-only state to an enterprise hidden-UI policy that flipped
-/// mid-session. The enterprise enforcement path hides (not destroys) windows, so
-/// this only flips the flags that gate pipe suppression and tray wake — without
-/// re-entering the NSPanel teardown. On un-hide, fall back to whatever the user's
-/// own headless settings dictate so a non-enterprise headless user isn't cleared.
-pub fn set_enterprise_hidden(app: &AppHandle, hidden: bool) {
+/// mid-session. On un-hide, fall back to the user's own headless preference and
+/// restore shortcuts when the enterprise policy was the reason UI was dormant.
+/// Returns true when the app transitioned back to an interactive UI state.
+pub fn set_enterprise_hidden(app: &AppHandle, hidden: bool) -> bool {
if hidden {
initialize(true, true);
- return;
+ return false;
}
let (dormant, record_only) = crate::store::SettingsStore::get(app)
@@ -55,7 +54,13 @@ pub fn set_enterprise_hidden(app: &AppHandle, hidden: bool) {
)
})
.unwrap_or((false, false));
- initialize(dormant, record_only);
+ if dormant {
+ initialize(true, record_only);
+ return false;
+ }
+
+ RECORD_ONLY.store(false, Ordering::SeqCst);
+ wake_from_tray(app)
}
#[cfg(target_os = "macos")]
@@ -192,13 +197,13 @@ fn enter_on_main_thread(app: &AppHandle) {
}
/// Tray UI actions are the sole wake path while dormant.
-pub fn wake_from_tray(app: &AppHandle) {
+pub fn wake_from_tray(app: &AppHandle) -> bool {
// Enterprise hidden-UI mode has no wake path; the UI stays dormant.
if crate::enterprise_policy::is_app_ui_hidden() {
- return;
+ return false;
}
if !UI_DORMANT.swap(false, Ordering::SeqCst) {
- return;
+ return false;
}
#[cfg(target_os = "macos")]
@@ -213,6 +218,7 @@ pub fn wake_from_tray(app: &AppHandle) {
});
info!("headless: UI woken from tray");
+ true
}
#[cfg(test)]
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 0c10b8e42..22f4058d5 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/window/mod.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/window/mod.rs
@@ -44,8 +44,8 @@ pub fn finalize_webview_window(window: tauri::WebviewWindow) -> tauri::WebviewWi
/// (macOS Accessory), then rebuild the tray so its "open app" entries
/// disappear. Incomplete onboarding remains visible until permissions are
/// finished.
-/// * visible → restore the normal activation policy + full tray menu; windows
-/// reopen on demand via the tray/shortcut.
+/// * visible → restore the normal activation policy + full tray menu and
+/// reopen Home immediately, unless the user separately enabled Headless.
///
/// Permission-recovery is intentionally never hidden — a managed background
/// device may still need the macOS permission flow to surface.
@@ -77,8 +77,26 @@ pub fn enforce_enterprise_ui_visibility(app: &tauri::AppHandle) {
tracing::info!("enterprise: hidden-UI policy enforced — headless teardown");
} else {
// Un-hide: restore dormant/record-only to the user's own headless prefs.
- // Windows reopen on demand via the tray/shortcut.
- crate::headless::set_enterprise_hidden(app, false);
+ // If enterprise policy was the only reason the UI was dormant, recreate
+ // Home immediately so the server-side change is visible without requiring
+ // the user to discover a newly restored tray item first.
+ if crate::headless::set_enterprise_hidden(app, false) {
+ let app_for_show = app.clone();
+ if let Err(error) = app.run_on_main_thread(move || {
+ match ShowRewindWindow::Home { page: None }.show(&app_for_show) {
+ Ok(_) => tracing::info!(
+ "enterprise: hidden-UI policy disabled — Home window restored"
+ ),
+ Err(error) => tracing::warn!(
+ "enterprise: failed to restore Home after hidden-UI policy disabled: {error}"
+ ),
+ }
+ }) {
+ tracing::warn!(
+ "enterprise: failed to schedule Home restore after hidden-UI policy disabled: {error}"
+ );
+ }
+ }
}
// Always re-apply the activation policy + tray so a policy change in EITHER