#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Add managed desktop sign-in and document privacy policies (#8392)
ConnorYoh4b718105e932
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex f6ce57f5c9..ef55dc295c 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -4355,6 +4355,10 @@ title = "Updated from disk"body = "\"{{name}}\" changed on disk. It is large enough that reloading it will take a while, so the version here has been left alone."title = "File changed on disk"+[desktopPrivacy]+blocked = "Your administrator requires documents to stay on this device. This feature is unavailable."+localFiles = "Local files"+[desktopUpdate]downloading = "Downloading update..."installing = "Installing update..."@@ -12044,6 +12048,7 @@ title = "Workspace"loginIncomplete = "Failed to complete login"noSaasServer = "No SaaS server configured"noServer = "No server configured"+policyUnavailable = "Unable to load your organisation's sign-in settings."saasLoginFailed = "SaaS login failed"saasLoginIncomplete = "Failed to complete SaaS login"selfHostedLoginFailed = "Self-hosted login failed"diff --git a/frontend/editor/src-tauri/provisioner/src/main.rs b/frontend/editor/src-tauri/provisioner/src/main.rsindex b946c31289..9f85551677 100644--- a/frontend/editor/src-tauri/provisioner/src/main.rs+++ b/frontend/editor/src-tauri/provisioner/src/main.rs@@ -11,6 +11,12 @@ struct ProvisioningConfig<'a> {#[serde(skip_serializing_if = "Option::is_none")]lock_connection_mode: Option<bool>,#[serde(skip_serializing_if = "Option::is_none")]+ require_sign_in: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ cloud_only: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ local_processing_only: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]login_agreement_enabled: Option<bool>,/// Optional headless-install update policy./// One of `"prompt"` (default), `"auto"`, or `"disabled"`.@@ -25,6 +31,18 @@ fn parse_bool(value: &str) -> bool {)}+fn parse_policy_bool(value: Option<&str>) -> Result<Option<bool>, String> {+ match value.unwrap_or("").trim().to_lowercase().as_str() {+ "" => Ok(None),+ "1" | "true" | "yes" | "y" => Ok(Some(true)),+ "0" | "false" | "no" | "n" => Ok(Some(false)),+ other => Err(format!(+ "Invalid policy boolean '{}': expected true or false",+ other+ )),+ }+}+/// Normalise the `--update-mode` argument into the lowercase tokens the app/// understands. Empty / whitespace values are treated as "not supplied" so/// MSI installs that don't pass STIRLING_UPDATE_MODE behave identically to@@ -46,6 +64,9 @@ fn main() -> Result<(), String> {let mut output: Option<PathBuf> = None;let mut url: Option<String> = None;let mut lock_value: Option<String> = None;+ let mut require_sign_in_arg: Option<String> = None;+ let mut cloud_only_arg: Option<String> = None;+ let mut local_processing_only_arg: Option<String> = None;let mut login_agreement_value: Option<String> = None;let mut update_mode_arg: Option<String> = None;@@ -70,6 +91,19 @@ fn main() -> Result<(), String> {.ok_or_else(|| "--lock requires a value".to_string())?;lock_value = Some(value);}+ "--require-sign-in" => {+ require_sign_in_arg =+ Some(args.next().ok_or("--require-sign-in requires a value")?);+ }+ "--cloud-only" | "--saas-only" => {+ cloud_only_arg = Some(args.next().ok_or("--cloud-only requires a value")?);+ }+ "--local-processing-only" => {+ local_processing_only_arg = Some(+ args.next()+ .ok_or("--local-processing-only requires a value")?,+ );+ }"--login-agreement" => {let value = args.next()@@ -109,10 +143,20 @@ fn main() -> Result<(), String> {.transpose()?.flatten();+ let require_sign_in = parse_policy_bool(require_sign_in_arg.as_deref())?;+ let cloud_only = parse_policy_bool(cloud_only_arg.as_deref())?;+ let local_processing_only = parse_policy_bool(local_processing_only_arg.as_deref())?;+// Nothing to write — avoid clobbering an existing provisioning file when the// MSI is invoked without any provisioning directives// (STIRLING_SERVER_URL / STIRLING_LOGIN_AGREEMENT / STIRLING_UPDATE_MODE).- if url.is_none() && login_agreement.is_none() && update_mode.is_none() {+ if url.is_none()+ && login_agreement.is_none()+ && update_mode.is_none()+ && require_sign_in.is_none()+ && cloud_only.is_none()+ && local_processing_only.is_none()+ {return Ok(());}@@ -130,15 +174,89 @@ fn main() -> Result<(), String> {let config = ProvisioningConfig {server_url: url.as_deref(),lock_connection_mode: lock,+ require_sign_in,+ cloud_only,+ local_processing_only,login_agreement_enabled: login_agreement,update_mode,};- let json = serde_json::to_string_pretty(&config)+ let mut merged = if output.exists() {+ let raw = fs::read_to_string(&output).map_err(|e| e.to_string())?;+ serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&raw)+ .map_err(|e| {+ format!(+ "Cannot merge existing provisioning file {}: {e}. Back up this file and replace it with the complete intended policy, then retry the installation. Existing policy data has not been changed.",+ output.display()+ )+ })?+ } else {+ serde_json::Map::new()+ };+ if let Some(legacy) = merged.remove("saasOnly") {+ if merged.contains_key("cloudOnly") {+ return Err(+ "Use only cloudOnly in provisioning data, not both policy names".to_string(),+ );+ }+ merged.insert("cloudOnly".to_string(), legacy);+ }+ let serde_json::Value::Object(updates) =+ serde_json::to_value(&config).map_err(|e| e.to_string())?+ else {+ return Err("Provisioning data must be an object".to_string());+ };+ merged.extend(updates);+ if merged.get("cloudOnly").and_then(|v| v.as_bool()) == Some(true) {+ if url.is_some() {+ return Err("cloudOnly cannot be combined with a self-hosted serverUrl".to_string());+ }+ merged.remove("serverUrl");+ merged.remove("lockConnectionMode");+ }+ let json = serde_json::to_string_pretty(&merged).map_err(|e| format!("Failed to serialize provisioning data: {}", e))?;- fs::write(&output, json)- .map_err(|e| format!("Failed to write provisioning file {}: {}", output.display(), e))?;+ fs::write(&output, json).map_err(|e| {+ format!(+ "Failed to write provisioning file {}: {}",+ output.display(),+ e+ )+ })?;Ok(())}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn policy_booleans_distinguish_omission_from_disabling() {+ assert_eq!(parse_policy_bool(None).unwrap(), None);+ assert_eq!(parse_policy_bool(Some(" ")).unwrap(), None);+ assert_eq!(parse_policy_bool(Some("1")).unwrap(), Some(true));+ assert_eq!(parse_policy_bool(Some("TRUE")).unwrap(), Some(true));+ assert_eq!(parse_policy_bool(Some("false")).unwrap(), Some(false));+ assert_eq!(parse_policy_bool(Some("0")).unwrap(), Some(false));+ assert!(parse_policy_bool(Some("treu")).is_err());+ }++ #[test]+ fn policy_only_config_needs_no_server_url() {+ let config = ProvisioningConfig {+ server_url: None,+ lock_connection_mode: None,+ require_sign_in: Some(true),+ cloud_only: Some(true),+ local_processing_only: Some(true),+ login_agreement_enabled: None,+ update_mode: None,+ };+ assert_eq!(+ serde_json::to_value(config).unwrap(),+ serde_json::json!({"requireSignIn": true, "cloudOnly": true, "localProcessingOnly": true})+ );+ }+}diff --git a/frontend/editor/src-tauri/provisioner/tests/provisioning.rs b/frontend/editor/src-tauri/provisioner/tests/provisioning.rsnew file mode 100644index 0000000000..413f8e8651--- /dev/null+++ b/frontend/editor/src-tauri/provisioner/tests/provisioning.rs@@ -0,0 +1,205 @@+use std::fs;+use std::path::PathBuf;+use std::process::{Command, Output};+use std::time::{SystemTime, UNIX_EPOCH};++struct ProvisioningFile(PathBuf);++impl ProvisioningFile {+ fn new() -> Self {+ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ Self(std::env::temp_dir().join(format!(+ "stirling-provision-{}-{}.json",+ std::process::id(),+ nonce+ )))+ }++ fn run(&self, args: &[&str]) -> Output {+ Command::new(env!("CARGO_BIN_EXE_stirling-provisioner"))+ .arg("--output")+ .arg(&self.0)+ .args(args)+ .output()+ .unwrap()+ }++ fn read(&self) -> serde_json::Value {+ serde_json::from_str(&fs::read_to_string(&self.0).unwrap()).unwrap()+ }+}++impl Drop for ProvisioningFile {+ fn drop(&mut self) {+ let _ = fs::remove_file(&self.0);+ }+}++#[test]+fn corrupt_existing_policy_is_preserved_with_repair_instructions() {+ let file = ProvisioningFile::new();+ let original = "{broken";+ fs::write(&file.0, original).unwrap();+ let result = file.run(&["--require-sign-in", "1"]);+ assert!(!result.status.success());+ assert_eq!(fs::read_to_string(&file.0).unwrap(), original);+ let message = String::from_utf8_lossy(&result.stderr);+ assert!(message.contains("complete intended policy"));+ assert!(message.contains(file.0.file_name().unwrap().to_str().unwrap()));+}++#[test]+fn sign_in_only_reinstall_preserves_the_managed_server() {+ let file = ProvisioningFile::new();+ assert!(file+ .run(&["--url", "https://pdf.example.org", "--lock", "1"])+ .status+ .success());+ assert!(file.run(&["--require-sign-in", "1"]).status.success());+ assert_eq!(+ file.read(),+ serde_json::json!({"serverUrl":"https://pdf.example.org","lockConnectionMode":true,"requireSignIn":true})+ );+}++#[test]+fn switching_to_self_hosted_explicitly_clears_cloud_restriction() {+ let file = ProvisioningFile::new();+ assert!(file+ .run(&[+ "--cloud-only",+ "1",+ "--require-sign-in",+ "1",+ "--local-processing-only",+ "1"+ ])+ .status+ .success());+ assert!(file+ .run(&["--url", "https://pdf.example.org", "--cloud-only", "0"])+ .status+ .success());+ assert_eq!(+ file.read(),+ serde_json::json!({"serverUrl":"https://pdf.example.org","lockConnectionMode":false,"cloudOnly":false,"requireSignIn":true,"localProcessingOnly":true})+ );+}++#[test]+fn updating_legacy_policy_preserves_then_explicitly_clears_it() {+ let file = ProvisioningFile::new();+ fs::write(&file.0, r#"{"saasOnly":true,"requireSignIn":true}"#).unwrap();+ assert!(file.run(&["--update-mode", "disabled"]).status.success());+ assert_eq!(+ file.read(),+ serde_json::json!({"cloudOnly":true,"requireSignIn":true,"updateMode":"disabled"})+ );+ fs::write(&file.0, r#"{"saasOnly":true,"requireSignIn":true}"#).unwrap();+ assert!(file.run(&["--cloud-only", "0"]).status.success());+ assert_eq!(+ file.read(),+ serde_json::json!({"cloudOnly":false,"requireSignIn":true})+ );+}++#[test]+fn legacy_cli_argument_writes_the_canonical_policy_name() {+ let file = ProvisioningFile::new();+ assert!(file.run(&["--saas-only", "1"]).status.success());+ assert_eq!(file.read(), serde_json::json!({"cloudOnly":true}));+}++#[test]+fn ambiguous_policy_names_do_not_overwrite_the_file() {+ let file = ProvisioningFile::new();+ let original = r#"{"cloudOnly":false,"saasOnly":true}"#;+ fs::write(&file.0, original).unwrap();+ assert!(!file.run(&["--update-mode", "disabled"]).status.success());+ assert_eq!(fs::read_to_string(&file.0).unwrap(), original);+}++#[test]+fn update_only_install_preserves_sign_in_requirements() {+ let file = ProvisioningFile::new();+ assert!(file+ .run(&["--require-sign-in", "1", "--cloud-only", "1"])+ .status+ .success());+ assert!(file+ .run(&[+ "--update-mode",+ "disabled",+ "--require-sign-in",+ "",+ "--cloud-only",+ ""+ ])+ .status+ .success());+ assert_eq!(+ file.read(),+ serde_json::json!({"requireSignIn":true,"cloudOnly":true,"updateMode":"disabled"})+ );+ assert!(file+ .run(&["--require-sign-in", "0", "--cloud-only", "0"])+ .status+ .success());+ assert_eq!(file.read()["requireSignIn"], false);+ assert_eq!(file.read()["cloudOnly"], false);+}++#[test]+fn switching_to_cloud_removes_the_old_self_hosted_target() {+ let file = ProvisioningFile::new();+ assert!(file+ .run(&["--url", "https://pdf.example.org", "--lock", "1"])+ .status+ .success());+ assert!(file+ .run(&["--require-sign-in", "1", "--cloud-only", "true"])+ .status+ .success());+ assert_eq!(+ file.read(),+ serde_json::json!({"requireSignIn":true,"cloudOnly":true})+ );+}++#[test]+fn conflicting_or_invalid_policies_do_not_overwrite_the_file() {+ let file = ProvisioningFile::new();+ assert!(file.run(&["--cloud-only", "1"]).status.success());+ assert!(!file+ .run(&["--url", "https://pdf.example.org"])+ .status+ .success());+ assert!(!file.run(&["--require-sign-in", "invalid"]).status.success());+ assert_eq!(file.read(), serde_json::json!({"cloudOnly":true}));+}++#[test]+fn privacy_policy_is_independent_preserved_and_explicitly_removable() {+ let file = ProvisioningFile::new();+ assert!(file.run(&["--local-processing-only", "1"]).status.success());+ assert_eq!(file.read(), serde_json::json!({"localProcessingOnly":true}));+ assert!(file+ .run(&["--cloud-only", "1", "--local-processing-only", ""])+ .status+ .success());+ assert_eq!(+ file.read(),+ serde_json::json!({"localProcessingOnly":true,"cloudOnly":true})+ );+ assert!(!file+ .run(&["--local-processing-only", "invalid"])+ .status+ .success());+ assert_eq!(file.read()["localProcessingOnly"], true);+ assert!(file.run(&["--local-processing-only", "0"]).status.success());+ assert_eq!(file.read()["localProcessingOnly"], false);+ assert_eq!(file.read()["cloudOnly"], true);+}diff --git a/frontend/editor/src-tauri/src/commands/connection.rs b/frontend/editor/src-tauri/src/commands/connection.rsindex a12040fb55..fd85ed6506 100644--- a/frontend/editor/src-tauri/src/commands/connection.rs+++ b/frontend/editor/src-tauri/src/commands/connection.rs@@ -1,13 +1,10 @@-use crate::state::connection_state::{- AppConnectionState,- ConnectionMode,- ServerConfig,-};+use crate::state::connection_state::{AppConnectionState, ConnectionMode, ServerConfig};use crate::utils::{add_log, app_data_dir, system_provisioning_dir};use serde::{Deserialize, Serialize};use std::fs;use std::path::PathBuf;use tauri::{AppHandle, Manager, State};+use tauri_plugin_dialog::{DialogExt, MessageDialogKind};use tauri_plugin_store::StoreExt;const STORE_FILE: &str = "connection.json";@@ -15,6 +12,9 @@ const FIRST_LAUNCH_KEY: &str = "setup_completed";const CONNECTION_MODE_KEY: &str = "connection_mode";const SERVER_CONFIG_KEY: &str = "server_config";const LOCK_CONNECTION_KEY: &str = "lock_connection_mode";+const REQUIRE_SIGN_IN_KEY: &str = "require_sign_in";+const CLOUD_ONLY_KEY: &str = "cloud_only";+const LOCAL_PROCESSING_ONLY_KEY: &str = "local_processing_only";const LOGIN_AGREEMENT_KEY: &str = "login_agreement_enabled";pub(crate) const UPDATE_MODE_KEY: &str = "update_mode";/// When `true` the update mode was written by a provisioning file and cannot@@ -63,6 +63,9 @@ pub struct ConnectionConfig {pub mode: ConnectionMode,pub server_config: Option<ServerConfig>,pub lock_connection_mode: bool,+ pub require_sign_in: bool,+ pub cloud_only: bool,+ pub local_processing_only: bool,}#[tauri::command]@@ -100,6 +103,19 @@ pub async fn get_connection_config(mode,server_config,lock_connection_mode,+ require_sign_in: store+ .get(REQUIRE_SIGN_IN_KEY)+ .and_then(|v| v.as_bool())+ .unwrap_or(false),+ cloud_only: store+ .get(CLOUD_ONLY_KEY)+ .or_else(|| store.get("saas_only"))+ .and_then(|v| v.as_bool())+ .unwrap_or(false),+ local_processing_only: store+ .get(LOCAL_PROCESSING_ONLY_KEY)+ .and_then(|v| v.as_bool())+ .unwrap_or(false),})}@@ -117,6 +133,20 @@ pub async fn set_connection_mode(.store(STORE_FILE).map_err(|e| format!("Failed to access store: {}", e))?;+ validate_managed_connection(+ store+ .get(REQUIRE_SIGN_IN_KEY)+ .and_then(|v| v.as_bool())+ .unwrap_or(false),+ store+ .get(CLOUD_ONLY_KEY)+ .or_else(|| store.get("saas_only"))+ .and_then(|v| v.as_bool())+ .unwrap_or(false),+ &mode,+ server_config.as_ref(),+ )?;+// If the store is already locked, protect connection_mode, server_config, and the lock// flag from being overwritten by any JS-side call.// Only allow marking setup_completed and updating auth-related fields.@@ -183,6 +213,10 @@ pub async fn set_connection_mode(struct ProvisioningConfig {server_url: Option<String>,lock_connection_mode: Option<bool>,+ require_sign_in: Option<bool>,+ #[serde(alias = "saasOnly")]+ cloud_only: Option<bool>,+ local_processing_only: Option<bool>,login_agreement_enabled: Option<bool>,/// Optional headless-install update policy (`"prompt"`, `"auto"`, `"disabled"`)./// When omitted the existing stored mode is left unchanged.@@ -191,11 +225,12 @@ struct ProvisioningConfig {fn provisioning_file_paths() -> Vec<PathBuf> {let mut paths = Vec::new();- paths.push(app_data_dir().join(PROVISIONING_FILE_NAME));+ // Machine policy must take precedence over user-writable provisioning.if let Some(system_dir) = system_provisioning_dir() {paths.push(system_dir.join(PROVISIONING_FILE_NAME));}+ paths.push(app_data_dir().join(PROVISIONING_FILE_NAME));paths}@@ -217,11 +252,65 @@ pub(crate) fn provisioning_path_is_admin_owned(}}+enum ProvisioningLoad {+ Ready(ProvisioningConfig),+ Quarantined { backup: PathBuf, reason: String },+}++fn load_provisioning(+ path: &std::path::Path,+ system_dir: Option<&std::path::Path>,+ stored_cloud_only: bool,+) -> Result<ProvisioningLoad, String> {+ let parsed = fs::read_to_string(path)+ .map_err(|err| format!("Failed to read provisioning file: {err}"))+ .and_then(|raw| {+ serde_json::from_str::<ProvisioningConfig>(&raw)+ .map_err(|err| format!("Failed to parse provisioning file: {err}"))+ })+ .and_then(|config| {+ if config.cloud_only.unwrap_or(stored_cloud_only)+ && config+ .server_url+ .as_ref()+ .is_some_and(|url| !url.trim().is_empty())+ {+ Err("cloudOnly cannot be combined with a self-hosted serverUrl".to_string())+ } else {+ Ok(config)+ }+ });++ match parsed {+ Ok(config) => Ok(ProvisioningLoad::Ready(config)),+ Err(reason) if provisioning_path_is_admin_owned(path, system_dir) => {+ Err(format!("{}: {reason}", path.display()))+ }+ Err(reason) => {+ let parent = path+ .parent()+ .ok_or("Provisioning file has no parent directory")?;+ let backup = tempfile::Builder::new()+ .prefix("stirling-provisioning.invalid-")+ .suffix(".json")+ .tempfile_in(parent)+ .map_err(|err| format!("{reason}; failed to create recovery copy: {err}"))?;+ fs::copy(path, backup.path())+ .map_err(|err| format!("{reason}; failed to back up provisioning: {err}"))?;+ let (_, backup) = backup+ .keep()+ .map_err(|err| format!("{reason}; failed to retain recovery copy: {err}"))?;+ fs::remove_file(path)+ .map_err(|err| format!("{reason}; failed to quarantine provisioning: {err}"))?;+ Ok(ProvisioningLoad::Quarantined { backup, reason })+ }+ }+}++/// Reapplies machine policy before startup. Invalid per-user input is backed up before any settings change; machine or persistence errors abort startup.pub fn apply_provisioning_if_present(app_handle: &AppHandle) -> Result<(), String> {let provisioning_paths = provisioning_file_paths();- let provisioning_path = provisioning_paths- .into_iter()- .find(|path| path.exists());+ let provisioning_path = provisioning_paths.into_iter().find(|path| path.exists());let provisioning_path = match provisioning_path {Some(path) => path,@@ -233,17 +322,49 @@ pub fn apply_provisioning_if_present(app_handle: &AppHandle) -> Result<(), Strinprovisioning_path.display()));- let raw = fs::read_to_string(&provisioning_path)- .map_err(|e| format!("Failed to read provisioning file: {}", e))?;- let parsed: ProvisioningConfig = serde_json::from_str(&raw)- .map_err(|e| format!("Failed to parse provisioning file: {}", e))?;+ let store = app_handle.store(STORE_FILE).map_err(|e| {+ format!(+ "Failed to access {STORE_FILE} while applying {}: {e}",+ provisioning_path.display()+ )+ })?;+ let stored_cloud_only = store+ .get(CLOUD_ONLY_KEY)+ .or_else(|| store.get("saas_only"))+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ let parsed = match load_provisioning(+ &provisioning_path,+ system_provisioning_dir().as_deref(),+ stored_cloud_only,+ )? {+ ProvisioningLoad::Ready(config) => config,+ ProvisioningLoad::Quarantined { backup, reason } => {+ let message = format!(+ "Your per-user provisioning file could not be applied. Existing settings have been kept.\n\n{reason}\n\nA recovery copy is saved at:\n{}\n\nCorrect that copy and save it as:\n{}\nThen restart Stirling PDF to apply it.",+ backup.display(), provisioning_path.display()+ );+ add_log(message.clone());+ app_handle+ .dialog()+ .message(message)+ .title("Stirling PDF provisioning")+ .kind(MessageDialogKind::Warning)+ .show(|_| {});+ return Ok(());+ }+ };+ let cloud_only = parsed.cloud_only.unwrap_or(stored_cloud_only);// Login agreement can be provisioned independently of a server URL so it also applies to// local, no-login desktop installs. Persist it before the server-URL handling below, which// may early-return when no URL is present.if let Some(login_agreement_enabled) = parsed.login_agreement_enabled {if let Ok(store) = app_handle.store(STORE_FILE) {- store.set(LOGIN_AGREEMENT_KEY, serde_json::json!(login_agreement_enabled));+ store.set(+ LOGIN_AGREEMENT_KEY,+ serde_json::json!(login_agreement_enabled),+ );let _ = store.save();}add_log(format!(@@ -263,6 +384,9 @@ pub fn apply_provisioning_if_present(app_handle: &AppHandle) -> Result<(), Strinif server_url.is_none()&& parsed.update_mode.is_none()&& parsed.login_agreement_enabled.is_none()+ && parsed.require_sign_in.is_none()+ && parsed.cloud_only.is_none()+ && parsed.local_processing_only.is_none(){add_log("⚠️ Provisioning file has no actionable fields (serverUrl/updateMode/loginAgreement); skipping apply"@@ -273,9 +397,26 @@ pub fn apply_provisioning_if_present(app_handle: &AppHandle) -> Result<(), Strinlet lock_flag = parsed.lock_connection_mode.unwrap_or(false);- let store = app_handle- .store(STORE_FILE)- .map_err(|e| format!("Failed to access store: {}", e))?;+ if let Some(required) = parsed.require_sign_in {+ store.set(REQUIRE_SIGN_IN_KEY, serde_json::json!(required));+ }+ if let Some(only) = parsed.cloud_only {+ store.set(CLOUD_ONLY_KEY, serde_json::json!(only));+ store.delete("saas_only");+ }+ if let Some(only) = parsed.local_processing_only {+ store.set(LOCAL_PROCESSING_ONLY_KEY, serde_json::json!(only));+ }+ if cloud_only {+ let previous_mode = store+ .get(CONNECTION_MODE_KEY)+ .and_then(|value| serde_json::from_value::<ConnectionMode>(value).ok());+ if previous_mode != Some(ConnectionMode::SaaS) {+ store.delete(SERVER_CONFIG_KEY);+ }+ store.set(CONNECTION_MODE_KEY, serde_json::json!(ConnectionMode::SaaS));+ store.set(LOCK_CONNECTION_KEY, serde_json::json!(false));+ }// Apply server URL / connection settings only when a URL was supplied — a// provisioning file containing just `updateMode` should be allowed to configure@@ -290,8 +431,7 @@ pub fn apply_provisioning_if_present(app_handle: &AppHandle) -> Result<(), Strinlet cfg = ServerConfig { url };store.set(SERVER_CONFIG_KEY,- serde_json::to_value(&cfg)- .map_err(|e| format!("Failed to serialize config: {}", e))?,+ serde_json::to_value(&cfg).map_err(|e| format!("Failed to serialize config: {}", e))?,);store.set(@@ -319,10 +459,7 @@ pub fn apply_provisioning_if_present(app_handle: &AppHandle) -> Result<(), Strin// selector permanently (the file is deleted after apply, but the// lock flag persists in the store).let system_dir = system_provisioning_dir();- let locked = provisioning_path_is_admin_owned(- &provisioning_path,- system_dir.as_deref(),- );+ let locked = provisioning_path_is_admin_owned(&provisioning_path, system_dir.as_deref());store.set(UPDATE_MODE_LOCKED_KEY, serde_json::json!(locked));add_log(format!("🧩 Provisioning set update mode to {:?} (locked={})",@@ -330,16 +467,25 @@ pub fn apply_provisioning_if_present(app_handle: &AppHandle) -> Result<(), Strin));}- store- .save()- .map_err(|e| format!("Failed to save store: {}", e))?;-- if let (Some(cfg), Ok(mut conn_state)) =- (server_config.as_ref(), app_handle.state::<AppConnectionState>().0.lock())- {- conn_state.mode = ConnectionMode::SelfHosted;- conn_state.server_config = Some(cfg.clone());- conn_state.lock_connection_mode = lock_flag;+ store.save().map_err(|e| {+ format!(+ "Failed to save {STORE_FILE} while applying {}: {e}",+ provisioning_path.display()+ )+ })?;++ if let Ok(mut conn_state) = app_handle.state::<AppConnectionState>().0.lock() {+ if cloud_only {+ conn_state.mode = ConnectionMode::SaaS;+ conn_state.server_config = store+ .get(SERVER_CONFIG_KEY)+ .and_then(|value| serde_json::from_value(value).ok());+ conn_state.lock_connection_mode = false;+ } else if let Some(cfg) = server_config {+ conn_state.mode = ConnectionMode::SelfHosted;+ conn_state.server_config = Some(cfg);+ conn_state.lock_connection_mode = lock_flag;+ }}let user_app_data = app_data_dir();@@ -358,6 +504,25 @@ pub fn apply_provisioning_if_present(app_handle: &AppHandle) -> Result<(), StrinOk(())}+fn validate_managed_connection(+ require_sign_in: bool,+ cloud_only: bool,+ mode: &ConnectionMode,+ server_config: Option<&ServerConfig>,+) -> Result<(), String> {+ if cloud_only && *mode == ConnectionMode::SelfHosted {+ return Err("Your administrator requires Stirling Cloud sign-in".to_string());+ }+ // Legacy renderers represent local mode as SaaS without a server.+ if require_sign_in+ && (*mode == ConnectionMode::Local+ || (*mode == ConnectionMode::SaaS && server_config.is_none()))+ {+ return Err("Your administrator requires sign-in before using this app".to_string());+ }+ Ok(())+}+/// Whether the login agreement was provisioned as enabled. Read by the backend launcher to pass/// the `-Dlegal.loginAgreement.enabled` flag to the bundled JVM in local desktop mode.pub fn login_agreement_enabled(app_handle: &AppHandle) -> bool {@@ -423,10 +588,7 @@ pub async fn get_update_mode(app_handle: AppHandle) -> Result<UpdateModeInfo, St/// Refuses to overwrite a provisioned (locked) value so an MDM-managed/// deployment can't be subverted by a user clicking in Settings.#[tauri::command]-pub async fn set_update_mode(- app_handle: AppHandle,- mode: UpdateMode,-) -> Result<(), String> {+pub async fn set_update_mode(app_handle: AppHandle, mode: UpdateMode) -> Result<(), String> {let store = app_handle.store(STORE_FILE).map_err(|e| format!("Failed to access store: {}", e))?;@@ -479,6 +641,152 @@ mod tests {use super::*;use std::path::PathBuf;+ #[test]+ fn invalid_user_provisioning_is_preserved_for_recovery() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join(PROVISIONING_FILE_NAME);+ for input in [+ "{broken",+ r#"{"cloudOnly":true,"serverUrl":"https://example.org"}"#,+ r#"{"saasOnly":true,"serverUrl":"https://example.org"}"#,+ r#"{"cloudOnly":false,"saasOnly":true}"#,+ ] {+ fs::write(&path, input).unwrap();+ let ProvisioningLoad::Quarantined { backup, .. } =+ load_provisioning(&path, None, false).unwrap()+ else {+ panic!("invalid per-user input must be quarantined");+ };+ assert_eq!(fs::read_to_string(backup).unwrap(), input);+ assert!(!path.exists());+ }+ }++ #[test]+ fn invalid_machine_provisioning_fails_closed_without_moving_the_file() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join(PROVISIONING_FILE_NAME);+ for input in [+ "{broken",+ r#"{"cloudOnly":true,"serverUrl":"https://example.org"}"#,+ r#"{"saasOnly":true,"serverUrl":"https://example.org"}"#,+ r#"{"cloudOnly":false,"saasOnly":true}"#,+ ] {+ fs::write(&path, input).unwrap();+ let Err(message) = load_provisioning(&path, Some(dir.path()), false) else {+ panic!("invalid machine provisioning must block startup");+ };+ assert!(message.contains(&path.display().to_string()));+ assert_eq!(fs::read_to_string(&path).unwrap(), input);+ }+ }++ #[test]+ fn valid_provisioning_remains_available_for_application() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join(PROVISIONING_FILE_NAME);+ fs::write(&path, r#"{"requireSignIn":true}"#).unwrap();+ let ProvisioningLoad::Ready(config) = load_provisioning(&path, None, false).unwrap() else {+ panic!("valid provisioning must be applied");+ };+ assert_eq!(config.require_sign_in, Some(true));+ assert!(path.exists());+ }++ #[test]+ fn unrecoverable_user_provisioning_fails_closed() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join(PROVISIONING_FILE_NAME);+ fs::create_dir(&path).unwrap();+ assert!(load_provisioning(&path, None, false).is_err());+ assert!(path.exists());+ }++ #[test]+ fn managed_sign_in_rejects_both_local_representations() {+ assert!(validate_managed_connection(true, false, &ConnectionMode::Local, None).is_err());+ assert!(validate_managed_connection(true, false, &ConnectionMode::SaaS, None).is_err());+ let server = ServerConfig {+ url: "https://example.org".into(),+ };+ assert!(+ validate_managed_connection(true, false, &ConnectionMode::SaaS, Some(&server)).is_ok()+ );+ assert!(validate_managed_connection(+ true,+ false,+ &ConnectionMode::SelfHosted,+ Some(&server)+ )+ .is_ok());+ }++ #[test]+ fn cloud_only_rejects_self_hosted_but_allows_optional_guest_access() {+ let server = ServerConfig {+ url: "https://example.org".into(),+ };+ assert!(validate_managed_connection(+ false,+ true,+ &ConnectionMode::SelfHosted,+ Some(&server)+ )+ .is_err());+ assert!(validate_managed_connection(false, true, &ConnectionMode::Local, None).is_ok());+ assert!(+ validate_managed_connection(true, true, &ConnectionMode::SaaS, Some(&server)).is_ok()+ );+ }++ #[test]+ fn provisioning_accepts_sign_in_policy_without_a_server() {+ let config: ProvisioningConfig =+ serde_json::from_str(r#"{"requireSignIn":true,"cloudOnly":true}"#).unwrap();+ assert_eq!(config.require_sign_in, Some(true));+ assert_eq!(config.cloud_only, Some(true));+ assert!(config.server_url.is_none());+ let legacy: ProvisioningConfig = serde_json::from_str(+ r#"{"serverUrl":"https://example.org","lockConnectionMode":true}"#,+ )+ .unwrap();+ assert_eq!(legacy.lock_connection_mode, Some(true));+ assert!(legacy.require_sign_in.is_none());+ assert!(legacy.local_processing_only.is_none());+ let privacy: ProvisioningConfig =+ serde_json::from_str(r#"{"localProcessingOnly":true}"#).unwrap();+ assert_eq!(privacy.local_processing_only, Some(true));+ assert!(privacy.require_sign_in.is_none());+ assert!(+ serde_json::from_str::<ProvisioningConfig>(r#"{"localProcessingOnly":"true"}"#)+ .is_err()+ );+ }++ #[test]+ fn legacy_cloud_policy_keeps_its_value() {+ for enabled in [false, true] {+ let config: ProvisioningConfig =+ serde_json::from_value(serde_json::json!({"saasOnly": enabled})).unwrap();+ assert_eq!(config.cloud_only, Some(enabled));+ }+ }++ #[test]+ fn renderer_config_uses_cloud_policy_name() {+ let config = ConnectionConfig {+ mode: ConnectionMode::SaaS,+ server_config: None,+ lock_connection_mode: false,+ require_sign_in: true,+ cloud_only: true,+ local_processing_only: false,+ };+ let value = serde_json::to_value(config).unwrap();+ assert_eq!(value["cloud_only"], true);+ assert!(value.get("saas_only").is_none());+ }+// Windows-path tests are cfg-gated because `Path::starts_with` is// component-wise: on Linux, `"C:\\foo\\bar"` is a SINGLE path component// (since backslash is a literal character there, not a separator) so@@ -507,9 +815,8 @@ mod tests {// A provisioning file in ProgramData\Stirling-PDF (or /Library, /etc)// requires admin/root rights to write — those locations are how MSI// and Intune deliver policy — so locking the UI here is correct.- let system_path = PathBuf::from(- "C:\\ProgramData\\Stirling-PDF\\stirling-provisioning.json",- );+ let system_path =+ PathBuf::from("C:\\ProgramData\\Stirling-PDF\\stirling-provisioning.json");let system_dir = PathBuf::from("C:\\ProgramData\\Stirling-PDF");assert!(provisioning_path_is_admin_owned(@@ -541,11 +848,9 @@ mod tests {#[test]fn macos_library_provisioning_does_lock_ui() {- let system_path = PathBuf::from(- "/Library/Application Support/Stirling-PDF/stirling-provisioning.json",- );- let system_dir =- PathBuf::from("/Library/Application Support/Stirling-PDF");+ let system_path =+ PathBuf::from("/Library/Application Support/Stirling-PDF/stirling-provisioning.json");+ let system_dir = PathBuf::from("/Library/Application Support/Stirling-PDF");assert!(provisioning_path_is_admin_owned(&system_path,Some(&system_dir),@@ -557,8 +862,7 @@ mod tests {let user_path = PathBuf::from("/Users/alice/Library/Application Support/Stirling-PDF/stirling-provisioning.json",);- let system_dir =- PathBuf::from("/Library/Application Support/Stirling-PDF");+ let system_dir = PathBuf::from("/Library/Application Support/Stirling-PDF");assert!(!provisioning_path_is_admin_owned(&user_path,Some(&system_dir),@@ -571,7 +875,8 @@ mod tests {// refuse to lock — the user-AppData file is the only thing we'd be// matching against, and that's the case we explicitly want to leave// unlocked.- let user_path = PathBuf::from("/home/alice/.config/Stirling-PDF/stirling-provisioning.json");+ let user_path =+ PathBuf::from("/home/alice/.config/Stirling-PDF/stirling-provisioning.json");assert!(!provisioning_path_is_admin_owned(&user_path, None));}}diff --git a/frontend/editor/src-tauri/src/lib.rs b/frontend/editor/src-tauri/src/lib.rsindex 661eeff7e8..7479c389df 100644--- a/frontend/editor/src-tauri/src/lib.rs+++ b/frontend/editor/src-tauri/src/lib.rs@@ -1,4 +1,5 @@use tauri::{AppHandle, Emitter, Manager, RunEvent, WindowEvent};+use tauri_plugin_dialog::{DialogExt, MessageDialogKind};use tauri_plugin_window_state::StateFlags;mod utils;@@ -158,6 +159,20 @@ pub fn run() {.setup(|app| {add_log("🚀 Tauri app setup started".to_string());+ if let Err(err) = apply_provisioning_if_present(app.handle()) {+ add_log(format!("⚠️ Failed to apply provisioning file: {}", err));+ let handle = app.handle().clone();+ app.dialog()+ .message(format!(+ "Stirling PDF could not apply your managed settings and cannot start.\n\n{err}\n\nContact your administrator to correct the provisioning file or restore access to the settings store, then restart Stirling PDF."+ ))+ .title("Stirling PDF — managed settings error")+ .kind(MessageDialogKind::Error)+ .show(move |_| handle.exit(1));+ // Keep the event loop alive for the dialog, without opening the workspace or backend.+ return Ok(());+ }+// The main window is built here, not in tauri.conf.json, so its chrome// (decorations, macOS overlay title bar, traffic-light inset) lives with// the spawned-window chrome in window.rs. Created first so the deep-link@@ -200,10 +215,6 @@ pub fn run() {});}- if let Err(err) = apply_provisioning_if_present(&app.handle()) {- add_log(format!("⚠️ Failed to apply provisioning file: {}", err));- }-// Start backend immediately, non-blockinglet app_handle = app.handle().clone();diff --git a/frontend/editor/src-tauri/windows/wix/provisioning.wxs b/frontend/editor/src-tauri/windows/wix/provisioning.wxsindex 6bf03d870f..ac67b5e56e 100644--- a/frontend/editor/src-tauri/windows/wix/provisioning.wxs+++ b/frontend/editor/src-tauri/windows/wix/provisioning.wxs@@ -3,6 +3,9 @@<Fragment><Property Id="STIRLING_SERVER_URL" Secure="yes" /><Property Id="STIRLING_LOCK_CONNECTION" Secure="yes" />+ <Property Id="STIRLING_REQUIRE_SIGN_IN" Secure="yes" />+ <Property Id="STIRLING_CLOUD_ONLY" Secure="yes" />+ <Property Id="STIRLING_LOCAL_PROCESSING_ONLY" Secure="yes" /><!-- STIRLING_LOGIN_AGREEMENT — "1"/"true" enables the login agreement popup on this install. --><Property Id="STIRLING_LOGIN_AGREEMENT" Secure="yes" /><!--@@ -73,25 +76,20 @@<CustomActionId="SetWriteProvisioningFilePerUser"Property="WriteProvisioningFilePerUser"- Value="--output "[AppDataFolder]Stirling-PDF\stirling-provisioning.json" --url "[STIRLING_SERVER_URL]" --lock "[STIRLING_LOCK_CONNECTION]" --login-agreement "[STIRLING_LOGIN_AGREEMENT]" --update-mode "[STIRLING_UPDATE_MODE]""+ Value="--output "[AppDataFolder]Stirling-PDF\stirling-provisioning.json" --url "[STIRLING_SERVER_URL]" --lock "[STIRLING_LOCK_CONNECTION]" --require-sign-in "[STIRLING_REQUIRE_SIGN_IN]" --cloud-only "[STIRLING_CLOUD_ONLY]" --local-processing-only "[STIRLING_LOCAL_PROCESSING_ONLY]" --login-agreement "[STIRLING_LOGIN_AGREEMENT]" --update-mode "[STIRLING_UPDATE_MODE]""/><CustomActionId="SetWriteProvisioningFileAllUsers"Property="WriteProvisioningFileAllUsers"- Value="--output "[CommonAppDataFolder]Stirling-PDF\stirling-provisioning.json" --url "[STIRLING_SERVER_URL]" --lock "[STIRLING_LOCK_CONNECTION]" --login-agreement "[STIRLING_LOGIN_AGREEMENT]" --update-mode "[STIRLING_UPDATE_MODE]""+ Value="--output "[CommonAppDataFolder]Stirling-PDF\stirling-provisioning.json" --url "[STIRLING_SERVER_URL]" --lock "[STIRLING_LOCK_CONNECTION]" --require-sign-in "[STIRLING_REQUIRE_SIGN_IN]" --cloud-only "[STIRLING_CLOUD_ONLY]" --local-processing-only "[STIRLING_LOCAL_PROCESSING_ONLY]" --login-agreement "[STIRLING_LOGIN_AGREEMENT]" --update-mode "[STIRLING_UPDATE_MODE]""/>- <!--- Run the provisioner when ANY of STIRLING_SERVER_URL, STIRLING_LOGIN_AGREEMENT, or- STIRLING_UPDATE_MODE is set. The provisioner is a no-op if all values end up empty,- so passing none is safe.- --><InstallExecuteSequence>- <Custom Action="SetWriteProvisioningFilePerUser" After="InstallFiles">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "") AND (NOT ALLUSERS OR ALLUSERS=0)</Custom>- <Custom Action="WriteProvisioningFilePerUser" After="SetWriteProvisioningFilePerUser">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "") AND (NOT ALLUSERS OR ALLUSERS=0)</Custom>- <Custom Action="SetWriteProvisioningFileAllUsers" After="InstallFiles">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "") AND (ALLUSERS=1 OR ALLUSERS=2)</Custom>- <Custom Action="WriteProvisioningFileAllUsers" After="SetWriteProvisioningFileAllUsers">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "") AND (ALLUSERS=1 OR ALLUSERS=2)</Custom>+ <Custom Action="SetWriteProvisioningFilePerUser" After="InstallFiles">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "") AND (NOT ALLUSERS OR ALLUSERS=0)</Custom>+ <Custom Action="WriteProvisioningFilePerUser" After="SetWriteProvisioningFilePerUser">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "") AND (NOT ALLUSERS OR ALLUSERS=0)</Custom>+ <Custom Action="SetWriteProvisioningFileAllUsers" After="InstallFiles">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "") AND (ALLUSERS=1 OR ALLUSERS=2)</Custom>+ <Custom Action="WriteProvisioningFileAllUsers" After="SetWriteProvisioningFileAllUsers">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "") AND (ALLUSERS=1 OR ALLUSERS=2)</Custom></InstallExecuteSequence></Fragment></Wix>diff --git a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx b/frontend/editor/src/core/components/filesPage/FileManagerView.tsxindex 5ac4b86c9d..9ae490f56d 100644--- a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx+++ b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx@@ -1,3 +1,4 @@+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import { Icon } from "@app/ui/Icon";import React, {useCallback,@@ -139,6 +140,7 @@ export default function FileManagerView() {"Sign in to refresh from the server.",));const uploadEnabled = appConfig?.storageEnabled === true;+ const localProcessingOnly = useLocalProcessingOnly();const saveToServerDisabledReason: string | null =signInRequiredReason ??(uploadEnabled@@ -1090,7 +1092,7 @@ export default function FileManagerView() {selectedCount={selectedFiles.length}onAddToWorkspace={() => handleAddToWorkspace(selectedFiles)}onSaveToServer={- localOnlySelectedStubs.length > 0+ !localProcessingOnly && localOnlySelectedStubs.length > 0? () => setSaveToServerTarget(localOnlySelectedStubs): undefined}@@ -1346,7 +1348,11 @@ export default function FileManagerView() {}),)}- onSaveToServer={(file) => setSaveToServerTarget([file])}+ onSaveToServer={+ localProcessingOnly+ ? undefined+ : (file) => setSaveToServerTarget([file])+ }onVersionHistory={(file) => setVersionHistoryFile(file)}onDownloadFile={handleDownloadFile}onRenameFile={setRenameTarget}@@ -1400,7 +1406,11 @@ export default function FileManagerView() {onAddToWorkspace={handleAddToWorkspace}onMove={promptMoveFiles}onRemove={handleRemoveFiles}- onSaveToServer={(files) => setSaveToServerTarget(files)}+ onSaveToServer={+ localProcessingOnly+ ? undefined+ : (files) => setSaveToServerTarget(files)+ }saveToServerDisabledReason={saveToServerDisabledReason}/>)}@@ -1450,7 +1460,11 @@ export default function FileManagerView() {onAddToWorkspace={handleAddToWorkspace}onMove={promptMoveFiles}onRemove={handleRemoveFiles}- onSaveToServer={(files) => setSaveToServerTarget(files)}+ onSaveToServer={+ localProcessingOnly+ ? undefined+ : (files) => setSaveToServerTarget(files)+ }saveToServerDisabledReason={saveToServerDisabledReason}compactVersionsonOpenVersionHistory={() => {diff --git a/frontend/editor/src/core/components/filesPage/FilesToolbarFilterMenu.tsx b/frontend/editor/src/core/components/filesPage/FilesToolbarFilterMenu.tsxindex 93b7262529..5fb36ee5c4 100644--- a/frontend/editor/src/core/components/filesPage/FilesToolbarFilterMenu.tsx+++ b/frontend/editor/src/core/components/filesPage/FilesToolbarFilterMenu.tsx@@ -1,5 +1,6 @@import { MultiSelect, Popover, Select, Stack } from "@mantine/core";import { useTranslation } from "react-i18next";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import { Icon } from "@app/ui/Icon";import { ActionIcon } from "@app/ui/ActionIcon";import { Button } from "@app/ui/Button";@@ -24,6 +25,7 @@ export function FilesToolbarFilterMenu({zIndex,}: FilesToolbarFilterMenuProps) {const { t } = useTranslation();+ const localOnly = useLocalProcessingOnly();const activeCount =(originFilter !== "all" ? 1 : 0) + (typeFilter.length > 0 ? 1 : 0);@@ -85,7 +87,12 @@ export function FilesToolbarFilterMenu({value: "shared-with-me",label: t("filesPage.origin.shared", "Shared"),},- ]}+ ].filter(+ (source) =>+ !localOnly ||+ source.value === "all" ||+ source.value === "local",+ )}label={t("filesPage.originFilter", "Filter by source")}comboboxProps={{ withinPortal: false }}/>diff --git a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsxindex 02c67305e2..8e88832a30 100644--- a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx+++ b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx@@ -1,5 +1,6 @@import React, { useCallback, useState } from "react";import { useTranslation } from "react-i18next";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import { Menu } from "@mantine/core";import { ActionIcon } from "@app/ui/ActionIcon";import { Icon } from "@app/ui/Icon";@@ -130,6 +131,7 @@ interface RootRowProps {function RootRow({ fileCount, isActive, onSelect, onDropFiles }: RootRowProps) {const { t } = useTranslation();+ const localOnly = useLocalProcessingOnly();const { setError } = useFolders();const { handlers, isOver } = useDropTarget({dragType: FILES_PAGE_DRAG_TYPE,@@ -173,7 +175,9 @@ function RootRow({ fileCount, isActive, onSelect, onDropFiles }: RootRowProps) {<Icon name="house" size={18} /></span><span className="files-page-tree-name">- {t("filesPage.allFiles", "Stirling library")}+ {localOnly+ ? t("desktopPrivacy.localFiles", "Local files")+ : t("filesPage.allFiles", "Stirling library")}</span><span className="files-page-tree-count">{fileCount}</span></div>diff --git a/frontend/editor/src/core/components/filesPage/LibraryTabs.tsx b/frontend/editor/src/core/components/filesPage/LibraryTabs.tsxindex d89e7d5fcb..7af7c63ac7 100644--- a/frontend/editor/src/core/components/filesPage/LibraryTabs.tsx+++ b/frontend/editor/src/core/components/filesPage/LibraryTabs.tsx@@ -1,5 +1,6 @@import { Fragment, type ReactNode } from "react";import { useTranslation } from "react-i18next";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import { Button, type ButtonProps } from "@app/ui/Button";import type { FilesPageTab } from "@app/contexts/FilesPageContext";@@ -23,10 +24,16 @@ export function LibraryTabs({libraryOnly?: boolean;}) {const { t } = useTranslation();+ const localOnly = useLocalProcessingOnly();const tabs: { id: FilesPageTab; label: string }[] = [{ id: "recent", label: t("filesPage.recentFiles", "Recents") },- { id: "all", label: t("filesPage.allFiles", "Stirling library") },- ...(sharingEnabled+ {+ id: "all",+ label: localOnly+ ? t("desktopPrivacy.localFiles", "Local files")+ : t("filesPage.allFiles", "Stirling library"),+ },+ ...(sharingEnabled && !localOnly? [{id: "shared" as const,diff --git a/frontend/editor/src/core/components/filesPage/LibraryToolbar.test.tsx b/frontend/editor/src/core/components/filesPage/LibraryToolbar.test.tsxnew file mode 100644index 0000000000..934828dd45--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/LibraryToolbar.test.tsx@@ -0,0 +1,60 @@+import { render } from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";+import { LibraryToolbar } from "@app/components/filesPage/LibraryToolbar";+import type { FilesPageOriginFilter } from "@app/contexts/FilesPageContext";++const policy = vi.hoisted(() => ({ localOnly: false }));+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => policy.localOnly,+}));+vi.mock("@mantine/core", () => ({+ Select: () => null,+ MultiSelect: () => null,+}));+vi.mock("@app/ui/SegmentedControl", () => ({ SegmentedControl: () => null }));+vi.mock("@app/ui/Icon", () => ({ Icon: () => null }));+vi.mock("@app/components/filesPage/FilesToolbarFilterMenu", () => ({+ FilesToolbarFilterMenu: () => null,+}));+vi.mock("@app/components/filesPage/FilesToolbarSortMenu", () => ({+ FilesToolbarSortMenu: () => null,+}));+vi.mock("@app/components/filesPage/FilenameSearch", () => ({+ FilenameSearch: () => null,+}));++beforeEach(() => {+ policy.localOnly = false;+});++it.each<FilesPageOriginFilter>(["cloud", "shared-with-me", "local", "all"])(+ "clears only hidden source filters when privacy mode starts (%s)",+ (originFilter) => {+ const setOriginFilter = vi.fn();+ const toolbar = (+ <LibraryToolbar+ isMobile={false}+ availableTypes={[]}+ originFilter={originFilter}+ setOriginFilter={setOriginFilter}+ typeFilter={[]}+ setTypeFilter={() => {}}+ search=""+ setSearch={() => {}}+ sortMode="modified-desc"+ setSortMode={() => {}}+ viewMode="grid"+ setViewMode={() => {}}+ />+ );+ const { rerender } = render(toolbar);+ expect(setOriginFilter).not.toHaveBeenCalled();+ policy.localOnly = true;+ rerender(<LibraryToolbar {...toolbar.props} />);+ if (originFilter === "cloud" || originFilter === "shared-with-me") {+ expect(setOriginFilter).toHaveBeenCalledWith("all");+ } else {+ expect(setOriginFilter).not.toHaveBeenCalled();+ }+ },+);diff --git a/frontend/editor/src/core/components/filesPage/LibraryToolbar.tsx b/frontend/editor/src/core/components/filesPage/LibraryToolbar.tsxindex 2af4293ebe..050f4a3209 100644--- a/frontend/editor/src/core/components/filesPage/LibraryToolbar.tsx+++ b/frontend/editor/src/core/components/filesPage/LibraryToolbar.tsx@@ -1,5 +1,7 @@import { MultiSelect, Select } from "@mantine/core";+import { useEffect } from "react";import { useTranslation } from "react-i18next";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import { Icon } from "@app/ui/Icon";import { SegmentedControl } from "@app/ui/SegmentedControl";import { FilesToolbarFilterMenu } from "@app/components/filesPage/FilesToolbarFilterMenu";@@ -47,6 +49,15 @@ export function LibraryToolbar({hideFilters = false,}: Props) {const { t } = useTranslation();+ const localOnly = useLocalProcessingOnly();+ useEffect(() => {+ if (+ localOnly &&+ (originFilter === "cloud" || originFilter === "shared-with-me")+ ) {+ setOriginFilter("all");+ }+ }, [localOnly, originFilter, setOriginFilter]);return (<>{!hideFilters &&@@ -85,7 +96,12 @@ export function LibraryToolbar({value: "shared-with-me",label: t("filesPage.origin.shared", "Shared"),},- ]}+ ].filter(+ (source) =>+ !localOnly ||+ source.value === "all" ||+ source.value === "local",+ )}style={{ width: 140 }}aria-label={t("filesPage.originFilter", "Filter by source")}/>diff --git a/frontend/editor/src/core/components/filesPage/NewFolderButton.tsx b/frontend/editor/src/core/components/filesPage/NewFolderButton.tsxindex 508caedbbb..fb839f95a2 100644--- a/frontend/editor/src/core/components/filesPage/NewFolderButton.tsx+++ b/frontend/editor/src/core/components/filesPage/NewFolderButton.tsx@@ -2,6 +2,7 @@ import { Icon } from "@app/ui/Icon";import type { ReactNode } from "react";import { Menu, Text, Tooltip } from "@mantine/core";import { useTranslation } from "react-i18next";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import { ActionIcon } from "@app/ui/ActionIcon";import { Button } from "@app/ui/Button";@@ -52,6 +53,7 @@ export function NewFolderButton({onOpenDialog,}: NewFolderButtonProps): ReactNode {const { t } = useTranslation();+ const localOnly = useLocalProcessingOnly();const iconOnly = trigger === "icon";const asRow = trigger === "row";@@ -200,23 +202,25 @@ export function NewFolderButton({{localFolderLabel ??t("filesPage.newFolderMenu.addExisting", "Add local folder")}</Menu.Item>- <Menu.Item- className="files-page-new-folder-option"- leftSection={<Icon name="cloud" size={20} />}- disabled={Boolean(serverDisabledReason)}- onClick={() => onOpenDialog(currentFolderId, "server")}- >- {t("filesPage.newFolderMenu.server", "New folder on the server")}- {/* The reason is the caption: a disabled item with no explanation+ {!localOnly && (+ <Menu.Item+ className="files-page-new-folder-option"+ leftSection={<Icon name="cloud" size={20} />}+ disabled={Boolean(serverDisabledReason)}+ onClick={() => onOpenDialog(currentFolderId, "server")}+ >+ {t("filesPage.newFolderMenu.server", "New folder on the server")}+ {/* The reason is the caption: a disabled item with no explanationreads as broken rather than unavailable. */}- <Text size="xs" c="dimmed">- {serverDisabledReason ??- t(- "filesPage.newFolderMenu.serverHint",- "Synced to your account, available wherever you sign in.",- )}- </Text>- </Menu.Item>+ <Text size="xs" c="dimmed">+ {serverDisabledReason ??+ t(+ "filesPage.newFolderMenu.serverHint",+ "Synced to your account, available wherever you sign in.",+ )}+ </Text>+ </Menu.Item>+ )}</Menu.Dropdown></Menu>);diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.processing.test.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.processing.test.tsxindex 554625b5e1..11081ce582 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.processing.test.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.processing.test.tsx@@ -13,6 +13,10 @@ import { EDITOR_BASENAME } from "@app/routes/editorBasename";const capability = vi.hoisted(() => ({ available: true }));const connected = vi.hoisted(() => ({ value: true }));+const privacy = vi.hoisted(() => ({ localOnly: false }));+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => privacy.localOnly,+}));vi.mock("@app/hooks/useProcessingFolderCreation", () => ({get canCreateProcessingFolders() {return capability.available;@@ -56,11 +60,26 @@ function setup(path: string, actions: QuickNavHostActions = {}) {}beforeEach(() => {+ privacy.localOnly = false;capability.available = true;connected.value = true;consumeProcessingFolderCreationRequest();});+it("hides off-device processing shortcuts under managed privacy", () => {+ privacy.localOnly = true;+ setup("/files");+ expect(+ screen.queryByRole("button", { name: "processingFolders.setup.title" }),+ ).toBeNull();+ expect(+ screen.queryByRole("button", { name: "quickAccess.automate" }),+ ).toBeNull();+ expect(+ screen.getByRole("button", { name: "fileSidebar.myFiles" }),+ ).toBeInTheDocument();+});+it.each(["/settings/general", "/docs", "/processor"])("keeps folder processing available on %s and carries the request to the editor",(path) => {diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsxindex 385c9dca18..f86a36721f 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx@@ -1,4 +1,5 @@import { useTranslation } from "react-i18next";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import { useState } from "react";import { SignMenu } from "@app/components/shared/signing/SignMenu";import { requestSigningIntent } from "@app/utils/pendingSigningIntent";@@ -32,6 +33,7 @@ const ACCOUNT_ANCHOR = "account";export function QuickNavRailHost() {const { t } = useTranslation();+ const localOnly = useLocalProcessingOnly();const navigate = useNavigate();const { pathname } = useLocation();const host = useQuickNavHost();@@ -160,7 +162,7 @@ export function QuickNavRailHost() {const surfaces: QuickNavEntry[] = [reader,editor,- ...(HAS_PORTAL ? [processor] : []),+ ...(HAS_PORTAL && !localOnly ? [processor] : []),];const within: QuickNavEntry[] = [@@ -195,7 +197,7 @@ export function QuickNavRailHost() {else go("/files");},},- ...(canCreateProcessingFolders+ ...(canCreateProcessingFolders && !localOnly? [{id: "createProcessingFolder",@@ -290,7 +292,10 @@ export function QuickNavRailHost() {return (<QuickNavRailContainer- groups={[surfaces, within]}+ groups={[+ surfaces,+ localOnly ? within.filter((entry) => entry.id !== "automate") : within,+ ]}onReturnHome={() => guarded(goToStartupView)}identity={host?.identity ?? null}onOpenAccount={openAccount}diff --git a/frontend/editor/src/core/components/shared/signing/SignMenu.tsx b/frontend/editor/src/core/components/shared/signing/SignMenu.tsxindex f69236cff4..ce57121e2c 100644--- a/frontend/editor/src/core/components/shared/signing/SignMenu.tsx+++ b/frontend/editor/src/core/components/shared/signing/SignMenu.tsx@@ -1,4 +1,5 @@import { useTranslation } from "react-i18next";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import { Dropdown, type DropdownTriggerProps } from "@app/ui/Dropdown";import type { QuickNavToolReasons } from "@app/contexts/QuickNavHostContext";import type { ToolId } from "@app/types/toolId";@@ -30,6 +31,7 @@ export function SignMenu({items,}: SignMenuProps) {const { t } = useTranslation();+ const localOnly = useLocalProcessingOnly();const sessions = useSignMenuSessions(items, opened);const openSigning = (intent: SigningIntent) => {onClose();@@ -58,11 +60,13 @@ export function SignMenu({placement="side"><SignMenuPersonalSection reasons={reasons} onSelectTool={selectTool} />- <SignMenuSessionsSection- sessions={sessions}- unavailableReason={reasons.sharedSign}- onOpenSigning={openSigning}- />+ {!localOnly && (+ <SignMenuSessionsSection+ sessions={sessions}+ unavailableReason={reasons.sharedSign}+ onOpenSigning={openSigning}+ />+ )}</Dropdown.Menu></Dropdown.Root>);diff --git a/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx b/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsxindex 1b1667e1b0..ba75e503e6 100644--- a/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx+++ b/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx@@ -13,6 +13,7 @@ import {import { getConversionEndpoints } from "@app/data/toolsTaxonomy";import { usePreferences } from "@app/contexts/PreferencesContext";import { useConversionCloudStatus } from "@app/hooks/useConversionCloudStatus";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import GroupedFormatDropdown from "@app/components/tools/convert/GroupedFormatDropdown";import ConvertToImageSettings from "@app/components/tools/convert/ConvertToImageSettings";import ConvertFromImageSettings from "@app/components/tools/convert/ConvertFromImageSettings";@@ -69,6 +70,9 @@ const ConvertSettings = ({const { t } = useTranslation();const theme = useMantineTheme();const { preferences } = usePreferences();+ const localProcessingOnly = useLocalProcessingOnly();+ const hideUnavailableConversions =+ localProcessingOnly || preferences.hideUnavailableConversions;const allEndpoints = useMemo(() => {const endpoints = getConversionEndpoints(EXTENSION_TO_ENDPOINT);@@ -116,9 +120,8 @@ const ConvertSettings = ({};});- // Filter out unavailable source formats if preference is enabledlet filteredOptions = baseOptions;- if (preferences.hideUnavailableConversions) {+ if (hideUnavailableConversions) {filteredOptions = baseOptions.filter((opt) => opt.enabled !== false);}@@ -143,7 +146,7 @@ const ConvertSettings = ({}, [parameters.fromExtension,endpointStatus,- preferences.hideUnavailableConversions,+ hideUnavailableConversions,conversionStatus,]);@@ -169,8 +172,7 @@ const ConvertSettings = ({};});- // Filter out unavailable conversions if preference is enabled- if (preferences.hideUnavailableConversions) {+ if (hideUnavailableConversions) {return enhanced.filter((opt) => opt.enabled !== false);}@@ -178,7 +180,7 @@ const ConvertSettings = ({}, [parameters.fromExtension,endpointStatus,- preferences.hideUnavailableConversions,+ hideUnavailableConversions,conversionStatus,]);diff --git a/frontend/editor/src/core/contexts/FilesPageContext.tsx b/frontend/editor/src/core/contexts/FilesPageContext.tsxindex e20afe22d3..27b46a8107 100644--- a/frontend/editor/src/core/contexts/FilesPageContext.tsx+++ b/frontend/editor/src/core/contexts/FilesPageContext.tsx@@ -1,3 +1,4 @@+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import React, {createContext,useCallback,@@ -185,7 +186,15 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {// Refs keep workspace changes from restarting library refreshes.const { openFileIdsRef, onOpenFilesDetached } = useDiskLinkReconcile();- const [allFiles, setAllFiles] = useState<StirlingFileStub[]>([]);+ const localOnly = useLocalProcessingOnly();+ const [storedFiles, setAllFiles] = useState<StirlingFileStub[]>([]);+ const allFiles = useMemo(+ () =>+ localOnly+ ? storedFiles.filter((file) => getFileOrigin(file) === "local")+ : storedFiles,+ [storedFiles, localOnly],+ );const [loading, setLoading] = useState(true);// Only the newest refresh may publish results or clear loading.const refreshGenRef = useRef(0);diff --git a/frontend/editor/src/core/contexts/FolderContext.tsx b/frontend/editor/src/core/contexts/FolderContext.tsxindex 5b5551769e..20eeeec0a7 100644--- a/frontend/editor/src/core/contexts/FolderContext.tsx+++ b/frontend/editor/src/core/contexts/FolderContext.tsx@@ -15,6 +15,7 @@* dialog Alert pattern.*/+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import React, {createContext,useCallback,@@ -286,6 +287,7 @@ function shouldStrandedReset(}export function FolderProvider({ children }: FolderProviderProps) {+ const localOnly = useLocalProcessingOnly();const [storedFolders, setFolders] = useState<FolderRecord[]>([]);// Never persisted: a directory is its own record, so a listing rebuilds these.const [diskSubfolders, setDiskSubfolders] = useState<@@ -302,10 +304,13 @@ export function FolderProvider({ children }: FolderProviderProps) {}}}- return synthesized.length+ const combined = synthesized.length? [...storedFolders, ...synthesized]: storedFolders;- }, [storedFolders, diskSubfolders]);+ return localOnly+ ? combined.filter((folder) => folderKind(folder) !== "server")+ : combined;+ }, [storedFolders, diskSubfolders, localOnly]);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);// Start `false` so folder-mutation buttons are disabled until the firstdiff --git a/frontend/editor/src/core/hooks/useLibraryRefresh.ts b/frontend/editor/src/core/hooks/useLibraryRefresh.tsindex 8cec0a3c84..452ac93eec 100644--- a/frontend/editor/src/core/hooks/useLibraryRefresh.ts+++ b/frontend/editor/src/core/hooks/useLibraryRefresh.ts@@ -1,5 +1,6 @@import { useCallback, useState } from "react";import { useTranslation } from "react-i18next";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import { useFilesPage } from "@app/contexts/FilesPageContext";import { useFolders } from "@app/contexts/FolderContext";@@ -13,6 +14,7 @@ export function useLibraryRefresh(): {refresh: () => Promise<void>;} {const { t } = useTranslation();+ const localOnly = useLocalProcessingOnly();const folders = useFolders();const { refresh, bumpDiskRevision } = useFilesPage();const [refreshing, setRefreshing] = useState(false);@@ -22,7 +24,9 @@ export function useLibraryRefresh(): {try {// pullFromServer bumps the folder revision, which the FolderProvider's effect// reacts to by re-running refresh() - no need to await folders.refresh() here.- const result = await folders.pullFromServer();+ const result = localOnly+ ? { ok: true as const }+ : await folders.pullFromServer();if (!result.ok && result.reason !== "endpoint-missing") {folders.setError(result.reason === "network"@@ -41,7 +45,7 @@ export function useLibraryRefresh(): {} finally {setRefreshing(false);}- }, [folders, refresh, bumpDiskRevision, t]);+ }, [folders, refresh, bumpDiskRevision, t, localOnly]);return { refreshing, refresh: run };}diff --git a/frontend/editor/src/core/hooks/useLocalProcessingOnly.ts b/frontend/editor/src/core/hooks/useLocalProcessingOnly.tsnew file mode 100644index 0000000000..5db86e6849--- /dev/null+++ b/frontend/editor/src/core/hooks/useLocalProcessingOnly.ts@@ -0,0 +1,4 @@+/** Web deployments have no managed device policy; desktop shadows this hook. */+export function useLocalProcessingOnly(): boolean {+ return false;+}diff --git a/frontend/editor/src/desktop/api/endpointAvailability.ts b/frontend/editor/src/desktop/api/endpointAvailability.tsindex 62ba2401f6..b30af6f4d5 100644--- a/frontend/editor/src/desktop/api/endpointAvailability.ts+++ b/frontend/editor/src/desktop/api/endpointAvailability.ts@@ -1,4 +1,8 @@import { isAxiosError } from "axios";+import {+ isLocalProcessingOnly,+ isOffDeviceEndpointName,+} from "@app/services/documentPrivacyService";import apiClient from "@app/services/apiClient";import { tauriBackendService } from "@app/services/tauriBackendService";import { selfHostedServerMonitor } from "@app/services/selfHostedServerMonitor";@@ -126,6 +130,14 @@ async function resolveOffline(export async function resolveEndpointsAvailability(endpoints: string[],): Promise<EndpointAvailabilityMap> {+ if (await isLocalProcessingOnly()) {+ const map = await resolveOffline(endpoints);+ for (const endpoint of endpoints) {+ if (isOffDeviceEndpointName(endpoint))+ map[endpoint] = { enabled: false, reason: "NOT_SUPPORTED_LOCALLY" };+ }+ return map;+ }if (isSelfHostedOffline()) {return resolveOffline(endpoints);}@@ -152,6 +164,8 @@ export async function resolveEndpointsAvailability(export async function resolveEndpointEnabled(endpoint: string,): Promise<boolean> {+ if (await isLocalProcessingOnly())+ return (await resolveEndpointsAvailability([endpoint]))[endpoint].enabled;if (isSelfHostedOffline()) {// ConvertSettings already filters unsupported endpoints from the dropdown,// so a selected endpoint is supported locally by the time it reaches here.diff --git a/frontend/editor/src/desktop/components/AppProviders.test.tsx b/frontend/editor/src/desktop/components/AppProviders.test.tsxnew file mode 100644index 0000000000..3503d92927--- /dev/null+++ b/frontend/editor/src/desktop/components/AppProviders.test.tsx@@ -0,0 +1,132 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import { AppProviders } from "@app/components/AppProviders";++const state = vi.hoisted(() => ({+ getConfig: vi.fn(),+ monitor: vi.fn(),+ preload: vi.fn(),+}));+vi.mock("@proprietary/components/AppProviders", () => ({+ AppProviders: ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ ),+}));+vi.mock("@app/services/connectionModeService", () => ({+ connectionModeService: {+ getCurrentConfig: state.getConfig,+ subscribeToModeChanges: () => () => {},+ },+ JWT_EXPIRED_PROMPTED_KEY: "expiry",+}));+vi.mock("@app/services/authService", () => ({+ authService: {+ isAuthenticated: async () => true,+ subscribeToAuth: () => () => {},+ getAuthToken: async () => null,+ hasManagedSession: async () => false,+ },+}));+vi.mock("@app/services/tauriBackendService", () => ({+ tauriBackendService: {+ getBackendUrl: () => "http://localhost:8080",+ isOnline: true,+ subscribeToStatus: () => () => {},+ },+}));+vi.mock("@app/services/selfHostedServerMonitor", () => ({+ selfHostedServerMonitor: { stop: vi.fn() },+}));+vi.mock("@app/services/endpointAvailabilityService", () => ({+ endpointAvailabilityService: { preloadEndpoints: state.preload },+}));+vi.mock("@app/hooks/useFirstLaunchCheck", () => ({+ useFirstLaunchCheck: () => ({ isFirstLaunch: false, setupComplete: true }),+}));+vi.mock("@app/hooks/useDesktopUpdatePopup", () => ({+ useDesktopUpdatePopup: () => ({ state: {}, actions: {} }),+}));+vi.mock("@app/hooks/useBackendInitializer", () => ({+ useBackendInitializer: state.monitor,+}));+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => false,+}));+vi.mock("@tauri-apps/api/core", () => ({ isTauri: () => false }));+vi.mock("@app/contexts/SaaSTeamContext", () => ({+ SaaSTeamProvider: ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ ),+}));+vi.mock("@mantine/core", () => {+ const Container = ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ );+ return {+ Center: Container,+ Stack: Container,+ Text: Container,+ Loader: () => null,+ };+});+vi.mock("@app/ui/Button", () => ({+ Button: ({+ children,+ onClick,+ }: {+ children: ReactNode;+ onClick: () => void;+ }) => <button onClick={onClick}>{children}</button>,+}));+vi.mock("@app/components/SetupWizard", () => ({+ SetupWizard: () => <div>Required sign-in</div>,+}));+vi.mock("@app/components/DesktopConfigSync", () => ({+ DesktopConfigSync: () => null,+}));+vi.mock("@app/components/DesktopQueryCacheReset", () => ({+ DesktopQueryCacheReset: () => null,+}));+vi.mock("@app/components/DesktopBannerInitializer", () => ({+ DesktopBannerInitializer: () => null,+}));+vi.mock("@app/components/SaveShortcutListener", () => ({+ SaveShortcutListener: () => null,+}));+vi.mock("@app/components/LocalProcessingFolders", () => ({+ LocalProcessingFolders: () => null,+}));+vi.mock("@app/components/shared/DiskConflictHost", () => ({+ DiskConflictHost: () => null,+}));+vi.mock("@app/components/DesktopOnboardingModal", () => ({+ DesktopOnboardingModal: () => null,+}));+vi.mock("@app/components/DesktopSaasOnboardingBootstrap", () => ({+ DesktopSaasOnboardingBootstrap: () => null,+}));+vi.mock(+ "@app/components/onboarding/classificationDemo/ClassificationBackgroundRunner",+ () => ({ ClassificationBackgroundRunner: () => null }),+);+vi.mock("@app/components/UsageLimitModalHost", () => ({ default: () => null }));+vi.mock("@app/components/SignInModal", () => ({ SignInModal: () => null }));+vi.mock("@core/components/shared/UpdateModal", () => ({ default: () => null }));++it("initializes backend monitoring and endpoint preload after a gate retry recovers configuration", async () => {+ state.getConfig.mockRejectedValue(new Error("Store unavailable"));+ render(<AppProviders>Workbench</AppProviders>);+ await screen.findByText("setup.error.policyUnavailable");+ expect(state.monitor).not.toHaveBeenCalledWith(true);+ expect(state.preload).not.toHaveBeenCalled();+ state.getConfig.mockResolvedValue({ mode: "saas", require_sign_in: true });+ fireEvent.click(screen.getByRole("button", { name: "common.retry" }));+ await screen.findByText("Required sign-in");+ await waitFor(() => expect(state.monitor).toHaveBeenCalledWith(true));+ expect(state.preload).toHaveBeenCalledWith(+ expect.any(Array),+ "http://localhost:8080",+ );+ expect(screen.queryByText("Workbench")).toBeNull();+});diff --git a/frontend/editor/src/desktop/components/AppProviders.tsx b/frontend/editor/src/desktop/components/AppProviders.tsxindex 75bd425724..645378be34 100644--- a/frontend/editor/src/desktop/components/AppProviders.tsx+++ b/frontend/editor/src/desktop/components/AppProviders.tsx@@ -1,4 +1,4 @@-import { ReactNode, useEffect, useRef, useState } from "react";+import { ReactNode, useCallback, useEffect, useRef, useState } from "react";import { AppProviders as ProprietaryAppProviders } from "@proprietary/components/AppProviders";import { DesktopConfigSync } from "@app/components/DesktopConfigSync";import { DesktopQueryCacheReset } from "@app/components/DesktopQueryCacheReset";@@ -11,6 +11,7 @@ import { DesktopSaasOnboardingBootstrap } from "@app/components/DesktopSaasOnboaimport { ClassificationBackgroundRunner } from "@app/components/onboarding/classificationDemo/ClassificationBackgroundRunner";import UsageLimitModalHost from "@app/components/UsageLimitModalHost";import { SignInModal } from "@app/components/SignInModal";+import { DesktopAccessGate } from "@app/components/DesktopAccessGate";import { OPEN_SIGN_IN_EVENT } from "@app/constants/signInEvents";import { ToolActionsContext } from "@app/contexts/ToolActionsContext";import { useFirstLaunchCheck } from "@app/hooks/useFirstLaunchCheck";@@ -19,6 +20,7 @@ import { DESKTOP_DEFAULT_APP_CONFIG } from "@app/config/defaultAppConfig";import {connectionModeService,JWT_EXPIRED_PROMPTED_KEY,+ type ConnectionConfig,} from "@app/services/connectionModeService";import { STIRLING_SAAS_URL } from "@app/constants/connection";import { tauriBackendService } from "@app/services/tauriBackendService";@@ -30,6 +32,7 @@ import { isTauri } from "@tauri-apps/api/core";import { SaaSTeamProvider } from "@app/contexts/SaaSTeamContext";import UpdateModal from "@core/components/shared/UpdateModal";import { useDesktopUpdatePopup } from "@app/hooks/useDesktopUpdatePopup";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";// Common tool endpoints to preload for faster first-useconst COMMON_TOOL_ENDPOINTS = [@@ -52,6 +55,7 @@ const COMMON_TOOL_ENDPOINTS = [* - Shows setup wizard on first launch*/export function AppProviders({ children }: { children: ReactNode }) {+ const localOnly = useLocalProcessingOnly();const { isFirstLaunch, setupComplete } = useFirstLaunchCheck();const updatePopup = useDesktopUpdatePopup();const [connectionMode, setConnectionMode] = useState<@@ -70,6 +74,13 @@ export function AppProviders({ children }: { children: ReactNode }) {// tree - that resets DesktopOnboardingModal mid-flow and re-shows the welcome slide.const lastAppliedMode = useRef<"saas" | "selfhosted" | "local" | null>(null);+ const initializeConnectionMode = useCallback((config: ConnectionConfig) => {+ if (hasLoadedInitialMode.current) return;+ setConnectionMode(config.mode);+ lastAppliedMode.current = config.mode;+ hasLoadedInitialMode.current = true;+ }, []);+// Files dropped outside a dropzone must never navigate the webview to the// file (Linux WebKit renders the PDF fullscreen and orphans the app UI).// Dropzone-level handlers run before these window-level listeners, so@@ -86,11 +97,10 @@ export function AppProviders({ children }: { children: ReactNode }) {// Load connection mode on mount and subscribe to future changesuseEffect(() => {- void connectionModeService.getCurrentMode().then((mode) => {- setConnectionMode(mode);- lastAppliedMode.current = mode;- hasLoadedInitialMode.current = true;- });+ void connectionModeService+ .getCurrentConfig()+ .then(initializeConnectionMode)+ .catch(() => setAuthChecked(true));const unsub = connectionModeService.subscribeToModeChanges((config) => {setConnectionMode(config.mode);@@ -112,9 +122,10 @@ export function AppProviders({ children }: { children: ReactNode }) {) {setAppKey((k) => k + 1);}+ hasLoadedInitialMode.current = true;});return unsub;- }, []);+ }, [initializeConnectionMode]);useEffect(() => {// Wait until connection mode is loaded before checking auth@@ -145,7 +156,7 @@ export function AppProviders({ children }: { children: ReactNode }) {const cfg = await connectionModeService.getCurrentConfig().catch(() => null);- if (!cfg?.lock_connection_mode) {+ if (cfg && !cfg.lock_connection_mode && !cfg.require_sign_in) {// JWT expired — fall back to local so local tools still work.await connectionModeService.switchToLocal()@@ -167,7 +178,7 @@ export function AppProviders({ children }: { children: ReactNode }) {const cfg = await connectionModeService.getCurrentConfig().catch(() => null);- if (!cfg?.lock_connection_mode) {+ if (cfg && !cfg.lock_connection_mode && !cfg.require_sign_in) {await connectionModeService.switchToLocal().catch(console.error);setConnectionMode("local");if (!localStorage.getItem(JWT_EXPIRED_PROMPTED_KEY)) {@@ -185,12 +196,13 @@ export function AppProviders({ children }: { children: ReactNode }) {connectionModeService.getCurrentConfig().then(async (cfg) => {- if (cfg.lock_connection_mode && cfg.server_config?.url) {- // Locked provisioned deployment — do NOT switch to local (would clear server_config- // from the store). Show onboarding normally; the sign-in slide handles locked auth.- // Still start the local backend so local tools work while the user signs in.+ if (+ cfg.require_sign_in ||+ (cfg.lock_connection_mode && cfg.server_config?.url)+ ) {+ // Preserve the managed connection; DesktopAccessGate controls access to local tools.await tauriBackendService.startBackend().catch(console.error);- setConnectionMode("selfhosted");+ setConnectionMode(cfg.mode);} else {// Normal first launch — auto-enter local mode.// The onboarding carousel + sign-in slide will be shown inside the main app.@@ -229,7 +241,7 @@ export function AppProviders({ children }: { children: ReactNode }) {const shouldMonitorBackend =setupComplete &&!isFirstLaunch &&- (connectionMode === "saas" || connectionMode === "local");+ (connectionMode === "saas" || connectionMode === "local" || localOnly);useBackendInitializer(shouldMonitorBackend);// Preload endpoint availability for the local bundled backend.@@ -372,29 +384,31 @@ export function AppProviders({ children }: { children: ReactNode }) {}}><DesktopQueryCacheReset />- <SaaSTeamProvider key={appKey}>- <DesktopConfigSync />- <DesktopBannerInitializer />- <SaveShortcutListener />- <LocalProcessingFolders />- <DiskConflictHost />- {children}- {/* Desktop onboarding modal: welcome slide → sign-in slide, shown once on first launch */}- <DesktopOnboardingModal />- {/* SaaS product onboarding (cloud flow, minus the desktop-download slide),+ <DesktopAccessGate onConfigLoaded={initializeConnectionMode}>+ <SaaSTeamProvider key={appKey}>+ <DesktopConfigSync />+ <DesktopBannerInitializer />+ <SaveShortcutListener />+ <LocalProcessingFolders />+ <DiskConflictHost />+ {children}+ {/* Desktop onboarding modal: welcome slide → sign-in slide, shown once on first launch */}+ <DesktopOnboardingModal />+ {/* SaaS product onboarding (cloud flow, minus the desktop-download slide),shown once after a SaaS sign-in. Mirrors saas's OnboardingBootstrap. */}- <DesktopSaasOnboardingBootstrap connectionMode={connectionMode} />- <ClassificationBackgroundRunner />- {/* Always-mounted host for the PAYG usage-limit modals (free-limit /+ <DesktopSaasOnboardingBootstrap connectionMode={connectionMode} />+ <ClassificationBackgroundRunner />+ {/* Always-mounted host for the PAYG usage-limit modals (free-limit /spend-cap). Resolves to the cloud implementation via @app; listensfor both the imperative open events (direct-call 402s) and theusageLimitBridge event (server-side policy/AI run 402s). */}- <UsageLimitModalHost />- {/* Global sign-in modal, opened via stirling:open-sign-in event */}- <SignInModal />- {/* Desktop auto-update popup */}- {updatePopupModal}- </SaaSTeamProvider>+ <UsageLimitModalHost />+ {/* Global sign-in modal, opened via stirling:open-sign-in event */}+ <SignInModal />+ {/* Desktop auto-update popup */}+ {updatePopupModal}+ </SaaSTeamProvider>+ </DesktopAccessGate></ToolActionsContext.Provider></ProprietaryAppProviders>);diff --git a/frontend/editor/src/desktop/components/ConnectionSettings.tsx b/frontend/editor/src/desktop/components/ConnectionSettings.tsxindex 746af00b25..0c245ac05f 100644--- a/frontend/editor/src/desktop/components/ConnectionSettings.tsx+++ b/frontend/editor/src/desktop/components/ConnectionSettings.tsx@@ -62,8 +62,7 @@ export const ConnectionSettings: React.FC = () => {);await authService.logout();}- // Always switch to local after logout so the app remains usable- await connectionModeService.switchToLocal();+ if (!config?.require_sign_in) await connectionModeService.switchToLocal();// Reload configconst newConfig = await connectionModeService.getCurrentConfig();diff --git a/frontend/editor/src/desktop/components/DesktopAccessGate.test.tsx b/frontend/editor/src/desktop/components/DesktopAccessGate.test.tsxnew file mode 100644index 0000000000..1d169958c9--- /dev/null+++ b/frontend/editor/src/desktop/components/DesktopAccessGate.test.tsx@@ -0,0 +1,252 @@+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import { MemoryRouter } from "react-router-dom";+import type { AuthStatus } from "@app/services/authService";+import { DesktopAccessGate } from "@app/components/DesktopAccessGate";+import { QuickNavRailHost } from "@app/components/shared/quickNav/QuickNavRailHost";+import {+ QuickNavHostProvider,+ useRegisterQuickNavView,+} from "@app/contexts/QuickNavHostContext";++const state = vi.hoisted(() => ({+ getConfig: vi.fn(),+ validate: vi.fn(),+ expired: vi.fn(),+ onAuth: (_status: AuthStatus) => {},+}));+vi.mock("@app/services/connectionModeService", () => ({+ connectionModeService: {+ getCurrentConfig: state.getConfig,+ subscribeToModeChanges: () => () => {},+ },+}));+vi.mock("@app/services/authService", () => ({+ authService: {+ getAuthStatus: () => "unauthenticated",+ subscribeToAuth: (listener: (status: AuthStatus) => void) => {+ state.onAuth = listener;+ return () => {};+ },+ hasManagedSession: state.validate,+ getAuthToken: async () => "token",+ isTokenExpiringSoon: state.expired,+ },+}));+vi.mock("@mantine/core", () => ({+ Center: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Stack: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Text: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Loader: () => <div>Loading</div>,+}));+vi.mock("@app/ui/Button", () => ({+ Button: ({+ children,+ onClick,+ }: {+ children: ReactNode;+ onClick: () => void;+ }) => <button onClick={onClick}>{children}</button>,+}));+vi.mock("@app/components/SetupWizard", () => ({+ SetupWizard: () => <div>Required sign-in</div>,+}));+vi.mock("@app/hooks/useConnectedServer", () => ({+ useConnectedServer: () => true,+}));+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => false,+}));+vi.mock("@app/ui/Icon", () => ({ Icon: () => null }));+vi.mock("@app/components/shared/signing/SignMenu", () => ({+ SignMenu: () => null,+}));+vi.mock("@app/components/shared/quickNav/QuickNavRailContainer", () => ({+ QuickNavRailContainer: () => <nav aria-label="App navigation" />,+}));++function WorkbenchWithNavigation() {+ useRegisterQuickNavView({}, {});+ return <div>Workbench</div>;+}++beforeEach(() => {+ state.getConfig.mockReset().mockResolvedValue({+ mode: "saas",+ require_sign_in: true,+ cloud_only: true,+ });+ state.validate.mockReset().mockResolvedValue(false);+ state.expired.mockReset().mockReturnValue(false);+});++it("withholds the workbench even if onboarding was previously completed", async () => {+ localStorage.setItem("stirling-desktop-onboarding-seen.v2", "true");+ render(+ <DesktopAccessGate>+ <div>Workbench</div>+ </DesktopAccessGate>,+ );+ expect(screen.queryByText("Workbench")).toBeNull();+ await screen.findByText("Required sign-in");+ expect(screen.queryByText("Workbench")).toBeNull();+});++it("admits a verified session and removes access on logout", async () => {+ state.validate.mockResolvedValue(true);+ render(+ <DesktopAccessGate>+ <div>Workbench</div>+ </DesktopAccessGate>,+ );+ await screen.findByText("Workbench");+ act(() => state.onAuth("authenticated"));+ state.validate.mockResolvedValue(false);+ act(() => state.onAuth("unauthenticated"));+ await screen.findByText("Required sign-in");+ expect(screen.queryByText("Workbench")).toBeNull();+});++it.each(["logout", "expiry"])(+ "hides the outer sidebar on %s and restores it after sign-in",+ async (reason) => {+ state.validate.mockResolvedValue(true);+ render(+ <MemoryRouter>+ <QuickNavHostProvider>+ <QuickNavRailHost />+ <DesktopAccessGate>+ <WorkbenchWithNavigation />+ </DesktopAccessGate>+ </QuickNavHostProvider>+ </MemoryRouter>,+ );+ await screen.findByRole("navigation", { name: "App navigation" });++ state.validate.mockResolvedValue(false);+ if (reason === "logout") {+ act(() => state.onAuth("unauthenticated"));+ } else {+ state.expired.mockReturnValue(true);+ act(() => window.dispatchEvent(new Event("focus")));+ }+ await screen.findByText("Required sign-in");+ expect(screen.queryByText("Workbench")).toBeNull();+ await waitFor(() => expect(screen.queryByRole("navigation")).toBeNull());++ state.expired.mockReturnValue(false);+ state.validate.mockResolvedValue(true);+ act(() => state.onAuth("authenticated"));+ await screen.findByText("Workbench");+ expect(+ await screen.findByRole("navigation", { name: "App navigation" }),+ ).toBeInTheDocument();+ },+);++it("does not let an in-flight validation reopen access after logout", async () => {+ let resolve: (value: boolean) => void = () => {};+ state.validate.mockReturnValueOnce(+ new Promise<boolean>((done) => {+ resolve = done;+ }),+ );+ render(+ <DesktopAccessGate>+ <div>Workbench</div>+ </DesktopAccessGate>,+ );+ await waitFor(() => expect(state.validate).toHaveBeenCalled());+ act(() => state.onAuth("authenticated"));+ act(() => state.onAuth("unauthenticated"));+ await act(async () => resolve(true));+ await screen.findByText("Required sign-in");+ expect(screen.queryByText("Workbench")).toBeNull();+});++it("allows unmanaged guest use without validating a session", async () => {+ state.getConfig.mockResolvedValue({ mode: "local", require_sign_in: false });+ render(+ <DesktopAccessGate>+ <div>Workbench</div>+ </DesktopAccessGate>,+ );+ await screen.findByText("Workbench");+ expect(state.validate).not.toHaveBeenCalled();+});++it("closes access on expiry even while a refresh request is pending", async () => {+ state.validate+ .mockResolvedValueOnce(true)+ .mockReturnValue(new Promise(() => {}));+ render(+ <DesktopAccessGate>+ <div>Workbench</div>+ </DesktopAccessGate>,+ );+ await screen.findByText("Workbench");+ act(() => window.dispatchEvent(new Event("focus")));+ await waitFor(() => expect(state.validate).toHaveBeenCalledTimes(2));+ state.expired.mockReturnValue(true);+ act(() => window.dispatchEvent(new Event("focus")));+ await screen.findByText("Required sign-in");+ expect(screen.queryByText("Workbench")).toBeNull();+});++it("does not grant access when policy loading fails", async () => {+ state.getConfig.mockRejectedValue(new Error("Unreadable policy"));+ render(+ <DesktopAccessGate>+ <div>Workbench</div>+ </DesktopAccessGate>,+ );+ await screen.findByText("setup.error.policyUnavailable");+ expect(screen.queryByText("Workbench")).toBeNull();+});++it("notifies the parent when a failed policy load succeeds on retry", async () => {+ state.getConfig.mockRejectedValue(new Error("Unreadable policy"));+ const onConfigLoaded = vi.fn();+ render(+ <DesktopAccessGate onConfigLoaded={onConfigLoaded}>+ Workbench+ </DesktopAccessGate>,+ );+ await screen.findByText("setup.error.policyUnavailable");+ expect(onConfigLoaded).not.toHaveBeenCalled();+ const config = { mode: "saas", require_sign_in: true };+ state.getConfig.mockResolvedValue(config);+ fireEvent.click(screen.getByRole("button", { name: "common.retry" }));+ await screen.findByText("Required sign-in");+ expect(onConfigLoaded).toHaveBeenCalledWith(config);+ expect(screen.queryByText("Workbench")).toBeNull();+});++it.each([false, undefined])(+ "shows navigation for unmanaged configs with require_sign_in=%s",+ async (required) => {+ state.getConfig.mockResolvedValue({+ mode: "local",+ require_sign_in: required,+ });+ render(+ <MemoryRouter>+ <QuickNavHostProvider>+ <QuickNavRailHost />+ <DesktopAccessGate>+ <WorkbenchWithNavigation />+ </DesktopAccessGate>+ </QuickNavHostProvider>+ </MemoryRouter>,+ );+ await screen.findByRole("navigation", { name: "App navigation" });+ expect(state.validate).not.toHaveBeenCalled();+ },+);diff --git a/frontend/editor/src/desktop/components/DesktopAccessGate.tsx b/frontend/editor/src/desktop/components/DesktopAccessGate.tsxnew file mode 100644index 0000000000..b70e50d8c1--- /dev/null+++ b/frontend/editor/src/desktop/components/DesktopAccessGate.tsx@@ -0,0 +1,127 @@+import { ReactNode, useEffect, useState } from "react";+import { Center, Loader, Stack, Text } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { Button } from "@app/ui/Button";+import { SetupWizard } from "@app/components/SetupWizard";+import { useSuppressQuickNavRail } from "@app/contexts/QuickNavHostContext";+import { authService } from "@app/services/authService";+import {+ ConnectionConfig,+ connectionModeService,+} from "@app/services/connectionModeService";++/** Withholds the workbench and background file handlers until managed sign-in succeeds. */+export function DesktopAccessGate({+ children,+ onConfigLoaded,+}: {+ children: ReactNode;+ /** Reinitializes the parent after a failed startup config read is retried. */+ onConfigLoaded?: (config: ConnectionConfig) => void;+}) {+ const { t } = useTranslation();+ const [config, setConfig] = useState<ConnectionConfig | null>(null);+ const [configError, setConfigError] = useState(false);+ const [allowed, setAllowed] = useState(false);+ const [checking, setChecking] = useState(true);+ const [revision, setRevision] = useState(0);+ const [authRevision, setAuthRevision] = useState(0);++ // The outer rail survives workbench unmounts, including logout.+ useSuppressQuickNavRail(+ configError ||+ !config ||+ (config.require_sign_in === true && (checking || !allowed)),+ );++ useEffect(+ () =>+ authService.subscribeToAuth((status) => {+ if (status === "unauthenticated") setAllowed(false);+ setAuthRevision((value) => value + 1);+ }),+ [],+ );++ useEffect(() => {+ let cancelled = false;+ void connectionModeService+ .getCurrentConfig()+ .then((value) => {+ if (!cancelled) {+ setConfig(value);+ setConfigError(false);+ onConfigLoaded?.(value);+ }+ })+ .catch(() => {+ if (!cancelled) setConfigError(true);+ });+ const unsubscribe = connectionModeService.subscribeToModeChanges(+ (value) => {+ setAllowed(false);+ setConfig(value);+ },+ );+ return () => {+ cancelled = true;+ unsubscribe();+ };+ }, [revision, onConfigLoaded]);++ useEffect(() => {+ if (!config?.require_sign_in) return;+ let cancelled = false;+ let running = false;+ const check = async () => {+ const token = await authService.getAuthToken().catch(() => null);+ if (cancelled) return;+ if (!token || authService.isTokenExpiringSoon(token, 0))+ setAllowed(false);+ if (running) return;+ running = true;+ const valid = await authService.hasManagedSession().catch(() => false);+ if (!cancelled) {+ setAllowed(valid);+ setChecking(false);+ }+ running = false;+ };+ void check();+ const interval = window.setInterval(() => void check(), 15000);+ window.addEventListener("focus", check);+ window.addEventListener("jwt-available", check);+ return () => {+ cancelled = true;+ window.clearInterval(interval);+ window.removeEventListener("focus", check);+ window.removeEventListener("jwt-available", check);+ };+ }, [config, authRevision, revision]);++ if (configError)+ return (+ <Center h="100%">+ <Stack>+ <Text>+ {t(+ "setup.error.policyUnavailable",+ "Unable to load your organisation's sign-in settings.",+ )}+ </Text>+ <Button onClick={() => setRevision((value) => value + 1)}>+ {t("common.retry", "Retry")}+ </Button>+ </Stack>+ </Center>+ );+ if (!config || (config.require_sign_in && checking))+ return (+ <Center h="100%">+ <Loader />+ </Center>+ );+ if (config.require_sign_in && !allowed)+ return <SetupWizard onComplete={() => setRevision((value) => value + 1)} />;+ return children;+}diff --git a/frontend/editor/src/desktop/components/SetupWizard/SaaSLoginScreen.tsx b/frontend/editor/src/desktop/components/SetupWizard/SaaSLoginScreen.tsxindex a698611d52..16242ca9a9 100644--- a/frontend/editor/src/desktop/components/SetupWizard/SaaSLoginScreen.tsx+++ b/frontend/editor/src/desktop/components/SetupWizard/SaaSLoginScreen.tsx@@ -14,7 +14,7 @@ interface SaaSLoginScreenProps {serverUrl: string;onLogin: (username: string, password: string) => Promise<void>;onOAuthSuccess: (userInfo: UserInfo) => Promise<void>;- onSelfHostedClick: () => void;+ onSelfHostedClick?: () => void;onSwitchToSignup: () => void;onSkipSignIn?: () => void;onClose?: () => void;@@ -121,7 +121,9 @@ export const SaaSLoginScreen: React.FC<SaaSLoginScreenProps> = ({</Button></div>- <SelfHostedLink onClick={onSelfHostedClick} disabled={loading} />+ {onSelfHostedClick && (+ <SelfHostedLink onClick={onSelfHostedClick} disabled={loading} />+ )}{onSkipSignIn && (<divdiff --git a/frontend/editor/src/desktop/components/SetupWizard/index.test.tsx b/frontend/editor/src/desktop/components/SetupWizard/index.test.tsxnew file mode 100644index 0000000000..b05de59f0c--- /dev/null+++ b/frontend/editor/src/desktop/components/SetupWizard/index.test.tsx@@ -0,0 +1,118 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import { SetupWizard } from "@app/components/SetupWizard";++const { getConfig } = vi.hoisted(() => ({ getConfig: vi.fn() }));+vi.mock("@app/services/connectionModeService", () => ({+ connectionModeService: { getCurrentConfig: getConfig },+}));+vi.mock("@app/services/authService", () => ({+ authService: {},+ AuthServiceError: class extends Error {},+}));+vi.mock("@app/services/tauriBackendService", () => ({+ tauriBackendService: {},+}));+vi.mock("@tauri-apps/api/event", () => ({ listen: async () => () => {} }));+vi.mock("@mantine/core", () => {+ const Container = ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ );+ return {+ Center: Container,+ Stack: Container,+ Text: Container,+ Alert: Container,+ Loader: () => <div>Loading</div>,+ };+});+vi.mock("@app/ui/Button", () => ({+ Button: ({+ children,+ onClick,+ }: {+ children: ReactNode;+ onClick: () => void;+ }) => <button onClick={onClick}>{children}</button>,+}));+vi.mock("@app/components/SetupWizard/DesktopAuthLayout", () => ({+ DesktopAuthLayout: ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ ),+}));+vi.mock("@app/components/SetupWizard/SaaSLoginScreen", () => ({+ SaaSLoginScreen: ({+ onSkipSignIn,+ onSelfHostedClick,+ onClose,+ }: {+ onSkipSignIn?: () => void;+ onSelfHostedClick?: () => void;+ onClose?: () => void;+ }) => (+ <div>+ Cloud sign-in{onSkipSignIn && <button>Skip</button>}+ {onSelfHostedClick && <button>Self-hosted</button>}+ {onClose && <button>Close</button>}+ </div>+ ),+}));+vi.mock("@app/components/SetupWizard/SaaSSignupScreen", () => ({+ SaaSSignupScreen: () => null,+}));+vi.mock("@app/components/SetupWizard/ServerSelectionScreen", () => ({+ ServerSelectionScreen: () => null,+}));+vi.mock("@app/components/SetupWizard/SelfHostedLoginScreen", () => ({+ SelfHostedLoginScreen: () => null,+}));+vi.mock("@app/components/shared/DisabledButtonWithTooltip", () => ({+ DisabledButtonWithTooltip: () => null,+}));++beforeEach(() => getConfig.mockReset());++it.each([+ { required: true, cloudOnly: true, skip: false, selfHosted: false },+ { required: true, cloudOnly: false, skip: false, selfHosted: true },+ { required: false, cloudOnly: true, skip: true, selfHosted: false },+ { required: false, cloudOnly: false, skip: true, selfHosted: true },+])(+ "applies independent sign-in policies: %j",+ async ({ required, cloudOnly, skip, selfHosted }) => {+ getConfig.mockResolvedValue({+ mode: "saas",+ lock_connection_mode: false,+ require_sign_in: required,+ cloud_only: cloudOnly,+ });+ render(<SetupWizard onComplete={() => {}} onClose={() => {}} />);+ await screen.findByText("Cloud sign-in");+ expect(!!screen.queryByRole("button", { name: "Skip" })).toBe(skip);+ expect(!!screen.queryByRole("button", { name: "Self-hosted" })).toBe(+ selfHosted,+ );+ expect(!!screen.queryByRole("button", { name: "Close" })).toBe(!required);+ },+);++it("offers policy retries without showing unrestricted sign-in choices", async () => {+ getConfig.mockRejectedValue(new Error("Store unavailable"));+ const onComplete = vi.fn();+ render(<SetupWizard onComplete={onComplete} />);+ await screen.findByText("setup.error.policyUnavailable");+ expect(screen.queryByText("Cloud sign-in")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "common.retry" }));+ await screen.findByText("setup.error.policyUnavailable");+ getConfig.mockResolvedValue({+ mode: "saas",+ require_sign_in: true,+ cloud_only: true,+ });+ fireEvent.click(screen.getByRole("button", { name: "common.retry" }));+ await screen.findByText("Cloud sign-in");+ expect(screen.queryByRole("button", { name: "Skip" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Self-hosted" })).toBeNull();+ expect(onComplete).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/desktop/components/SetupWizard/index.tsx b/frontend/editor/src/desktop/components/SetupWizard/index.tsxindex ea3671c0f6..2e5eaa8381 100644--- a/frontend/editor/src/desktop/components/SetupWizard/index.tsx+++ b/frontend/editor/src/desktop/components/SetupWizard/index.tsx@@ -53,6 +53,10 @@ export const SetupWizard: React.FC<SetupWizardProps> = ({const [selfHostedMfaCode, setSelfHostedMfaCode] = useState("");const [selfHostedMfaRequired, setSelfHostedMfaRequired] = useState(false);const [lockConnectionMode, setLockConnectionMode] = useState(false);+ const [requireSignIn, setRequireSignIn] = useState(false);+ const [cloudOnly, setCloudOnly] = useState(false);+ const [policyLoaded, setPolicyLoaded] = useState(false);+ const [policyError, setPolicyError] = useState(false);const [lockedServerUnreachable, setLockedServerUnreachable] = useState(false);const [lockedServerChecking, setLockedServerChecking] = useState(false);@@ -66,10 +70,7 @@ export const SetupWizard: React.FC<SetupWizardProps> = ({setLoading(true);setError(null);- // Only attempt password login if a password is provided- // If password is empty, assume OAuth login already completed- const isAlreadyAuthenticated = await authService.isAuthenticated();- if (!isAlreadyAuthenticated && password) {+ if (password) {await authService.login(serverConfig.url, username, password);}@@ -134,7 +135,7 @@ export const SetupWizard: React.FC<SetupWizardProps> = ({};const handleSelfHostedClick = () => {- if (lockConnectionMode) {+ if (lockConnectionMode || cloudOnly) {return;}setError(null);@@ -297,6 +298,8 @@ export const SetupWizard: React.FC<SetupWizardProps> = ({return;}+ await connectionModeService.assertSelfHostedAllowed(serverUrl);+setLoading(true);setError(null);@@ -365,7 +368,17 @@ export const SetupWizard: React.FC<SetupWizardProps> = ({};const loadLockedConfig = useCallback(async () => {- const currentConfig = await connectionModeService.getCurrentConfig();+ setPolicyError(false);+ const currentConfig = await connectionModeService+ .getCurrentConfig()+ .catch(() => null);+ if (!currentConfig) {+ setPolicyError(true);+ return;+ }+ setRequireSignIn(currentConfig.require_sign_in ?? false);+ setCloudOnly(currentConfig.cloud_only ?? false);+ setPolicyLoaded(true);if (!currentConfig.lock_connection_mode) return;const serverUrl = currentConfig.server_config?.url;if (!serverUrl) return;@@ -431,6 +444,30 @@ export const SetupWizard: React.FC<SetupWizardProps> = ({void loadLockedConfig();}, [loadLockedConfig]);+ if (policyError)+ return (+ <Center py="xl">+ <Stack>+ <Text>+ {t(+ "setup.error.policyUnavailable",+ "Unable to load your organisation's sign-in settings.",+ )}+ </Text>+ <Button onClick={() => void loadLockedConfig()}>+ {t("common.retry", "Retry")}+ </Button>+ </Stack>+ </Center>+ );++ if (!policyLoaded)+ return (+ <Center py="xl">+ <Loader />+ </Center>+ );+const wizardContent = (<>{/* Step Content */}@@ -439,10 +476,10 @@ export const SetupWizard: React.FC<SetupWizardProps> = ({serverUrl={serverConfig?.url || STIRLING_SAAS_URL}onLogin={handleSaaSLogin}onOAuthSuccess={handleSaaSLoginOAuth}- onSelfHostedClick={handleSelfHostedClick}+ onSelfHostedClick={cloudOnly ? undefined : handleSelfHostedClick}onSwitchToSignup={handleSwitchToSignup}- onSkipSignIn={handleLocalMode}- onClose={onClose}+ onSkipSignIn={requireSignIn ? undefined : handleLocalMode}+ onClose={requireSignIn ? undefined : onClose}loading={loading}error={error}/>@@ -457,13 +494,15 @@ export const SetupWizard: React.FC<SetupWizardProps> = ({/>)}- {!lockConnectionMode && activeStep === SetupStep.ServerSelection && (- <ServerSelectionScreen- onSelect={handleServerSelection}- loading={loading}- error={error}- />- )}+ {!lockConnectionMode &&+ !cloudOnly &&+ activeStep === SetupStep.ServerSelection && (+ <ServerSelectionScreen+ onSelect={handleServerSelection}+ loading={loading}+ error={error}+ />+ )}{lockConnectionMode && lockedServerChecking && (<Center py="xl">@@ -527,17 +566,19 @@ export const SetupWizard: React.FC<SetupWizardProps> = ({)}</Button>)}- <Button- variant="tertiary"- accent="neutral"- fullWidth- onClick={handleLocalMode}- >- {t(- "setup.selfhosted.unreachable.continueOffline",- "Use local tools instead",- )}- </Button>+ {!requireSignIn && (+ <Button+ variant="tertiary"+ accent="neutral"+ fullWidth+ onClick={handleLocalMode}+ >+ {t(+ "setup.selfhosted.unreachable.continueOffline",+ "Use local tools instead",+ )}+ </Button>+ )}</Stack>)}@@ -557,19 +598,24 @@ export const SetupWizard: React.FC<SetupWizardProps> = ({loading={loading}error={error}/>- <div- className="navigation-link-container"- style={{ marginTop: "1.5rem" }}- >- <Button- variant="tertiary"- onClick={handleLocalMode}- className="navigation-link-button"- disabled={loading}+ {!requireSignIn && (+ <div+ className="navigation-link-container"+ style={{ marginTop: "1.5rem" }}>- {t("setup.selfhosted.switchToLocal", "Use local tools instead")}- </Button>- </div>+ <Button+ variant="tertiary"+ onClick={handleLocalMode}+ className="navigation-link-button"+ disabled={loading}+ >+ {t(+ "setup.selfhosted.switchToLocal",+ "Use local tools instead",+ )}+ </Button>+ </div>+ )}</>)}diff --git a/frontend/editor/src/desktop/components/SignInModal.tsx b/frontend/editor/src/desktop/components/SignInModal.tsxindex fec53c213c..966a31b466 100644--- a/frontend/editor/src/desktop/components/SignInModal.tsx+++ b/frontend/editor/src/desktop/components/SignInModal.tsx@@ -37,7 +37,7 @@ export function SignInModal() {><SetupWizardnoLayout- onClose={() => setOpened(false)}+ onClose={locked ? undefined : () => setOpened(false)}onComplete={() => {setOpened(false);// No reload needed — AppProviders remounts the SaaS provider tree viadiff --git a/frontend/editor/src/desktop/components/filesPage/LibraryPrivacy.test.tsx b/frontend/editor/src/desktop/components/filesPage/LibraryPrivacy.test.tsxnew file mode 100644index 0000000000..7b5a7bc6bd--- /dev/null+++ b/frontend/editor/src/desktop/components/filesPage/LibraryPrivacy.test.tsx@@ -0,0 +1,49 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { expect, test, vi } from "vitest";+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => true,+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),+}));+import { LibraryTabs } from "@app/components/filesPage/LibraryTabs";+import { SignMenu } from "@app/components/shared/signing/SignMenu";++test("keeps local files accessible without offering Stirling library or shared files", () => {+ render(+ <MantineProvider>+ <LibraryTabs+ currentTab="recent"+ onChange={() => {}}+ onOpenRoot={() => {}}+ sharingEnabled+ />+ </MantineProvider>,+ );+ expect(screen.getByRole("button", { name: "Local files" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Recents" })).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Stirling library" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Shared with you" })).toBeNull();+});++test("hides shared signing while retaining local personal signing", () => {+ const select = vi.fn();+ render(+ <SignMenu+ opened+ onClose={() => {}}+ onSelect={select}+ onOpenSigning={() => {}}+ reasons={{}}+ items={[]}+ >+ <button>Sign</button>+ </SignMenu>,+ );+ expect(+ screen.queryByRole("button", { name: "Request signatures" }),+ ).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: /Personal signature/ }));+ expect(select).toHaveBeenCalledWith("sign");+});diff --git a/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.test.ts b/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.test.tsindex f561303ec3..bacd0ee841 100644--- a/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.test.ts+++ b/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.test.ts@@ -77,3 +77,6 @@ describe("desktop notification availability", () => {expect(result.current).toBe(false);});});+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => false,+}));diff --git a/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.ts b/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.tsindex 9ecc2c30cb..ed443646bc 100644--- a/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.ts+++ b/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.ts@@ -1,8 +1,10 @@import { useEffect, useState } from "react";import { connectionModeService } from "@app/services/connectionModeService";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";/** The bundled backend has no notification API; wait for the mode before polling. */export function useNotificationsAvailable(): boolean {+ const localOnly = useLocalProcessingOnly();const [available, setAvailable] = useState(false);useEffect(() => {@@ -20,5 +22,5 @@ export function useNotificationsAvailable(): boolean {};}, []);- return available;+ return available && !localOnly;}diff --git a/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.test.ts b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.test.tsindex 1b5553348e..e7f07ede55 100644--- a/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.test.ts+++ b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.test.ts@@ -3,11 +3,15 @@ import { beforeEach, describe, expect, test, vi } from "vitest";import type { AuthStatus } from "@app/services/authService";import type { ConnectionMode } from "@app/services/connectionModeService";const state = vi.hoisted(() => ({+ localOnly: false,mode: "local" as ConnectionMode,authenticated: false,authListener: (_status: AuthStatus, _user?: { username: string }) => {},modeListener: () => {},}));+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => state.localOnly,+}));vi.mock("@app/services/authService", () => ({authService: {isAuthenticated: vi.fn(async () => state.authenticated),@@ -32,6 +36,7 @@ import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled"describe("desktop automation availability", () => {beforeEach(() => {+ state.localOnly = false;state.mode = "local";state.authenticated = false;});@@ -63,6 +68,14 @@ describe("desktop automation availability", () => {await act(async () => {});expect(result.current).toBe(false);});+ test("managed document privacy disables automation for a signed-in SaaS user", async () => {+ state.localOnly = true;+ state.mode = "saas";+ state.authenticated = true;+ const { result } = renderHook(usePoliciesEnabled);+ await act(async () => {});+ expect(result.current).toBe(false);+ });test("token refresh does not unmount active processing", async () => {state.mode = "saas";state.authenticated = true;diff --git a/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.tsindex 08be559ee1..e59bd44644 100644--- a/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts+++ b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts@@ -1,6 +1,9 @@import { useConnectedServer } from "@app/hooks/useConnectedServer";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";/** Automation requires a confirmed server connection and session. */export function usePoliciesEnabled(): boolean {- return useConnectedServer();+ const connected = useConnectedServer();+ const localOnly = useLocalProcessingOnly();+ return connected && !localOnly;}diff --git a/frontend/editor/src/desktop/components/tools/convert/ConvertSettings.test.tsx b/frontend/editor/src/desktop/components/tools/convert/ConvertSettings.test.tsxnew file mode 100644index 0000000000..330d6aa1c3--- /dev/null+++ b/frontend/editor/src/desktop/components/tools/convert/ConvertSettings.test.tsx@@ -0,0 +1,70 @@+import { beforeEach, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import ConvertSettings from "@app/components/tools/convert/ConvertSettings";+import { defaultParameters } from "@app/hooks/tools/convert/useConvertParameters";++const state = vi.hoisted(() => ({ localOnly: true }));+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => state.localOnly,+}));+vi.mock("@app/contexts/PreferencesContext", () => ({+ usePreferences: () => ({+ preferences: { hideUnavailableConversions: false },+ }),+}));+vi.mock("@app/hooks/useEndpointConfig", () => ({+ useMultipleEndpointsEnabled: () => ({+ endpointStatus: {+ "pdf-to-img": true,+ "pdf-to-word": false,+ "file-to-pdf": false,+ },+ }),+}));+vi.mock("@app/hooks/useConversionCloudStatus", () => ({+ useConversionCloudStatus: () => ({+ availability: {},+ cloudStatus: {},+ localOnly: {},+ }),+}));+vi.mock("@app/ui/Icon", () => ({ Icon: () => null }));++beforeEach(() => {+ state.localOnly = true;+});++function renderSettings() {+ return render(+ <MantineProvider>+ <ConvertSettings+ parameters={{ ...defaultParameters, fromExtension: "pdf" }}+ onParameterChange={vi.fn()}+ />+ </MantineProvider>,+ );+}++it.each([+ ["from", "pdf"],+ ["to", "png"],+])(+ "removes unsupported %s formats under privacy even when the preference is off",+ async (direction, supported) => {+ renderSettings();+ fireEvent.click(screen.getByTestId(`convert-${direction}-dropdown`));+ expect(+ await screen.findByTestId(`format-option-${supported}`),+ ).toBeEnabled();+ expect(screen.queryByTestId("format-option-docx")).toBeNull();+ },+);++it("keeps disabled formats visible when privacy and the hiding preference are off", async () => {+ state.localOnly = false;+ renderSettings();+ fireEvent.click(screen.getByTestId("convert-to-dropdown"));+ expect(await screen.findByTestId("format-option-docx")).toBeDisabled();+ expect(screen.getByTestId("format-option-png")).toBeEnabled();+});diff --git a/frontend/editor/src/desktop/components/tools/toolPicker/ToolButton.tsx b/frontend/editor/src/desktop/components/tools/toolPicker/ToolButton.tsxindex 39b71f9d38..522f2e0874 100644--- a/frontend/editor/src/desktop/components/tools/toolPicker/ToolButton.tsx+++ b/frontend/editor/src/desktop/components/tools/toolPicker/ToolButton.tsx@@ -6,6 +6,7 @@ import {useToolWorkflowData,} from "@app/contexts/ToolWorkflowContext";import { useAppConfig } from "@app/contexts/AppConfigContext";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import {connectionModeService,type ConnectionMode,@@ -24,6 +25,7 @@ const ToolButton: React.FC<CoreToolButtonProps> = (props) => {const { toolAvailability } = useToolWorkflowData();const { handleToolSelectForced } = useToolWorkflowActions();const { config } = useAppConfig();+ const localOnly = useLocalProcessingOnly();const premiumEnabled = config?.premiumEnabled;const [connectionMode, setConnectionMode] = useState<ConnectionMode | null>(null,@@ -48,12 +50,14 @@ const ToolButton: React.FC<CoreToolButtonProps> = (props) => {// user can see the settings; the disabled execute button handles the sign-in prompt.// comingSoon and selfHostedOffline tools remain dimmed — they have no usable UI to show.const handleUnavailableClick =+ !localOnly &&connectionMode === "local" &&disabledReason !== "comingSoon" &&disabledReason !== "selfHostedOffline"? () => handleToolSelectForced(props.id): undefined;+ if (localOnly && props.tool.hiddenFromToolList) return null;return (<CoreToolButton {...props} onUnavailableClick={handleUnavailableClick} />);diff --git a/frontend/editor/src/desktop/contexts/AppConfigContext.test.tsx b/frontend/editor/src/desktop/contexts/AppConfigContext.test.tsxnew file mode 100644index 0000000000..a250b442a7--- /dev/null+++ b/frontend/editor/src/desktop/contexts/AppConfigContext.test.tsx@@ -0,0 +1,42 @@+import { renderHook } from "@testing-library/react";+import { expect, test, vi } from "vitest";++const state = vi.hoisted(() => ({ localOnly: true }));+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => state.localOnly,+}));+vi.mock("@core/contexts/AppConfigContext", () => ({+ AppConfigProvider: () => null,+ useAppConfig: () => ({+ config: {+ storageEnabled: true,+ storageSharingEnabled: true,+ storageShareLinksEnabled: true,+ storageGroupSigningEnabled: true,+ aiEngineEnabled: true,+ enableMobileScanner: true,+ enableMobileSignature: true,+ premiumEnabled: true,+ },+ }),+}));+import { useAppConfig } from "@app/contexts/AppConfigContext";++test("managed privacy overrides server document features while preserving account capabilities", () => {+ state.localOnly = true;+ const { result, rerender } = renderHook(useAppConfig);+ expect(result.current.config).toMatchObject({+ storageEnabled: false,+ storageSharingEnabled: false,+ storageShareLinksEnabled: false,+ storageGroupSigningEnabled: false,+ aiEngineEnabled: false,+ enableMobileScanner: false,+ enableMobileSignature: false,+ premiumEnabled: true,+ });+ state.localOnly = false;+ rerender();+ expect(result.current.config?.storageEnabled).toBe(true);+ expect(result.current.config?.storageGroupSigningEnabled).toBe(true);+});diff --git a/frontend/editor/src/desktop/contexts/AppConfigContext.tsx b/frontend/editor/src/desktop/contexts/AppConfigContext.tsxnew file mode 100644index 0000000000..3372b3bd2f--- /dev/null+++ b/frontend/editor/src/desktop/contexts/AppConfigContext.tsx@@ -0,0 +1,37 @@+import { useMemo } from "react";+import { useAppConfig as useCoreAppConfig } from "@core/contexts/AppConfigContext";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";++export { AppConfigProvider } from "@core/contexts/AppConfigContext";+export type {+ AppConfig,+ AppConfigProviderProps,+ AppConfigRetryOptions,+ AppConfigBootstrapMode,+} from "@core/contexts/AppConfigContext";++/** The managed device policy takes precedence over server feature flags and cached config. */+export function useAppConfig() {+ const context = useCoreAppConfig();+ const localOnly = useLocalProcessingOnly();+ return useMemo(+ () =>+ !localOnly || !context.config+ ? context+ : {+ ...context,+ config: {+ ...context.config,+ storageEnabled: false,+ storageSharingEnabled: false,+ storageShareLinksEnabled: false,+ storageShareEmailEnabled: false,+ storageGroupSigningEnabled: false,+ aiEngineEnabled: false,+ enableMobileScanner: false,+ enableMobileSignature: false,+ },+ },+ [context, localOnly],+ );+}diff --git a/frontend/editor/src/desktop/data/useTranslatedToolRegistry.test.tsx b/frontend/editor/src/desktop/data/useTranslatedToolRegistry.test.tsxnew file mode 100644index 0000000000..3ad1d68f15--- /dev/null+++ b/frontend/editor/src/desktop/data/useTranslatedToolRegistry.test.tsx@@ -0,0 +1,61 @@+import { renderHook } from "@testing-library/react";+import { expect, test, vi } from "vitest";+const state = vi.hoisted(() => ({+ localOnly: true,+ status: {} as Record<string, boolean>,+}));+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => state.localOnly,+}));+vi.mock("@app/hooks/useEndpointConfig", () => ({+ useMultipleEndpointsEnabled: () => ({ endpointStatus: state.status }),+}));+vi.mock("@core/data/useTranslatedToolRegistry", () => {+ const tools = {+ merge: { name: "Merge", endpoints: ["merge-pdfs"] },+ ocr: { name: "OCR", endpoints: ["ocr-pdf"] },+ convert: { name: "Convert", endpoints: ["pdf-to-img", "pdf-to-word"] },+ };+ const catalog = {+ allTools: tools,+ regularTools: tools,+ superTools: {},+ linkTools: {},+ };+ return { useTranslatedToolCatalog: () => catalog };+});+import { useTranslatedToolCatalog } from "@app/data/useTranslatedToolRegistry";+import { filterToolRegistryByQuery } from "@app/utils/toolSearch";++test("catalogue and search hide unavailable tools but keep conversions with a local format", () => {+ state.localOnly = true;+ state.status = {};+ const { result, rerender } = renderHook(useTranslatedToolCatalog);+ expect(filterToolRegistryByQuery(result.current.regularTools, "")).toEqual(+ [],+ );+ state.status = {+ "merge-pdfs": true,+ "ocr-pdf": false,+ "pdf-to-img": true,+ "pdf-to-word": false,+ };+ rerender();+ expect(+ filterToolRegistryByQuery(result.current.regularTools, "").map(+ ({ item }) => item[0],+ ),+ ).toEqual(["merge", "convert"]);+ expect(+ filterToolRegistryByQuery(result.current.regularTools, "OCR").map(+ ({ item }) => item[0],+ ),+ ).not.toContain("ocr");+ state.localOnly = false;+ rerender();+ expect(+ filterToolRegistryByQuery(result.current.regularTools, "OCR").map(+ ({ item }) => item[0],+ ),+ ).toContain("ocr");+});diff --git a/frontend/editor/src/desktop/data/useTranslatedToolRegistry.tsx b/frontend/editor/src/desktop/data/useTranslatedToolRegistry.tsxnew file mode 100644index 0000000000..79481263d4--- /dev/null+++ b/frontend/editor/src/desktop/data/useTranslatedToolRegistry.tsx@@ -0,0 +1,58 @@+import { useMemo } from "react";+import {+ useTranslatedToolCatalog as useCoreCatalog,+ type TranslatedToolCatalog,+} from "@core/data/useTranslatedToolRegistry";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";+import { useMultipleEndpointsEnabled } from "@app/hooks/useEndpointConfig";+import type { ToolRegistryEntry } from "@app/data/toolsTaxonomy";++export type { TranslatedToolCatalog } from "@core/data/useTranslatedToolRegistry";++/** Hide server-only tools from every catalogue consumer, including search and favourites. */+export function useTranslatedToolCatalog(): TranslatedToolCatalog {+ const catalog = useCoreCatalog();+ const localOnly = useLocalProcessingOnly();+ const endpoints = useMemo(+ () =>+ localOnly+ ? [+ ...new Set(+ Object.values(catalog.allTools).flatMap(+ (tool) => tool.endpoints ?? [],+ ),+ ),+ ]+ : [],+ [catalog, localOnly],+ );+ const { endpointStatus } = useMultipleEndpointsEnabled(endpoints);+ return useMemo(() => {+ if (!localOnly) return catalog;+ const restrict = <T extends Record<string, ToolRegistryEntry>>(+ registry: T,+ ): T =>+ Object.fromEntries(+ Object.entries(registry).map(([id, tool]) => [+ id,+ {+ ...tool,+ hiddenFromToolList:+ tool.hiddenFromToolList ||+ Boolean(+ tool.endpoints?.length &&+ !tool.endpoints.some(+ (endpoint) => endpointStatus[endpoint] === true,+ ),+ ),+ },+ ]),+ ) as T;+ return {+ allTools: restrict(catalog.allTools),+ regularTools: restrict(catalog.regularTools),+ superTools: restrict(catalog.superTools),+ linkTools: catalog.linkTools,+ };+ }, [catalog, endpointStatus, localOnly]);+}diff --git a/frontend/editor/src/desktop/extensions/accountLogout.ts b/frontend/editor/src/desktop/extensions/accountLogout.tsindex 76eab02f07..83bfb9b429 100644--- a/frontend/editor/src/desktop/extensions/accountLogout.ts+++ b/frontend/editor/src/desktop/extensions/accountLogout.ts@@ -34,8 +34,8 @@ export function useAccountLogout() {) {localStorage.setItem("server_url", currentConfig.server_config.url);}- // Always switch to local after logout so the app remains usable- await connectionModeService.switchToLocal();+ if (!currentConfig.require_sign_in)+ await connectionModeService.switchToLocal();window.history.replaceState({}, "", "/");// No reload needed — AppProviders remounts the SaaS provider tree viadiff --git a/frontend/editor/src/desktop/extensions/platformSessionBridge.test.ts b/frontend/editor/src/desktop/extensions/platformSessionBridge.test.tsnew file mode 100644index 0000000000..caffdbceda--- /dev/null+++ b/frontend/editor/src/desktop/extensions/platformSessionBridge.test.ts@@ -0,0 +1,67 @@+import { beforeEach, expect, it, vi } from "vitest";+import { refreshPlatformSession } from "@app/extensions/platformSessionBridge";++const state = vi.hoisted(() => ({+ mode: vi.fn(),+ refresh: vi.fn(),+ token: vi.fn(),+ expired: vi.fn(),+ verified: vi.fn(),+}));+vi.mock("@app/services/connectionModeService", () => ({+ connectionModeService: {+ getCurrentMode: state.mode,+ getServerConfig: async () => ({ url: "https://self.example.org" }),+ },+}));+vi.mock("@app/services/authService", () => ({+ authService: {+ refreshSupabaseToken: state.refresh,+ refreshToken: state.refresh,+ getAuthToken: state.token,+ isTokenExpiringSoon: state.expired,+ hasManagedSession: state.verified,+ },+}));++beforeEach(() => {+ vi.resetAllMocks();+ state.mode.mockResolvedValue("saas");+ state.refresh.mockResolvedValue(false);+ state.token.mockResolvedValue("token");+ state.expired.mockReturnValue(false);+ state.verified.mockResolvedValue(true);+});++it.each(["saas", "selfhosted"])(+ "keeps a verified %s session usable by the auth client after a temporary refresh failure",+ async (mode) => {+ state.mode.mockResolvedValue(mode);+ expect(await refreshPlatformSession()).toBe(true);+ expect(state.expired).toHaveBeenCalledWith("token", 0);+ expect(state.verified).toHaveBeenCalledOnce();+ },+);++it("does not preserve an expired session", async () => {+ state.expired.mockReturnValue(true);+ expect(await refreshPlatformSession()).toBe(false);+ expect(state.verified).not.toHaveBeenCalled();+});++it("does not preserve a session whose credentials were cleared", async () => {+ state.token.mockResolvedValue(null);+ expect(await refreshPlatformSession()).toBe(false);+ expect(state.verified).not.toHaveBeenCalled();+});++it("does not admit an unverified session during an outage", async () => {+ state.verified.mockResolvedValue(false);+ expect(await refreshPlatformSession()).toBe(false);+});++it("accepts successful refreshes without a fallback check", async () => {+ state.refresh.mockResolvedValue(true);+ expect(await refreshPlatformSession()).toBe(true);+ expect(state.verified).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/desktop/extensions/platformSessionBridge.ts b/frontend/editor/src/desktop/extensions/platformSessionBridge.tsindex 58909d95aa..aa297828e2 100644--- a/frontend/editor/src/desktop/extensions/platformSessionBridge.ts+++ b/frontend/editor/src/desktop/extensions/platformSessionBridge.ts@@ -117,19 +117,29 @@ export async function getPlatformSessionUser(): Promise<PlatformSessionUser | nu};}+/** Keeps a verified, unexpired session usable when a refresh fails temporarily. */export async function refreshPlatformSession(): Promise<boolean> {try {const mode = await connectionModeService.getCurrentMode();+ let refreshed: boolean;if (mode === "saas") {- return await authService.refreshSupabaseToken(STIRLING_SAAS_URL);+ refreshed = await authService.refreshSupabaseToken(STIRLING_SAAS_URL);} else if (mode === "selfhosted") {const serverConfig = await connectionModeService.getServerConfig();if (!serverConfig) {return false;}- return await authService.refreshToken(serverConfig.url);+ refreshed = await authService.refreshToken(serverConfig.url);+ } else {+ return false;}- return false;+ if (refreshed) return true;+ const token = await authService.getAuthToken();+ return (+ !!token &&+ !authService.isTokenExpiringSoon(token, 0) &&+ (await authService.hasManagedSession())+ );} catch {return false;}diff --git a/frontend/editor/src/desktop/hooks/useBackendHealth.ts b/frontend/editor/src/desktop/hooks/useBackendHealth.tsindex ae77eca3d0..bd7dc0925f 100644--- a/frontend/editor/src/desktop/hooks/useBackendHealth.ts+++ b/frontend/editor/src/desktop/hooks/useBackendHealth.ts@@ -4,6 +4,7 @@ import { selfHostedServerMonitor } from "@app/services/selfHostedServerMonitor";import { tauriBackendService } from "@app/services/tauriBackendService";import { connectionModeService } from "@app/services/connectionModeService";import type { BackendHealthState } from "@app/types/backendHealth";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";/*** Hook to read backend health state for UI (Run button, BackendHealthIndicator).@@ -19,6 +20,7 @@ import type { BackendHealthState } from "@app/types/backendHealth";* - Self-hosted mode (server offline, local port unknown): false*/export function useBackendHealth() {+ const localOnly = useLocalProcessingOnly();const [health, setHealth] = useState<BackendHealthState>(() =>backendHealthMonitor.getSnapshot(),);@@ -58,7 +60,7 @@ export function useBackendHealth() {}, []);const isOnline =- connectionMode === "selfhosted"+ !localOnly && connectionMode === "selfhosted"? serverStatus !== "offline" || !!localUrl: health.isOnline;diff --git a/frontend/editor/src/desktop/hooks/useConversionCloudStatus.ts b/frontend/editor/src/desktop/hooks/useConversionCloudStatus.tsindex 3a83a61f4d..d47f674a5d 100644--- a/frontend/editor/src/desktop/hooks/useConversionCloudStatus.ts+++ b/frontend/editor/src/desktop/hooks/useConversionCloudStatus.ts@@ -1,10 +1,12 @@-import { useState, useEffect } from "react";+import { useState, useEffect, useMemo } from "react";import { connectionModeService } from "@app/services/connectionModeService";import { endpointAvailabilityService } from "@app/services/endpointAvailabilityService";import { tauriBackendService } from "@app/services/tauriBackendService";import { selfHostedServerMonitor } from "@app/services/selfHostedServerMonitor";import { EXTENSION_TO_ENDPOINT } from "@app/constants/convertConstants";import { getEndpointName } from "@app/utils/convertUtils";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";+import { useMultipleEndpointsEnabled } from "@app/hooks/useEndpointConfig";/*** Comprehensive conversion status data@@ -21,13 +23,48 @@ export interface ConversionStatus {* @returns Object with availability, cloudStatus, and localOnly maps*/export function useConversionCloudStatus(): ConversionStatus {+ const localProcessingOnly = useLocalProcessingOnly();+ const endpoints = useMemo(+ () =>+ localProcessingOnly+ ? [+ ...new Set(+ Object.values(EXTENSION_TO_ENDPOINT).flatMap(Object.values),+ ),+ ]+ : [],+ [localProcessingOnly],+ );+ const { endpointStatus } = useMultipleEndpointsEnabled(endpoints);+ // Share readiness-gated checks with the tool catalogue: early probes can cache+ // disabled conversions while the bundled backend is still starting.+ const localStatus = useMemo<ConversionStatus | null>(() => {+ if (!localProcessingOnly) return null;+ const availability: Record<string, boolean> = {};+ const cloudStatus: Record<string, boolean> = {};+ const localOnly: Record<string, boolean> = {};+ for (const [from, targets] of Object.entries(EXTENSION_TO_ENDPOINT)) {+ for (const [to, endpoint] of Object.entries(targets)) {+ const key = `${from}-${to}`;+ availability[key] = endpointStatus[endpoint] !== false;+ cloudStatus[key] = false;+ localOnly[key] = availability[key];+ }+ }+ return { availability, cloudStatus, localOnly };+ }, [endpointStatus, localProcessingOnly]);const [status, setStatus] = useState<ConversionStatus>({- availability: {},+ availability: Object.fromEntries(+ Object.entries(EXTENSION_TO_ENDPOINT).flatMap(([from, targets]) =>+ Object.keys(targets).map((to) => [`${from}-${to}`, false]),+ ),+ ),cloudStatus: {},localOnly: {},});useEffect(() => {+ if (localProcessingOnly) return;const checkConversions = async () => {const mode = await connectionModeService.getCurrentMode();@@ -179,7 +216,7 @@ export function useConversionCloudStatus(): ConversionStatus {unsubLocal();unsubServer();};- }, []);+ }, [localProcessingOnly]);- return status;+ return localStatus ?? status;}diff --git a/frontend/editor/src/desktop/hooks/useEndpointConfig.test.tsx b/frontend/editor/src/desktop/hooks/useEndpointConfig.test.tsxindex 25935acd49..baa4a3adcd 100644--- a/frontend/editor/src/desktop/hooks/useEndpointConfig.test.tsx+++ b/frontend/editor/src/desktop/hooks/useEndpointConfig.test.tsx@@ -16,6 +16,7 @@ import {useMultipleEndpointsEnabled,} from "@app/hooks/useEndpointConfig";import apiClient from "@app/services/apiClient";+import { useConversionCloudStatus } from "@app/hooks/useConversionCloudStatus";/*** Characterisation tests for the desktop endpoint-availability hooks. They@@ -48,14 +49,18 @@ const mockGet = apiClient.get as unknown as Mock;// --- connection mode ---let mode: "saas" | "selfhosted" | "local" = "saas";+let localProcessingOnly = false;vi.mock("@app/services/connectionModeService", () => ({connectionModeService: {+ getCachedLocalProcessingOnly: () => localProcessingOnly,+ subscribeToModeChanges: () => () => {},getCurrentMode: () => Promise.resolve(mode),getCurrentConfig: () =>Promise.resolve({mode,server_config: null,lock_connection_mode: false,+ local_processing_only: localProcessingOnly,}),},}));@@ -127,6 +132,7 @@ function availability(map: Record<string, { enabled: boolean }>) {beforeEach(() => {vi.clearAllMocks();+ localProcessingOnly = false;mode = "saas";backendStatus = "healthy";backendUrl = "http://127.0.0.1:8080";@@ -135,6 +141,74 @@ beforeEach(() => {selfHostedListeners.clear();});+describe("managed document privacy", () => {+ it("offers local tools immediately, then removes unsupported tools without SaaS fallback", async () => {+ localProcessingOnly = true;+ mockLocalSupport.mockImplementation(+ async (endpoint: string) => endpoint === "merge",+ );+ const { result } = renderHook(+ () => useMultipleEndpointsEnabled(["merge", "ocr", "timestamp-pdf"]),+ { wrapper: TestQueryProvider },+ );+ expect(result.current.endpointStatus.ocr).toBe(true);+ expect(result.current.endpointStatus["timestamp-pdf"]).toBe(false);+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.endpointStatus).toEqual({+ merge: true,+ ocr: false,+ "timestamp-pdf": false,+ });+ expect(mockGet).not.toHaveBeenCalled();+ });+ it("offers local conversions while the backend is starting", () => {+ localProcessingOnly = true;+ backendStatus = "starting";+ const { result } = renderHook(() => useEndpointEnabled("pdf-to-word"), {+ wrapper: TestQueryProvider,+ });+ expect(result.current.enabled).toBe(true);+ expect(mockGet).not.toHaveBeenCalled();+ });++ it.each(["saas", "selfhosted"] as const)(+ "shows tools during %s startup and updates conversion formats without refreshing",+ async (connectionMode) => {+ mode = connectionMode;+ selfHostedStatus = connectionMode === "selfhosted" ? "offline" : "online";+ localProcessingOnly = true;+ backendStatus = "starting";+ mockLocalSupport.mockImplementation(+ async (endpoint: string) =>+ endpoint === "merge" || endpoint === "pdf-to-img",+ );+ const { result } = renderHook(+ () => ({+ tools: useMultipleEndpointsEnabled(["merge", "timestamp-pdf"]),+ conversions: useConversionCloudStatus(),+ }),+ { wrapper: TestQueryProvider },+ );+ expect(result.current.tools.endpointStatus.merge).toBe(true);+ expect(result.current.tools.endpointStatus["timestamp-pdf"]).toBe(false);+ expect(result.current.conversions.availability["pdf-png"]).toBe(true);+ await act(async () => {});+ expect(mockLocalSupport).not.toHaveBeenCalled();++ setBackendStatus("healthy");+ await waitFor(() =>+ expect(result.current.conversions.availability["pdf-docx"]).toBe(false),+ );+ expect(result.current.tools.endpointStatus.merge).toBe(true);+ expect(result.current.conversions.availability["pdf-png"]).toBe(true);+ expect(+ Object.values(result.current.conversions.cloudStatus),+ ).not.toContain(true);+ expect(mockGet).not.toHaveBeenCalled();+ },+ );+});+afterEach(() => {vi.useRealTimers();});diff --git a/frontend/editor/src/desktop/hooks/useEndpointConfig.ts b/frontend/editor/src/desktop/hooks/useEndpointConfig.tsindex b8cce7af48..d23655ae47 100644--- a/frontend/editor/src/desktop/hooks/useEndpointConfig.ts+++ b/frontend/editor/src/desktop/hooks/useEndpointConfig.ts@@ -11,6 +11,8 @@ import { tauriBackendService } from "@app/services/tauriBackendService";import { selfHostedServerMonitor } from "@app/services/selfHostedServerMonitor";import { isBackendNotReadyError } from "@app/constants/backendErrors";import { connectionModeService } from "@app/services/connectionModeService";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";+import { isOffDeviceEndpointName } from "@app/services/documentPrivacyService";import { qk } from "@app/query/keys";import { CONFIG_STALE_TIME } from "@app/query/staleTime";import {@@ -41,18 +43,20 @@ const getBackendOnline = () => tauriBackendService.isOnline;const getOffline = () => isSelfHostedOffline();/**- * When the desktop backend is reachable: either the bundled backend is healthy,- * or the self-hosted server is offline but the local one answers. A query only- * runs once this is true, and a change re-runs it — which is how a reconnect- * swaps the offline local-check answer for the live remote one.+ * Capability probes wait for the bundled backend under managed privacy. Other+ * modes also allow self-hosted offline fallback; reconnects refresh that answer.*/-function useBackendReadiness() {+function useBackendReadiness(localOnly: boolean) {const backendOnline = useSyncExternalStore(subscribeReadiness,getBackendOnline,);const offline = useSyncExternalStore(subscribeReadiness, getOffline);- return { ready: backendOnline || offline, backendOnline, offline };+ return {+ ready: backendOnline || (!localOnly && offline),+ backendOnline,+ offline,+ };}const retryWhileStarting = (_count: number, error: unknown) =>@@ -66,8 +70,9 @@ export function useEndpointEnabled(endpoint: string): {refetch: () => Promise<void>;} {const queryClient = useQueryClient();- const { ready, backendOnline, offline } = useBackendReadiness();- const queryKey = qk.endpointEnabled(endpoint);+ const localOnly = useLocalProcessingOnly();+ const { ready, backendOnline, offline } = useBackendReadiness(localOnly);+ const queryKey = [...qk.endpointEnabled(endpoint), localOnly];const { data, refetch } = useQuery({queryKey,@@ -89,8 +94,9 @@ export function useEndpointEnabled(endpoint: string): {}, [readinessMark]);return {- enabled: endpoint ? (data ?? true) : null,- // Optimistic by design: the desktop endpoint check never blocks the UI.+ enabled: endpoint+ ? (data ?? (!localOnly || !isOffDeviceEndpointName(endpoint)))+ : null,loading: false,error: null,refetch: useCallback(async () => {@@ -107,7 +113,8 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {refetch: () => Promise<void>;} {const queryClient = useQueryClient();- const { ready, backendOnline, offline } = useBackendReadiness();+ const localOnly = useLocalProcessingOnly();+ const { ready, backendOnline, offline } = useBackendReadiness(localOnly);const wanted = endpoints ?? [];const key = wanted.join(",");// Keyed by the endpoint set, not shared across consumers. A constant key@@ -116,7 +123,7 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {// resolve only the endpoints they were handed. Consumers pass disjoint sets,// so a shared entry would leave the second consumer's endpoints unresolved// and reading as available. Prefix invalidation below still covers every set.- const queryKey = [...qk.endpointsAvailability(), key];+ const queryKey = [...qk.endpointsAvailability(), key, localOnly];const { data, isPending, refetch } = useQuery({queryKey,@@ -143,16 +150,18 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {const projected = useMemo(() => {const status: Record<string, boolean> = {};const details: Record<string, EndpointAvailabilityDetails> = {};- if (!data) return { status, details };+ if (!data && !localOnly) return { status, details };for (const endpoint of key ? key.split(",") : []) {- // Safe because the entry is per-set: a miss here means the server does- // not know the endpoint, which the old code also treated as available.- const detail = data[endpoint] ?? OPTIMISTIC;+ const detail =+ data?.[endpoint] ??+ (localOnly && isOffDeviceEndpointName(endpoint)+ ? { enabled: false, reason: "NOT_SUPPORTED_LOCALLY" as const }+ : OPTIMISTIC);status[endpoint] = detail.enabled;details[endpoint] = detail;}return { status, details };- }, [data, key]);+ }, [data, key, localOnly]);return {endpointStatus: projected.status,@@ -181,7 +190,11 @@ export function useEndpointConfig(): EndpointConfig {connectionModeService.getCurrentConfig().then((config) => {- if (config.mode === "selfhosted" && config.server_config?.url) {+ if (+ !config.local_processing_only &&+ config.mode === "selfhosted" &&+ config.server_config?.url+ ) {setBackendUrl(config.server_config.url);} else {// SaaS mode - use default from env vars (local backend)diff --git a/frontend/editor/src/desktop/hooks/useGroupEnabled.test.tsx b/frontend/editor/src/desktop/hooks/useGroupEnabled.test.tsxindex cf21191e6b..38ececc67b 100644--- a/frontend/editor/src/desktop/hooks/useGroupEnabled.test.tsx+++ b/frontend/editor/src/desktop/hooks/useGroupEnabled.test.tsx@@ -5,6 +5,10 @@ import { useGroupEnabled } from "@app/hooks/useGroupEnabled";import { fetchGroupEnabled } from "@app/api/config";vi.mock("@app/api/config", () => ({ fetchGroupEnabled: vi.fn() }));+const privacy = vi.hoisted(() => ({ localOnly: false }));+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => privacy.localOnly,+}));vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (_k: string, fallback: string) => fallback }),@@ -37,11 +41,23 @@ const mockFetch = vi.mocked(fetchGroupEnabled);describe("desktop useGroupEnabled", () => {beforeEach(() => {+ privacy.localOnly = false;vi.clearAllMocks();status = "online";cachedSnapshot = { status };});+ it("keeps bundled dependencies available under privacy even when the account server is offline", async () => {+ privacy.localOnly = true;+ setStatus("offline");+ mockFetch.mockResolvedValue(true);+ const { result } = renderHook(() => useGroupEnabled("ImageMagick"), {+ wrapper: TestQueryProvider,+ });+ await waitFor(() => expect(result.current.enabled).toBe(true));+ expect(result.current.unavailableReason).toBeNull();+ });+it("skips the request entirely when the server is offline", async () => {setStatus("offline");diff --git a/frontend/editor/src/desktop/hooks/useGroupEnabled.ts b/frontend/editor/src/desktop/hooks/useGroupEnabled.tsindex a58cd2a255..5a739bd1e9 100644--- a/frontend/editor/src/desktop/hooks/useGroupEnabled.ts+++ b/frontend/editor/src/desktop/hooks/useGroupEnabled.ts@@ -6,6 +6,7 @@ import { selfHostedServerMonitor } from "@app/services/selfHostedServerMonitor";import { qk } from "@app/query/keys";import { CONFIG_STALE_TIME } from "@app/query/staleTime";import type { GroupEnabledResult } from "@app/types/groupEnabled";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";const OFFLINE_REASON_FALLBACK ="Requires your Stirling-PDF server (currently offline)";@@ -20,16 +21,17 @@ const getIsOffline = () =>export function useGroupEnabled(group: string): GroupEnabledResult {const { t } = useTranslation();const isOffline = useSyncExternalStore(subscribeToMonitor, getIsOffline);+ const localOnly = useLocalProcessingOnly();const { data, isPending } = useQuery({- queryKey: qk.groupEnabled(group),+ queryKey: [...qk.groupEnabled(group), localOnly],queryFn: () => fetchGroupEnabled(group),staleTime: CONFIG_STALE_TIME,- enabled: !isOffline,+ enabled: localOnly || !isOffline,});// Before the query: a disabled query stays isPending, which would read as loading forever.- if (isOffline) {+ if (isOffline && !localOnly) {return {enabled: false,unavailableReason: t(diff --git a/frontend/editor/src/desktop/hooks/useLocalProcessingOnly.test.tsx b/frontend/editor/src/desktop/hooks/useLocalProcessingOnly.test.tsxnew file mode 100644index 0000000000..9ffd24b2c9--- /dev/null+++ b/frontend/editor/src/desktop/hooks/useLocalProcessingOnly.test.tsx@@ -0,0 +1,39 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, expect, test, vi } from "vitest";+const state = vi.hoisted(() => ({+ cached: undefined as boolean | undefined,+ load: vi.fn(),+}));+vi.mock("@app/services/connectionModeService", () => ({+ connectionModeService: {+ getCachedLocalProcessingOnly: () => state.cached,+ getCurrentConfig: state.load,+ subscribeToModeChanges: () => () => {},+ },+}));+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";++beforeEach(() => {+ state.cached = undefined;+ state.load.mockReset();+});++test("keeps off-device features hidden until provisioning resolves", async () => {+ let resolve!: (config: { local_processing_only: boolean }) => void;+ state.load.mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ const { result } = renderHook(useLocalProcessingOnly);+ expect(result.current).toBe(true);+ await act(async () => resolve({ local_processing_only: false }));+ expect(result.current).toBe(false);+});++test("a policy read failure never grants off-device processing", async () => {+ state.load.mockRejectedValue(new Error("Native store unavailable"));+ const { result } = renderHook(useLocalProcessingOnly);+ await act(async () => {});+ expect(result.current).toBe(true);+});diff --git a/frontend/editor/src/desktop/hooks/useLocalProcessingOnly.ts b/frontend/editor/src/desktop/hooks/useLocalProcessingOnly.tsnew file mode 100644index 0000000000..45e89d481e--- /dev/null+++ b/frontend/editor/src/desktop/hooks/useLocalProcessingOnly.ts@@ -0,0 +1,28 @@+import { useEffect, useState } from "react";+import { connectionModeService } from "@app/services/connectionModeService";++/** Hides off-device features until the native policy is known, including on read errors. */+export function useLocalProcessingOnly(): boolean {+ const [restricted, setRestricted] = useState(+ () => connectionModeService.getCachedLocalProcessingOnly() ?? true,+ );+ useEffect(() => {+ let mounted = true;+ void connectionModeService+ .getCurrentConfig()+ .then((config) => {+ if (mounted) setRestricted(Boolean(config.local_processing_only));+ })+ .catch(() => {+ if (mounted) setRestricted(true);+ });+ const unsubscribe = connectionModeService.subscribeToModeChanges((config) =>+ setRestricted(Boolean(config.local_processing_only)),+ );+ return () => {+ mounted = false;+ unsubscribe();+ };+ }, []);+ return restricted;+}diff --git a/frontend/editor/src/desktop/hooks/useServerFolderBlock.ts b/frontend/editor/src/desktop/hooks/useServerFolderBlock.tsindex 9a16c63ff7..26a90beaf7 100644--- a/frontend/editor/src/desktop/hooks/useServerFolderBlock.ts+++ b/frontend/editor/src/desktop/hooks/useServerFolderBlock.ts@@ -1,5 +1,6 @@import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";import { connectionModeService } from "@app/services/connectionModeService";import type { ConnectionMode } from "@app/services/connectionModeService";import { useServerFolderBlock as useCoreServerFolderBlock } from "@core/hooks/useServerFolderBlock";@@ -11,6 +12,7 @@ import { useServerFolderBlock as useCoreServerFolderBlock } from "@core/hooks/usexport function useServerFolderBlock(): string | null {const { t } = useTranslation();const coreReason = useCoreServerFolderBlock();+ const localOnly = useLocalProcessingOnly();// Seeded from the cache so a remount answers on its first frame; the effect covers// the first-ever load and later mode switches.const [mode, setMode] = useState<ConnectionMode | null>(() =>@@ -33,6 +35,11 @@ export function useServerFolderBlock(): string | null {// any mode where the item would be blocked, signing in or connecting a server IS the// way out — unlike the core reasons, which in local mode point at a storage setting// that doesn't exist.+ if (localOnly)+ return t(+ "desktopPrivacy.blocked",+ "Your administrator requires documents to stay on this device. This feature is unavailable.",+ );if (mode === "local" || mode === null) {return t("filesPage.serverFolderNeedsConnection",diff --git a/frontend/editor/src/desktop/hooks/useServerProcessingBlock.test.ts b/frontend/editor/src/desktop/hooks/useServerProcessingBlock.test.tsindex 325047240e..ea8020a531 100644--- a/frontend/editor/src/desktop/hooks/useServerProcessingBlock.test.ts+++ b/frontend/editor/src/desktop/hooks/useServerProcessingBlock.test.ts@@ -1,5 +1,8 @@import { renderHook } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+vi.mock("@app/hooks/useLocalProcessingOnly", () => ({+ useLocalProcessingOnly: () => false,+}));const { useConnectedServerMock } = vi.hoisted(() => ({useConnectedServerMock: vi.fn(),diff --git a/frontend/editor/src/desktop/hooks/useServerProcessingBlock.ts b/frontend/editor/src/desktop/hooks/useServerProcessingBlock.tsindex 572cb609ef..3c8a86be93 100644--- a/frontend/editor/src/desktop/hooks/useServerProcessingBlock.ts+++ b/frontend/editor/src/desktop/hooks/useServerProcessingBlock.ts@@ -1,11 +1,18 @@import { useTranslation } from "react-i18next";import { useConnectedServer } from "@app/hooks/useConnectedServer";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";/** Desktop: folder processing runs on the connected server, so it waits for one. Fails closed* while the connection resolves, or the Downloads offer probes the bundled backend for nothing. */export function useServerProcessingBlock(): string | null {const { t } = useTranslation();- if (useConnectedServer()) return null;+ const connected = useConnectedServer();+ if (useLocalProcessingOnly())+ return t(+ "desktopPrivacy.blocked",+ "Your administrator requires documents to stay on this device. This feature is unavailable.",+ );+ if (connected) return null;return t("filesPage.processing.blockedNeedsConnection","Sign in to Stirling Cloud or connect a self-hosted server to process folders.",diff --git a/frontend/editor/src/desktop/hooks/useToolCloudStatus.ts b/frontend/editor/src/desktop/hooks/useToolCloudStatus.tsindex 29ec4f3ee3..30db996ca3 100644--- a/frontend/editor/src/desktop/hooks/useToolCloudStatus.ts+++ b/frontend/editor/src/desktop/hooks/useToolCloudStatus.ts@@ -2,6 +2,7 @@ import { useState, useEffect } from "react";import { connectionModeService } from "@app/services/connectionModeService";import { endpointAvailabilityService } from "@app/services/endpointAvailabilityService";import { tauriBackendService } from "@app/services/tauriBackendService";+import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";/*** Desktop hook to check if a tool endpoint will use cloud backend@@ -9,11 +10,12 @@ import { tauriBackendService } from "@app/services/tauriBackendService";* @returns true if the tool will use cloud credits, false otherwise*/export function useToolCloudStatus(endpointName?: string): boolean {+ const localOnly = useLocalProcessingOnly();const [usesCloud, setUsesCloud] = useState(false);useEffect(() => {const checkCloudRouting = async () => {- if (!endpointName) {+ if (localOnly || !endpointName) {setUsesCloud(false);return;}@@ -69,7 +71,7 @@ export function useToolCloudStatus(endpointName?: string): boolean {});return unsubscribe;- }, [endpointName]);+ }, [endpointName, localOnly]);- return usesCloud;+ return !localOnly && usesCloud;}diff --git a/frontend/editor/src/desktop/services/aiBaseUrl.test.ts b/frontend/editor/src/desktop/services/aiBaseUrl.test.tsindex 408e48e91f..18b4e193d5 100644--- a/frontend/editor/src/desktop/services/aiBaseUrl.test.ts+++ b/frontend/editor/src/desktop/services/aiBaseUrl.test.ts@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({vi.mock("@app/services/connectionModeService", () => ({connectionModeService: {+ getCurrentConfig: async () => ({ local_processing_only: false }),getCurrentMode: async () => mocks.mode,getServerConfig: async () => mocks.serverConfig,},diff --git a/frontend/editor/src/desktop/services/authService.managed.test.ts b/frontend/editor/src/desktop/services/authService.managed.test.tsnew file mode 100644index 0000000000..5f9100f13c--- /dev/null+++ b/frontend/editor/src/desktop/services/authService.managed.test.ts@@ -0,0 +1,219 @@+import { beforeEach, expect, it, vi } from "vitest";+import { AuthService } from "@app/services/authService";+import { AxiosError } from "axios";++const state = vi.hoisted(() => ({+ invoke: vi.fn(),+ getConfig: vi.fn(),+ get: vi.fn(),+ post: vi.fn(),+ allowSelfHosted: vi.fn(),+}));+vi.mock("@tauri-apps/api/core", () => ({+ invoke: state.invoke,+ isTauri: () => true,+}));+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));+vi.mock("@tauri-apps/plugin-shell", () => ({ open: vi.fn() }));+vi.mock("@app/services/connectionModeService", () => ({+ connectionModeService: {+ getCurrentConfig: state.getConfig,+ assertSelfHostedAllowed: state.allowSelfHosted,+ },+}));+vi.mock("@app/services/tauriBackendService", () => ({+ tauriBackendService: {},+}));+vi.mock("@app/services/tauriHttpClient", () => ({+ default: { post: state.post },+}));+vi.mock("@app/constants/connection", () => ({+ STIRLING_SAAS_URL: "https://cloud.example.org",+ SUPABASE_KEY: "public-key",+ DESKTOP_DEEP_LINK_CALLBACK: "stirlingpdf://auth",+}));+vi.mock("axios", async (importOriginal) => {+ const actual = await importOriginal<typeof import("axios")>();+ return {+ ...actual,+ default: { ...actual.default, get: state.get, post: state.post },+ };+});++function token(expiresIn: number) {+ return `header.${btoa(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + expiresIn }))}.signature`;+}++beforeEach(() => {+ vi.resetAllMocks();+ localStorage.clear();+ state.getConfig.mockResolvedValue({+ mode: "saas",+ require_sign_in: true,+ cloud_only: true,+ });+ state.invoke.mockResolvedValue(token(3600));+ state.get.mockResolvedValue({ data: { id: "user-id", is_anonymous: false } });+});++it.each(["saas", "selfhosted"])(+ "retains verified %s access after refresh even if account validation goes offline",+ async (mode) => {+ const serverUrl =+ mode === "saas"+ ? "https://cloud.example.org"+ : "https://self.example.org";+ state.getConfig.mockResolvedValue({+ mode,+ server_config: { url: serverUrl },+ });+ state.get.mockResolvedValue({ data: { id: "user-id", username: "user" } });+ const service = new AuthService();+ expect(await service.hasManagedSession()).toBe(true);+ const refreshed = token(7200);+ state.post.mockResolvedValue({ data: { access_token: refreshed } });+ state.get.mockRejectedValue(new AxiosError("Offline", "ERR_NETWORK"));+ expect(+ await (mode === "saas"+ ? service.refreshSupabaseToken(serverUrl)+ : service.refreshToken(serverUrl)),+ ).toBe(true);+ expect(await service.hasManagedSession()).toBe(true);+ expect(state.get).toHaveBeenCalledTimes(1);+ },+);++it("does not extend verification to a refresh from another server", async () => {+ const service = new AuthService();+ expect(await service.hasManagedSession()).toBe(true);+ state.post.mockResolvedValue({ data: { access_token: token(7200) } });+ await service.refreshToken("https://other.example.org");+ state.get.mockRejectedValue(new AxiosError("Offline", "ERR_NETWORK"));+ expect(await service.hasManagedSession()).toBe(false);+});++it("revalidates when the connection mode changes even at the same URL", async () => {+ const service = new AuthService();+ expect(await service.hasManagedSession()).toBe(true);+ state.getConfig.mockResolvedValue({+ mode: "selfhosted",+ server_config: { url: "https://cloud.example.org" },+ });+ state.get.mockRejectedValue(new AxiosError("Offline", "ERR_NETWORK"));+ expect(await service.hasManagedSession()).toBe(false);+});++it.each([undefined, 408, 429, 503])(+ "retains an unexpired verified session after a transient refresh failure (%s)",+ async (status) => {+ const service = new AuthService();+ expect(await service.hasManagedSession()).toBe(true);+ state.post.mockRejectedValue(+ Object.assign(new AxiosError("Temporarily unavailable"), {+ response: status ? { status } : undefined,+ }),+ );+ expect(+ await service.refreshSupabaseToken("https://cloud.example.org"),+ ).toBe(false);+ expect(await service.hasManagedSession()).toBe(true);+ expect(state.invoke).not.toHaveBeenCalledWith("clear_auth_token");+ },+);++it("revokes an expired session even when refresh is rate limited", async () => {+ state.invoke.mockResolvedValue(token(-60));+ const service = new AuthService();+ state.post.mockRejectedValue(+ Object.assign(new AxiosError("Rate limited"), {+ response: { status: 429 },+ }),+ );+ expect(await service.hasManagedSession()).toBe(false);+ expect(state.invoke).toHaveBeenCalledWith("clear_auth_token");+});++it("does not refresh or revoke a verified token before its actual expiry", async () => {+ state.invoke.mockResolvedValue(token(20));+ const service = new AuthService();+ const refresh = vi.spyOn(service, "refreshSupabaseToken");+ expect(await service.hasManagedSession()).toBe(true);+ state.get.mockRejectedValue(new AxiosError("Offline", "ERR_NETWORK"));+ expect(await service.hasManagedSession()).toBe(true);+ expect(refresh).not.toHaveBeenCalled();+});++it("revokes verification after an explicit refresh rejection", async () => {+ const service = new AuthService();+ expect(await service.hasManagedSession()).toBe(true);+ state.post.mockRejectedValue(+ Object.assign(new AxiosError("Unauthorized"), {+ response: { status: 401 },+ }),+ );+ await service.refreshSupabaseToken("https://cloud.example.org");+ expect(state.invoke).toHaveBeenCalledWith("clear_auth_token");+ state.get.mockRejectedValue(new AxiosError("Offline", "ERR_NETWORK"));+ expect(await service.hasManagedSession()).toBe(false);+});++it("does not admit an unverified session during a network failure", async () => {+ state.get.mockRejectedValue(new AxiosError("Offline", "ERR_NETWORK"));+ expect(await new AuthService().hasManagedSession()).toBe(false);+});++it("verifies a stored session against Cloud before admitting it", async () => {+ const service = new AuthService();+ expect(await service.hasManagedSession()).toBe(true);+ expect(state.get).toHaveBeenCalledWith(+ "https://cloud.example.org/auth/v1/user",+ expect.objectContaining({+ headers: expect.objectContaining({ apikey: "public-key" }),+ }),+ );+ expect(await service.hasManagedSession()).toBe(true);+ expect(state.get).toHaveBeenCalledTimes(1);+});++it("rejects an old self-hosted token that Cloud does not recognise", async () => {+ state.get.mockRejectedValue(new Error("Unauthorized"));+ expect(await new AuthService().hasManagedSession()).toBe(false);+});++it("rejects anonymous Cloud accounts", async () => {+ state.get.mockResolvedValue({ data: { id: "guest-id", is_anonymous: true } });+ expect(await new AuthService().hasManagedSession()).toBe(false);+});++it("requires successful refresh before admitting an expired token", async () => {+ state.invoke.mockResolvedValue(token(-60));+ const service = new AuthService();+ const refresh = vi+ .spyOn(service, "refreshSupabaseToken")+ .mockResolvedValue(false);+ expect(await service.hasManagedSession()).toBe(false);+ expect(refresh).toHaveBeenCalled();+ expect(state.get).not.toHaveBeenCalled();+});++it("does not validate a prohibited connection mode", async () => {+ state.getConfig.mockResolvedValue({+ mode: "selfhosted",+ cloud_only: true,+ server_config: { url: "https://self.example.org" },+ });+ expect(await new AuthService().hasManagedSession()).toBe(false);+ expect(state.get).not.toHaveBeenCalled();+});++it("checks policy before accepting self-hosted SSO tokens", async () => {+ state.allowSelfHosted.mockRejectedValue(new Error("Cloud required"));+ await expect(+ new AuthService().completeSelfHostedSession(+ "https://self.example.org",+ token(3600),+ ),+ ).rejects.toThrow("Cloud required");+ expect(state.get).not.toHaveBeenCalled();+ expect(state.invoke).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/desktop/services/authService.ts b/frontend/editor/src/desktop/services/authService.tsindex d2c069c810..19062a1828 100644--- a/frontend/editor/src/desktop/services/authService.ts+++ b/frontend/editor/src/desktop/services/authService.ts@@ -50,6 +50,11 @@ export class AuthService {private authStatus: AuthStatus = "unauthenticated";private userInfo: UserInfo | null = null;private cachedToken: string | null = null;+ private verifiedManagedSession: {+ mode: "saas" | "selfhosted";+ serverUrl: string;+ token: string;+ } | null = null;private lastTokenSaveTime: number = 0;private authListeners = new Set<(status: AuthStatus, userInfo: UserInfo | null) => void@@ -157,6 +162,7 @@ export class AuthService {* Clear token from all storage locations*/private async clearTokenEverywhere(): Promise<void> {+ this.verifiedManagedSession = null;// Invalidate cachethis.cachedToken = null;@@ -231,6 +237,7 @@ export class AuthService {}private setAuthStatus(status: AuthStatus, userInfo: UserInfo | null = null) {+ if (status === "unauthenticated") this.verifiedManagedSession = null;this.authStatus = status;this.userInfo = userInfo;this.notifyListeners();@@ -330,6 +337,9 @@ export class AuthService {password: string,mfaCode?: string,): Promise<UserInfo> {+ if (serverUrl !== STIRLING_SAAS_URL) {+ await connectionModeService.assertSelfHostedAllowed(serverUrl);+ }try {// Validate SaaS configuration if connecting to SaaSif (serverUrl === STIRLING_SAAS_URL) {@@ -626,6 +636,106 @@ export class AuthService {return token !== null;}+ /** Managed access requires an unexpired session verified by the selected server, including its authenticated refresh responses. */+ async hasManagedSession(): Promise<boolean> {+ const config = await connectionModeService.getCurrentConfig();+ if (+ config.mode === "local" ||+ (config.cloud_only && config.mode !== "saas")+ )+ return false;+ const serverUrl =+ config.mode === "saas" ? STIRLING_SAAS_URL : config.server_config?.url;+ if (!serverUrl) return false;+ let token = await this.getAuthToken();+ if (!token) return false;+ if (this.isTokenExpiringSoon(token, 0)) {+ const refreshed =+ config.mode === "saas"+ ? await this.refreshSupabaseToken(serverUrl)+ : await this.refreshToken(serverUrl);+ if (!refreshed) return false;+ token = await this.getAuthToken();+ }+ if (!token || this.isTokenExpiringSoon(token, 0)) return false;+ if (+ this.verifiedManagedSession?.mode === config.mode &&+ this.verifiedManagedSession?.serverUrl === serverUrl &&+ this.verifiedManagedSession.token === token+ )+ return true;+ try {+ const response = await axios.get(+ config.mode === "saas"+ ? `${serverUrl}/auth/v1/user`+ : `${serverUrl.replace(/\/+$/, "")}/api/v1/auth/me`,+ {+ headers: {+ Authorization: `Bearer ${token}`,+ ...(config.mode === "saas" ? { apikey: SUPABASE_KEY } : {}),+ },+ timeout: 15000,+ },+ );+ const user = response.data?.user ?? response.data;+ const authenticated =+ config.mode === "saas"+ ? !!user?.id && user.is_anonymous !== true+ : !!user?.username && user.username !== "anonymousUser";+ if (+ !authenticated ||+ token !== (await this.getAuthToken()) ||+ this.isTokenExpiringSoon(token, 0)+ ) {+ this.verifiedManagedSession = null;+ return false;+ }+ this.verifiedManagedSession = { mode: config.mode, serverUrl, token };+ return true;+ } catch {+ this.verifiedManagedSession = null;+ return false;+ }+ }++ private async saveRefreshedToken(+ mode: "saas" | "selfhosted",+ serverUrl: string,+ previousToken: string | null,+ token: string,+ refreshToken?: string | null,+ ): Promise<void> {+ const verified = this.verifiedManagedSession;+ await this.saveTokenEverywhere(token, refreshToken, false);+ // Only an authenticated refresh of this verified session can extend offline access.+ if (+ verified &&+ this.verifiedManagedSession === verified &&+ verified.mode === mode &&+ verified.serverUrl === serverUrl &&+ verified.token === previousToken+ ) {+ this.verifiedManagedSession = { mode, serverUrl, token };+ }+ }++ private async handleRefreshFailure(error: unknown): Promise<void> {+ const token = await this.getAuthToken();+ if (+ axios.isAxiosError(error) &&+ (!error.response ||+ error.response.status >= 500 ||+ error.response.status === 408 ||+ error.response.status === 429) &&+ token &&+ !this.isTokenExpiringSoon(token, 0)+ ) {+ this.setAuthStatus("authenticated", this.userInfo);+ return;+ }+ await this.logout();+ }+async getUserInfo(): Promise<UserInfo | null> {if (this.userInfo) {console.log(@@ -778,7 +888,12 @@ export class AuthService {}// Save token to all storage locations- await this.saveTokenEverywhere(token, undefined, false);+ await this.saveRefreshedToken(+ "selfhosted",+ serverUrl,+ currentToken,+ token,+ );const userInfo = await this.getUserInfo();this.setAuthStatus("authenticated", userInfo);@@ -787,10 +902,7 @@ export class AuthService {return true;} catch (error) {console.error("[Desktop AuthService] Token refresh failed:", error);- this.setAuthStatus("unauthenticated", null);-- // Clear stored credentials on refresh failure- await this.logout();+ await this.handleRefreshFailure(error);return false;}@@ -818,6 +930,7 @@ export class AuthService {): Promise<boolean> {try {console.log("[Desktop AuthService] Refreshing Supabase token");+ const currentToken = await this.getAuthToken();this.setAuthStatus("refreshing", this.userInfo);const refreshToken = await this.getRefreshToken();@@ -844,7 +957,13 @@ export class AuthService {const { access_token, refresh_token: newRefreshToken } = response.data;// Save new tokens- await this.saveTokenEverywhere(access_token, newRefreshToken, false);+ await this.saveRefreshedToken(+ "saas",+ authServerUrl,+ currentToken,+ access_token,+ newRefreshToken,+ );const userInfo = await this.getUserInfo();this.setAuthStatus("authenticated", userInfo);@@ -858,10 +977,7 @@ export class AuthService {"[Desktop AuthService] Supabase token refresh failed:",error,);- this.setAuthStatus("unauthenticated", null);-- // Clear stored credentials on refresh failure- await this.logout();+ await this.handleRefreshFailure(error);return false;}@@ -1228,6 +1344,7 @@ export class AuthService {serverUrl: string,token: string,): Promise<UserInfo> {+ await connectionModeService.assertSelfHostedAllowed(serverUrl);const userInfo = await this.fetchSelfHostedUserInfo(serverUrl, token);await this.saveTokenEverywhere(token);diff --git a/frontend/editor/src/desktop/services/backgroundRequestErrors.test.ts b/frontend/editor/src/desktop/services/backgroundRequestErrors.test.tsindex 2b2a9e05ea..7762f8de61 100644--- a/frontend/editor/src/desktop/services/backgroundRequestErrors.test.ts+++ b/frontend/editor/src/desktop/services/backgroundRequestErrors.test.ts@@ -40,6 +40,7 @@ vi.mock("@app/services/authService", () => ({}));vi.mock("@app/services/connectionModeService", () => ({connectionModeService: {+ getCurrentConfig: async () => ({ local_processing_only: false }),getCurrentMode: vi.fn(),subscribeToModeChanges: vi.fn(() => () => {}),},diff --git a/frontend/editor/src/desktop/services/connectionModeService.test.ts b/frontend/editor/src/desktop/services/connectionModeService.test.tsnew file mode 100644index 0000000000..2654bb850e--- /dev/null+++ b/frontend/editor/src/desktop/services/connectionModeService.test.ts@@ -0,0 +1,117 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ ConnectionModeService,+ LOCAL_MODE_STORAGE_KEY,+} from "@app/services/connectionModeService";++const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));+vi.mock("@tauri-apps/api/core", () => ({ invoke, isTauri: () => true }));+vi.mock("@tauri-apps/plugin-http", () => ({ fetch: vi.fn() }));+vi.mock("@app/services/endpointAvailabilityService", () => ({+ endpointAvailabilityService: { clearCache: vi.fn() },+}));+vi.mock("@app/services/selfHostedServerMonitor", () => ({+ selfHostedServerMonitor: { start: vi.fn() },+}));++beforeEach(() => {+ localStorage.clear();+ invoke.mockReset();+});++describe("managed connections", () => {+ it("ignores an old guest preference when sign-in is required", async () => {+ localStorage.setItem(LOCAL_MODE_STORAGE_KEY, "true");+ invoke.mockResolvedValue({+ mode: "saas",+ server_config: null,+ lock_connection_mode: false,+ require_sign_in: true,+ cloud_only: true,+ });+ const service = new ConnectionModeService();+ expect(await service.getCurrentMode()).toBe("saas");+ await expect(service.switchToLocal()).rejects.toThrow("requires sign-in");+ expect(localStorage.getItem(LOCAL_MODE_STORAGE_KEY)).toBeNull();+ expect(invoke).not.toHaveBeenCalledWith(+ "set_connection_mode",+ expect.anything(),+ );+ });++ it("rejects self-hosted connections before changing native or browser state", async () => {+ invoke.mockResolvedValue({+ mode: "saas",+ server_config: null,+ lock_connection_mode: false,+ cloud_only: true,+ });+ const service = new ConnectionModeService();+ await expect(+ service.switchToSelfHosted({ url: "https://example.org" }),+ ).rejects.toThrow("Stirling Cloud");+ expect(invoke).toHaveBeenCalledTimes(1);+ });++ it("preserves all policies after SaaS sign-in", async () => {+ invoke.mockResolvedValue({+ mode: "saas",+ server_config: null,+ lock_connection_mode: false,+ require_sign_in: true,+ cloud_only: true,+ local_processing_only: true,+ });+ const service = new ConnectionModeService();+ await service.switchToSaaS("https://cloud.example.org");+ expect(await service.getCurrentConfig()).toMatchObject({+ require_sign_in: true,+ cloud_only: true,+ local_processing_only: true,+ mode: "saas",+ });+ await expect(service.switchToLocal()).rejects.toThrow("requires sign-in");+ });++ it("allows guest use when only Cloud-only is set", async () => {+ invoke.mockResolvedValue({+ mode: "saas",+ server_config: null,+ lock_connection_mode: false,+ cloud_only: true,+ });+ const service = new ConnectionModeService();+ await service.switchToLocal();+ expect(await service.getCurrentMode()).toBe("local");+ });++ it("retains the locked self-hosted server restriction", async () => {+ invoke.mockResolvedValue({+ mode: "selfhosted",+ server_config: { url: "https://managed.example.org" },+ lock_connection_mode: true,+ });+ const service = new ConnectionModeService();+ await expect(+ service.assertSelfHostedAllowed("https://managed.example.org/"),+ ).resolves.toBeUndefined();+ await expect(+ service.assertSelfHostedAllowed("https://other.example.org"),+ ).rejects.toThrow("locked");+ await expect(+ service.switchToSaaS("https://cloud.example.org"),+ ).rejects.toThrow("locked");+ await service.switchToLocal();+ await expect(+ service.assertSelfHostedAllowed("https://managed.example.org"),+ ).resolves.toBeUndefined();+ });++ it("fails closed if the native policy cannot be read", async () => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ invoke.mockRejectedValue(new Error("Store unavailable"));+ await expect(+ new ConnectionModeService().getCurrentConfig(),+ ).rejects.toThrow("Store unavailable");+ });+});diff --git a/frontend/editor/src/desktop/services/connectionModeService.ts b/frontend/editor/src/desktop/services/connectionModeService.tsindex 3ee8dfb579..467279b822 100644--- a/frontend/editor/src/desktop/services/connectionModeService.ts+++ b/frontend/editor/src/desktop/services/connectionModeService.ts@@ -22,6 +22,12 @@ export interface ConnectionConfig {mode: ConnectionMode;server_config: ServerConfig | null;lock_connection_mode: boolean;+ /** Absent in older native configurations; defaults to false. */+ require_sign_in?: boolean;+ /** Restricts account connections to Stirling Cloud, independently of guest access. */+ cloud_only?: boolean;+ /** Keeps documents on this device while allowing account and billing requests. */+ local_processing_only?: boolean;}export interface DiagnosticResult {@@ -77,6 +83,13 @@ export class ConnectionModeService {return this.currentConfig?.mode ?? null;}+ /** Undefined until provisioning has loaded; consumers must fail closed. */+ getCachedLocalProcessingOnly(): boolean | undefined {+ return this.currentConfig+ ? Boolean(this.currentConfig.local_processing_only)+ : undefined;+ }+/** The server already in memory, or null before the first load. Synchronous so* callers that build a URL inline (raw fetch, template string) can reach it. */getCachedServerConfig(): ServerConfig | null {@@ -109,7 +122,10 @@ export class ConnectionModeService {const localFlag = localStorage.getItem(LOCAL_MODE_STORAGE_KEY);- if (localFlag === "true") {+ if (config.require_sign_in) {+ localStorage.removeItem(LOCAL_MODE_STORAGE_KEY);+ if (config.mode === "local") config.mode = "saas";+ } else if (localFlag === "true") {// User previously chose local-only mode (signed out or explicitly went offline).// Applies to both 'saas' and 'selfhosted' store modes — the Rust guard on locked// deployments can't change 'selfhosted' to 'saas' in the store, so we check the@@ -135,19 +151,14 @@ export class ConnectionModeService {this.configLoadedOnce = true;} catch (error) {console.error("Failed to load connection config:", error);- // Default to local mode on error — safer than showing SaaS UI for a- // desktop app whose bundled backend is always available.- this.currentConfig = {- mode: "local",- server_config: null,- lock_connection_mode: false,- };- this.configLoadedOnce = true;+ // An unreadable policy must not grant guest access on a managed install.+ throw error;}}async switchToSaaS(saasServerUrl: string): Promise<void> {- if (this.currentConfig?.lock_connection_mode) {+ const currentConfig = await this.getCurrentConfig();+ if (currentConfig.lock_connection_mode && currentConfig.mode !== "saas") {throw new Error("Connection mode is locked by provisioning");}@@ -166,6 +177,7 @@ export class ConnectionModeService {});this.currentConfig = {+ ...currentConfig,mode: "saas",server_config: serverConfig,lock_connection_mode: this.currentConfig?.lock_connection_mode ?? false,@@ -203,17 +215,22 @@ export class ConnectionModeService {}async switchToLocal(): Promise<void> {+ const currentConfig = await this.getCurrentConfig();+ if (currentConfig.require_sign_in) {+ throw new Error(+ "Your administrator requires sign-in before using this app",+ );+ }console.log("Switching to local-only mode");// Persist local mode preference via localStorage so no Rust enum change is needed.// The Rust store records this as 'saas' (same bundled-backend behaviour); we overlay// the 'local' distinction purely on the TypeScript side.- localStorage.setItem(LOCAL_MODE_STORAGE_KEY, "true");-await invoke("set_connection_mode", {mode: "saas",serverConfig: null,});+ localStorage.setItem(LOCAL_MODE_STORAGE_KEY, "true");// For locked deployments, preserve server_config so the sign-in form can still// show the correct server URL if the user wants to sign in later.@@ -223,6 +240,7 @@ export class ConnectionModeService {: null;this.currentConfig = {+ ...currentConfig,mode: "local",server_config: preservedServerConfig,lock_connection_mode: isLocked,@@ -235,6 +253,7 @@ export class ConnectionModeService {}async switchToSelfHosted(serverConfig: ServerConfig): Promise<void> {+ await this.assertSelfHostedAllowed(serverConfig.url);// Clear local-only flag and expiry-prompted flag when signing inlocalStorage.removeItem(LOCAL_MODE_STORAGE_KEY);localStorage.removeItem(JWT_EXPIRED_PROMPTED_KEY);@@ -249,6 +268,7 @@ export class ConnectionModeService {});this.currentConfig = {+ ...this.currentConfig,mode: "selfhosted",server_config: serverConfig,lock_connection_mode: this.currentConfig?.lock_connection_mode ?? false,@@ -280,6 +300,22 @@ export class ConnectionModeService {console.log("Switched to self-hosted mode successfully");}+ /** Rejects disallowed servers before credentials or deep-link tokens are accepted. */+ async assertSelfHostedAllowed(serverUrl: string): Promise<void> {+ const config = await this.getCurrentConfig();+ if (config.cloud_only) {+ throw new Error("Your administrator requires Stirling Cloud sign-in");+ }+ if (+ config.lock_connection_mode &&+ (config.mode === "saas" ||+ config.server_config?.url.replace(/\/+$/, "") !==+ serverUrl.replace(/\/+$/, ""))+ ) {+ throw new Error("Connection mode is locked by provisioning");+ }+ }+/*** Test connection to a server URL with comprehensive multi-stage diagnostics* @returns Detailed test results with diagnostics and recommendationsdiff --git a/frontend/editor/src/desktop/services/documentPrivacyService.test.ts b/frontend/editor/src/desktop/services/documentPrivacyService.test.tsnew file mode 100644index 0000000000..3aa6661642--- /dev/null+++ b/frontend/editor/src/desktop/services/documentPrivacyService.test.ts@@ -0,0 +1,135 @@+import { beforeEach, describe, expect, test, vi } from "vitest";++const state = vi.hoisted(() => ({+ restricted: true,+ loadError: false,+ localUrl: "http://127.0.0.1:62994" as string | null,+ fetch: vi.fn(),+}));+vi.mock("@tauri-apps/plugin-http", () => ({ fetch: state.fetch }));+vi.mock("@app/services/connectionModeService", () => ({+ connectionModeService: {+ getCurrentConfig: async () => {+ if (state.loadError) throw new Error("Policy unavailable");+ return {+ local_processing_only: state.restricted,+ server_config: { url: "https://selfhosted.test" },+ };+ },+ },+}));+vi.mock("@app/services/tauriBackendService", () => ({+ tauriBackendService: { getBackendUrl: () => state.localUrl },+}));+vi.mock("@app/constants/connection", () => ({+ STIRLING_SAAS_BACKEND_API_URL: "https://cloud.test",+}));+vi.mock("@app/i18n", () => ({+ default: { t: (_key: string, fallback: string) => fallback },+}));+vi.mock("@app/services/tauriLocalProxy", () => ({+ shouldUseFastLocalTransport: () => false,+}));++import { create } from "@app/services/tauriHttpClient";++beforeEach(() => {+ state.restricted = true;+ state.loadError = false;+ state.localUrl = "http://127.0.0.1:62994";+ state.fetch+ .mockReset()+ .mockImplementation(+ async () =>+ new Response("{}", { headers: { "Content-Type": "application/json" } }),+ );+});++describe("managed document request boundary", () => {+ test.each([+ "https://cloud.test/api/v1/misc/compress-pdf",+ "https://selfhosted.test/api/v1/convert/pdf/word",+ "https://uploads.test/signed-object?signature=abc",+ "https://cloud.test/api/v1/storage/files",+ "https://cloud.test/api/v1/security/cert-sign/sessions",+ "https://cloud.test/api/v1/ai/orchestrate/stream",+ "http://127.0.0.1:62994/api/v1/policies/run",+ "http://127.0.0.1:62994/api/v1/security/timestamp-pdf",+ "http://127.0.0.1:62994/api/v1/security/cert-sign/sessions",+ "http://127.0.0.1:62994/api/v1/storage/files",+ "http://127.0.0.1:62994/api/v1/mobile-scanner/create-session",+ "http://127.0.0.1:7777/api/v1/misc/compress-pdf",+ "https://cloud.test.attacker.test/api/v1/payg/wallet",+ ])("sends nothing to %s", async (url) => {+ const body = new FormData();+ body.append("fileInput", new File(["private"], "private.pdf"));+ await expect(create().post(url, body)).rejects.toThrow(+ "stay on this device",+ );+ expect(state.fetch).not.toHaveBeenCalled();+ });++ test("blocks document JSON and remote reads as well as multipart uploads", async () => {+ const client = create({ baseURL: "https://cloud.test" });+ await expect(+ client.post("/api/v1/ai/orchestrate/stream", {+ text: "private document text",+ }),+ ).rejects.toThrow("stay on this device");+ await expect(client.get("/api/v1/storage/files")).rejects.toThrow(+ "stay on this device",+ );+ expect(state.fetch).not.toHaveBeenCalled();+ });++ test("permits bundled processing and disables redirect forwarding", async () => {+ const body = new FormData();+ body.append("fileInput", new File(["private"], "private.pdf"));+ await create().post(+ "http://127.0.0.1:62994/api/v1/misc/compress-pdf",+ body,+ );+ expect(state.fetch).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ body, maxRedirections: 0 }),+ );+ });++ test("permits account and billing requests, but no file payloads to account APIs", async () => {+ const client = create({ baseURL: "https://cloud.test" });+ await client.get("/api/v1/auth/me");+ await client.get("/api/v1/payg/wallet");+ await client.post("/api/v1/team/invite", {+ email: "[email protected]",+ });+ expect(state.fetch).toHaveBeenCalledTimes(3);+ await expect(+ client.post("/api/v1/team/invite", new Blob(["private"])),+ ).rejects.toThrow("stay on this device");+ expect(state.fetch).toHaveBeenCalledTimes(3);+ });++ test("an unreadable policy or an undiscovered local backend does not permit uploads", async () => {+ state.localUrl = null;+ await expect(+ create().post(+ "http://127.0.0.1:62994/api/v1/misc/compress-pdf",+ "private",+ ),+ ).rejects.toThrow();+ state.loadError = true;+ await expect(+ create().post("https://cloud.test/api/v1/misc/compress-pdf", "private"),+ ).rejects.toThrow("Policy unavailable");+ expect(state.fetch).not.toHaveBeenCalled();+ });++ test("unmanaged installs retain cloud processing", async () => {+ state.restricted = false;+ await create().post(+ "https://cloud.test/api/v1/misc/compress-pdf",+ "document",+ );+ expect(state.fetch).toHaveBeenCalledOnce();+ });+});diff --git a/frontend/editor/src/desktop/services/documentPrivacyService.ts b/frontend/editor/src/desktop/services/documentPrivacyService.tsnew file mode 100644index 0000000000..4e04864066--- /dev/null+++ b/frontend/editor/src/desktop/services/documentPrivacyService.ts@@ -0,0 +1,82 @@+import i18n from "@app/i18n";+import { connectionModeService } from "@app/services/connectionModeService";+import { tauriBackendService } from "@app/services/tauriBackendService";+import { STIRLING_SAAS_BACKEND_API_URL } from "@app/constants/connection";++/** These endpoints can send document data onward even from the bundled backend. */+export function requiresOffDeviceProcessing(endpoint: string): boolean {+ const path = decodeURIComponent(new URL(endpoint, "http://local").pathname);+ return (+ /^\/api\/v1\/(?:ai|storage|sharing|share|signing|workflow|policies|processing-folders|automation|pipeline|mobile-scanner)(?:\/|$)/.test(+ path,+ ) ||+ /^\/api\/v1\/security\/(?:timestamp-pdf(?:\/|$)|cert-sign\/)/.test(path)+ );+}++/** Capability names whose implementations need another device, regardless of local availability. */+export function isOffDeviceEndpointName(endpoint: string): boolean {+ return ["automate", "classify-and-label", "timestamp-pdf"].includes(endpoint);+}++/** A translated policy error shared by direct requests and stale UI actions. */+export function documentPrivacyError(): Error {+ return new Error(+ i18n.t(+ "desktopPrivacy.blocked",+ "Your administrator requires documents to stay on this device. This feature is unavailable.",+ ),+ );+}++/** Rejects if provisioning cannot be read; callers must never infer permission on failure. */+export async function isLocalProcessingOnly(): Promise<boolean> {+ return Boolean(+ (await connectionModeService.getCurrentConfig()).local_processing_only,+ );+}++function isWithinBase(url: URL, base: string): boolean {+ const parsed = new URL(base);+ const prefix = parsed.pathname.replace(/\/$/, "");+ return (+ url.origin === parsed.origin &&+ (url.pathname === prefix || url.pathname.startsWith(`${prefix}/`))+ );+}++/** Checks the final destination, including absolute and signed URLs, before any body is sent.+ * Returns whether redirects must be disabled for the request. */+export async function enforceDocumentPrivacy(+ url: string,+ method: string,+ data?: unknown,+): Promise<boolean> {+ const config = await connectionModeService.getCurrentConfig();+ if (!config.local_processing_only) return false;+ const target = new URL(url);+ if (requiresOffDeviceProcessing(target.href)) throw documentPrivacyError();+ const localUrl = tauriBackendService.getBackendUrl();+ if (localUrl && isWithinBase(target, localUrl)) return true;++ // Only account APIs may leave the device. Unknown future APIs default to blocked.+ const trusted = [STIRLING_SAAS_BACKEND_API_URL, config.server_config?.url]+ .filter((base): base is string => Boolean(base))+ .some((base) => isWithinBase(target, base));+ const path = decodeURIComponent(target.pathname);+ const accountApi = /^\/api\/v1\/(?:auth|team|payg|user|admin)(?:\/|$)/.test(+ path,+ );+ const metadata =+ method === "GET" &&+ /^\/api\/v1\/(?:config|info|proprietary\/ui-data)(?:\/|$)/.test(path);+ const binaryBody =+ (data instanceof FormData &&+ [...data.values()].some((value) => value instanceof Blob)) ||+ data instanceof Blob ||+ data instanceof ArrayBuffer ||+ ArrayBuffer.isView(data);+ if (!trusted || (!accountApi && !metadata) || binaryBody)+ throw documentPrivacyError();+ return true;+}diff --git a/frontend/editor/src/desktop/services/operationRouter.test.ts b/frontend/editor/src/desktop/services/operationRouter.test.tsindex 648de9ffae..042574c21e 100644--- a/frontend/editor/src/desktop/services/operationRouter.test.ts+++ b/frontend/editor/src/desktop/services/operationRouter.test.ts@@ -18,6 +18,9 @@ vi.mock("@app/services/authService", () => ({// literals (not SAAS_URL/LOCAL_URL) to avoid a TDZ ReferenceError.vi.mock("@app/services/connectionModeService", () => ({connectionModeService: {+ getCurrentConfig: vi+ .fn()+ .mockResolvedValue({ local_processing_only: false }),getCurrentMode: vi.fn().mockResolvedValue("saas"),getServerConfig: vi.fn()@@ -50,8 +53,15 @@ import { operationRouter } from "@app/services/operationRouter";import { connectionModeService } from "@app/services/connectionModeService";import { authService } from "@app/services/authService";import { selfHostedServerMonitor } from "@app/services/selfHostedServerMonitor";+import { endpointAvailabilityService } from "@app/services/endpointAvailabilityService";beforeEach(() => {+ vi.mocked(connectionModeService.getCurrentConfig).mockResolvedValue({+ mode: "saas",+ server_config: null,+ lock_connection_mode: false,+ local_processing_only: false,+ });vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue("saas");vi.mocked(authService.isAuthenticated).mockResolvedValue(true);});@@ -101,6 +111,63 @@ describe("server-owned automation", () => {});});+describe("managed local document processing", () => {+ beforeEach(() => {+ vi.mocked(connectionModeService.getCurrentConfig).mockResolvedValue({+ mode: "saas",+ server_config: null,+ lock_connection_mode: false,+ local_processing_only: true,+ });+ vi.mocked(+ endpointAvailabilityService.isEndpointSupportedLocally,+ ).mockResolvedValue(true);+ vi.mocked(+ endpointAvailabilityService.isEndpointSupportedOnSaaS,+ ).mockClear();+ });+ test.each(["saas", "selfhosted", "local"] as const)(+ "processes supported tools locally in %s mode",+ async (mode) => {+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue(mode);+ await expect(+ operationRouter.getBaseUrl("/api/v1/misc/compress-pdf"),+ ).resolves.toBe("http://localhost:62994");+ expect(+ endpointAvailabilityService.isEndpointSupportedOnSaaS,+ ).not.toHaveBeenCalled();+ },+ );+ test("does not fall back to SaaS when a tool is missing locally", async () => {+ vi.mocked(+ endpointAvailabilityService.isEndpointSupportedLocally,+ ).mockResolvedValue(false);+ await expect(+ operationRouter.getBaseUrl("/api/v1/misc/ocr-pdf"),+ ).rejects.toThrow("stay on this device");+ expect(+ endpointAvailabilityService.isEndpointSupportedOnSaaS,+ ).not.toHaveBeenCalled();+ await expect(+ operationRouter.willRouteToSaaS("/api/v1/misc/ocr-pdf"),+ ).resolves.toBe(false);+ await expect(+ operationRouter.shouldSkipBackendReadyCheck("/api/v1/misc/ocr-pdf"),+ ).resolves.toBe(false);+ });+ test("blocks raw AI/automation destinations while allowing billing", async () => {+ await expect(operationRouter.getConnectedServerBaseUrl()).rejects.toThrow(+ "stay on this device",+ );+ await expect(+ operationRouter.getBaseUrl("/api/v1/storage/files"),+ ).rejects.toThrow("stay on this device");+ await expect(+ operationRouter.getBaseUrl("/api/v1/payg/wallet"),+ ).resolves.toBe(SAAS_URL);+ });+});+describe("operationRouter.getBaseUrl — SaaS mode cloud-only routing", () => {test.each(["/api/v1/payg/wallet",diff --git a/frontend/editor/src/desktop/services/operationRouter.ts b/frontend/editor/src/desktop/services/operationRouter.tsindex 8e4582ab0e..dfd71054b0 100644--- a/frontend/editor/src/desktop/services/operationRouter.ts+++ b/frontend/editor/src/desktop/services/operationRouter.ts@@ -1,4 +1,9 @@import i18n from "@app/i18n";+import {+ isLocalProcessingOnly,+ requiresOffDeviceProcessing,+ documentPrivacyError,+} from "@app/services/documentPrivacyService";import { authService } from "@app/services/authService";import { connectionModeService } from "@app/services/connectionModeService";import { tauriBackendService } from "@app/services/tauriBackendService";@@ -33,6 +38,7 @@ export class OperationRouter {/** Resolves the authenticated server; automation must never fall back to the bundled backend. */async getConnectedServerBaseUrl(): Promise<string> {+ if (await isLocalProcessingOnly()) throw documentPrivacyError();const mode = await connectionModeService.getCurrentMode();await authService.awaitRefreshIfInProgress();if (mode === "local" || !(await authService.isAuthenticated())) {@@ -171,6 +177,28 @@ export class OperationRouter {* @returns Base URL for API calls*/async getBaseUrl(operation?: string): Promise<string> {+ if (await isLocalProcessingOnly()) {+ if (operation && requiresOffDeviceProcessing(operation))+ throw documentPrivacyError();+ if (!operation || !this.isSaaSBackendEndpoint(operation)) {+ const localUrl = tauriBackendService.getBackendUrl();+ if (!localUrl)+ throw new Error(+ "Backend URL not available - backend may still be starting",+ );+ if (+ operation &&+ this.isToolEndpoint(operation) &&+ !(await endpointAvailabilityService.isEndpointSupportedLocally(+ this.extractEndpointName(operation),+ localUrl,+ ))+ ) {+ throw documentPrivacyError();+ }+ return localUrl.replace(/\/$/, "");+ }+ }if (this.isServerAutomationEndpoint(operation)) {return this.getConnectedServerBaseUrl();}@@ -370,6 +398,12 @@ export class OperationRouter {* @returns Promise<boolean> - true if endpoint should skip backend readiness check*/async shouldSkipBackendReadyCheck(endpoint?: string): Promise<boolean> {+ if (await isLocalProcessingOnly())+ return Boolean(+ endpoint &&+ this.isSaaSBackendEndpoint(endpoint) &&+ !requiresOffDeviceProcessing(endpoint),+ );if (this.isServerAutomationEndpoint(endpoint)) return true;if (endpoint?.startsWith("http")) return true;// Team endpoints always skip (existing logic)@@ -402,6 +436,7 @@ export class OperationRouter {* @returns Promise<boolean> - true if endpoint will route to SaaS*/async willRouteToSaaS(endpoint: string): Promise<boolean> {+ if (await isLocalProcessingOnly()) return false;const mode = await connectionModeService.getCurrentMode();// In local mode, show cloud badge for tools not supported locally// (clicking them will prompt sign-in via onUnavailableClick)diff --git a/frontend/editor/src/desktop/services/policyOutputBaseUrl.test.ts b/frontend/editor/src/desktop/services/policyOutputBaseUrl.test.tsindex f63d2f323c..bbd2c40e63 100644--- a/frontend/editor/src/desktop/services/policyOutputBaseUrl.test.ts+++ b/frontend/editor/src/desktop/services/policyOutputBaseUrl.test.ts@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({vi.mock("@app/services/connectionModeService", () => ({connectionModeService: {+ getCurrentConfig: async () => ({ local_processing_only: false }),getCurrentMode: async () => mocks.mode,getServerConfig: async () => mocks.serverConfig,},diff --git a/frontend/editor/src/desktop/services/tauriHttpClient.test.ts b/frontend/editor/src/desktop/services/tauriHttpClient.test.tsindex 015f0da4db..186fdf16af 100644--- a/frontend/editor/src/desktop/services/tauriHttpClient.test.ts+++ b/frontend/editor/src/desktop/services/tauriHttpClient.test.ts@@ -7,6 +7,9 @@ import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";const { fetchMock } = vi.hoisted(() => ({ fetchMock: vi.fn() }));vi.mock("@tauri-apps/plugin-http", () => ({ fetch: fetchMock }));+vi.mock("@app/services/documentPrivacyService", () => ({+ enforceDocumentPrivacy: vi.fn().mockResolvedValue(false),+}));import { create } from "@app/services/tauriHttpClient";diff --git a/frontend/editor/src/desktop/services/tauriHttpClient.ts b/frontend/editor/src/desktop/services/tauriHttpClient.tsindex 45181ca7cd..168ea74976 100644--- a/frontend/editor/src/desktop/services/tauriHttpClient.ts+++ b/frontend/editor/src/desktop/services/tauriHttpClient.ts@@ -1,5 +1,6 @@/* oxlint-disable typescript/no-explicit-any -- Axios-compatible API requires matching axios's `any` signatures */import { fetch } from "@tauri-apps/plugin-http";+import { enforceDocumentPrivacy } from "@app/services/documentPrivacyService";import {shouldUseFastLocalTransport,fetchViaLocalProxy,@@ -212,6 +213,11 @@ class TauriHttpClient {const url = this.buildUrl(finalConfig);const method = (finalConfig.method || "GET").toUpperCase();+ const localProcessingOnly = await enforceDocumentPrivacy(+ url,+ method,+ finalConfig.data,+ );// Prepare request body and headerslet body: BodyInit | undefined;@@ -260,6 +266,7 @@ class TauriHttpClient {// Make the request using Tauri's native HTTP client (standard Fetch API)// Enable certificate bypass for HTTPS to handle missing intermediate certs and self-signed certsconst fetchOptions: RequestInit & {+ maxRedirections?: number;danger?: {acceptInvalidCerts: boolean;acceptInvalidHostnames: boolean;@@ -272,6 +279,7 @@ class TauriHttpClient {? { Origin: "tauri://localhost", ...headers }: headers,body,+ ...(localProcessingOnly ? { maxRedirections: 0 } : {}),credentials,...(finalConfig.signal ? { signal: finalConfig.signal } : {}),};