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

Add default-enabled enterprise policy for automatic AI-tool setup (#7653)

Louis Beaumont0a0fd82a1a71
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 0e496857c..17e392b3f 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/enterprise/policy.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/enterprise/policy.rs
@@ -42,6 +42,82 @@ static IMMUTABLE_DEPLOYMENT_TRAY_HIDDEN: Lazy<bool> =
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()));
+// Missing policy preserves automatic setup, including managed hidden installs.
+static AUTO_CONNECT_AI_TOOLS: Lazy<AiToolPolicy> = Lazy::new(|| {
+ AiToolPolicy::new(
+ read_auto_connect_ai_tools_at(&user_enterprise_config_path()),
+ !cfg!(feature = "enterprise-build"),
+ )
+});
+
+/// A coherent installer snapshot. Revision preserves changes that happen
+/// between scans, including disable/re-enable back to the same value.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct AiToolSetupPolicy {
+ pub allowed: bool,
+ pub revision: u64,
+}
+
+pub(crate) struct AiToolPolicy {
+ state: Mutex<AiToolPolicyState>,
+}
+
+struct AiToolPolicyState {
+ enabled: bool,
+ initial_refresh_complete: bool,
+ revision: u64,
+ next_request: u64,
+ last_applied_request: u64,
+}
+
+impl AiToolPolicy {
+ pub(crate) fn new(enabled: bool, initial_refresh_complete: bool) -> Self {
+ Self {
+ state: Mutex::new(AiToolPolicyState {
+ enabled,
+ initial_refresh_complete,
+ revision: 0,
+ next_request: 0,
+ last_applied_request: 0,
+ }),
+ }
+ }
+
+ pub(crate) fn snapshot(&self) -> AiToolSetupPolicy {
+ let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
+ AiToolSetupPolicy {
+ allowed: state.initial_refresh_complete && state.enabled,
+ revision: state.revision,
+ }
+ }
+
+ pub(crate) fn begin_refresh(&self) -> u64 {
+ let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
+ state.next_request += 1;
+ state.next_request
+ }
+
+ /// An older in-flight response cannot reverse a more recent successful
+ /// fetch. Failed newer requests do not discard an older valid response.
+ pub(crate) fn update(&self, request: u64, enabled: bool) -> bool {
+ let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
+ if request < state.last_applied_request {
+ return false;
+ }
+ state.last_applied_request = request;
+ if state.enabled != enabled {
+ state.revision += 1;
+ state.enabled = enabled;
+ }
+ state.initial_refresh_complete = true;
+ true
+ }
+
+ fn finish_initial_refresh(&self) {
+ self.state.lock().unwrap_or_else(|error| error.into_inner())
+ .initial_refresh_complete = true;
+ }
+}
static POLICY_UPDATE_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
/// Per-stream sync policy. Established streams preserve their historical
@@ -292,6 +368,86 @@ fn persist_enforce_auto_start(enabled: bool) {
}
}
+/// The control plane serializes select values as strings; accept JSON booleans
+/// too. Missing/null uses the enabled default; malformed values defer setup.
+pub(crate) fn auto_connect_ai_tools_value(value: Option<&serde_json::Value>) -> bool {
+ match value {
+ None | Some(serde_json::Value::Null) => true,
+ Some(serde_json::Value::Bool(enabled)) => *enabled,
+ Some(serde_json::Value::String(value)) => value == "true",
+ _ => false,
+ }
+}
+
+fn read_auto_connect_ai_tools_at(path: &Path) -> bool {
+ let raw = match std::fs::read_to_string(path) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return true,
+ Err(error) => {
+ tracing::warn!("enterprise: AI-tool policy cache unreadable; deferring setup: {error}");
+ return false;
+ }
+ };
+ match serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&raw) {
+ Ok(json) => auto_connect_ai_tools_value(json.get("auto_connect_ai_tools")),
+ Err(error) => {
+ tracing::warn!("enterprise: AI-tool policy cache invalid; deferring setup: {error}");
+ false
+ }
+ }
+}
+
+fn persist_auto_connect_ai_tools_at(path: &Path, enabled: bool) -> Result<bool, String> {
+ crate::enterprise_config_file::update(path, |object| {
+ object.insert(
+ "auto_connect_ai_tools".to_string(),
+ serde_json::Value::Bool(enabled),
+ );
+ Ok(())
+ })
+}
+
+/// Independent of UI visibility. Read on each background AI-tool scan so live
+/// policy changes take effect without launching a webview or restarting.
+pub(crate) fn ai_tool_setup_policy() -> AiToolSetupPolicy {
+ AUTO_CONNECT_AI_TOOLS.snapshot()
+}
+
+/// A fresh Enterprise install must observe its first policy response before
+/// auto-installing anything. On an unavailable response, use the cached decision
+/// (or the enabled default when no cache exists) until the next refresh.
+pub(crate) fn finish_initial_ai_tool_policy_refresh() {
+ AUTO_CONNECT_AI_TOOLS.finish_initial_refresh();
+}
+
+/// The authenticated native policy fetch owns this setting, independently of
+/// recording, enrollment, UI lifetime, and slow recorder reconfiguration.
+pub(crate) fn begin_ai_tool_policy_refresh() -> impl FnOnce(bool) + Send {
+ let request = AUTO_CONNECT_AI_TOOLS.begin_refresh();
+ move |enabled| {
+ if let Err(error) = apply_ai_tool_policy_at(
+ &AUTO_CONNECT_AI_TOOLS, request, enabled, &user_enterprise_config_path(),
+ ) {
+ tracing::warn!("enterprise: failed to cache AI-tool policy: {error}");
+ }
+ }
+}
+
+fn apply_ai_tool_policy_at(
+ policy: &AiToolPolicy,
+ request: u64,
+ enabled: bool,
+ path: &Path,
+) -> Result<bool, String> {
+ let _update_guard = POLICY_UPDATE_LOCK
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ if !policy.update(request, enabled) {
+ return Ok(false);
+ }
+ persist_auto_connect_ai_tools_at(path, enabled)
+}
+
fn enterprise_config_hides_app_ui(path: &std::path::Path) -> bool {
let Ok(raw) = std::fs::read_to_string(path) else {
return false;
@@ -617,6 +773,116 @@ pub(crate) fn sync_streams_test_lock() -> std::sync::MutexGuard<'static, ()> {
mod tests {
use super::*;
+ #[test]
+ fn ai_tool_policy_waits_for_first_refresh_and_preserves_offline_decisions() {
+ let enabled_default = AiToolPolicy::new(true, false);
+ assert!(
+ !enabled_default.snapshot().allowed,
+ "do not race the first server disable"
+ );
+ enabled_default.update(enabled_default.begin_refresh(), false);
+ assert!(!enabled_default.snapshot().allowed);
+ enabled_default.update(enabled_default.begin_refresh(), true);
+ assert!(enabled_default.snapshot().allowed);
+
+ for cached in [true, false] {
+ let offline = AiToolPolicy::new(cached, false);
+ assert!(!offline.snapshot().allowed);
+ offline.finish_initial_refresh();
+ assert_eq!(offline.snapshot().allowed, cached);
+ }
+ assert!(
+ AiToolPolicy::new(true, true).snapshot().allowed,
+ "consumer setup is immediate"
+ );
+ }
+
+ #[test]
+ fn ai_tool_policy_tracks_brief_transitions_and_rejects_stale_responses() {
+ let policy = AiToolPolicy::new(true, true);
+ let before = policy.snapshot();
+ let old = policy.begin_refresh();
+ let new = policy.begin_refresh();
+ assert!(policy.update(new, false));
+ assert!(!policy.update(old, true));
+ assert!(!policy.snapshot().allowed);
+ assert!(policy.update(policy.begin_refresh(), true));
+ assert!(policy.snapshot().allowed);
+ assert_ne!(policy.snapshot().revision, before.revision);
+ let unchanged = policy.snapshot();
+ assert!(policy.update(policy.begin_refresh(), true));
+ assert_eq!(policy.snapshot(), unchanged);
+ let valid = policy.begin_refresh();
+ let _failed = policy.begin_refresh();
+ assert!(
+ policy.update(valid, false),
+ "failed newer fetch must not lose valid policy"
+ );
+ }
+
+ #[test]
+ fn ai_tool_policy_stale_response_cannot_overwrite_cached_disable() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("enterprise.json");
+ let policy = AiToolPolicy::new(true, false);
+ let old = policy.begin_refresh();
+ let new = policy.begin_refresh();
+ assert!(apply_ai_tool_policy_at(&policy, new, false, &path).unwrap());
+ let disabled_cache = std::fs::read(&path).unwrap();
+ assert!(!apply_ai_tool_policy_at(&policy, old, true, &path).unwrap());
+ assert_eq!(std::fs::read(&path).unwrap(), disabled_cache);
+ assert!(!policy.snapshot().allowed);
+ assert!(!read_auto_connect_ai_tools_at(&path));
+
+ // A failed cache write still enforces the current server disable.
+ policy.update(policy.begin_refresh(), true);
+ assert!(
+ apply_ai_tool_policy_at(&policy, policy.begin_refresh(), false, dir.path()).is_err()
+ );
+ assert!(!policy.snapshot().allowed);
+ }
+
+ #[test]
+ fn ai_tool_policy_cache_errors_defer_setup_without_overwriting_data() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("enterprise.json");
+ for raw in ["{broken", "null", "[]", "true"] {
+ std::fs::write(&path, raw).unwrap();
+ assert!(!read_auto_connect_ai_tools_at(&path));
+ assert!(persist_auto_connect_ai_tools_at(&path, false).is_err());
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), raw);
+ }
+ assert!(
+ !read_auto_connect_ai_tools_at(dir.path()),
+ "unreadable is not missing"
+ );
+ for value in [
+ serde_json::json!(0),
+ serde_json::json!({}),
+ serde_json::json!("invalid"),
+ ] {
+ assert!(!auto_connect_ai_tools_value(Some(&value)));
+ }
+ }
+
+ #[test]
+ fn ai_tool_policy_cache_preserves_false_and_unrelated_deployment_fields() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("enterprise.json");
+ assert!(read_auto_connect_ai_tools_at(&path));
+ std::fs::write(&path, r#"{"hide_app":true,"license_key":"fixture"}"#).unwrap();
+ assert!(read_auto_connect_ai_tools_at(&path));
+ assert!(persist_auto_connect_ai_tools_at(&path, false).unwrap());
+ assert!(!read_auto_connect_ai_tools_at(&path));
+ assert!(!persist_auto_connect_ai_tools_at(&path, false).unwrap());
+ let cached: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
+ assert_eq!(cached["hide_app"], true);
+ assert_eq!(cached["license_key"], "fixture");
+ assert!(persist_auto_connect_ai_tools_at(&path, true).unwrap());
+ assert!(read_auto_connect_ai_tools_at(&path));
+ }
+
#[test]
fn truthy_accepts_common_deployment_values() {
for value in ["1", "true", "yes", "on", "hidden", "managed_background"] {
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 8afc3eca8..3f444a8b0 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/enterprise_sync.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/enterprise_sync.rs
@@ -986,6 +986,7 @@ mod imp {
hidden_sections: Vec<String>,
locked_settings: HashMap<String, serde_json::Value>,
enforce_auto_start: bool,
+ auto_connect_ai_tools: bool,
require_account_login: bool,
recording_allowed: bool,
sync_streams: NativeSyncStreams,
@@ -1006,7 +1007,11 @@ mod imp {
.extend(self.locked_settings.keys().cloned());
self.hidden_sections.sort();
self.hidden_sections.dedup();
+ let auto_connect_ai_tools = crate::enterprise_policy::auto_connect_ai_tools_value(
+ self.locked_settings.get("autoConnectAiTools"),
+ );
NativeEnterprisePolicy {
+ auto_connect_ai_tools,
hidden_sections: self.hidden_sections,
locked_settings: self.locked_settings,
enforce_auto_start,
@@ -1127,11 +1132,12 @@ mod imp {
}
}
- async fn fetch_native_policy(
+ async fn fetch_and_apply_native_policy(
http: &reqwest::Client,
policy_url: &str,
device_id: &str,
credential: &EnterprisePolicyCredential,
+ apply_ai_tool_policy: impl FnOnce(bool),
) -> Result<NativeEnterprisePolicy, NativePolicyFetchError> {
let request = http.get(policy_url).header("X-Device-Id", device_id);
let request = apply_enterprise_credential(request, credential);
@@ -1152,11 +1158,16 @@ mod imp {
"policy",
));
}
- response
+ let policy = response
.json::<NativePolicyResponse>()
.await
.map(NativePolicyResponse::into_native_policy)
- .map_err(|error| NativePolicyFetchError::Unavailable(error.to_string()))
+ .map_err(|error| NativePolicyFetchError::Unavailable(error.to_string()))?;
+ // GET authenticated this workspace's policy. Apply AI setup before
+ // recording-paused branches or fallible enrollment/settings work can
+ // discard it. This never grants recording or bypasses seat checks.
+ apply_ai_tool_policy(policy.auto_connect_ai_tools);
+ Ok(policy)
}
async fn send_enrollment_heartbeat(
@@ -1216,7 +1227,15 @@ mod imp {
let mut account_required = false;
for credential in credentials {
- match fetch_native_policy(http, policy_url, device_id, &credential).await {
+ match fetch_and_apply_native_policy(
+ http,
+ policy_url,
+ device_id,
+ &credential,
+ crate::enterprise_policy::begin_ai_tool_policy_refresh(),
+ )
+ .await
+ {
Ok(policy) if !policy.recording_allowed => {
return NativeAuthorizationResult::RecordingDisabled;
}
@@ -1418,7 +1437,15 @@ mod imp {
.map_err(|error| format!("enterprise policy client: {error}"))?;
let device_id = settings_device_id(app).unwrap_or_else(|| "unknown".to_string());
- match fetch_native_policy(&http, &policy_url, &device_id, &credential).await {
+ match fetch_and_apply_native_policy(
+ &http,
+ &policy_url,
+ &device_id,
+ &credential,
+ crate::enterprise_policy::begin_ai_tool_policy_refresh(),
+ )
+ .await
+ {
Ok(policy)
if credential_authorizes_policy(
credential.kind(),
@@ -1542,6 +1569,10 @@ mod imp {
let authorization =
resolve_native_authorization(&http, &policy_url, &heartbeat_url, &device_id)
.await;
+ // Also release the first-pass barrier after an offline/rejected
+ // response; an unknown policy keeps its documented default,
+ // while a cached disable remains disabled.
+ crate::enterprise_policy::finish_initial_ai_tool_policy_refresh();
let mut next_poll = native_policy_poll_interval(&authorization);
match authorization {
NativeAuthorizationResult::Authorized(policy) => {
@@ -2224,6 +2255,215 @@ mod imp {
assert_eq!(policy.sync_streams.frame_images_mode(), "all");
}
+ #[tokio::test]
+ async fn ai_tool_policy_applies_on_fetch_even_when_recording_is_paused() {
+ use wiremock::{
+ matchers::{header, method, path},
+ Mock, MockServer, ResponseTemplate,
+ };
+ let server = MockServer::start().await;
+ let http = reqwest::Client::new();
+ for (value, expected) in [
+ (serde_json::Value::Null, true),
+ (serde_json::json!(false), false),
+ (serde_json::json!("false"), false),
+ (serde_json::json!(true), true),
+ (serde_json::json!("true"), true),
+ (serde_json::json!("invalid"), false),
+ ] {
+ server.reset().await;
+ Mock::given(method("GET"))
+ .and(path("/policy"))
+ .and(header("X-Device-Id", "fixture-device"))
+ .and(header("X-License-Key", "fixture-key"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "hiddenSections": ["app_ui"],
+ "recordingAllowed": false,
+ "lockedSettings": {"autoConnectAiTools": value}
+ })))
+ .mount(&server)
+ .await;
+ let mut applied = None;
+ let policy = super::fetch_and_apply_native_policy(
+ &http,
+ &format!("{}/policy", server.uri()),
+ "fixture-device",
+ &super::EnterprisePolicyCredential::LicenseKey("fixture-key".into()),
+ |enabled| applied = Some(enabled),
+ )
+ .await
+ .unwrap();
+ assert_eq!(applied, Some(expected));
+ assert!(!policy.recording_allowed, "setup must not grant recording");
+ }
+ }
+
+ #[tokio::test]
+ async fn ai_tool_policy_late_response_cannot_reverse_newer_disable() {
+ use axum::{routing::get, Json, Router};
+ use std::sync::Arc;
+ let release_older = Arc::new(tokio::sync::Notify::new());
+ let wait_for_newer = release_older.clone();
+ let router = Router::new()
+ .route(
+ "/older",
+ get(move || async move {
+ wait_for_newer.notified().await;
+ Json(serde_json::json!({"lockedSettings":{"autoConnectAiTools":true}}))
+ }),
+ )
+ .route(
+ "/newer",
+ get(|| async {
+ Json(serde_json::json!({"lockedSettings":{"autoConnectAiTools":false}}))
+ }),
+ );
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move {
+ axum::Server::from_tcp(listener)
+ .unwrap()
+ .serve(router.into_make_service())
+ .await
+ .unwrap();
+ });
+ let http = reqwest::Client::new();
+ let policy = crate::enterprise_policy::AiToolPolicy::new(true, false);
+ let older = policy.begin_refresh();
+ let newer = policy.begin_refresh();
+ let credential = super::EnterprisePolicyCredential::LicenseKey("fixture-key".into());
+ let older_url = format!("{base}/older");
+ let newer_url = format!("{base}/newer");
+ let results = tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ tokio::join!(
+ super::fetch_and_apply_native_policy(
+ &http,
+ &older_url,
+ "fixture-device",
+ &credential,
+ |enabled| {
+ assert!(!policy.update(older, enabled));
+ }
+ ),
+ super::fetch_and_apply_native_policy(
+ &http,
+ &newer_url,
+ "fixture-device",
+ &credential,
+ |enabled| {
+ assert!(policy.update(newer, enabled));
+ release_older.notify_one();
+ }
+ ),
+ )
+ })
+ .await;
+ server.abort();
+ let (old_result, new_result) = results.unwrap();
+ assert!(old_result.is_ok());
+ assert!(new_result.is_ok());
+ assert!(!policy.snapshot().allowed);
+ }
+
+ #[tokio::test]
+ async fn ai_tool_policy_fetch_failures_preserve_last_decision() {
+ use wiremock::{matchers::path, Mock, MockServer, ResponseTemplate};
+ let server = MockServer::start().await;
+ let http = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_millis(100))
+ .build()
+ .unwrap();
+ for response in [
+ ResponseTemplate::new(401),
+ ResponseTemplate::new(403).set_body_json(serde_json::json!({
+ "code": RECORDING_DISABLED_BY_ADMIN_CODE,
+ })),
+ ResponseTemplate::new(500),
+ ResponseTemplate::new(200).set_body_string("{broken"),
+ ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({}))
+ .set_delay(std::time::Duration::from_secs(2)),
+ ] {
+ server.reset().await;
+ Mock::given(path("/policy"))
+ .respond_with(response)
+ .mount(&server)
+ .await;
+ let mut called = false;
+ let result = super::fetch_and_apply_native_policy(
+ &http,
+ &format!("{}/policy", server.uri()),
+ "fixture-device",
+ &super::EnterprisePolicyCredential::LicenseKey("fixture-key".into()),
+ |_| called = true,
+ )
+ .await;
+ assert!(result.is_err());
+ assert!(!called, "failed fetch must not overwrite a cached disable");
+ }
+ }
+
+ #[tokio::test]
+ async fn ai_tool_policy_stalled_response_body_preserves_last_decision() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}/policy", listener.local_addr().unwrap());
+ let (headers_sent, mut headers_received) = tokio::sync::oneshot::channel();
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut request = [0; 4096];
+ socket.read(&mut request).await.unwrap();
+ socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 1000\r\n\r\n{\"lockedSettings\":").await.unwrap();
+ headers_sent.send(()).unwrap();
+ std::future::pending::<()>().await;
+ });
+ let http = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_millis(500))
+ .build()
+ .unwrap();
+ let credential = super::EnterprisePolicyCredential::LicenseKey("fixture-key".into());
+ let mut called = false;
+ let result = tokio::time::timeout(
+ std::time::Duration::from_secs(5),
+ super::fetch_and_apply_native_policy(
+ &http,
+ &url,
+ "fixture-device",
+ &credential,
+ |_| called = true,
+ ),
+ )
+ .await;
+ server.abort();
+ let _ = server.await;
+ assert!(headers_received.try_recv().is_ok(), "must exercise a stalled body after headers");
+ assert!(matches!(
+ result.unwrap(),
+ Err(NativePolicyFetchError::Unavailable(_))
+ ));
+ assert!(!called, "headers alone must not apply a default policy");
+ }
+
+ #[test]
+ fn ai_tool_policy_defaults_on_even_with_hidden_ui() {
+ for (value, expected) in [
+ (serde_json::Value::Null, true),
+ (serde_json::json!(true), true),
+ (serde_json::json!("true"), true),
+ (serde_json::json!(false), false),
+ (serde_json::json!("false"), false),
+ ] {
+ let response: NativePolicyResponse = serde_json::from_value(serde_json::json!({
+ "hiddenSections": ["app_ui"],
+ "lockedSettings": {"autoConnectAiTools": value}
+ })).unwrap();
+ assert_eq!(response.into_native_policy().auto_connect_ai_tools, expected);
+ }
+ let response: NativePolicyResponse = serde_json::from_value(serde_json::json!({})).unwrap();
+ assert!(response.into_native_policy().auto_connect_ai_tools);
+ }
+
#[test]
fn recording_control_defaults_on_for_older_control_planes() {
let response: NativePolicyResponse = serde_json::from_value(serde_json::json!({
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 6d99c2ea2..689d2079a 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -1751,14 +1751,8 @@ async fn main() {
// setup is backgrounded and idempotent: it installs missing MCP +
// skill entries, refreshes stale screenpipe launchers, and leaves
// unrelated tool settings alone.
- if !app_ui_hidden {
- let local_api = recording::local_api_context_from_app(&app.handle());
- skills::connect_detected_ai_tools_in_background(
- app.handle().clone(),
- store.recording.api_auth,
- local_api.port,
- );
- }
+ let local_api_config = store.to_recording_config(data_dir.clone());
+ skills::connect_detected_ai_tools_in_background(&local_api_config);
// Enterprise hidden-UI deployments always run headless with the
// recorder only, regardless of user settings or onboarding state.
@@ -2033,12 +2027,11 @@ async fn main() {
};
server_runtime.block_on(async move {
- // Resolve + seed the shared api_auth_key cache before building
- // the config. `to_recording_config` is sync and reads the
- // cache; without this step the server would start with
- // `api_auth_key = None` on the app-auto-start path and every
- // request would 403. Mirrors the path in `spawn_screenpipe`.
- if store_clone.recording.api_auth {
+ // Use effective auth: LAN access requires a key even when
+ // the persisted auth toggle is off. Match `spawn_screenpipe`
+ // and seed the same key the background installer waits for.
+ let mut config = store_clone.to_recording_config(data_dir_clone.clone());
+ if config.api_auth {
let settings_key_opt = if store_clone.recording.api_key.is_empty() {
None
} else {
@@ -2050,11 +2043,13 @@ async fn main() {
)
.await
{
- Ok(key) => crate::store::seed_api_auth_key(key),
+ Ok(key) => {
+ crate::store::seed_api_auth_key(key.clone());
+ config.api_auth_key = Some(key);
+ },
Err(e) => tracing::error!("failed to resolve api auth key: {}", e),
}
}
- let config = store_clone.to_recording_config(data_dir_clone.clone());
// Check if server already running
let server_running = tokio::time::timeout(
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/skills.rs b/apps/screenpipe-app-tauri/src-tauri/src/skills.rs
index fb4559f5a..7eea8caaf 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/skills.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/skills.rs
@@ -153,7 +153,10 @@ fn background_bun_path() -> Option<PathBuf> {
crate::pi::find_bun_executable().map(PathBuf::from)
}
-async fn wait_for_background_api_key(api_auth_enabled: bool) -> Option<String> {
+async fn wait_for_background_api_key(
+ api_auth_enabled: bool,
+ resolved_api_key: impl Fn() -> Option<String>,
+) -> Option<String> {
if !api_auth_enabled {
return None;
}
@@ -165,7 +168,7 @@ async fn wait_for_background_api_key(api_auth_enabled: bool) -> Option<String> {
// clock deadline: slow keychain prompts or first-run database recovery must
// not permanently miss setup merely because onboarding completed meanwhile.
loop {
- if let Some(key) = crate::store::resolved_api_auth_key() {
+ if let Some(key) = resolved_api_key() {
return Some(key);
}
tokio::time::sleep(Duration::from_secs(1)).await;
@@ -175,11 +178,9 @@ async fn wait_for_background_api_key(api_auth_enabled: bool) -> Option<String> {
/// Repair detected AI tools at startup, then watch for later installs. Successful
/// targets are cached for this session; an explicit Settings disconnect still
/// wins. Filesystem work stays off the async/UI threads.
-pub fn connect_detected_ai_tools_in_background(
- _app: tauri::AppHandle,
- api_auth_enabled: bool,
- api_port: u16,
-) {
+pub fn connect_detected_ai_tools_in_background(config: &screenpipe_engine::RecordingConfig) {
+ let api_auth_enabled = config.api_auth;
+ let api_port = config.port;
let Some(home) = background_ai_tools_home() else {
info!("AI tool background setup skipped: no home directory");
return;
@@ -191,7 +192,8 @@ pub fn connect_detected_ai_tools_in_background(
// Grok Bot requires explicit credential access from Connections.
// Keep ordinary local MCP/skill configuration automatic.
tauri::async_runtime::spawn(async move {
- let api_key = wait_for_background_api_key(api_auth_enabled).await;
+ let api_key =
+ wait_for_background_api_key(api_auth_enabled, crate::store::resolved_api_auth_key).await;
connect_detected_ai_tools_in(
home,
bun_path,
@@ -199,6 +201,7 @@ pub fn connect_detected_ai_tools_in_background(
format!("http://localhost:{api_port}"),
ai_tool_auto_connect_opt_out_dir(),
AI_TOOL_CHECK_INTERVAL,
+ crate::enterprise_policy::ai_tool_setup_policy,
)
.await;
});
@@ -211,11 +214,26 @@ async fn connect_detected_ai_tools_in(
api_url: String,
opt_out_dir: PathBuf,
check_interval: Duration,
+ auto_connect_policy: impl Fn() -> crate::enterprise_policy::AiToolSetupPolicy + Send + 'static,
) {
let mut reconciler = screenpipe_engine::cli::agent::DesktopAgentReconciler::default();
let mut previous_report = None;
let mut attempt = 0;
+ let mut policy_revision = None;
loop {
+ let policy = auto_connect_policy();
+ if policy_revision != Some(policy.revision) {
+ reconciler = Default::default();
+ previous_report = None;
+ attempt = 0;
+ policy_revision = Some(policy.revision);
+ }
+ // Keep the watcher alive while disabled so the next policy refresh can
+ // enable setup, including on deployments with no webview.
+ if !policy.allowed {
+ tokio::time::sleep(check_interval).await;
+ continue;
+ }
attempt = (attempt + 1).min(3);
let home = home.clone();
let bun_path = bun_path.clone();
@@ -228,6 +246,11 @@ async fn connect_detected_ai_tools_in(
// returns, no older launch repair can still reconnect that target.
let result = {
let _guard = AI_TOOL_AUTO_CONNECT_LOCK.lock().await;
+ let latest_policy = auto_connect_policy();
+ if !latest_policy.allowed || latest_policy.revision != policy.revision {
+ // Retry with a coherent policy/cache after any lock-wait change.
+ continue;
+ }
tokio::task::spawn_blocking(move || {
let opted_out = ai_tool_auto_connect_opt_outs_in(&opt_out_dir);
let report =
@@ -1746,6 +1769,7 @@ mod tests {
"http://localhost:3137".into(),
opt_out_dir.clone(),
Duration::from_millis(20),
+ || crate::enterprise_policy::AiToolSetupPolicy { allowed: true, revision: 0 },
));
let outcome = tokio::time::timeout(Duration::from_secs(5), async {
tokio::time::sleep(Duration::from_millis(100)).await;
@@ -1790,6 +1814,102 @@ mod tests {
outcome.expect("background poll did not connect later installs");
}
+ #[tokio::test]
+ async fn ai_tool_setup_waits_for_effective_lan_auth_key() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ let settings = screenpipe_config::RecordingSettings {
+ api_auth: false,
+ listen_on_lan: true,
+ ..Default::default()
+ };
+ let config = screenpipe_engine::RecordingConfig::from_settings(
+ &settings,
+ PathBuf::from("unused-fixture-path"),
+ None,
+ );
+ let attempts = AtomicUsize::new(0);
+ let key = tokio::time::timeout(
+ Duration::from_secs(3),
+ wait_for_background_api_key(config.api_auth, || {
+ (attempts.fetch_add(1, Ordering::SeqCst) > 0).then(|| "sp-fixture".to_string())
+ }),
+ )
+ .await
+ .expect("installer must resume after the server resolves its key");
+ assert_eq!(key.as_deref(), Some("sp-fixture"));
+ assert_eq!(attempts.load(Ordering::SeqCst), 2);
+ assert_eq!(
+ wait_for_background_api_key(false, || panic!("unauthenticated local API needs no key")).await,
+ None
+ );
+ }
+
+ #[tokio::test]
+ async fn ai_tool_policy_pauses_and_resumes_background_setup() {
+ use std::sync::Arc;
+ let fixture = tempfile::tempdir().unwrap();
+ let home = fixture.path().join("home");
+ std::fs::create_dir_all(home.join(".cursor")).unwrap();
+ let enabled = Arc::new(crate::enterprise_policy::AiToolPolicy::new(false, true));
+ let policy = enabled.clone();
+ let task = tokio::spawn(connect_detected_ai_tools_in(
+ home.clone(),
+ home.join("bun"),
+ Some("sp-fixture".into()),
+ "http://localhost:3137".into(),
+ fixture.path().join("opt-outs"),
+ Duration::from_millis(20),
+ move || policy.snapshot(),
+ ));
+ let outcome = tokio::time::timeout(Duration::from_secs(5), async {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ if home.join(".cursor/mcp.json").exists() || home.join(".cursor/skills").exists() {
+ return Err("disabled policy wrote a configuration".to_string());
+ }
+ enabled.update(enabled.begin_refresh(), true);
+ while !home.join(".cursor/skills/screenpipe-api/SKILL.md").is_file()
+ || !home.join(".cursor/mcp.json").is_file()
+ {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ {
+ let _guard = AI_TOOL_AUTO_CONNECT_LOCK.lock().await;
+ enabled.update(enabled.begin_refresh(), false);
+ std::fs::remove_file(home.join(".cursor/mcp.json")).map_err(|e| e.to_string())?;
+ enabled.update(enabled.begin_refresh(), true);
+ }
+ while !home.join(".cursor/mcp.json").is_file() {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ enabled.update(enabled.begin_refresh(), false);
+ // Drain an in-flight pass before introducing the next tool.
+ {
+ let _guard = AI_TOOL_AUTO_CONNECT_LOCK.lock().await;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ std::fs::create_dir_all(home.join(".runner")).map_err(|e| e.to_string())?;
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ if home.join(".runner/mcp.json").exists() || !home.join(".cursor/mcp.json").is_file() {
+ return Err("disabled policy must preserve existing connections without adding new ones".to_string());
+ }
+ // A successful target may be changed while the org disables setup.
+ // Re-enabling must reconcile it again, not retain a stale success.
+ std::fs::remove_file(home.join(".cursor/mcp.json")).map_err(|e| e.to_string())?;
+ enabled.update(enabled.begin_refresh(), true);
+ while !home.join(".runner/mcp.json").is_file()
+ || !home.join(".cursor/mcp.json").is_file()
+ {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ Ok::<(), String>(())
+ })
+ .await;
+ let _guard = AI_TOOL_AUTO_CONNECT_LOCK.lock().await;
+ task.abort();
+ let _ = task.await;
+ outcome.expect("AI-tool policy did not resume setup").unwrap();
+ }
+
#[tokio::test]
async fn grokbot_network_work_does_not_block_other_ai_tool_choices() {
let root = tempfile::tempdir().unwrap();
diff --git a/docs/enterprise-ai-tool-policy.md b/docs/enterprise-ai-tool-policy.md
new file mode 100644
index 000000000..a8ef9b91b
--- /dev/null
+++ b/docs/enterprise-ai-tool-policy.md
@@ -0,0 +1,55 @@
+# Enterprise AI-tool setup policy
+
+<!-- doc-covers: none -->
+
+`lockedSettings.autoConnectAiTools` controls automatic local Screenpipe MCP and
+skill setup for supported, detected AI tools. It defaults to enabled when absent.
+Both JSON booleans and the control plane's `"true"` / `"false"` strings are accepted.
+Malformed values defer automatic setup; missing/null values use the enabled default.
+The control plane preserves malformed values as an explicit disable instead of
+dropping the key. Clearing the policy in the editor restores the enabled default.
+
+```json
+{
+ "hiddenSections": ["app_ui"],
+ "lockedSettings": { "autoConnectAiTools": "true" }
+}
+```
+
+The native policy fetch owns this setting, independently of app visibility and
+recording authorization. A workspace pause or failed enrollment does not discard
+an authenticated AI-tool policy. The background installer checks it before each
+scan and after acquiring the setup lock. Re-enabling starts a fresh reconciliation
+so changes made while setup was disabled are discovered. A revision counter
+preserves even disable/re-enable transitions between scans. Request ordering
+prevents a delayed older response from overriding a newer successful decision.
+
+Enterprise startup waits for the first native policy attempt before automatic
+setup, preventing an initial enabled default from racing a server-side disable.
+A failed attempt releases that barrier using the last cached decision, or the
+enabled default when no cache exists. The native watcher continues retrying.
+The most recent authenticated decision is cached as `auto_connect_ai_tools` in
+the user's `enterprise.json`. Unreadable or malformed caches defer setup until a
+valid server policy arrives; existing configuration is never overwritten to
+repair a malformed cache. Removing the server setting restores the enabled
+default on refresh. Authentication recovery preserves the last decision.
+
+A cache-write failure is logged and the current process still applies the server
+policy. After restart, the last successfully persisted decision is used until a
+fresh policy arrives. An older cached enabled value can therefore remain active
+offline if persisting a later disable failed.
+
+Setting it to `false` stops future automatic setup passes. A pass already running
+may finish; existing MCP configurations and skills remain installed. This is not
+an access-revocation policy. Explicit per-tool disconnects remain respected when
+the organization enables automatic setup.
+
+Only detected clients supported by Screenpipe are configured. MCP-only clients
+receive MCP configuration; supported skill clients also receive the bundled
+Screenpipe skills. Screenpipe does not install the AI applications themselves.
+The policy requires a desktop version that implements it; older versions retain
+their existing behavior.
+
+Automatic setup uses the effective local API authentication setting, including
+authentication forced by LAN access. It waits for the server to resolve the
+shared key before writing authenticated MCP configuration.