diff --git a/Cargo.lock b/Cargo.lock index be7f06f6ed6..1ee0fb1c9d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9584,6 +9584,7 @@ dependencies = [ "libc", "maka-agent-facts", "maka-capabilities", + "maka-computer-use", "maka-config", "maka-event-log", "maka-fs-tools", diff --git a/packages/plugin-sdk/src/contracts.ts b/packages/plugin-sdk/src/contracts.ts index eee707f5ac7..73ce16b7beb 100644 --- a/packages/plugin-sdk/src/contracts.ts +++ b/packages/plugin-sdk/src/contracts.ts @@ -20485,6 +20485,109 @@ export const contracts: { }, resources: {}, }, + hostPermissions: { + mode: 'query', + input: { + $schema: 'https://json-schema.org/draft/2020-12/schema', + title: 'HostPermissionsRead', + type: 'object', + properties: { + grant: { + anyOf: [ + { + $ref: '#/$defs/SystemPermissionGrant', + }, + { + type: 'null', + }, + ], + }, + }, + additionalProperties: false, + $defs: { + SystemPermissionGrant: { + description: + 'A macOS privacy grant (TCC) that the Host process itself needs before native\nComputer Use can run. This is operating-system state the user changes in\nSystem Settings, not a Maka grant; the Host observes it and commits the outcome.', + oneOf: [ + { + description: 'System Settings > Privacy & Security > Accessibility.', + type: 'string', + const: 'accessibility', + }, + { + description: + 'System Settings > Privacy & Security > Screen & System Audio Recording.', + type: 'string', + const: 'screen_recording', + }, + ], + }, + }, + }, + output: { + $schema: 'https://json-schema.org/draft/2020-12/schema', + title: 'HostPermissions', + type: 'object', + properties: { + stateDomain: { + type: 'string', + }, + supported: { + type: 'boolean', + }, + application: { + type: 'string', + }, + bundlePath: { + type: ['string', 'null'], + }, + grants: { + type: 'array', + items: { + $ref: '#/$defs/HostGrantState', + }, + }, + }, + additionalProperties: false, + required: ['stateDomain', 'supported', 'application', 'bundlePath', 'grants'], + $defs: { + HostGrantState: { + type: 'object', + properties: { + grant: { + $ref: '#/$defs/SystemPermissionGrant', + }, + effective: { + type: 'boolean', + }, + pendingHost: { + type: 'boolean', + }, + }, + additionalProperties: false, + required: ['grant', 'effective'], + }, + SystemPermissionGrant: { + description: + 'A macOS privacy grant (TCC) that the Host process itself needs before native\nComputer Use can run. This is operating-system state the user changes in\nSystem Settings, not a Maka grant; the Host observes it and commits the outcome.', + oneOf: [ + { + description: 'System Settings > Privacy & Security > Accessibility.', + type: 'string', + const: 'accessibility', + }, + { + description: + 'System Settings > Privacy & Security > Screen & System Audio Recording.', + type: 'string', + const: 'screen_recording', + }, + ], + }, + }, + }, + resources: {}, + }, import: { mode: 'mutation', input: { diff --git a/packages/plugin-sdk/src/generated/methods.ts b/packages/plugin-sdk/src/generated/methods.ts index b04b759c84e..074e4b96e21 100644 --- a/packages/plugin-sdk/src/generated/methods.ts +++ b/packages/plugin-sdk/src/generated/methods.ts @@ -584,6 +584,12 @@ export type AgentHistoryRequestsOutput_AgentHistoryRequestRetry = kind: 'cancelled'; [k: string]: unknown | undefined; }; +/** + * A macOS privacy grant (TCC) that the Host process itself needs before native + * Computer Use can run. This is operating-system state the user changes in + * System Settings, not a Maka grant; the Host observes it and commits the outcome. + */ +export type AgentHostPermissionsOutput_SystemPermissionGrant = 'accessibility' | 'screen_recording'; export type AgentLoadHistoryCheckpointOutput_AgentCheckpointLoadState = | { kind: 'preparing'; @@ -3686,6 +3692,19 @@ export interface ServiceMethods { [k: string]: unknown | undefined; }; }; + hostPermissions: { + mode: 'query'; + input: { + grant?: Runtime.SystemPermissionGrant | null; + }; + output: { + stateDomain: string; + supported: boolean; + application: string; + bundlePath: string | null; + grants: AgentHostPermissionsOutput_HostGrantState[]; + }; + }; import: { mode: 'mutation'; input: Runtime.AgentImportChange; @@ -6416,6 +6435,11 @@ export interface AgentHistoryRequestsOutput_ModelUsage { reasoning_tokens?: number | null; [k: string]: unknown | undefined; } +export interface AgentHostPermissionsOutput_HostGrantState { + grant: AgentHostPermissionsOutput_SystemPermissionGrant; + effective: boolean; + pendingHost?: boolean; +} export interface AgentLoadHistoryCheckpointOutput_AgentHistoryCheckpointHead { revision: string; manifest: AgentLoadHistoryCheckpointOutput_AgentHistoryCheckpointObject; diff --git a/platform/computer-use/src/desktop/worker/macos.rs b/platform/computer-use/src/desktop/worker/macos.rs index d75698e121c..bce111ff601 100644 --- a/platform/computer-use/src/desktop/worker/macos.rs +++ b/platform/computer-use/src/desktop/worker/macos.rs @@ -34,7 +34,7 @@ use std::{ #[derive(Clone, Copy)] pub(crate) enum MacRole { - PermissionStatus, + PermissionStatus(Option), PermissionRequest(SystemPermissionGrant), ListApps, ListWindows { pid: Option }, @@ -43,7 +43,13 @@ pub(crate) enum MacRole { impl MacRole { fn arguments(self) -> Vec { let arguments = match self { - Self::PermissionStatus => vec!["--macos-permission-status"], + Self::PermissionStatus(None) => vec!["--macos-permission-status"], + Self::PermissionStatus(Some(SystemPermissionGrant::Accessibility)) => { + vec!["--macos-permission-status", "accessibility"] + } + Self::PermissionStatus(Some(SystemPermissionGrant::ScreenRecording)) => { + vec!["--macos-permission-status", "screen_recording"] + } Self::PermissionRequest(SystemPermissionGrant::Accessibility) => { vec!["--macos-permission-request", "accessibility"] } @@ -63,7 +69,14 @@ impl MacRole { fn parse(arguments: &[OsString]) -> Option> { let first = arguments.first()?.to_str()?; let role = match first { - "--macos-permission-status" if arguments.len() == 1 => Self::PermissionStatus, + "--macos-permission-status" if arguments.len() == 1 => Self::PermissionStatus(None), + "--macos-permission-status" if arguments.len() == 2 => { + Self::PermissionStatus(Some(match arguments[1].to_str() { + Some("accessibility") => SystemPermissionGrant::Accessibility, + Some("screen_recording") => SystemPermissionGrant::ScreenRecording, + _ => return Some(Err("Unsupported status grant".into())), + })) + } "--macos-list-apps" if arguments.len() == 1 => Self::ListApps, "--macos-list-windows" if arguments.len() == 1 => Self::ListWindows { pid: None }, "--macos-list-windows" if arguments.len() == 2 => { @@ -213,7 +226,7 @@ fn read_output(mut input: impl Read, limit: usize) -> io::Result> { pub(super) fn bootstrap(arguments: &[OsString]) -> Option { let role = MacRole::parse(arguments)?; let result = role.and_then(|role| match role { - MacRole::PermissionStatus => crate::system_permission::process::finite_status(), + MacRole::PermissionStatus(only) => crate::system_permission::process::finite_status(only), MacRole::PermissionRequest(grant) => { watch_request_owner()?; crate::system_permission::process::finite_request(grant) diff --git a/platform/computer-use/src/system_permission.rs b/platform/computer-use/src/system_permission.rs index 1d4b675a89c..fcbad04a5cf 100644 --- a/platform/computer-use/src/system_permission.rs +++ b/platform/computer-use/src/system_permission.rs @@ -87,6 +87,28 @@ pub fn required(command: &Command) -> &'static [SystemPermissionGrant] { } } +/// Effective state in the serving Host compared with a fresh process of the same identity. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PermissionState { + Missing, + Effective, + PendingHost, +} + +pub fn states( + required: &[SystemPermissionGrant], +) -> Result, String> { + #[cfg(all(feature = "native-desktop", target_os = "macos"))] + { + process::states(required) + } + #[cfg(not(all(feature = "native-desktop", target_os = "macos")))] + { + let _ = required; + Ok(Vec::new()) + } +} + /// Whether this Host can observe and request macOS privacy grants. pub const fn supported() -> bool { cfg!(all(feature = "native-desktop", target_os = "macos")) diff --git a/platform/computer-use/src/system_permission/process.rs b/platform/computer-use/src/system_permission/process.rs index 1a0d921b898..bfab9baf8e9 100644 --- a/platform/computer-use/src/system_permission/process.rs +++ b/platform/computer-use/src/system_permission/process.rs @@ -101,10 +101,12 @@ struct Grants { } impl Grants { - fn read() -> Self { + fn read(only: Option) -> Self { Self { - accessibility: tcc::raw_present(Grant::Accessibility), - screen_recording: tcc::raw_present(Grant::ScreenRecording), + accessibility: only != Some(SystemPermissionGrant::ScreenRecording) + && tcc::raw_present(Grant::Accessibility), + screen_recording: only != Some(SystemPermissionGrant::Accessibility) + && tcc::raw_present(Grant::ScreenRecording), } } @@ -145,23 +147,58 @@ pub(super) fn missing( if required.is_empty() { return Ok(Vec::new()); } + missing_from_states(states(required)?) +} + +pub(super) fn states( + required: &[SystemPermissionGrant], +) -> Result, String> { let expected = Subject::current()?; - let value = - macos_finite(MacRole::PermissionStatus, &|| false).map_err(|error| error.to_string())?; + let value = macos_finite( + MacRole::PermissionStatus(match required { + [grant] => Some(*grant), + _ => None, + }), + &|| false, + ) + .map_err(|error| error.to_string())?; let observed = decode(value, &expected)?; - missing_from_snapshot(required, &observed, |grant| tcc::raw_present(grant.into())) + Ok(classify(required, &observed, |grant| { + tcc::raw_present(grant.into()) + })) } -fn missing_from_snapshot( +fn classify( required: &[SystemPermissionGrant], observed: &Snapshot, mut main_present: impl FnMut(SystemPermissionGrant) -> bool, +) -> Vec<(SystemPermissionGrant, super::PermissionState)> { + use super::PermissionState::*; + required + .iter() + .map(|&grant| { + ( + grant, + if !observed.grants.present(grant) { + Missing + } else if main_present(grant) { + Effective + } else { + PendingHost + }, + ) + }) + .collect() +} + +fn missing_from_states( + states: Vec<(SystemPermissionGrant, super::PermissionState)>, ) -> Result, String> { let mut missing = Vec::new(); - for &grant in required { - if !observed.grants.present(grant) { + for (grant, state) in states { + if state == super::PermissionState::Missing { missing.push(grant); - } else if !main_present(grant) { + } else if state == super::PermissionState::PendingHost { return Err(format!( "system_permission_state_disagreement: {} is granted to a fresh process but not effective in Host PID {}", Grant::from(grant).code(), @@ -183,11 +220,11 @@ pub(crate) fn request( Ok(()) } -pub(crate) fn finite_status() -> Result { +pub(crate) fn finite_status(only: Option) -> Result { let subject = Subject::finite_child()?; serde_json::to_value(Snapshot { subject, - grants: Grants::read(), + grants: Grants::read(only), }) .map_err(|error| error.to_string()) } @@ -200,7 +237,7 @@ pub(crate) fn finite_request(grant: SystemPermissionGrant) -> Result bool, + ) -> Result, String> { + missing_from_states(classify(required, observed, main)) + } #[test] fn fresh_grants_require_host_confirmation_without_probing_denied_grants() { let directory = tempfile::tempdir().unwrap(); @@ -246,6 +290,13 @@ mod tests { }) .unwrap(); assert_eq!(missing, [ScreenRecording]); + assert_eq!( + classify(&[Accessibility, ScreenRecording], &observed, |_| false), + [ + (Accessibility, super::super::PermissionState::PendingHost), + (ScreenRecording, super::super::PermissionState::Missing) + ] + ); let error = missing_from_snapshot(&[Accessibility], &observed, |_| false).unwrap_err(); assert!(error.contains("system_permission_state_disagreement: accessibility")); } diff --git a/platform/host-runtime/Cargo.toml b/platform/host-runtime/Cargo.toml index 42c701e3d47..718d10380f7 100644 --- a/platform/host-runtime/Cargo.toml +++ b/platform/host-runtime/Cargo.toml @@ -27,6 +27,7 @@ publish.workspace = true cap-std.workspace = true rusqlite.workspace = true hex.workspace = true +maka-computer-use.workspace = true maka-agent-facts.workspace = true maka-packages.workspace = true maka-capabilities.workspace = true diff --git a/platform/host-runtime/src/application/host.rs b/platform/host-runtime/src/application/host.rs index ecb64aad12e..7536ead1ce0 100644 --- a/platform/host-runtime/src/application/host.rs +++ b/platform/host-runtime/src/application/host.rs @@ -658,6 +658,16 @@ impl Host { ) .await } + Request::RequestComputerPermission { grant } => { + authority.local()?; + let stop = self.accept_closed.clone(); + let result = tokio::task::spawn_blocking(move || { + maka_computer_use::system_permission::request(&[grant], &|| stop.is_cancelled()) + }) + .await + .map_err(|error| error.to_string())?; + wire::write(&mut output, &Response::ComputerPermissionRequested(result)).await + } Request::RemoteAccessStatus { invite_id } => { authority.local()?; wire::write( diff --git a/platform/host-runtime/src/application/host/client.rs b/platform/host-runtime/src/application/host/client.rs index 7cdc8c1a6ea..6d47a117e63 100644 --- a/platform/host-runtime/src/application/host/client.rs +++ b/platform/host-runtime/src/application/host/client.rs @@ -629,11 +629,15 @@ impl Client { _ => Err("Host configuration response mismatch".into()), } } + pub fn is_local_owner(&self) -> bool { + self.phase == Phase::Ready && self.peer.is_none() && !self.target.is_remote() + } + pub fn local_owner_control( &self, request: Request, ) -> impl Future> + use<> { - let local = self.phase == Phase::Ready && self.peer.is_none() && !self.target.is_remote(); + let local = self.is_local_owner(); let target = self.target.clone(); let epoch = self.connected.epoch; async move { diff --git a/platform/host-runtime/src/application/host/protocol.rs b/platform/host-runtime/src/application/host/protocol.rs index c18a878f58b..95af1e3ec9c 100644 --- a/platform/host-runtime/src/application/host/protocol.rs +++ b/platform/host-runtime/src/application/host/protocol.rs @@ -176,6 +176,9 @@ pub enum Request { RevokeAccess { credential: String, }, + RequestComputerPermission { + grant: maka_agent_facts::interaction::SystemPermissionGrant, + }, RemoteAccessStatus { #[serde(default, skip_serializing_if = "Option::is_none")] invite_id: Option, @@ -221,6 +224,7 @@ pub enum Response { PeerAccessRevoked, Pairing(Result), Revoked(Result), + ComputerPermissionRequested(Result<()>), RemoteAccessStatus(Result), RemoteAccessUpdated(Result), PeerPairingInvite(Result), diff --git a/platform/host-runtime/tests/integration/remote_host.rs b/platform/host-runtime/tests/integration/remote_host.rs index 76adb1143f4..71077ad63d8 100644 --- a/platform/host-runtime/tests/integration/remote_host.rs +++ b/platform/host-runtime/tests/integration/remote_host.rs @@ -919,6 +919,9 @@ async fn local_pairing_invite_grants_only_the_redeeming_native_peer_and_can_be_r .is_err() ); for request in [ + Request::RequestComputerPermission { + grant: maka_agent_facts::interaction::SystemPermissionGrant::Accessibility, + }, Request::RemoteAccessStatus { invite_id: Some("invite".into()), }, diff --git a/plugins/agent/api/src/contract.rs b/plugins/agent/api/src/contract.rs index 8422340a50a..b7ec0611a41 100644 --- a/plugins/agent/api/src/contract.rs +++ b/plugins/agent/api/src/contract.rs @@ -2867,6 +2867,7 @@ pub fn contract() -> Contract { MethodMode::Query, ), ), + ("hostPermissions".into(), method::(MethodMode::Query)), ( "systemPermissionStatus".into(), method::(MethodMode::Query), diff --git a/plugins/agent/api/src/contract/interaction.rs b/plugins/agent/api/src/contract/interaction.rs index d20f5e6bdcb..baec77706e0 100644 --- a/plugins/agent/api/src/contract/interaction.rs +++ b/plugins/agent/api/src/contract/interaction.rs @@ -142,3 +142,29 @@ pub struct RequestSystemPermission { pub request_id: String, pub grant: maka_agent_facts::interaction::SystemPermissionGrant, } + +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct HostPermissionsRead { + pub grant: Option, +} + +#[derive(Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct HostPermissions { + pub state_domain: String, + pub supported: bool, + pub application: String, + #[schemars(with = "maka_plugin_core::wire_schema::RequiredNullable")] + pub bundle_path: Option, + pub grants: Vec, +} + +#[derive(Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct HostGrantState { + pub grant: maka_agent_facts::interaction::SystemPermissionGrant, + pub effective: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub pending_host: bool, +} diff --git a/plugins/agent/native/src/service.rs b/plugins/agent/native/src/service.rs index a14bda1473c..9df095667ad 100644 --- a/plugins/agent/native/src/service.rs +++ b/plugins/agent/native/src/service.rs @@ -568,6 +568,45 @@ impl Handler for Agent { .await?, ) }), + "hostPermissions" => json_rpc(&mut args, |owner, input, _context| async move { + let input: HostPermissionsRead = decode(input)?; + use maka_agent_facts::interaction::SystemPermissionGrant::{ + Accessibility, ScreenRecording, + }; + use maka_computer_use::system_permission as os; + let state_domain = owner.data_source.state_domain.clone(); + let snapshot = tokio::task::spawn_blocking(move || { + let supported = os::supported(); + let (application, bundle) = os::application(); + let mut grants = Vec::new(); + if supported { + let required = input.grant.as_slice(); + let all = [Accessibility, ScreenRecording]; + let required = if required.is_empty() { + &all[..] + } else { + required + }; + grants.extend(os::states(required)?.into_iter().map(|(grant, state)| { + HostGrantState { + grant, + effective: state == os::PermissionState::Effective, + pending_host: state == os::PermissionState::PendingHost, + } + })); + } + Ok::<_, String>(HostPermissions { + state_domain, + supported, + application, + bundle_path: bundle.and_then(|p| p.into_os_string().into_string().ok()), + grants, + }) + }) + .await + .map_err(|e| e.to_string())??; + encode(snapshot) + }), "systemPermissionStatus" => json_rpc(&mut args, |owner, input, context| async move { let input: InteractionRead = decode(input)?; owner diff --git a/plugins/settings/settings/package.ts b/plugins/settings/settings/package.ts index 74003fd7ec8..7eeed28f27c 100644 --- a/plugins/settings/settings/package.ts +++ b/plugins/settings/settings/package.ts @@ -70,6 +70,10 @@ export default localizePackage({ kind: 'settings', title: localizedTitle('Network'), }, + 'system-permissions': { + kind: 'settings', + title: localizedTitle('System permissions'), + }, 'remote-access': { kind: 'settings', title: localizedTitle('Remote Access'), diff --git a/plugins/settings/settings/ui.tsx b/plugins/settings/settings/ui.tsx index b8d3ed99f9d..3fe4e135732 100644 --- a/plugins/settings/settings/ui.tsx +++ b/plugins/settings/settings/ui.tsx @@ -32,6 +32,8 @@ import { SettingsSkeleton } from '../../../products/maka/workbench/app/Loading'; import { SettingsProblem } from '../../../products/maka/workbench/app/SettingsPage'; import { ConnectionSettings } from '../../../products/maka/workbench/app/ConnectionSettings'; import { GeneralSettings } from '../../../products/maka/workbench/app/GeneralSettings'; +import { SystemPermissionSettings } from '../../../products/maka/workbench/app/SystemPermissionSettings'; +import { createPermissionSettings } from '../../../products/maka/workbench/app/permissionSettingsState'; import { RemoteAccessSettings } from '../../../products/maka/workbench/app/RemoteAccessSettings'; import { createRemoteAccessSettings } from '../../../products/maka/workbench/app/remoteAccessSettingsState'; import { NetworkSettings } from '../../../products/maka/workbench/app/NetworkSettings'; @@ -150,6 +152,7 @@ export const activate: UiModule['activate'] = (context) => { (locale) => runtime.setLocale(locale), ); const webSearch = createWebSearchSettings(host, operations, active('web-search')); + const permissions = createPermissionSettings(host); const remoteAccess = createRemoteAccessSettings(); const network = createNetworkSettings(host, operations, active('network'), restored?.network); const plugins = createPluginSettings( @@ -580,6 +583,28 @@ export const activate: UiModule['activate'] = (context) => { () => , ), }, + 'system-permissions': { + kind: 'settings', + render: (props) => + mountPage( + 'system-permissions', + permissions, + props, + { + title: () => tr('System permissions'), + navigation: permissions.navigation, + nested: () => false, + back: permissions.back, + ownsError: () => true, + action: () => ({ + label: tr('Refresh'), + run: permissions.refresh, + disabled: permissions.busy(), + }), + }, + () => , + ), + }, 'remote-access': { kind: 'settings', render: (props) => diff --git a/plugins/shared/manifest-locales/de.json b/plugins/shared/manifest-locales/de.json index 89866118a91..9131934dfd2 100644 --- a/plugins/shared/manifest-locales/de.json +++ b/plugins/shared/manifest-locales/de.json @@ -113,6 +113,7 @@ "title.Stop": "Stoppen", "title.Subagents": "Subagenten", "title.Summarize context for the next request": "Kontext für die nächste Anfrage zusammenfassen", + "title.System permissions": "Systemberechtigungen", "title.Text Snippets": "Textbausteine", "title.Web search": "Websuche", "title.Your persistent Bot conversation, created on first use": "Ihre dauerhafte Bot-Unterhaltung, wird bei erster Nutzung erstellt" diff --git a/plugins/shared/manifest-locales/en.json b/plugins/shared/manifest-locales/en.json index 002ec5d77ac..e19868990f2 100644 --- a/plugins/shared/manifest-locales/en.json +++ b/plugins/shared/manifest-locales/en.json @@ -113,6 +113,7 @@ "title.Stop": "Stop", "title.Subagents": "Subagents", "title.Summarize context for the next request": "Summarize context for the next request", + "title.System permissions": "System permissions", "title.Text Snippets": "Text Snippets", "title.Web search": "Web search", "title.Your persistent Bot conversation, created on first use": "Your persistent Bot conversation, created on first use" diff --git a/plugins/shared/manifest-locales/es.json b/plugins/shared/manifest-locales/es.json index 2ab8264c02a..ad1ceb75f2d 100644 --- a/plugins/shared/manifest-locales/es.json +++ b/plugins/shared/manifest-locales/es.json @@ -113,6 +113,7 @@ "title.Stop": "Detener", "title.Subagents": "Subagentes", "title.Summarize context for the next request": "Resumir el contexto para la próxima solicitud", + "title.System permissions": "Permisos del sistema", "title.Text Snippets": "Fragmentos de texto", "title.Web search": "Búsqueda web", "title.Your persistent Bot conversation, created on first use": "Tu conversación persistente con Bot, creada en el primer uso" diff --git a/plugins/shared/manifest-locales/fr.json b/plugins/shared/manifest-locales/fr.json index 429f14a34dd..b9eb953a491 100644 --- a/plugins/shared/manifest-locales/fr.json +++ b/plugins/shared/manifest-locales/fr.json @@ -113,6 +113,7 @@ "title.Stop": "Arrêter", "title.Subagents": "Sous-agents", "title.Summarize context for the next request": "Résumer le contexte pour la prochaine requête", + "title.System permissions": "Autorisations système", "title.Text Snippets": "Extraits de texte", "title.Web search": "Recherche Web", "title.Your persistent Bot conversation, created on first use": "Votre conversation Bot persistante, créée lors de la première utilisation" diff --git a/plugins/shared/manifest-locales/it.json b/plugins/shared/manifest-locales/it.json index 1a932624632..aa19e8d303a 100644 --- a/plugins/shared/manifest-locales/it.json +++ b/plugins/shared/manifest-locales/it.json @@ -113,6 +113,7 @@ "title.Stop": "Interrompi", "title.Subagents": "Subagenti", "title.Summarize context for the next request": "Riassumi il contesto per la richiesta successiva", + "title.System permissions": "Permessi di sistema", "title.Text Snippets": "Frammenti di testo", "title.Web search": "Ricerca web", "title.Your persistent Bot conversation, created on first use": "La tua conversazione persistente con il Bot, creata al primo utilizzo" diff --git a/plugins/shared/manifest-locales/ja.json b/plugins/shared/manifest-locales/ja.json index fc8b86f3080..140c4e6f33e 100644 --- a/plugins/shared/manifest-locales/ja.json +++ b/plugins/shared/manifest-locales/ja.json @@ -113,6 +113,7 @@ "title.Stop": "停止", "title.Subagents": "サブエージェント", "title.Summarize context for the next request": "次のリクエストに向けてコンテキストを要約", + "title.System permissions": "システム権限", "title.Text Snippets": "テキストスニペット", "title.Web search": "ウェブ検索", "title.Your persistent Bot conversation, created on first use": "初回利用時に作成される常駐 Bot との会話" diff --git a/plugins/shared/manifest-locales/ko.json b/plugins/shared/manifest-locales/ko.json index a94b6d6513b..9066dfc1e9a 100644 --- a/plugins/shared/manifest-locales/ko.json +++ b/plugins/shared/manifest-locales/ko.json @@ -113,6 +113,7 @@ "title.Stop": "중지", "title.Subagents": "서브에이전트", "title.Summarize context for the next request": "다음 요청을 위해 컨텍스트 요약", + "title.System permissions": "시스템 권한", "title.Text Snippets": "텍스트 스니펫", "title.Web search": "웹 검색", "title.Your persistent Bot conversation, created on first use": "처음 사용할 때 생성되는 상시 Bot 대화" diff --git a/plugins/shared/manifest-locales/pt-BR.json b/plugins/shared/manifest-locales/pt-BR.json index c1b29a36c61..2991de718b5 100644 --- a/plugins/shared/manifest-locales/pt-BR.json +++ b/plugins/shared/manifest-locales/pt-BR.json @@ -113,6 +113,7 @@ "title.Stop": "Parar", "title.Subagents": "Subagentes", "title.Summarize context for the next request": "Resumir o contexto para a próxima solicitação", + "title.System permissions": "Permissões do sistema", "title.Text Snippets": "Trechos de texto", "title.Web search": "Pesquisa na web", "title.Your persistent Bot conversation, created on first use": "Sua conversa persistente com o Bot, criada no primeiro uso" diff --git a/plugins/shared/manifest-locales/ru.json b/plugins/shared/manifest-locales/ru.json index 90b2e899b4d..b38651b8294 100644 --- a/plugins/shared/manifest-locales/ru.json +++ b/plugins/shared/manifest-locales/ru.json @@ -113,6 +113,7 @@ "title.Stop": "Остановить", "title.Subagents": "Субагенты", "title.Summarize context for the next request": "Суммировать контекст для следующего запроса", + "title.System permissions": "Системные разрешения", "title.Text Snippets": "Фрагменты текста", "title.Web search": "Поиск в интернете", "title.Your persistent Bot conversation, created on first use": "Ваш постоянный диалог с Bot, создаваемый при первом использовании" diff --git a/plugins/shared/manifest-locales/zh-CN.json b/plugins/shared/manifest-locales/zh-CN.json index 3a8b9c9e2e1..98c9150f108 100644 --- a/plugins/shared/manifest-locales/zh-CN.json +++ b/plugins/shared/manifest-locales/zh-CN.json @@ -113,6 +113,7 @@ "title.Stop": "停止", "title.Subagents": "子 Agent", "title.Summarize context for the next request": "为下一次请求整理上下文摘要", + "title.System permissions": "系统权限", "title.Text Snippets": "文本片段", "title.Web search": "网页搜索", "title.Your persistent Bot conversation, created on first use": "常驻的 Bot 对话,首次使用时创建" diff --git a/plugins/shared/manifest-locales/zh-HK.json b/plugins/shared/manifest-locales/zh-HK.json index c0eb0974c60..514710581b3 100644 --- a/plugins/shared/manifest-locales/zh-HK.json +++ b/plugins/shared/manifest-locales/zh-HK.json @@ -38,5 +38,6 @@ "title.Network": "網絡", "title.Plugin marketplace": "插件市集", "title.Remote Access": "遙距存取", - "title.Start a conversation in another folder": "在其他檔案夾中開始對話" + "title.Start a conversation in another folder": "在其他檔案夾中開始對話", + "title.System permissions": "系統權限" } diff --git a/plugins/shared/manifest-locales/zh-TW.json b/plugins/shared/manifest-locales/zh-TW.json index 62cac463ec5..7b36a4a135f 100644 --- a/plugins/shared/manifest-locales/zh-TW.json +++ b/plugins/shared/manifest-locales/zh-TW.json @@ -113,6 +113,7 @@ "title.Stop": "停止", "title.Subagents": "子 Agent", "title.Summarize context for the next request": "為下一次請求整理上下文摘要", + "title.System permissions": "系統權限", "title.Text Snippets": "文字片段", "title.Web search": "網頁搜尋", "title.Your persistent Bot conversation, created on first use": "常駐的 Bot 對話,首次使用時建立" diff --git a/products/maka/cli/src/desktop.rs b/products/maka/cli/src/desktop.rs index ffde4cc1795..3f6100dd2eb 100644 --- a/products/maka/cli/src/desktop.rs +++ b/products/maka/cli/src/desktop.rs @@ -100,6 +100,24 @@ impl Args { _ = stop.cancelled() => return Ok(ExitCode::SUCCESS), }; let result = Self::launch(&root, &client, &stop).await; + #[cfg(target_os = "macos")] + let result = { + let mut result = result; + while matches!(result, Ok(code) if code == i32::from(maka_updater::RELAUNCH_DESKTOP)) { + if stop.is_cancelled() { + result = Ok(0); + break; + } + // Retain the lease until the old shell has exited and the new shell is admitted. + // If the UI reconnected to a replacement Host, follow the same Root. + if !runs(&root, client.epoch()).await { + let _ = client.close().await; + client = crate::deployment::connect_local(root.clone()).await?; + } + result = Self::launch(&root, &client, &stop).await; + } + result + }; let mut cleanup = if matches!(&result, Ok(0)) { client.quit_ephemeral().await } else { @@ -142,7 +160,12 @@ impl Args { let executable = desktop_shell_path(&launcher); let root = std::path::absolute(root)?; let epoch = registered.host_epoch.to_string(); - let variables: [(&str, &std::ffi::OsStr); 4] = [ + let variables: &[(&str, &std::ffi::OsStr)] = &[ + #[cfg(target_os = "macos")] + ( + maka_updater::RELAUNCH_SUPPORTED_ENV, + std::ffi::OsStr::new("1"), + ), ("MAKA_HOST_ROOT", root.as_ref()), ("MAKA_HOST_ENDPOINT", registered.endpoint.as_ref()), ("MAKA_HOST_EPOCH", epoch.as_ref()), @@ -150,10 +173,10 @@ impl Args { ("MAKA_LAUNCHER", launcher.as_ref()), ]; #[cfg(target_os = "macos")] - let child = disclaimed::Shell::spawn(&executable, &variables); + let child = disclaimed::Shell::spawn(&executable, variables); #[cfg(not(target_os = "macos"))] let child = Command::new(&executable) - .envs(variables) + .envs(variables.iter().copied()) .kill_on_drop(true) .spawn(); let mut child = child.map_err(|error| format!("{}: {error}", executable.display()))?; diff --git a/products/maka/client/src/lib.rs b/products/maka/client/src/lib.rs index e6bfe1dc12f..d1723138ae4 100644 --- a/products/maka/client/src/lib.rs +++ b/products/maka/client/src/lib.rs @@ -406,6 +406,10 @@ impl Client { .clone()) } + pub async fn is_local_owner(&self) -> bool { + self.0.host.lock().await.is_local_owner() + } + pub async fn local_owner_control( &self, request: maka_host_runtime::application::host::protocol::Request, diff --git a/products/maka/desktop-shell/Cargo.toml b/products/maka/desktop-shell/Cargo.toml index 18e7a64a669..6382d7e8f6d 100644 --- a/products/maka/desktop-shell/Cargo.toml +++ b/products/maka/desktop-shell/Cargo.toml @@ -61,7 +61,7 @@ maka-ui-build.workspace = true nsh-platform-macos = { workspace = true, features = ["terminal"] } block2 = { version = "0.6.2", default-features = false, features = ["std"] } dispatch2 = { version = "0.3.1", default-features = false, features = ["std", "objc2"] } -objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "objc2-core-foundation", "objc2-core-graphics", "NSApplication", "NSAttributedString", "block2", "NSBezierPath", "NSBitmapImageRep", "NSColor", "NSColorSpace", "NSActionCell", "NSCell", "NSControl", "NSCursor", "NSDraggingItem", "NSDraggingSession", "NSEvent", "NSFont", "NSGraphics", "NSGraphicsContext", "NSImage", "NSImageCell", "NSImageRep", "NSImageView", "NSPanel", "NSPasteboard", "NSOpenPanel", "NSResponder", "NSSavePanel", "NSScreen", "NSStringDrawing", "NSText", "NSTextField", "NSTrackingArea", "NSView", "NSWindow", "NSWorkspace"] } +objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "objc2-core-foundation", "objc2-core-graphics", "NSApplication", "NSAttributedString", "block2", "NSBezierPath", "NSBitmapImageRep", "NSColor", "NSColorSpace", "NSActionCell", "NSCell", "NSControl", "NSCursor", "NSDraggingItem", "NSDraggingSession", "NSEvent", "NSFont", "NSGraphics", "NSGraphicsContext", "NSImage", "NSImageCell", "NSImageRep", "NSImageView", "NSPanel", "NSRunningApplication", "libc", "NSPasteboard", "NSOpenPanel", "NSResponder", "NSSavePanel", "NSScreen", "NSStringDrawing", "NSText", "NSTextField", "NSTrackingArea", "NSView", "NSWindow", "NSWorkspace"] } objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["std", "CFArray", "CFCGTypes"] } objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "CGBitmapContext", "CGColorSpace", "CGContext", "CGDirectDisplay", "CGError", "CGImage", "CGRemoteOperation", "CGWindow"] } objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "objc2-core-foundation", "NSArray", "NSBundle", "NSData", "NSDate", "NSDateFormatter", "NSDictionary", "NSError", "NSFormatter", "NSGeometry", "NSPathUtilities", "NSString", "NSURL", "NSUserDefaults", "NSValue"] } diff --git a/products/maka/desktop-shell/src/appkit.rs b/products/maka/desktop-shell/src/appkit.rs index 0e4e11ae510..8f9d644d143 100644 --- a/products/maka/desktop-shell/src/appkit.rs +++ b/products/maka/desktop-shell/src/appkit.rs @@ -21,6 +21,7 @@ //! belong to that connection and close before a replacement client is loaded. mod permissions; +pub(crate) mod relaunch; use crate::{ host::{self, Connection, Root}, @@ -66,6 +67,7 @@ pub(crate) fn start(target: crate::Target) -> Result<(), String> { } pub fn run(first: Connection, root: Root, runtime: Runtime) -> Result<(), String> { + relaunch::remember_executable(); let directory = first .config .data_dir @@ -109,6 +111,7 @@ pub fn run(first: Connection, root: Root, runtime: Runtime) -> Result<(), String ) }; carry_out(requests, &runtime); + shell.enable_permission_restart(&first.bindings); let windows = permission_requests(&first); refuse_reloads( first @@ -245,6 +248,12 @@ async fn follow( if let Some(request) = request { let alive = alive.clone(); let configuration = configuration.clone(); + if let Some(guide)=request.guide.clone() { + tokio::spawn(async move { + guide.closed().await; + with_running_view(move |_|permissions::close_guide(Some(guide.id))); + }); + } with_running_view(move |_| { if alive.load(Ordering::Acquire) { permissions::open(request, alive, &configuration); } }); @@ -253,6 +262,9 @@ async fn follow( } } alive.store(false, Ordering::Release); + if let Some(current) = bindings.as_ref() { + current.close_permission_guide(); + } if wait_while_updating(&mut updating, &mut quit).await { break 'connected; } @@ -319,6 +331,7 @@ async fn follow( break 'connected; } }; + shell.enable_permission_restart(&next.bindings); windows = permission_requests(&next); let Connection { bindings: admitted, @@ -354,7 +367,9 @@ async fn follow( }); } if let Some(bindings) = bindings { - if !*updating.borrow() { + if relaunch::RESTARTING.load(Ordering::Acquire) { + host::detach(bindings, &endpoint, epoch).await; + } else if !*updating.borrow() { host::quit(bindings).await; } } diff --git a/products/maka/desktop-shell/src/appkit/permissions.rs b/products/maka/desktop-shell/src/appkit/permissions.rs index ccbbee936de..7737aa6d368 100644 --- a/products/maka/desktop-shell/src/appkit/permissions.rs +++ b/products/maka/desktop-shell/src/appkit/permissions.rs @@ -20,16 +20,23 @@ //! Permission setup windows and their application-file drag source. Paths only //! enter through the verified workbench request, never component props. -use maka_workbench::bindings::SystemPermissionWindow; +use maka_workbench::bindings::{PermissionGuide, SystemPermissionWindow}; use nsh_engine::{EngineConfig, JsonValue}; use nsh_platform_macos::{ AppOptions, AppView, - objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, rc::Retained}, + objc2::{ + DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, rc::Retained, + runtime::ProtocolObject, + }, objc2_app_kit::{ - NSBackingStoreType, NSResponder, NSWindow, NSWindowButton, NSWindowStyleMask, - NSWindowTitleVisibility, + NSBackingStoreType, NSFloatingWindowLevel, NSPanel, NSResponder, NSWindow, NSWindowButton, + NSWindowCollectionBehavior, NSWindowStyleMask, NSWindowTitleVisibility, + NSWindowWillMoveNotification, + }, + objc2_foundation::{ + NSNotification, NSNotificationCenter, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, + NSString, }, - objc2_foundation::{NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString}, }; use std::{ cell::RefCell, @@ -46,7 +53,24 @@ struct SetupWindow { view: Rc, } +struct GuideWindow { + lease: PermissionGuide, + panel: Retained, + view: Rc, + moved: Rc>, + observer: Retained>, +} +impl Drop for GuideWindow { + fn drop(&mut self) { + // SAFETY: this is our observer token, registered on the default center. + unsafe { + NSNotificationCenter::defaultCenter().removeObserver(self.observer.as_ref()); + } + } +} + thread_local! { + static GUIDE: RefCell> = const { RefCell::new(None) }; static WINDOWS: RefCell> = RefCell::new(HashMap::new()); } @@ -99,12 +123,21 @@ pub(super) fn open(request: SystemPermissionWindow, alive: Arc, pare data_dir: config.data_dir.clone(), ..Default::default() }; + let lease = request.guide.clone(); + if lease.as_ref().is_some_and(|guide| !guide.active()) { + return; + } + let drag_alive = alive.clone(); + let drag_lease = lease.clone(); let native_drag = match request.application() { Some(application) => match crate::permission_application::register( &options.components, mtm, application, - alive.clone(), + Rc::new(move || { + drag_alive.load(Ordering::Acquire) + && drag_lease.as_ref().is_none_or(PermissionGuide::active) + }), ) { Ok(()) => true, Err(error) => { @@ -117,6 +150,10 @@ pub(super) fn open(request: SystemPermissionWindow, alive: Arc, pare let mut params = config.host.params(); params.insert("nativeApplicationDrag".into(), JsonValue::Bool(native_drag)); config.host.set_params(params); + if let Some(guide) = lease { + open_guide(guide, config, options, mtm); + return; + } let resizing = key.clone(); let resize_alive = alive.clone(); config.host.handle( @@ -197,6 +234,115 @@ pub(super) fn open(request: SystemPermissionWindow, alive: Arc, pare }); } +fn open_guide( + guide: PermissionGuide, + config: EngineConfig, + mut options: AppOptions, + mtm: MainThreadMarker, +) { + close_guide(None); + if !guide.active() { + return; + } + options.size = (400, 144); + let closing = guide.clone(); + config + .host + .handle("computerPermissions.close", move |call| { + closing.close(); + call.resolve(JsonValue::Null); + }); + let size = NSSize::new(400., 144.); + // SAFETY: the main thread owns the panel, its engine and its content view. + let panel = NSPanel::initWithContentRect_styleMask_backing_defer( + NSPanel::alloc(mtm), + NSRect::new(NSPoint::ZERO, size), + NSWindowStyleMask::NonactivatingPanel + | NSWindowStyleMask::Titled + | NSWindowStyleMask::FullSizeContentView, + NSBackingStoreType::Buffered, + false, + ); + unsafe { + panel.setReleasedWhenClosed(false); + } + panel.setTitleVisibility(NSWindowTitleVisibility::Hidden); + panel.setTitlebarAppearsTransparent(true); + panel.setFloatingPanel(true); + panel.setHidesOnDeactivate(false); + panel.setBecomesKeyOnlyIfNeeded(true); + panel.setMovableByWindowBackground(true); + let view = AppView::new(mtm, options); + panel.setContentView(Some(&view.view())); + panel.setLevel(NSFloatingWindowLevel); + panel.setCollectionBehavior( + NSWindowCollectionBehavior::CanJoinAllSpaces + | NSWindowCollectionBehavior::FullScreenAuxiliary, + ); + let fits = crate::permission_window::place_guide(&panel); + view.load_with_config(config); + if fits { + panel.orderFrontRegardless(); + } + let moved = Rc::new(std::cell::Cell::new(false)); + let observer = observe_interactive_move(&panel, moved.clone()); + let id = guide.id; + GUIDE.with(|slot| { + *slot.borrow_mut() = Some(GuideWindow { + lease: guide, + panel, + view, + moved, + observer, + }) + }); + follow_settings(id); +} + +fn follow_settings(id: uuid::Uuid) { + let next = dispatch2::DispatchTime::NOW.time(350_000_000); + if let Err(error) = dispatch2::DispatchQueue::main().after(next, move || { + let panel = GUIDE.with(|slot| { + let slot = slot.borrow(); + let window = slot.as_ref()?; + (window.lease.id == id && window.lease.active() && !window.moved.get()) + .then(|| window.panel.clone()) + }); + if let Some(panel) = panel { + let fits = crate::permission_window::place_guide(&panel); + if fits && !panel.isVisible() { + panel.orderFrontRegardless(); + } + if !fits && panel.isVisible() { + panel.orderOut(None); + } + follow_settings(id); + } + }) { + eprintln!("maka-desktop-shell: scheduling permission guide placement: {error:?}"); + } +} + +pub(super) fn close_guide(id: Option) { + let old = GUIDE.with(|slot| { + let mut slot = slot.borrow_mut(); + if slot + .as_ref() + .is_some_and(|window| id.is_none_or(|id| id == window.lease.id)) + { + slot.take() + } else { + None + } + }); + if let Some(window) = old { + window.lease.close(); + window.panel.orderOut(None); + window.view.stop(); + window.panel.close(); + } +} + fn close(key: &str) { let window = WINDOWS.with(|windows| windows.borrow().get(key).map(|w| w.window.clone())); if let Some(window) = window { @@ -205,6 +351,7 @@ fn close(key: &str) { } pub(super) fn close_all() { + close_guide(None); // Close outside the borrow: NSWindow's close override removes its entry. let windows: Vec<_> = WINDOWS.with(|windows| { windows @@ -217,3 +364,43 @@ pub(super) fn close_all() { window.close(); } } + +fn observe_interactive_move( + sender: &NSObject, + drag: Rc>, +) -> Retained> { + let block = block2::RcBlock::new(move |_: std::ptr::NonNull| drag.set(true)); + // WillMove is the AppKit notification for the start of an interactive move. + // Frame changes made by setFrame:display: only post DidMove. + unsafe { + NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock( + Some(NSWindowWillMoveNotification), + Some(sender), + None, + &block, + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn only_an_interactive_move_of_this_panel_disables_following() { + use nsh_platform_macos::objc2_app_kit::NSWindowDidMoveNotification; + let panel = NSObject::new(); + let other = NSObject::new(); + let moved = Rc::new(std::cell::Cell::new(false)); + let observer = observe_interactive_move(&panel, moved.clone()); + let center = NSNotificationCenter::defaultCenter(); + // SAFETY: notifications and registration are synchronous on this test thread. + unsafe { + center.postNotificationName_object(NSWindowDidMoveNotification, Some(&panel)); + center.postNotificationName_object(NSWindowWillMoveNotification, Some(&other)); + assert!(!moved.get()); + center.postNotificationName_object(NSWindowWillMoveNotification, Some(&panel)); + center.removeObserver(observer.as_ref()); + } + assert!(moved.get()); + } +} diff --git a/products/maka/desktop-shell/src/appkit/relaunch.rs b/products/maka/desktop-shell/src/appkit/relaunch.rs new file mode 100644 index 00000000000..88c5613ab90 --- /dev/null +++ b/products/maka/desktop-shell/src/appkit/relaunch.rs @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +//! Local macOS grants belong to this desktop process. +use dispatch2::DispatchQueue; +use std::{ + os::unix::fs::{MetadataExt, PermissionsExt}, + sync::{Arc, OnceLock}, +}; +use tokio::sync::oneshot::Sender; + +static STARTED_EXECUTABLE: OnceLock<(u64, u64)> = OnceLock::new(); +fn executable_identity() -> Option<(u64, u64)> { + let file = std::fs::metadata(std::env::current_exe().ok()?).ok()?; + (file.is_file() && file.permissions().mode() & 0o111 != 0).then(|| (file.dev(), file.ino())) +} +pub(crate) fn remember_executable() { + if let Some(id) = executable_identity() { + let _ = STARTED_EXECUTABLE.set(id); + } +} + +// Set only after the ordinary Quit path accepted the request. +pub(crate) static RESTARTING: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + +pub(crate) fn restart(call: Sender>, updater: Arc) { + use nsh_platform_macos::objc2::MainThreadMarker; + use std::sync::atomic::Ordering; + if !supported() { + let _ = call.send(Err("The current launcher cannot reopen this desktop".into())); + return; + } + DispatchQueue::main().exec_async(move || { + let mtm = MainThreadMarker::new().expect("restart runs on AppKit's main thread"); + if !updater.reserve_desktop_restart() { + let _ = call.send(Err("An update or restart is in progress".into())); + return; + } + if nsh_platform_macos::try_quit_for_relaunch(mtm) { + RESTARTING.store(true, Ordering::Release); + let _ = call.send(Ok(())); + } else { + updater.cancel_desktop_restart(); + let _ = call.send(Err("The desktop could not complete its normal quit".into())); + } + }); +} + +pub(crate) fn supported() -> bool { + std::env::var(maka_updater::RELAUNCH_SUPPORTED_ENV).as_deref() == Ok("1") + && executable_identity().is_some_and(|id| STARTED_EXECUTABLE.get() == Some(&id)) +} diff --git a/products/maka/desktop-shell/src/main.rs b/products/maka/desktop-shell/src/main.rs index 545484ad538..5913b657111 100644 --- a/products/maka/desktop-shell/src/main.rs +++ b/products/maka/desktop-shell/src/main.rs @@ -44,6 +44,8 @@ mod permission_window; mod screenshot; #[cfg(windows)] mod screenshot_windows; +#[cfg(target_os = "macos")] +mod window_list; #[cfg(windows)] use direct2d as backend; #[cfg(any(target_os = "linux", target_os = "macos", windows))] @@ -178,6 +180,10 @@ fn main() -> ExitCode { return ExitCode::SUCCESS; } match run() { + #[cfg(target_os = "macos")] + Ok(()) if appkit::relaunch::RESTARTING.load(std::sync::atomic::Ordering::Acquire) => { + ExitCode::from(maka_updater::RELAUNCH_DESKTOP) + } Ok(()) => ExitCode::SUCCESS, Err(error) => { eprintln!("maka-desktop-shell: {error}"); @@ -200,6 +206,10 @@ fn run() -> Result<(), String> { return launch(); } let target = Target::from(|name| std::env::var_os(name))?; + #[cfg(target_os = "macos")] + if let Ok(shell) = std::env::current_exe().and_then(|path| path.canonicalize()) { + reopen_root(&shell, Some(&target.root)); + } backend::start(target) } @@ -254,6 +264,26 @@ fn launcher_path(shell: &std::path::Path) -> Result { .map(|dir| dir.join(binary)) } +/// LaunchServices reopens the bundle without the CLI environment. Remember only the +/// Root for this installation. The CLI discovers and verifies its current Host. +#[cfg(target_os = "macos")] +fn reopen_root(shell: &std::path::Path, save: Option<&std::path::Path>) -> Option { + use objc2_foundation::{NSString, NSURL, NSUserDefaults}; + + let installation = NSURL::from_file_path(shell)?.absoluteString()?; + let key = NSString::from_str(&format!("MakaDesktopRoot/{installation}")); + let defaults = NSUserDefaults::standardUserDefaults(); + if let Some(root) = save { + let url = NSURL::from_directory_path(root)?; + defaults.setURL_forKey(Some(&url), &key); + return Some(root.to_owned()); + } + defaults + .URLForKey(&key)? + .to_file_path() + .filter(|path| path.is_absolute()) +} + /// Runs `maka desktop` from the directory the launcher stages the shell in, /// forwarding Windows shortcut arguments or defaulting to the restarted Root. #[cfg(any(target_os = "linux", target_os = "macos", windows))] @@ -266,9 +296,11 @@ fn launch() -> Result<(), String> { command.arg("desktop"); #[cfg(windows)] command.args(std::env::args_os().skip(1)); + let root = std::env::var_os(maka_updater::RESTART_ROOT_ENV).filter(|root| !root.is_empty()); + #[cfg(target_os = "macos")] + let root = root.or_else(|| reopen_root(&shell, None).map(PathBuf::into_os_string)); if command.get_args().len() == 1 - && let Some(root) = - std::env::var_os(maka_updater::RESTART_ROOT_ENV).filter(|root| !root.is_empty()) + && let Some(root) = root { command.arg("--root").arg(root); } @@ -314,6 +346,31 @@ mod tests { assert_eq!(answer(&[]), None); } + #[cfg(target_os = "macos")] + #[test] + fn launchservices_reopen_restores_only_this_installations_root() { + use objc2_foundation::{NSString, NSURL, NSUserDefaults}; + let dir = std::env::temp_dir().join(uuid::Uuid::new_v4().to_string()); + let shell = dir.join("Maka Preview.app/Contents/MacOS/maka-desktop-shell"); + let root = dir.join("isolated host"); + assert_eq!(reopen_root(&shell, None), None); + reopen_root(&shell, Some(&root)); + assert_eq!(reopen_root(&shell, None), Some(root)); + assert_eq!( + reopen_root( + &dir.join("other/Maka Preview.app/Contents/MacOS/maka-desktop-shell"), + None + ), + None + ); + let url = NSURL::from_file_path(&shell) + .unwrap() + .absoluteString() + .unwrap(); + NSUserDefaults::standardUserDefaults() + .removeObjectForKey(&NSString::from_str(&format!("MakaDesktopRoot/{url}"))); + } + #[cfg(target_os = "macos")] #[test] fn launcher_path_prefers_self_contained_bundle_and_falls_back_to_sibling_layout() { diff --git a/products/maka/desktop-shell/src/permission_application.rs b/products/maka/desktop-shell/src/permission_application.rs index 9f1f95172bb..97718b375d0 100644 --- a/products/maka/desktop-shell/src/permission_application.rs +++ b/products/maka/desktop-shell/src/permission_application.rs @@ -34,22 +34,14 @@ use nsh_platform_macos::{ NSArray, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString, NSURL, }, }; -use std::{ - cell::Cell, - path::Path, - rc::Rc, - sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - }, -}; +use std::{cell::Cell, path::Path, rc::Rc}; /// The caller supplies the verified Host application; UI props cannot choose it. pub(crate) fn register( components: &Components, mtm: MainThreadMarker, application: &Path, - alive: Arc, + alive: Rc bool>, ) -> Result<(), String> { let path = application .to_str() @@ -114,10 +106,18 @@ impl DragGesture { } } +fn file_drag_operations(context: NSDraggingContext, active: bool) -> NSDragOperation { + if active && context == NSDraggingContext::OutsideApplication { + NSDragOperation::Copy | NSDragOperation::Link | NSDragOperation::Generic + } else { + NSDragOperation::None + } +} + struct IconState { icon: Retained, url: Retained, - alive: Arc, + alive: Rc bool>, gesture: DragGesture, context: ComponentContext, } @@ -131,8 +131,8 @@ define_class!( unsafe impl NSObjectProtocol for ApplicationIcon {} unsafe impl NSDraggingSource for ApplicationIcon { #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))] - fn drag_operations(&self, _session: &NSDraggingSession, _context: NSDraggingContext) -> NSDragOperation { - if self.ivars().alive.load(Ordering::Acquire) { NSDragOperation::Copy } else { NSDragOperation::None } + fn drag_operations(&self, _session: &NSDraggingSession, context: NSDraggingContext) -> NSDragOperation { + file_drag_operations(context, (self.ivars().alive)()) } #[unsafe(method(draggingSession:endedAtPoint:operation:))] fn drag_ended(&self, _session: &NSDraggingSession, _point: NSPoint, _operation: NSDragOperation) { @@ -149,17 +149,17 @@ define_class!( fn mouse_down_can_move_window(&self) -> bool { false } #[unsafe(method(acceptsFirstMouse:))] fn accepts_first_mouse(&self, _event: Option<&NSEvent>) -> bool { - self.ivars().alive.load(Ordering::Acquire) + (self.ivars().alive)() } #[unsafe(method(mouseDown:))] fn mouse_down(&self, _event: &NSEvent) { - if self.ivars().alive.load(Ordering::Acquire) { self.ivars().gesture.press(); } + if (self.ivars().alive)() { self.ivars().gesture.press(); } } #[unsafe(method(mouseUp:))] fn mouse_up(&self, _event: &NSEvent) { self.ivars().gesture.release(); } #[unsafe(method(mouseDragged:))] fn mouse_dragged(&self, event: &NSEvent) { - if !self.ivars().alive.load(Ordering::Acquire) || !self.ivars().gesture.begin() { return; } + if !(self.ivars().alive)() || !self.ivars().gesture.begin() { return; } let writer = ProtocolObject::from_ref(&*self.ivars().url); let item = NSDraggingItem::initWithPasteboardWriter(NSDraggingItem::alloc(), writer); // SAFETY: contents is an NSImage, one of AppKit's supported drag images. @@ -189,7 +189,7 @@ impl ApplicationIcon { mtm: MainThreadMarker, icon: Retained, url: Retained, - alive: Arc, + alive: Rc bool>, context: ComponentContext, ) -> Retained { let allocated = Self::alloc(mtm).set_ivars(IconState { @@ -228,7 +228,21 @@ impl NativeComponent for ApplicationComponent { #[cfg(test)] mod tests { - use super::DragGesture; + use super::*; + + #[test] + fn external_settings_list_can_negotiate_a_file_drop() { + let external = NSDraggingContext::OutsideApplication; + let mask = file_drag_operations(external, true); + assert!( + mask.contains(NSDragOperation::Copy | NSDragOperation::Generic | NSDragOperation::Link) + ); + assert_eq!(file_drag_operations(external, false), NSDragOperation::None); + assert_eq!( + file_drag_operations(NSDraggingContext::WithinApplication, true), + NSDragOperation::None + ); + } #[test] fn a_gesture_starts_only_one_session_even_with_reentrant_mouse_events() { diff --git a/products/maka/desktop-shell/src/permission_window.rs b/products/maka/desktop-shell/src/permission_window.rs index c00133ba4f0..1eaeb97300d 100644 --- a/products/maka/desktop-shell/src/permission_window.rs +++ b/products/maka/desktop-shell/src/permission_window.rs @@ -21,8 +21,8 @@ use nsh_platform_macos::{ objc2::MainThreadOnly, - objc2_app_kit::{NSFloatingWindowLevel, NSScreen, NSWindow}, - objc2_foundation::{NSPoint, NSRect, NSSize}, + objc2_app_kit::{NSFloatingWindowLevel, NSRunningApplication, NSScreen, NSWindow}, + objc2_foundation::{NSPoint, NSRect, NSSize, NSString}, }; /// Only for a newly opened permission utility, never its parent workbench or a @@ -30,23 +30,199 @@ use nsh_platform_macos::{ pub(crate) fn configure(window: &NSWindow) { window.setLevel(NSFloatingWindowLevel); if let Some(screen) = NSScreen::mainScreen(window.mtm()).or_else(|| window.screen()) { - let visible = screen.visibleFrame(); - let size = window.frame().size; - let size = NSSize::new( - size.width.min(visible.size.width), - size.height.min(visible.size.height), - ); - window.setFrame_display( - NSRect::new( - NSPoint::new( - (visible.origin.x + visible.size.width - size.width - 16.0) - .max(visible.origin.x), - (visible.origin.y + visible.size.height - size.height - 16.0) - .max(visible.origin.y), - ), - size, + window.setFrame_display(corner(window.frame().size, screen.visibleFrame()), false); + } +} + +/// Called only for the nonactivating Settings guide, while its lease is live. +pub(crate) fn place_guide(window: &NSWindow) -> bool { + let mtm = window.mtm(); + let screens = NSScreen::screens(mtm); + let Some(primary) = screens.firstObject() else { + return false; + }; + let fallback = NSScreen::mainScreen(mtm) + .unwrap_or_else(|| primary.clone()) + .visibleFrame(); + let settings = NSRunningApplication::runningApplicationsWithBundleIdentifier( + &NSString::from_str("com.apple.systempreferences"), + ) + .firstObject() + .and_then(|app| { + // A sheet may be in front of the main window. Prefer the largest normal window. + crate::window_list::on_screen(Some(app.processIdentifier())) + .into_iter() + .map(|w| w.bounds) + .max_by(|a, b| area(*a).total_cmp(&area(*b))) + }) + .map(|bounds| appkit_bounds(bounds, primary.frame().max().y)); + let frame = guide_frame( + window.frame().size, + settings, + screens.iter().map(|s| (s.frame(), s.visibleFrame())), + fallback, + ); + let Some(frame) = frame else { return false }; + if window.frame() != frame { + window.setFrame_display(frame, false); + } + true +} + +fn appkit_bounds(cg: NSRect, primary_top: f64) -> NSRect { + NSRect::new(NSPoint::new(cg.min().x, primary_top - cg.max().y), cg.size) +} + +fn fit(size: NSSize, visible: NSRect) -> NSSize { + NSSize::new( + size.width.min(visible.size.width), + size.height.min(visible.size.height), + ) +} + +fn corner(size: NSSize, visible: NSRect) -> NSRect { + let size = fit(size, visible); + NSRect::new( + NSPoint::new( + (visible.max().x - size.width - 16.).max(visible.min().x), + (visible.max().y - size.height - 16.).max(visible.min().y), + ), + size, + ) +} + +fn area(rect: NSRect) -> f64 { + rect.size.width * rect.size.height +} + +fn guide_frame( + size: NSSize, + settings: Option, + screens: impl IntoIterator, + fallback: NSRect, +) -> Option { + let Some(settings) = settings else { + return Some(corner(size, fallback)); + }; + let screens: Vec<_> = screens.into_iter().collect(); + let overlap = |frame: NSRect| { + let width = frame.max().x.min(settings.max().x) - frame.min().x.max(settings.min().x); + let height = frame.max().y.min(settings.max().y) - frame.min().y.max(settings.min().y); + width.max(0.) * height.max(0.) + }; + let Some((_, visible)) = screens + .iter() + .filter(|(f, _)| overlap(*f) > 0.) + .max_by(|(a, _), (b, _)| overlap(*a).total_cmp(&overlap(*b))) + else { + return Some(corner(size, fallback)); + }; + const GAP: f64 = 8.; + for visible in + std::iter::once(visible).chain(screens.iter().map(|(_, v)| v).filter(|v| *v != visible)) + { + if visible.size.width < size.width || visible.size.height < size.height { + continue; + } + let max_x = visible.max().x - size.width; + let max_y = visible.max().y - size.height; + let x = (settings.mid().x - size.width / 2.) + .round() + .clamp(visible.min().x, max_x); + let y = (settings.mid().y - size.height / 2.) + .round() + .clamp(visible.min().y, max_y); + for origin in [ + NSPoint::new(x, (settings.min().y - GAP - size.height).min(max_y)), + NSPoint::new(x, (settings.max().y + GAP).max(visible.min().y)), + NSPoint::new((settings.max().x + GAP).max(visible.min().x), y), + NSPoint::new((settings.min().x - GAP - size.width).min(max_x), y), + ] { + if (visible.min().x..=max_x).contains(&origin.x) + && (visible.min().y..=max_y).contains(&origin.y) + { + return Some(NSRect::new(origin, size)); + } + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + const PANEL: NSSize = NSSize::new(400., 180.); + fn rect(x: f64, y: f64, w: f64, h: f64) -> NSRect { + NSRect::new(NSPoint::new(x, y), NSSize::new(w, h)) + } + #[test] + fn converts_quartz_global_points_using_primary_top_even_above_the_primary() { + assert_eq!( + appkit_bounds(rect(-540., -400., 500., 300.), 900.), + rect(-540., 1000., 500., 300.) + ); + assert_eq!( + appkit_bounds(rect(100., 80., 700., 400.), 900.), + rect(100., 420., 700., 400.) + ); + } + #[test] + fn centers_below_settings_on_the_screen_with_the_largest_intersection() { + let main = rect(0., 0., 1440., 900.); + let left = rect(-1024., 200., 1024., 768.); + let screens = [ + (main, rect(0., 40., 1440., 830.)), + (left, rect(-1024., 240., 1024., 700.)), + ]; + assert_eq!( + guide_frame(PANEL, Some(rect(200., 340., 800., 440.)), screens, main), + Some(rect(400., 152., 400., 180.)) + ); + assert_eq!( + guide_frame(PANEL, Some(rect(-520., 580., 680., 340.)), screens, main), + Some(rect(-400., 392., 400., 180.)) + ); + } + #[test] + fn prefers_above_then_the_unobstructed_side() { + let screen = rect(0., 0., 1200., 900.); + let visible = rect(40., 60., 1160., 810.); + let screens = [(screen, visible)]; + assert_eq!( + guide_frame(PANEL, Some(rect(900., 100., 400., 500.)), screens, visible), + Some(rect(800., 608., 400., 180.)) + ); + assert_eq!( + guide_frame(PANEL, Some(rect(-100., 100., 400., 720.)), screens, visible), + Some(rect(308., 370., 400., 180.)) + ); + } + #[test] + fn guides_use_the_left_side_or_wait_for_room_instead_of_covering_settings() { + let visible = rect(0., 0., 1200., 900.); + assert_eq!( + guide_frame( + PANEL, + Some(rect(420., 5., 770., 890.)), + [(visible, visible)], + visible ), - false, + Some(rect(12., 360., 400., 180.)) + ); + assert_eq!( + guide_frame(PANEL, Some(visible), [(visible, visible)], visible), + None ); } + #[test] + fn falls_back_to_the_visible_top_right_without_an_onscreen_settings_window() { + let visible = rect(-1280., 40., 1280., 800.); + for missing in [None, Some(rect(300., 400., 500., 300.))] { + assert_eq!( + guide_frame(PANEL, missing, [(visible, visible)], visible), + Some(rect(-416., 644., 400., 180.)) + ); + } + } } diff --git a/products/maka/desktop-shell/src/screenshot.rs b/products/maka/desktop-shell/src/screenshot.rs index 94ab1124d35..8cc48f93454 100644 --- a/products/maka/desktop-shell/src/screenshot.rs +++ b/products/maka/desktop-shell/src/screenshot.rs @@ -62,8 +62,7 @@ use nsh_platform_macos::{ use objc2_core_foundation::{CFRetained, CGPoint, CGRect, CGSize}; use objc2_core_graphics::{ CGDirectDisplayID, CGDisplayBounds, CGImage, CGPreflightScreenCaptureAccess, - CGRequestScreenCaptureAccess, CGWarpMouseCursorPosition, CGWindowListCopyWindowInfo, - CGWindowListOption, + CGRequestScreenCaptureAccess, CGWarpMouseCursorPosition, }; use objc2_screen_capture_kit::{ SCCaptureResolutionType, SCContentFilter, SCScreenshotManager, SCShareableContent, @@ -399,7 +398,7 @@ impl Stage { }; let scale = screen.backingScaleFactor(); let origin = CGDisplayBounds(display).origin; - let sources = windows_on(); + let sources = crate::window_list::on_screen(None); let stage = Arc::new(MainThreadBound::new(self.retain(), self.mtm())); let found = RcBlock::new( move |content: *mut SCShareableContent, error: *mut NSError| { @@ -452,13 +451,13 @@ impl Stage { } } - fn freeze(&self, mut shot: Shot, sources: Vec) { + fn freeze(&self, mut shot: Shot, sources: Vec) { if !matches!(*self.ivars().phase.borrow(), Phase::Capturing) { return; } let whole = shot.whole; let smallest = (SMALLEST_WINDOW * shot.scale) as i64; - let (windows, sources): (Vec, Vec) = sources + let (windows, sources): (Vec, Vec) = sources .into_iter() .filter_map(|source| { let area = shot.area(source.bounds)?; @@ -1197,7 +1196,7 @@ impl NativeComponent for StageComponent { fn deliver( stage: Arc>>, - shot: Result<(Shot, Vec), String>, + shot: Result<(Shot, Vec), String>, ) { DispatchQueue::main().exec_async(move || { let mtm = MainThreadMarker::new().expect("the main queue runs on the main thread"); @@ -1265,47 +1264,6 @@ fn display_of(screen: &NSScreen) -> Option { Some(number.unsignedIntValue()) } -/// The on-screen windows of the normal level, front to back. -fn windows_on() -> Vec { - let Some(list) = CGWindowListCopyWindowInfo( - CGWindowListOption::OptionOnScreenOnly | CGWindowListOption::ExcludeDesktopElements, - 0, - ) else { - return Vec::new(); - }; - // SAFETY: CFArray is toll-free bridged to NSArray, and the window server's entries are - // dictionaries with string keys; `list` outlives the borrow. - let list: &NSArray> = - unsafe { &*CFRetained::as_ptr(&list).as_ptr().cast() }; - let number = |info: &NSDictionary, key: &str| { - info.objectForKey(&NSString::from_str(key))? - .downcast::() - .ok() - .map(|number| number.doubleValue()) - }; - list.iter() - .filter_map(|info| { - if number(&info, "kCGWindowLayer")? != 0.0 || number(&info, "kCGWindowAlpha")? == 0.0 { - return None; - } - let bounds = info - .objectForKey(&NSString::from_str("kCGWindowBounds"))? - .downcast::() - .ok()?; - // SAFETY: the window server keys a window's bounds by string. - let bounds: Retained> = - unsafe { Retained::cast_unchecked(bounds) }; - Some(elements::Source { - pid: number(&info, "kCGWindowOwnerPID")? as i32, - bounds: CGRect::new( - CGPoint::new(number(&bounds, "X")?, number(&bounds, "Y")?), - CGSize::new(number(&bounds, "Width")?, number(&bounds, "Height")?), - ), - }) - }) - .collect() -} - /// `rect`, in global points, in pixels of the display at `origin`. fn pixels(rect: CGRect, origin: CGPoint, scale: f64) -> Option { let pixel = |value: f64, start: f64| ((value - start) * scale).round() as i64; diff --git a/products/maka/desktop-shell/src/screenshot/elements.rs b/products/maka/desktop-shell/src/screenshot/elements.rs index e5196323c38..a6497ba4f28 100644 --- a/products/maka/desktop-shell/src/screenshot/elements.rs +++ b/products/maka/desktop-shell/src/screenshot/elements.rs @@ -26,13 +26,6 @@ use std::{ time::{Duration, Instant}, }; -/// A window as the window server lists it, in global points. -#[derive(Clone, Copy)] -pub(super) struct Source { - pub pid: i32, - pub bounds: CGRect, -} - /// Points a control must span on each side to be a target. const SMALLEST: f64 = 6.0; /// Bounds on one window's walk: some apps (browsers) have tens of thousands of nodes. @@ -66,7 +59,7 @@ pub(super) fn request() { /// The controls of each of `windows`, in global points; none for a window Accessibility cannot /// read. Blocks on the apps' answers, so it runs off the main thread. -pub(super) fn scan(windows: &[Source]) -> Vec> { +pub(super) fn scan(windows: &[crate::window_list::Window]) -> Vec> { let mut found = vec![Vec::new(); windows.len()]; let deadline = Instant::now() + BUDGET; let attributes = Attributes::new(); diff --git a/products/maka/desktop-shell/src/shell.rs b/products/maka/desktop-shell/src/shell.rs index 1bb8a75fe58..5f233f9b11f 100644 --- a/products/maka/desktop-shell/src/shell.rs +++ b/products/maka/desktop-shell/src/shell.rs @@ -82,6 +82,17 @@ impl Shell { self } + #[cfg(target_os = "macos")] + pub(crate) fn enable_permission_restart(&self, bindings: &maka_workbench::bindings::Bindings) { + if let Some(controller) = self.updater.clone() + && crate::appkit::relaunch::supported() + { + bindings.set_permission_restart(move |reply| { + crate::appkit::relaunch::restart(reply, controller.clone()) + }); + } + } + pub(crate) fn attach(&self, mut config: EngineConfig) -> EngineConfig { config.context = config .context diff --git a/products/maka/desktop-shell/src/updater.rs b/products/maka/desktop-shell/src/updater.rs index 08d2618af84..5a60fcedf12 100644 --- a/products/maka/desktop-shell/src/updater.rs +++ b/products/maka/desktop-shell/src/updater.rs @@ -64,6 +64,8 @@ pub(crate) struct Snapshot { } struct State { + #[cfg(target_os = "macos")] + desktop_restarting: bool, snapshot: Snapshot, staged: Option, } @@ -193,6 +195,8 @@ impl Controller { active: None, }), state: Mutex::new(State { + #[cfg(target_os = "macos")] + desktop_restarting: false, snapshot, staged: None, }), @@ -573,9 +577,31 @@ impl Controller { }); } + #[cfg(target_os = "macos")] + pub(crate) fn reserve_desktop_restart(&self) -> bool { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.desktop_restarting || state.snapshot.status == Status::Installing { + return false; + } + state.desktop_restarting = true; + true + } + + #[cfg(target_os = "macos")] + pub(crate) fn cancel_desktop_restart(&self) { + self.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .desktop_restarting = false; + } + pub(crate) async fn install_and_restart(&self) -> Result<(), String> { let staged = { let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner()); + #[cfg(target_os = "macos")] + if guard.desktop_restarting { + return Err("The desktop is restarting.".into()); + } if guard.snapshot.status != Status::Ready { return Err("No verified update is ready to install.".into()); } @@ -748,6 +774,8 @@ mod tests { active: None, }), state: Mutex::new(State { + #[cfg(target_os = "macos")] + desktop_restarting: false, snapshot: Snapshot { channel, current_version: "0.2.0-nightly.1".into(), @@ -763,6 +791,25 @@ mod tests { (rt, controller) } + #[test] + #[cfg(target_os = "macos")] + fn restart_reservation_excludes_install_and_allows_retry_after_cancellation() { + let (runtime, controller) = test_controller(Channel::Dev); + assert!(controller.reserve_desktop_restart()); + assert!(!controller.reserve_desktop_restart()); + assert!( + runtime + .block_on(controller.install_and_restart()) + .unwrap_err() + .contains("restarting") + ); + controller.cancel_desktop_restart(); + controller.state.lock().unwrap().snapshot.status = Status::Installing; + assert!(!controller.reserve_desktop_restart()); + controller.state.lock().unwrap().snapshot.status = Status::Idle; + assert!(controller.reserve_desktop_restart()); + } + fn sample_update() -> AvailableUpdate { AvailableUpdate { version: "0.2.0-nightly.2".into(), diff --git a/products/maka/desktop-shell/src/window_list.rs b/products/maka/desktop-shell/src/window_list.rs new file mode 100644 index 00000000000..4635559a2c8 --- /dev/null +++ b/products/maka/desktop-shell/src/window_list.rs @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +//! WindowServer geometry in global display points. Reading bounds requires no TCC grant. + +use nsh_platform_macos::{ + objc2::{rc::Retained, runtime::AnyObject}, + objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString}, +}; +use objc2_core_foundation::{CFRetained, CGPoint, CGRect, CGSize}; +use objc2_core_graphics::{CGWindowListCopyWindowInfo, CGWindowListOption}; + +/// A window as the window server lists it, in global points. +#[derive(Clone, Copy)] +pub(crate) struct Window { + pub pid: i32, + pub bounds: CGRect, +} + +/// The on-screen windows of the normal level, front to back. +pub(crate) fn on_screen(owner: Option) -> Vec { + let Some(list) = CGWindowListCopyWindowInfo( + CGWindowListOption::OptionOnScreenOnly | CGWindowListOption::ExcludeDesktopElements, + 0, + ) else { + return Vec::new(); + }; + // SAFETY: CFArray is toll-free bridged to NSArray, and the window server's entries are + // dictionaries with string keys; `list` outlives the borrow. + let list: &NSArray> = + unsafe { &*CFRetained::as_ptr(&list).as_ptr().cast() }; + let number = |info: &NSDictionary, key: &str| { + info.objectForKey(&NSString::from_str(key))? + .downcast::() + .ok() + .map(|number| number.doubleValue()) + }; + list.iter() + .filter_map(|info| { + if number(&info, "kCGWindowLayer")? != 0.0 || number(&info, "kCGWindowAlpha")? == 0.0 { + return None; + } + let pid = number(&info, "kCGWindowOwnerPID")? as i32; + if owner.is_some_and(|owner| owner != pid) { + return None; + } + let bounds = info + .objectForKey(&NSString::from_str("kCGWindowBounds"))? + .downcast::() + .ok()?; + // SAFETY: the window server keys a window's bounds by string. + let bounds: Retained> = + unsafe { Retained::cast_unchecked(bounds) }; + Some(Window { + pid, + bounds: CGRect::new( + CGPoint::new(number(&bounds, "X")?, number(&bounds, "Y")?), + CGSize::new(number(&bounds, "Width")?, number(&bounds, "Height")?), + ), + }) + }) + .collect() +} diff --git a/products/maka/updater/src/lib.rs b/products/maka/updater/src/lib.rs index 562853d69d7..6adc429ac68 100644 --- a/products/maka/updater/src/lib.rs +++ b/products/maka/updater/src/lib.rs @@ -40,6 +40,10 @@ pub use nsh_updater::install::Staged as StagedUpdate; /// Application identifier shared across desktop bundles and `latest.json`. pub const APP_ID: &str = "org.apache.maka.desktop"; +/// A clean desktop-shell exit asking its supervising launcher to open another window process. +pub const RELAUNCH_DESKTOP: u8 = 75; +/// Advertised only by launchers that understand the desktop relaunch exit code. +pub const RELAUNCH_SUPPORTED_ENV: &str = "MAKA_DESKTOP_RELAUNCH_SUPPORTED"; /// Default GitHub repository hosting releases and nightly prereleases. pub const DEFAULT_REPO: &str = "apache/maka"; /// Environment variable carrying a custom State Root across an update restart. diff --git a/products/maka/workbench/app/ComputerPermissionSetup.tsx b/products/maka/workbench/app/ComputerPermissionSetup.tsx index a580f756049..b15701f26ba 100644 --- a/products/maka/workbench/app/ComputerPermissionSetup.tsx +++ b/products/maka/workbench/app/ComputerPermissionSetup.tsx @@ -47,7 +47,7 @@ import { errorText, renderText } from './text'; import { bodyTextStyle, captionTextStyle, C, Disclosure } from './ui'; // The native factory owns the trusted application URL; no path crosses from the UI. -const PermissionApplication = nativeComponent< +export const PermissionApplication = nativeComponent< {}, { dragError: { message: string }; diff --git a/products/maka/workbench/app/ComputerPermissionSetupEntry.tsx b/products/maka/workbench/app/ComputerPermissionSetupEntry.tsx index dd12bc1833c..4b3906b4621 100644 --- a/products/maka/workbench/app/ComputerPermissionSetupEntry.tsx +++ b/products/maka/workbench/app/ComputerPermissionSetupEntry.tsx @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -import { mount, View, host as shell } from 'nsh'; +import { mount, View, Text, signal, host as shell } from 'nsh'; import { Window } from 'nsh/desktop'; import type { LanguagePreference } from '../../../../packages/plugin-sdk/src/index.js'; import { TITLE_BAR_HEIGHT } from './chrome'; @@ -25,12 +25,18 @@ import { initializeAppearance } from './appearance'; import { applyLanguagePreference, tr } from './locale'; import { installWorkbenchLocaleCatalog } from './localeCatalog'; import { computerPermissionClient } from './computerPermissionClient'; -import { ComputerPermissionSetup } from './ComputerPermissionSetup'; +import { SettingsButton } from './SettingsPage'; +import { + ComputerPermissionSetup, + PermissionApplication, + systemPermissionName, +} from './ComputerPermissionSetup'; import type { SystemPermissionRequest } from './computerPermissionSetupState'; -import { C } from './ui'; +import { C, captionTextStyle } from './ui'; function ComputerPermissionSetupEntry() { const params = shell.params as { + settingsGuide?: { application: string; grant: Parameters[0] }; systemPermission?: { sessionId: string; requestId: string; request: SystemPermissionRequest }; nativeApplicationDrag?: boolean; languagePreference: { @@ -46,6 +52,65 @@ function ComputerPermissionSetupEntry() { ); installWorkbenchLocaleCatalog(); void initializeAppearance(); + if (params.settingsGuide) { + const { application, grant } = params.settingsGuide; + const error = signal(''); + const reveal = async () => { + try { + await shell.call('permissionGuide.reveal'); + } catch { + error.set(tr('permissionGuide.finderFailed')); + } + }; + return ( + + + + {systemPermissionName(grant) + ' · ' + application} + + + + error.set(tr('permissionSetup.dragFailed'))} + /> + + + + {tr('permissionGuide.switch', { application })} + + + + {tr('permissionGuide.drag')} + + + + + + {error()} + + + + void reveal()} + /> + + void shell.call('computerPermissions.close')} + /> + + + + ); + } const host = createHost(uiHost); const owner = params.systemPermission; if (!owner?.sessionId || !owner.requestId) diff --git a/products/maka/workbench/app/ModelSettings.tsx b/products/maka/workbench/app/ModelSettings.tsx index 8d54603904f..2d32e3f2c7d 100644 --- a/products/maka/workbench/app/ModelSettings.tsx +++ b/products/maka/workbench/app/ModelSettings.tsx @@ -101,7 +101,15 @@ export function ModelSettings(props: { sameValue(tool.instance.instance, item.instance.instance), ); const pages = computed(() => { - const shown = runtime.settings().filter((item) => !quickTool(item)); + const shown = runtime + .settings() + .filter( + (item) => + !quickTool(item) && + (item.id !== 'system-permissions' || + !sameValue(item.instance.instance, props.context.instance) || + (platform.os === 'macos' && platform.idiom !== 'terminal')), + ); return [ ...shown.filter((item) => item.id !== quickToolsSettings), ...shown.filter((item) => item.id === quickToolsSettings), diff --git a/products/maka/workbench/app/SettingsPage.tsx b/products/maka/workbench/app/SettingsPage.tsx index 2fc579c1c79..21d2751921a 100644 --- a/products/maka/workbench/app/SettingsPage.tsx +++ b/products/maka/workbench/app/SettingsPage.tsx @@ -137,6 +137,8 @@ export function SettingsLede(props: { children: string }) { /** A group of rows on `card`, optionally named, with an optional note below. */ export function SettingsSection(props: { title?: string; + titleTag?: string; + description?: JSX.Element; trailing?: JSX.Element; note?: string; /** The note reports something that went wrong, not how the section works. */ @@ -155,21 +157,36 @@ export function SettingsSection(props: { paddingLeft: inset, }} > - - {props.title ?? ''} - + + {props.title ?? ''} + + + + + {props.titleTag} + + + + {props.trailing} + {props.description} ; +}) { + if (desktopAvailable) { + cleanup( + currentWindow().on('focusChange', ({ focused }) => { + if (focused) void owner.refresh(); + }), + ); + } + const desktop = () => { + const d = owner.desktop(); + return d?.supported ? d : null; + }; + const host = () => owner.host()?.status; + const row = (subject: Subject, grant: Grant, purpose: MessageKey) => { + const file = grant === 'files' || grant === 'disk'; + const value = () => + subject === 'host' + ? host()?.grants.find((g) => g.grant === grant)?.effective + : grant === 'files' || grant === 'disk' + ? undefined + : desktop()?.[grant]; + const local = () => subject === 'desktop' || !!owner.host()?.local; + const pendingHost = () => + subject === 'host' && host()?.grants.some((g) => g.grant === grant && g.pendingHost); + const blocked = () => value() === 'denied' || value() === 'restricted'; + const showRestart = () => + subject === 'desktop' && + owner.restartHint() === grant && + value() === false && + desktop()?.canRestart; + const requestable = () => value() === false || value() === 'notDetermined'; + return ( + + + + {tr('permissionGuide.pending', { application: host()?.application ?? '' })} + + + + + {tr('permissionGuide.restartHint')} + + + + } + trailing={ + + + + + {tr(statusLabel(value()))} + + + + void owner.refresh()} + /> + + + + void owner.act('desktop', 'restart', grant)} + /> + + + void owner.act(subject, 'request', grant)} + /> + + + + + + void owner.act(subject, 'open', grant)} + /> + + + + } + /> + ); + }; + const finder = (subject: Subject) => ( + void owner.act(subject, 'reveal', 'accessibility')} + /> + ); + return ( + + + + + + {finder('desktop')}} + > + + + + + + + + {row('desktop', 'microphone', 'Use for dictation')} + {row( + 'desktop', + 'accessibility', + 'Allow Accessibility to snap to the controls inside windows.', + )} + {row('desktop', 'screen_recording', 'Take a screenshot')} + + + + + + {tr('Connected to a remote device.')} + + + {tr('permissionSettings.hostInfo')} + + + } + trailing={{finder('host')}} + > + + + + + + + + + + + {row('host', 'accessibility', 'permissionSetup.accessibilityPurpose')} + {row('host', 'screen_recording', 'permissionSetup.screenPurpose')} + + + + {tr('permissionSettings.filesInfo')}} + > + {row('desktop', 'files', 'Desktop, Documents and Downloads')} + {row('desktop', 'disk', 'Access protected data when a task requires it.')} + + + + ); +} diff --git a/products/maka/workbench/app/host.ts b/products/maka/workbench/app/host.ts index 707ade325a6..49cc5eac9cc 100644 --- a/products/maka/workbench/app/host.ts +++ b/products/maka/workbench/app/host.ts @@ -229,6 +229,20 @@ export function createHost(application: UiHost) { get localFolderPicker() { return nativeHost.localFolderPicker; }, + desktopPermissionSettings: () => + nativeHost.desktopPermissionSettings() as Promise< + import('./permissionSettingsState').DesktopStatus + >, + hostPermissionSettings: () => + nativeHost.hostPermissionSettings() as Promise< + import('./permissionSettingsState').HostStatus + >, + observePermissionSetting: (subject: string, grant: string) => + nativeHost.observePermissionSetting(subject, grant) as Promise< + import('./permissionSettingsState').Observation | null + >, + performPermissionSetting: (subject: string, action: string, grant: string) => + nativeHost.performPermissionSetting(subject, action, grant), openSystemPermissionSetup: (sessionId: string, requestId: string) => nativeHost.openSystemPermissionSetup(sessionId, requestId), systemPermissionStatus: (sessionId: string, requestId: string) => diff --git a/products/maka/workbench/app/permissionSettingsState.ts b/products/maka/workbench/app/permissionSettingsState.ts new file mode 100644 index 00000000000..883985e0325 --- /dev/null +++ b/products/maka/workbench/app/permissionSettingsState.ts @@ -0,0 +1,276 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { signal } from 'nsh'; +import type { Output } from './host'; +import { tr, type MessageKey } from './locale'; + +export type Grant = 'microphone' | 'screen_recording' | 'accessibility' | 'disk' | 'files'; +type Microphone = 'granted' | 'denied' | 'notDetermined' | 'restricted' | 'unknown'; +export type DesktopStatus = + | { supported: false } + | { + supported: true; + application: string; + canReveal: boolean; + canRestart: boolean; + microphone: Microphone; + accessibility: boolean; + screen_recording: boolean; + }; +export type HostStatus = { local: boolean; status: Output<'agent', 'hostPermissions'> }; +export type Subject = 'desktop' | 'host'; +type Action = 'open' | 'reveal' | 'request' | 'restart' | 'end' | 'guide'; +type GuidedGrant = 'accessibility' | 'screen_recording'; +export type Observation = { effective: boolean; pendingHost: boolean }; +interface Client { + observePermissionSetting(subject: Subject, grant: GuidedGrant): Promise; + desktopPermissionSettings(): Promise; + hostPermissionSettings(): Promise; + performPermissionSetting(subject: Subject, action: Action, grant: Grant): Promise; +} +export const names: Record = { + microphone: 'Microphone', + accessibility: 'Accessibility', + screen_recording: 'Screen & System Audio Recording', + files: 'Files and folders', + disk: 'Full disk access', +}; +export function statusLabel(state: Microphone | boolean | undefined) { + switch (state) { + case true: + case 'granted': + return 'Allowed'; + case false: + return 'permissionSetup.notEnabled'; + case 'restricted': + return 'Restricted'; + case 'notDetermined': + return 'Not requested'; + case 'denied': + return 'Denied'; + default: + return 'Unknown'; + } +} +export function createPermissionSettings(client: Client) { + const desktop = signal(null); + const host = signal(null); + const desktopError = signal(''); + const hostError = signal(''); + const actionError = signal(''); + const busy = signal(false); + let active = false; + let generation = 0; + let observation = 0; + const restartHint = signal(null); + let guide: { + subject: Subject; + grant: GuidedGrant; + awaitingGrant: boolean; + needsSettings: boolean; + } | null = null; + let timer: ReturnType | undefined; + function stopGuide() { + clearTimeout(timer); + const previous = guide; + guide = null; + if (previous) + void client.performPermissionSetting(previous.subject, 'end', previous.grant).catch(() => {}); + } + function poll(target: NonNullable, remaining = 32) { + timer = setTimeout( + async () => { + if (target !== guide || !active) return; + try { + const state = await client.observePermissionSetting(target.subject, target.grant); + if (target !== guide) return; + if (!state) { + stopGuide(); + return; + } + if (target.subject === 'desktop') { + const d = desktop(); + if (d?.supported) desktop.set({ ...d, [target.grant]: state.effective }); + restartHint.set(state.effective ? null : target.grant); + } else { + const h = host(); + if (!h?.local) { + stopGuide(); + return; + } + host.set({ + ...h, + status: { + ...h.status, + grants: h.status.grants.map((g) => + g.grant === target.grant ? { ...g, ...state } : g, + ), + }, + }); + } + if (target.awaitingGrant && state.effective) { + stopGuide(); + return; + } + if (target.needsSettings && !state.effective && !state.pendingHost) { + target.needsSettings = false; + await client.performPermissionSetting(target.subject, 'guide', target.grant); + } + if (target === guide && remaining > 1 && !state.effective) poll(target, remaining - 1); + } catch (e) { + if (target === guide) { + actionError.set(String(e)); + stopGuide(); + } + } + }, + target.needsSettings ? 1750 : 1250, + ); + } + async function refresh() { + if (!active) return; + const token = ++observation; + async function read( + query: () => Promise, + store: (v: T | null) => void, + error: (s: string) => void, + ) { + try { + const value = await query(); + if (token === observation) { + store(value); + error(''); + } + } catch (e) { + if (token === observation) { + store(null); + error(String(e)); + } + } + } + await Promise.all([ + read( + client.desktopPermissionSettings, + (v) => desktop.set(v), + (e) => desktopError.set(e), + ), + read( + client.hostPermissionSettings, + (v) => host.set(v), + (e) => hostError.set(e), + ), + ]); + if (token !== observation) return; + const d = desktop(); + if (guide?.subject === 'desktop' && d?.supported && !d[guide.grant]) + restartHint.set(guide.grant); + const hint = restartHint(); + if (hint && d?.supported && d[hint]) restartHint.set(null); + if ( + guide?.subject === 'host' && + (!host()?.local || + (guide.awaitingGrant && + host()?.status.grants.some((g) => g.grant === guide?.grant && g.effective))) + ) + stopGuide(); + if (guide?.subject === 'desktop' && guide.awaitingGrant && d?.supported && d[guide.grant]) + stopGuide(); + } + async function act(subject: Subject, action: Action, grant: Grant) { + if (!active || busy() || (subject === 'host' && !host()?.local)) return; + const d = desktop(); + if (subject === 'desktop' && !d?.supported) return; + if ( + action === 'restart' && + (subject !== 'desktop' || restartHint() !== grant || !d?.supported || !d.canRestart) + ) + return; + if (action === 'open' || action === 'request') { + stopGuide(); + restartHint.set(null); + if (grant === 'screen_recording' || grant === 'accessibility') { + const effective = + subject === 'desktop' + ? d?.supported && d[grant] + : host()?.status.grants.find((g) => g.grant === grant)?.effective; + guide = { + subject, + grant, + awaitingGrant: effective === false, + needsSettings: action === 'request', + }; + } + } + const token = generation; + busy.set(true); + actionError.set(''); + try { + await client.performPermissionSetting(subject, action, grant); + if (token === generation && guide && (action === 'open' || action === 'request')) poll(guide); + } catch (e) { + if (token === generation && (action === 'open' || action === 'request')) stopGuide(); + if (token === generation) + actionError.set( + action === 'open' + ? tr('Open System Settings → Privacy & Security → {permission}.', { + permission: tr(names[grant]), + }) + : action === 'restart' + ? tr('permissionGuide.restartFailed') + : String(e), + ); + } finally { + if (token === generation) { + busy.set(false); + await refresh(); + } + } + } + return { + desktop, + restartHint, + host, + desktopError, + hostError, + actionError, + busy, + refresh, + act, + activate() { + active = true; + void refresh(); + }, + deactivate() { + active = false; + stopGuide(); + restartHint.set(null); + generation++; + observation++; + desktop.set(null); + host.set(null); + busy.set(false); + actionError.set(''); + desktopError.set(''); + hostError.set(''); + }, + back: () => false, + navigation: () => 'system-permissions', + }; +} diff --git a/products/maka/workbench/build.rs b/products/maka/workbench/build.rs index 752536ff537..04820d5ee28 100644 --- a/products/maka/workbench/build.rs +++ b/products/maka/workbench/build.rs @@ -26,6 +26,7 @@ fn main() { .flag("-fobjc-arc") .compile("maka_dictation"); for framework in [ + "ApplicationServices", "AVFoundation", "AppKit", "AudioToolbox", diff --git a/products/maka/workbench/examples/ui_types.rs b/products/maka/workbench/examples/ui_types.rs index cab75b7f998..a3486b67706 100644 --- a/products/maka/workbench/examples/ui_types.rs +++ b/products/maka/workbench/examples/ui_types.rs @@ -46,6 +46,8 @@ const SOURCES: &[&str] = &[ "products/maka/workbench/tests/fixtures/discovery.tsx", "products/maka/workbench/tests/fixtures/stage-quotes.tsx", "products/maka/workbench/tests/fixtures/model-select.tsx", + "products/maka/workbench/tests/fixtures/permission-settings.tsx", + "products/maka/workbench/tests/fixtures/permission-settings-unsupported.tsx", "products/maka/workbench/tests/fixtures/models-settings.tsx", "products/maka/workbench/tests/fixtures/terminal-sidebar.tsx", "products/maka/workbench/tests/fixtures/skill-input.tsx", diff --git a/products/maka/workbench/locales/de.json b/products/maka/workbench/locales/de.json index fe172412493..a73b5914ba8 100644 --- a/products/maka/workbench/locales/de.json +++ b/products/maka/workbench/locales/de.json @@ -25,6 +25,7 @@ "Access allowed · {scope}": "Zugriff erlaubt · {scope}", "Access denied": "Zugriff verweigert", "Access key ID": "Zugriffsschlüssel-ID", + "Access protected data when a task requires it.": "Bei Bedarf auf geschützte Daten zugreifen.", "Access stopped for this turn": "Zugriff für diesen Durchgang gestoppt", "Accessibility": "Bedienungshilfen", "Account": "Konto", @@ -79,6 +80,7 @@ "After a reply": "Nach einer Antwort", "After the current turn": "Nach dem aktuellen Durchgang", "Agent": "Agent", + "Agent computer control": "Computersteuerung durch den Agenten", "Agent conversation": "Agenten-Unterhaltung", "Agent message": "Agentennachricht", "Agent messages": "Agentennachrichten", @@ -472,6 +474,7 @@ "Connect {name}": "{name} verbinden", "Connected": "Verbunden", "Connected relays": "Verbundene Relays", + "Connected to a remote device.": "Mit einem entfernten Gerät verbunden.", "Connecting to terminal…": "Verbindung zum Terminal wird hergestellt…", "Connecting…": "Verbindung wird hergestellt…", "Connection ID": "Verbindungs-ID", @@ -735,6 +738,8 @@ "Deployment change saved": "Bereitstellungsänderung gespeichert", "Deployment conflict": "Bereitstellungskonflikt", "Description": "Beschreibung", + "Desktop features": "Desktopfunktionen", + "Desktop, Documents and Downloads": "Schreibtisch, Dokumente und Downloads", "Detached HEAD": "Losgelöster HEAD", "Details": "Details", "Details for skill {name} at {path}": "Details zur Fähigkeit {name} unter {path}", @@ -961,6 +966,7 @@ "Fetch the provider’s catalog or add its exact model ID.": "Rufen Sie den Katalog des Anbieters ab oder fügen Sie die genaue Modell-ID hinzu.", "Fetching models…": "Modelle werden abgerufen…", "File": "Datei", + "File access": "Dateizugriff", "File actions": "Dateiaktionen", "File changed on disk.": "Datei wurde auf dem Datenträger geändert.", "File changes": "Dateiänderungen", @@ -974,6 +980,7 @@ "File updates ended. Retry to reconnect.": "Dateiaktualisierungen beendet. Versuchen Sie erneut, sich zu verbinden.", "Files": "Dateien", "Files already changed": "Bereits geänderte Dateien", + "Files and folders": "Dateien und Ordner", "Filesystem: no additional access": "Dateisystem: kein zusätzlicher Zugriff", "Filter branches…": "Branches filtern…", "Filter commits…": "Commits filtern…", @@ -1034,6 +1041,7 @@ "From {title}": "Von {title}", "Full access": "Vollzugriff", "Full access · Sandbox off": "Vollzugriff · Sandbox aus", + "Full disk access": "Festplattenvollzugriff", "Full screen image viewer": "Vollbild-Bildbetrachter", "General": "Allgemein", "Generating answer…": "Antwort wird generiert…", @@ -1499,6 +1507,7 @@ "Not completed": "Nicht abgeschlossen", "Not installed": "Nicht installiert", "Not loaded": "Nicht geladen", + "Not requested": "Noch nicht angefragt", "Not sent. Choose a workspace, then retry.": "Nicht gesendet. Wähle einen Arbeitsbereich aus und versuche es erneut.", "Not set": "Nicht festgelegt", "Not signed in": "Nicht angemeldet", @@ -1529,6 +1538,7 @@ "Open Maka": "Maka öffnen", "Open Maka Bot": "Maka Bot öffnen", "Open System Settings": "Systemeinstellungen öffnen", + "Open System Settings → Privacy & Security → {permission}.": "Systemeinstellungen → Datenschutz & Sicherheit → {permission} öffnen.", "Open a location, then choose a workspace folder.": "Öffnen Sie einen Speicherort und wählen Sie dann einen Arbeitsbereichsordner.", "Open a plugin in this group to edit its settings.": "Öffnen Sie ein Plugin in dieser Gruppe, um dessen Einstellungen zu bearbeiten.", "Open as a conversation": "Als Unterhaltung öffnen", @@ -1953,6 +1963,7 @@ "Restore room": "Raum wiederherstellen", "Restore this conversation to continue it.": "Stellen Sie diese Unterhaltung wieder her, um sie fortzusetzen.", "Restoring attachment drafts…": "Entwurfsanhänge werden wiederhergestellt…", + "Restricted": "Eingeschränkt", "Result URL path": "Pfad zur Ergebnis-URL", "Result limit location": "Position des Ergebnislimits", "Result limit parameter (optional)": "Parameter für Ergebnislimit (optional)", @@ -2380,11 +2391,13 @@ "System": "System", "System permission": "Systemberechtigung", "System permission request": "Systemberechtigungsanfrage", + "System permissions": "Systemberechtigungen", "System permissions granted": "Systemberechtigungen erteilt", "System tray icon": "Taskleistensymbol", "TLS CA certificate path": "Pfad zum TLS-CA-Zertifikat", "TLS certificate SHA-256": "SHA-256 des TLS-Zertifikats", "Table of contents": "Inhaltsverzeichnis", + "Take a screenshot": "Bildschirmfoto aufnehmen", "Take a seat hint": "Jemanden mit @ an den Tisch holen", "Taken by another app": "Von einer anderen App belegt", "Target conversation": "Unterhaltung", @@ -2892,6 +2905,18 @@ "orphaned": "verwaist", "other": "sonstige", "path and descendants": "Pfad und Unterelemente", + "permissionGuide.drag": "Ziehe das Symbol in die Liste oder klicke auf + und wähle die im Finder angezeigte App.", + "permissionGuide.finderFailed": "Die App konnte im Finder nicht angezeigt werden.", + "permissionGuide.pending": "Die Berechtigung wurde erteilt, ist in {application} aber noch nicht wirksam.", + "permissionGuide.recheck": "Erneut prüfen", + "permissionGuide.restart": "Maka neu starten", + "permissionGuide.restartFailed": "Maka konnte nicht neu starten. Schließe ausstehende Updates oder Rückfragen zum Beenden ab und versuche es erneut.", + "permissionGuide.restartHint": "Wenn der Schalter aktiviert ist, starte Maka neu, um die Änderung anzuwenden.", + "permissionGuide.switch": "Wenn {application} aufgeführt ist, aktiviere den Schalter.", + "permissionSettings.filesInfo": "Den Dateizugriff verwalten Sie in den macOS-Systemeinstellungen. Maka durchsucht keine geschützten Ordner, um Berechtigungen zu prüfen.", + "permissionSettings.go": "Systemeinstellungen öffnen", + "permissionSettings.hostInfo": "Maka Host steuert den Computer im Hintergrund und hat eigene Berechtigungen in den Systemeinstellungen.", + "permissionSettings.unsupported": "Der Berechtigungsstatus ist auf diesem Host nicht verfügbar.", "permissionSetup.accessibilityPurpose": "Oberflächenelemente lesen sowie in erlaubten Programmen klicken und tippen.", "permissionSetup.application": "Berechtigungs-App", "permissionSetup.cancel": "Einrichtung abbrechen", diff --git a/products/maka/workbench/locales/en.json b/products/maka/workbench/locales/en.json index 0ecd78468b5..419d9f51228 100644 --- a/products/maka/workbench/locales/en.json +++ b/products/maka/workbench/locales/en.json @@ -25,6 +25,7 @@ "Access allowed · {scope}": "Access allowed · {scope}", "Access denied": "Access denied", "Access key ID": "Access key ID", + "Access protected data when a task requires it.": "Access protected data when a task requires it.", "Access stopped for this turn": "Access stopped for this turn", "Accessibility": "Accessibility", "Account": "Account", @@ -79,6 +80,7 @@ "After a reply": "After a reply", "After the current turn": "After the current turn", "Agent": "Agent", + "Agent computer control": "Agent computer control", "Agent conversation": "Agent conversation", "Agent message": "Agent message", "Agent messages": "Agent messages", @@ -472,6 +474,7 @@ "Connect {name}": "Connect {name}", "Connected": "Connected", "Connected relays": "Connected relays", + "Connected to a remote device.": "Connected to a remote device.", "Connecting to terminal…": "Connecting to terminal…", "Connecting…": "Connecting…", "Connection ID": "Connection ID", @@ -735,6 +738,8 @@ "Deployment change saved": "Deployment change saved", "Deployment conflict": "Deployment conflict", "Description": "Description", + "Desktop features": "Desktop features", + "Desktop, Documents and Downloads": "Desktop, Documents and Downloads", "Detached HEAD": "Detached HEAD", "Details": "Details", "Details for skill {name} at {path}": "Details for skill {name} at {path}", @@ -961,6 +966,7 @@ "Fetch the provider’s catalog or add its exact model ID.": "Fetch the provider’s catalog or add its exact model ID.", "Fetching models…": "Fetching models…", "File": "File", + "File access": "File access", "File actions": "File actions", "File changed on disk.": "File changed on disk.", "File changes": "File changes", @@ -974,6 +980,7 @@ "File updates ended. Retry to reconnect.": "File updates ended. Retry to reconnect.", "Files": "Files", "Files already changed": "Files already changed", + "Files and folders": "Files and folders", "Filesystem: no additional access": "Filesystem: no additional access", "Filter branches…": "Filter branches…", "Filter commits…": "Filter commits…", @@ -1034,6 +1041,7 @@ "From {title}": "From {title}", "Full access": "Full access", "Full access · Sandbox off": "Full access · Sandbox off", + "Full disk access": "Full disk access", "Full screen image viewer": "Full screen image viewer", "General": "General", "Generating answer…": "Generating answer…", @@ -1499,6 +1507,7 @@ "Not completed": "Not completed", "Not installed": "Not installed", "Not loaded": "Not loaded", + "Not requested": "Not requested", "Not sent. Choose a workspace, then retry.": "Not sent. Choose a workspace, then retry.", "Not set": "Not set", "Not signed in": "Not signed in", @@ -1529,6 +1538,7 @@ "Open Maka": "Open Maka", "Open Maka Bot": "Open Maka Bot", "Open System Settings": "Open System Settings", + "Open System Settings → Privacy & Security → {permission}.": "Open System Settings → Privacy & Security → {permission}.", "Open a location, then choose a workspace folder.": "Open a location, then choose a workspace folder.", "Open a plugin in this group to edit its settings.": "Open a plugin in this group to edit its settings.", "Open as a conversation": "Open as a conversation", @@ -1953,6 +1963,7 @@ "Restore room": "Restore room", "Restore this conversation to continue it.": "Restore this conversation to continue it.", "Restoring attachment drafts…": "Restoring attachment drafts…", + "Restricted": "Restricted", "Result URL path": "Result URL path", "Result limit location": "Result limit location", "Result limit parameter (optional)": "Result limit parameter (optional)", @@ -2380,11 +2391,13 @@ "System": "System", "System permission": "System permission", "System permission request": "System permission request", + "System permissions": "System permissions", "System permissions granted": "System permissions granted", "System tray icon": "System tray icon", "TLS CA certificate path": "TLS CA certificate path", "TLS certificate SHA-256": "TLS certificate SHA-256", "Table of contents": "Table of contents", + "Take a screenshot": "Take a screenshot", "Take a seat hint": "@ someone to take a seat", "Taken by another app": "Taken by another app", "Target conversation": "Conversation", @@ -2892,6 +2905,18 @@ "orphaned": "orphaned", "other": "other", "path and descendants": "path and descendants", + "permissionGuide.drag": "Drag the icon into the list, or click + and choose the app shown in Finder.", + "permissionGuide.finderFailed": "Finder could not show the application.", + "permissionGuide.pending": "Permission granted. It hasn’t taken effect in {application} yet.", + "permissionGuide.recheck": "Check again", + "permissionGuide.restart": "Restart Maka", + "permissionGuide.restartFailed": "Maka could not restart. Finish any pending quit or update, then try again.", + "permissionGuide.restartHint": "If you’ve turned on the switch, restart Maka to apply the change.", + "permissionGuide.switch": "If {application} is listed, turn on its switch.", + "permissionSettings.filesInfo": "Manage file access in macOS System Settings. Maka never scans protected folders to check access.", + "permissionSettings.go": "Open System Settings", + "permissionSettings.hostInfo": "Maka Host handles computer control in the background and has its own permissions in System Settings.", + "permissionSettings.unsupported": "Permission status is unavailable on this Host.", "permissionSetup.accessibilityPurpose": "Read interface elements, click, and type in applications you allow.", "permissionSetup.application": "Permission application", "permissionSetup.cancel": "Cancel setup", diff --git a/products/maka/workbench/locales/es.json b/products/maka/workbench/locales/es.json index 9710b0e7525..c74e27e838c 100644 --- a/products/maka/workbench/locales/es.json +++ b/products/maka/workbench/locales/es.json @@ -25,6 +25,7 @@ "Access allowed · {scope}": "Acceso permitido · {scope}", "Access denied": "Acceso denegado", "Access key ID": "ID de clave de acceso", + "Access protected data when a task requires it.": "Acceder a datos protegidos cuando la tarea lo requiera.", "Access stopped for this turn": "Acceso detenido para este turno", "Accessibility": "Accesibilidad", "Account": "Cuenta", @@ -79,6 +80,7 @@ "After a reply": "Después de una respuesta", "After the current turn": "Después del turno actual", "Agent": "Agente", + "Agent computer control": "Control del equipo por el agente", "Agent conversation": "Conversación del agente", "Agent message": "Mensaje del agente", "Agent messages": "Mensajes del agente", @@ -472,6 +474,7 @@ "Connect {name}": "Conectar {name}", "Connected": "Conectado", "Connected relays": "Relés conectados", + "Connected to a remote device.": "Conexión a un dispositivo remoto.", "Connecting to terminal…": "Conectando al terminal…", "Connecting…": "Conectando…", "Connection ID": "ID de conexión", @@ -735,6 +738,8 @@ "Deployment change saved": "Cambio de despliegue guardado", "Deployment conflict": "Conflicto de despliegue", "Description": "Descripción", + "Desktop features": "Funciones de escritorio", + "Desktop, Documents and Downloads": "Escritorio, Documentos y Descargas", "Detached HEAD": "HEAD desacoplado", "Details": "Detalles", "Details for skill {name} at {path}": "Detalles de la habilidad {name} en {path}", @@ -961,6 +966,7 @@ "Fetch the provider’s catalog or add its exact model ID.": "Obtén el catálogo del proveedor o añade su ID de modelo exacto.", "Fetching models…": "Obteniendo modelos…", "File": "Archivo", + "File access": "Acceso a archivos", "File actions": "Acciones de archivo", "File changed on disk.": "El archivo cambió en el disco.", "File changes": "Cambios de archivos", @@ -974,6 +980,7 @@ "File updates ended. Retry to reconnect.": "Finalizaron las actualizaciones de archivos. Reintenta para reconectar.", "Files": "Archivos", "Files already changed": "Archivos ya modificados", + "Files and folders": "Archivos y carpetas", "Filesystem: no additional access": "Sistema de archivos: sin acceso adicional", "Filter branches…": "Filtrar ramas…", "Filter commits…": "Filtrar commits…", @@ -1034,6 +1041,7 @@ "From {title}": "Desde {title}", "Full access": "Acceso completo", "Full access · Sandbox off": "Acceso completo · Sin aislamiento", + "Full disk access": "Acceso total al disco", "Full screen image viewer": "Visor de imágenes a pantalla completa", "General": "General", "Generating answer…": "Generando respuesta…", @@ -1499,6 +1507,7 @@ "Not completed": "Sin completar", "Not installed": "No instalado", "Not loaded": "No cargado", + "Not requested": "Sin solicitar", "Not sent. Choose a workspace, then retry.": "No enviado. Elige un espacio de trabajo e inténtalo de nuevo.", "Not set": "Sin establecer", "Not signed in": "Sin iniciar sesión", @@ -1529,6 +1538,7 @@ "Open Maka": "Abrir Maka", "Open Maka Bot": "Abrir Maka Bot", "Open System Settings": "Abrir Configuración del Sistema", + "Open System Settings → Privacy & Security → {permission}.": "Abre Ajustes del Sistema → Privacidad y seguridad → {permission}.", "Open a location, then choose a workspace folder.": "Abre una ubicación y elige una carpeta de espacio de trabajo.", "Open a plugin in this group to edit its settings.": "Abre un plugin de este grupo para editar su configuración.", "Open as a conversation": "Abrir como conversación", @@ -1953,6 +1963,7 @@ "Restore room": "Restaurar sala", "Restore this conversation to continue it.": "Restaura esta conversación para continuarla.", "Restoring attachment drafts…": "Restaurando borradores de adjuntos…", + "Restricted": "Restringido", "Result URL path": "Ruta de URL de resultado", "Result limit location": "Ubicación del límite de resultados", "Result limit parameter (optional)": "Parámetro de límite de resultados (opcional)", @@ -2380,11 +2391,13 @@ "System": "Sistema", "System permission": "Permiso del sistema", "System permission request": "Solicitud de permiso del sistema", + "System permissions": "Permisos del sistema", "System permissions granted": "Permisos del sistema concedidos", "System tray icon": "Icono de la bandeja del sistema", "TLS CA certificate path": "Ruta del certificado de CA TLS", "TLS certificate SHA-256": "SHA-256 del certificado TLS", "Table of contents": "Tabla de contenidos", + "Take a screenshot": "Capturar la pantalla", "Take a seat hint": "Menciona con @ a alguien para que participe", "Taken by another app": "En uso por otra aplicación", "Target conversation": "Conversación", @@ -2892,6 +2905,18 @@ "orphaned": "huérfano", "other": "otro", "path and descendants": "ruta y subrutas", + "permissionGuide.drag": "Arrastra el icono a la lista o pulsa + y elige la app que se muestra en Finder.", + "permissionGuide.finderFailed": "No se pudo mostrar la aplicación en Finder.", + "permissionGuide.pending": "Permiso concedido. Aún no ha surtido efecto en {application}.", + "permissionGuide.recheck": "Volver a comprobar", + "permissionGuide.restart": "Reiniciar Maka", + "permissionGuide.restartFailed": "No se pudo reiniciar Maka. Confirma la salida o termina la actualización y vuelve a intentarlo.", + "permissionGuide.restartHint": "Si ya activaste el interruptor, reinicia Maka para aplicar el cambio.", + "permissionGuide.switch": "Si {application} aparece en la lista, activa su interruptor.", + "permissionSettings.filesInfo": "Gestiona el acceso a archivos en Ajustes del Sistema de macOS. Maka no examina carpetas protegidas para comprobar los permisos.", + "permissionSettings.go": "Abrir Ajustes del Sistema", + "permissionSettings.hostInfo": "Maka Host controla el ordenador en segundo plano y tiene sus propios permisos en Ajustes del Sistema.", + "permissionSettings.unsupported": "Este host no permite consultar el estado de los permisos.", "permissionSetup.accessibilityPurpose": "Leer elementos de la interfaz, hacer clic y escribir en las aplicaciones que permitas.", "permissionSetup.application": "Aplicación de permisos", "permissionSetup.cancel": "Cancelar configuración", diff --git a/products/maka/workbench/locales/fr.json b/products/maka/workbench/locales/fr.json index 087b6d02b52..35bff02d011 100644 --- a/products/maka/workbench/locales/fr.json +++ b/products/maka/workbench/locales/fr.json @@ -25,6 +25,7 @@ "Access allowed · {scope}": "Accès autorisé · {scope}", "Access denied": "Accès refusé", "Access key ID": "ID de clé d’accès", + "Access protected data when a task requires it.": "Accéder aux données protégées si la tâche l’exige.", "Access stopped for this turn": "Accès arrêté pour ce tour", "Accessibility": "Accessibilité", "Account": "Compte", @@ -79,6 +80,7 @@ "After a reply": "Après une réponse", "After the current turn": "Après le tour en cours", "Agent": "Agent", + "Agent computer control": "Contrôle de l’ordinateur par l’agent", "Agent conversation": "Conversation d’agent", "Agent message": "Message d’agent", "Agent messages": "Messages d’agent", @@ -472,6 +474,7 @@ "Connect {name}": "Connecter {name}", "Connected": "Connecté", "Connected relays": "Relais connectés", + "Connected to a remote device.": "Connexion à un appareil distant.", "Connecting to terminal…": "Connexion au terminal…", "Connecting…": "Connexion…", "Connection ID": "ID de connexion", @@ -735,6 +738,8 @@ "Deployment change saved": "Modification de déploiement enregistrée", "Deployment conflict": "Conflit de déploiement", "Description": "Description", + "Desktop features": "Fonctions du bureau", + "Desktop, Documents and Downloads": "Bureau, Documents et Téléchargements", "Detached HEAD": "HEAD détaché", "Details": "Détails", "Details for skill {name} at {path}": "Détails de la compétence {name} dans {path}", @@ -961,6 +966,7 @@ "Fetch the provider’s catalog or add its exact model ID.": "Récupérez le catalogue du fournisseur ou ajoutez son ID de modèle exact.", "Fetching models…": "Récupération des modèles…", "File": "Fichier", + "File access": "Accès aux fichiers", "File actions": "Actions sur le fichier", "File changed on disk.": "Fichier modifié sur le disque.", "File changes": "Modifications de fichiers", @@ -974,6 +980,7 @@ "File updates ended. Retry to reconnect.": "Les mises à jour des fichiers sont terminées. Réessayez pour vous reconnecter.", "Files": "Fichiers", "Files already changed": "Fichiers déjà modifiés", + "Files and folders": "Fichiers et dossiers", "Filesystem: no additional access": "Système de fichiers : aucun accès supplémentaire", "Filter branches…": "Filtrer les branches…", "Filter commits…": "Filtrer les commits…", @@ -1034,6 +1041,7 @@ "From {title}": "De {title}", "Full access": "Accès complet", "Full access · Sandbox off": "Accès complet · Bac à sable désactivé", + "Full disk access": "Accès complet au disque", "Full screen image viewer": "Visionneuse d’images plein écran", "General": "Général", "Generating answer…": "Génération de la réponse…", @@ -1499,6 +1507,7 @@ "Not completed": "Non terminé", "Not installed": "Non installé", "Not loaded": "Non chargé", + "Not requested": "Pas encore demandé", "Not sent. Choose a workspace, then retry.": "Non envoyé. Choisissez un espace de travail, puis réessayez.", "Not set": "Non défini", "Not signed in": "Non connecté", @@ -1529,6 +1538,7 @@ "Open Maka": "Ouvrir Maka", "Open Maka Bot": "Ouvrir Maka Bot", "Open System Settings": "Ouvrir Réglages Système", + "Open System Settings → Privacy & Security → {permission}.": "Ouvrez Réglages Système → Confidentialité et sécurité → {permission}.", "Open a location, then choose a workspace folder.": "Ouvrez un emplacement, puis choisissez un dossier d’espace de travail.", "Open a plugin in this group to edit its settings.": "Ouvrez un plugin dans ce groupe pour modifier ses paramètres.", "Open as a conversation": "Ouvrir comme conversation", @@ -1953,6 +1963,7 @@ "Restore room": "Restaurer le salon", "Restore this conversation to continue it.": "Restaurez cette conversation pour la poursuivre.", "Restoring attachment drafts…": "Restauration des brouillons de pièces jointes…", + "Restricted": "Accès restreint", "Result URL path": "Chemin d’URL de résultat", "Result limit location": "Emplacement de la limite de résultats", "Result limit parameter (optional)": "Paramètre de limite de résultats (facultatif)", @@ -2380,11 +2391,13 @@ "System": "Système", "System permission": "Permission système", "System permission request": "Demande de permission système", + "System permissions": "Autorisations système", "System permissions granted": "Permissions système accordées", "System tray icon": "Icône de la zone de notification", "TLS CA certificate path": "Chemin du certificat de CA TLS", "TLS certificate SHA-256": "SHA-256 du certificat TLS", "Table of contents": "Table des matières", + "Take a screenshot": "Capturer l’écran", "Take a seat hint": "@ quelqu’un pour l’inviter à la table", "Taken by another app": "Utilisé par une autre application", "Target conversation": "Conversation", @@ -2892,6 +2905,18 @@ "orphaned": "orphelin", "other": "autre", "path and descendants": "chemin et descendants", + "permissionGuide.drag": "Faites glisser l’icône dans la liste ou cliquez sur + et choisissez l’app affichée dans le Finder.", + "permissionGuide.finderFailed": "Impossible d’afficher l’application dans le Finder.", + "permissionGuide.pending": "L’autorisation a été accordée mais n’a pas encore pris effet dans {application}.", + "permissionGuide.recheck": "Vérifier à nouveau", + "permissionGuide.restart": "Redémarrer Maka", + "permissionGuide.restartFailed": "Impossible de redémarrer Maka. Terminez la mise à jour ou la confirmation de fermeture, puis réessayez.", + "permissionGuide.restartHint": "Si l’interrupteur est activé, redémarrez Maka pour appliquer la modification.", + "permissionGuide.switch": "Si {application} figure dans la liste, activez son interrupteur.", + "permissionSettings.filesInfo": "Gérez l’accès aux fichiers dans Réglages Système de macOS. Maka ne parcourt pas les dossiers protégés pour vérifier les autorisations.", + "permissionSettings.go": "Ouvrir Réglages Système", + "permissionSettings.hostInfo": "Maka Host contrôle l’ordinateur en arrière-plan et dispose de ses propres autorisations dans Réglages Système.", + "permissionSettings.unsupported": "L’état des autorisations est indisponible sur cet hôte.", "permissionSetup.accessibilityPurpose": "Lire les éléments d’interface, cliquer et saisir dans les applications que vous autorisez.", "permissionSetup.application": "Application d’autorisation", "permissionSetup.cancel": "Annuler la configuration", diff --git a/products/maka/workbench/locales/it.json b/products/maka/workbench/locales/it.json index 188f4c2a4a8..e9caf214452 100644 --- a/products/maka/workbench/locales/it.json +++ b/products/maka/workbench/locales/it.json @@ -25,6 +25,7 @@ "Access allowed · {scope}": "Accesso consentito · {scope}", "Access denied": "Accesso negato", "Access key ID": "ID chiave di accesso", + "Access protected data when a task requires it.": "Accedi ai dati protetti quando il lavoro lo richiede.", "Access stopped for this turn": "Accesso interrotto per questo turno", "Accessibility": "Accessibilità", "Account": "Account", @@ -79,6 +80,7 @@ "After a reply": "Dopo una risposta", "After the current turn": "Dopo il turno corrente", "Agent": "Agente", + "Agent computer control": "Controllo del computer tramite agente", "Agent conversation": "Conversazione agente", "Agent message": "Messaggio agente", "Agent messages": "Messaggi agente", @@ -472,6 +474,7 @@ "Connect {name}": "Connetti {name}", "Connected": "Connesso", "Connected relays": "Relay connessi", + "Connected to a remote device.": "Connessione a un dispositivo remoto.", "Connecting to terminal…": "Connessione al terminale…", "Connecting…": "Connessione…", "Connection ID": "ID connessione", @@ -735,6 +738,8 @@ "Deployment change saved": "Modifica distribuzione salvata", "Deployment conflict": "Conflitto di distribuzione", "Description": "Descrizione", + "Desktop features": "Funzioni desktop", + "Desktop, Documents and Downloads": "Scrivania, Documenti e Download", "Detached HEAD": "HEAD scollegato", "Details": "Dettagli", "Details for skill {name} at {path}": "Dettagli della competenza {name} in {path}", @@ -961,6 +966,7 @@ "Fetch the provider’s catalog or add its exact model ID.": "Recupera il catalogo del provider o aggiungi l’ID modello esatto.", "Fetching models…": "Recupero modelli in corso…", "File": "File", + "File access": "Accesso ai file", "File actions": "Azioni file", "File changed on disk.": "File modificato su disco.", "File changes": "Modifiche file", @@ -974,6 +980,7 @@ "File updates ended. Retry to reconnect.": "Gli aggiornamenti dei file sono terminati. Riprova per riconnetterti.", "Files": "File", "Files already changed": "File già modificati", + "Files and folders": "File e cartelle", "Filesystem: no additional access": "Filesystem: nessun accesso aggiuntivo", "Filter branches…": "Filtra branch…", "Filter commits…": "Filtra commit…", @@ -1034,6 +1041,7 @@ "From {title}": "Da {title}", "Full access": "Accesso completo", "Full access · Sandbox off": "Accesso completo · Sandbox disattivata", + "Full disk access": "Accesso completo al disco", "Full screen image viewer": "Visualizzatore immagine a schermo intero", "General": "Generali", "Generating answer…": "Generazione risposta in corso…", @@ -1499,6 +1507,7 @@ "Not completed": "Non completato", "Not installed": "Non installato", "Not loaded": "Non caricato", + "Not requested": "Non ancora richiesto", "Not sent. Choose a workspace, then retry.": "Non inviato. Scegli uno spazio di lavoro, quindi riprova.", "Not set": "Non impostato", "Not signed in": "Accesso non effettuato", @@ -1529,6 +1538,7 @@ "Open Maka": "Apri Maka", "Open Maka Bot": "Apri Maka Bot", "Open System Settings": "Apri Impostazioni di Sistema", + "Open System Settings → Privacy & Security → {permission}.": "Apri Impostazioni di Sistema → Privacy e sicurezza → {permission}.", "Open a location, then choose a workspace folder.": "Apri una posizione, quindi scegli una cartella workspace.", "Open a plugin in this group to edit its settings.": "Apri un plugin in questo gruppo per modificarne le impostazioni.", "Open as a conversation": "Apri come conversazione", @@ -1953,6 +1963,7 @@ "Restore room": "Ripristina stanza", "Restore this conversation to continue it.": "Ripristina questa conversazione per continuarla.", "Restoring attachment drafts…": "Ripristino bozze allegati…", + "Restricted": "Con restrizioni", "Result URL path": "Percorso URL risultato", "Result limit location": "Posizione limite risultati", "Result limit parameter (optional)": "Parametro limite risultati (facoltativo)", @@ -2380,11 +2391,13 @@ "System": "Sistema", "System permission": "Autorizzazione di sistema", "System permission request": "Richiesta autorizzazione di sistema", + "System permissions": "Permessi di sistema", "System permissions granted": "Autorizzazioni di sistema concesse", "System tray icon": "Icona barra delle applicazioni", "TLS CA certificate path": "Percorso del certificato CA TLS", "TLS certificate SHA-256": "SHA-256 del certificato TLS", "Table of contents": "Sommario", + "Take a screenshot": "Acquisire lo schermo", "Take a seat hint": "@ qualcuno per prendere posto", "Taken by another app": "In uso da un’altra app", "Target conversation": "Conversazione", @@ -2892,6 +2905,18 @@ "orphaned": "orfano", "other": "altro", "path and descendants": "percorso e sottocartelle", + "permissionGuide.drag": "Trascina l’icona nell’elenco oppure fai clic su + e scegli l’app mostrata nel Finder.", + "permissionGuide.finderFailed": "Impossibile mostrare l’app nel Finder.", + "permissionGuide.pending": "Autorizzazione concessa, ma non ancora attiva in {application}.", + "permissionGuide.recheck": "Verifica di nuovo", + "permissionGuide.restart": "Riavvia Maka", + "permissionGuide.restartFailed": "Impossibile riavviare Maka. Completa la conferma di uscita o l’aggiornamento e riprova.", + "permissionGuide.restartHint": "Se hai attivato l’interruttore, riavvia Maka per applicare la modifica.", + "permissionGuide.switch": "Se {application} compare nell’elenco, attiva il suo interruttore.", + "permissionSettings.filesInfo": "Gestisci l’accesso ai file in Impostazioni di Sistema di macOS. Maka non esamina le cartelle protette per verificare le autorizzazioni.", + "permissionSettings.go": "Apri Impostazioni di Sistema", + "permissionSettings.hostInfo": "Maka Host controlla il computer in background e ha autorizzazioni proprie in Impostazioni di Sistema.", + "permissionSettings.unsupported": "Lo stato delle autorizzazioni non è disponibile su questo host.", "permissionSetup.accessibilityPurpose": "Legge gli elementi dell’interfaccia, fa clic e digita nelle applicazioni che consenti.", "permissionSetup.application": "Applicazione di autorizzazione", "permissionSetup.cancel": "Annulla configurazione", diff --git a/products/maka/workbench/locales/ja.json b/products/maka/workbench/locales/ja.json index 19b0847e5b0..8f2132c7fb1 100644 --- a/products/maka/workbench/locales/ja.json +++ b/products/maka/workbench/locales/ja.json @@ -25,6 +25,7 @@ "Access allowed · {scope}": "アクセス許可済み · {scope}", "Access denied": "アクセスが拒否されました", "Access key ID": "アクセスキー ID", + "Access protected data when a task requires it.": "タスクに必要な場合に保護されたデータにアクセスします。", "Access stopped for this turn": "このターンのアクセスを停止しました", "Accessibility": "アクセシビリティ", "Account": "アカウント", @@ -79,6 +80,7 @@ "After a reply": "返信後", "After the current turn": "現在のターン終了後", "Agent": "エージェント", + "Agent computer control": "エージェントのコンピュータ操作", "Agent conversation": "エージェント会話", "Agent message": "エージェントメッセージ", "Agent messages": "エージェントメッセージ", @@ -472,6 +474,7 @@ "Connect {name}": "{name} に接続", "Connected": "接続済み", "Connected relays": "接続済みのリレー", + "Connected to a remote device.": "リモートデバイスに接続しています。", "Connecting to terminal…": "ターミナルに接続しています…", "Connecting…": "接続中…", "Connection ID": "接続 ID", @@ -735,6 +738,8 @@ "Deployment change saved": "デプロイ変更を保存しました", "Deployment conflict": "デプロイの競合", "Description": "説明", + "Desktop features": "デスクトップ機能", + "Desktop, Documents and Downloads": "デスクトップ、書類、ダウンロードなど", "Detached HEAD": "Detached HEAD", "Details": "詳細", "Details for skill {name} at {path}": "{path} のスキル「{name}」の詳細", @@ -961,6 +966,7 @@ "Fetch the provider’s catalog or add its exact model ID.": "プロバイダーのカタログを取得するか、正確なモデル ID を追加してください。", "Fetching models…": "モデルを取得しています…", "File": "ファイル", + "File access": "ファイルアクセス", "File actions": "ファイルアクション", "File changed on disk.": "ディスク上のファイルが変更されました。", "File changes": "ファイルの変更", @@ -974,6 +980,7 @@ "File updates ended. Retry to reconnect.": "ファイルの更新が終了しました。再接続するには再試行してください。", "Files": "ファイル", "Files already changed": "すでに変更されたファイル", + "Files and folders": "ファイルとフォルダ", "Filesystem: no additional access": "ファイルシステム:追加アクセスなし", "Filter branches…": "ブランチを絞り込む…", "Filter commits…": "コミットを絞り込む…", @@ -1034,6 +1041,7 @@ "From {title}": "{title} から", "Full access": "フルアクセス", "Full access · Sandbox off": "フルアクセス · サンドボックス無効", + "Full disk access": "フルディスクアクセス", "Full screen image viewer": "全画面画像ビューアー", "General": "一般", "Generating answer…": "回答を生成しています…", @@ -1499,6 +1507,7 @@ "Not completed": "未完了", "Not installed": "未インストール", "Not loaded": "未読み込み", + "Not requested": "未要求", "Not sent. Choose a workspace, then retry.": "送信されませんでした。ワークスペースを選択してから再試行してください。", "Not set": "未設定", "Not signed in": "未サインイン", @@ -1529,6 +1538,7 @@ "Open Maka": "Maka を開く", "Open Maka Bot": "Maka Bot を開く", "Open System Settings": "システム設定を開く", + "Open System Settings → Privacy & Security → {permission}.": "システム設定 → プライバシーとセキュリティ → {permission} を開いてください。", "Open a location, then choose a workspace folder.": "場所を開いてからワークスペースフォルダーを選択してください。", "Open a plugin in this group to edit its settings.": "設定を編集するには、このグループ内のプラグインを開いてください。", "Open as a conversation": "会話として開く", @@ -1953,6 +1963,7 @@ "Restore room": "ルームを復元", "Restore this conversation to continue it.": "続けるにはこの会話を復元してください。", "Restoring attachment drafts…": "添付ファイルの下書きを復元しています…", + "Restricted": "制限あり", "Result URL path": "結果 URL のパス", "Result limit location": "取得件数パラメータの位置", "Result limit parameter (optional)": "取得件数パラメータ(任意)", @@ -2380,11 +2391,13 @@ "System": "システム", "System permission": "システム権限", "System permission request": "システム権限のリクエスト", + "System permissions": "システム権限", "System permissions granted": "システム権限が付与されています", "System tray icon": "システムトレイアイコン", "TLS CA certificate path": "TLS CA 証明書のパス", "TLS certificate SHA-256": "TLS 証明書の SHA-256", "Table of contents": "目次", + "Take a screenshot": "スクリーンショットを撮る", "Take a seat hint": "@ でメンションして参加させる", "Taken by another app": "他のアプリで使用中", "Target conversation": "対象の会話", @@ -2892,6 +2905,18 @@ "orphaned": "孤立", "other": "その他", "path and descendants": "このパスと配下すべて", + "permissionGuide.drag": "アイコンをリストにドラッグするか、+ を押して Finder に表示されたアプリを選んでください。", + "permissionGuide.finderFailed": "Finder でアプリを表示できませんでした。", + "permissionGuide.pending": "権限は許可されていますが、{application} にはまだ反映されていません。", + "permissionGuide.recheck": "再確認", + "permissionGuide.restart": "Maka を再起動", + "permissionGuide.restartFailed": "Maka を再起動できませんでした。終了の確認や更新を完了してから、もう一度お試しください。", + "permissionGuide.restartHint": "スイッチをオンにした場合は、Maka を再起動すると反映されます。", + "permissionGuide.switch": "一覧に {application} があれば、スイッチをオンにしてください。", + "permissionSettings.filesInfo": "ファイルアクセスは macOS のシステム設定で管理します。Maka は権限の確認のために保護されたフォルダをスキャンしません。", + "permissionSettings.go": "システム設定を開く", + "permissionSettings.hostInfo": "Maka Host は Maka に付属するバックグラウンドコンポーネントです。コンピュータ操作の権限はシステム設定で個別に許可します。", + "permissionSettings.unsupported": "このホストでは権限の状態を確認できません。", "permissionSetup.accessibilityPurpose": "許可したアプリ内の UI 要素の読み取り、クリック、入力を行います。", "permissionSetup.application": "権限対象のアプリ", "permissionSetup.cancel": "セットアップをキャンセル", diff --git a/products/maka/workbench/locales/ko.json b/products/maka/workbench/locales/ko.json index 1235c532cd0..e59df9d74aa 100644 --- a/products/maka/workbench/locales/ko.json +++ b/products/maka/workbench/locales/ko.json @@ -25,6 +25,7 @@ "Access allowed · {scope}": "접근 허용됨 · {scope}", "Access denied": "접근 거부됨", "Access key ID": "액세스 키 ID", + "Access protected data when a task requires it.": "작업에 필요한 경우 보호된 데이터에 접근합니다.", "Access stopped for this turn": "이 턴의 접근이 중지되었습니다", "Accessibility": "손쉬운 사용", "Account": "계정", @@ -79,6 +80,7 @@ "After a reply": "응답 후", "After the current turn": "현재 턴 완료 후", "Agent": "에이전트", + "Agent computer control": "에이전트 컴퓨터 제어", "Agent conversation": "에이전트 대화", "Agent message": "에이전트 메시지", "Agent messages": "에이전트 메시지", @@ -472,6 +474,7 @@ "Connect {name}": "{name} 연결", "Connected": "연결됨", "Connected relays": "연결된 릴레이", + "Connected to a remote device.": "원격 기기에 연결되어 있습니다.", "Connecting to terminal…": "터미널에 연결 중…", "Connecting…": "연결 중…", "Connection ID": "연결 ID", @@ -735,6 +738,8 @@ "Deployment change saved": "배포 변경 사항이 저장되었습니다", "Deployment conflict": "배포 충돌", "Description": "설명", + "Desktop features": "데스크톱 기능", + "Desktop, Documents and Downloads": "데스크탑, 문서 및 다운로드", "Detached HEAD": "분리된 HEAD", "Details": "세부 정보", "Details for skill {name} at {path}": "{path}의 스킬 {name} 세부 정보", @@ -961,6 +966,7 @@ "Fetch the provider’s catalog or add its exact model ID.": "프로바이더 카탈로그를 가져오거나 정확한 모델 ID를 추가하세요.", "Fetching models…": "모델 가져오는 중…", "File": "파일", + "File access": "파일 접근", "File actions": "파일 작업", "File changed on disk.": "디스크에서 파일이 변경되었습니다.", "File changes": "파일 변경 사항", @@ -974,6 +980,7 @@ "File updates ended. Retry to reconnect.": "파일 업데이트가 종료되었습니다. 다시 연결하려면 재시도하세요.", "Files": "파일", "Files already changed": "이미 변경된 파일", + "Files and folders": "파일 및 폴더", "Filesystem: no additional access": "파일 시스템: 추가 접근 권한 없음", "Filter branches…": "브랜치 필터링…", "Filter commits…": "커밋 필터링…", @@ -1034,6 +1041,7 @@ "From {title}": "{title}에서", "Full access": "전체 접근", "Full access · Sandbox off": "전체 접근 · 샌드박스 꺼짐", + "Full disk access": "전체 디스크 접근 권한", "Full screen image viewer": "전체 화면 이미지 뷰어", "General": "일반", "Generating answer…": "답변 생성 중…", @@ -1499,6 +1507,7 @@ "Not completed": "미완료", "Not installed": "미설치", "Not loaded": "로드되지 않음", + "Not requested": "요청 전", "Not sent. Choose a workspace, then retry.": "전송되지 않았습니다. 작업 공간을 선택한 후 다시 시도하세요.", "Not set": "설정 안 됨", "Not signed in": "로그인되지 않음", @@ -1529,6 +1538,7 @@ "Open Maka": "Maka 열기", "Open Maka Bot": "Maka Bot 열기", "Open System Settings": "시스템 설정 열기", + "Open System Settings → Privacy & Security → {permission}.": "시스템 설정 → 개인정보 보호 및 보안 → {permission}을 여세요.", "Open a location, then choose a workspace folder.": "위치를 연 다음 워크스페이스 폴더를 선택하세요.", "Open a plugin in this group to edit its settings.": "설정을 편집하려면 이 그룹에서 플러그인을 여세요.", "Open as a conversation": "대화로 열기", @@ -1953,6 +1963,7 @@ "Restore room": "룸 복원", "Restore this conversation to continue it.": "계속하려면 이 대화를 복원하세요.", "Restoring attachment drafts…": "첨부 파일 초안 복원 중…", + "Restricted": "제한됨", "Result URL path": "결과 URL 경로", "Result limit location": "결과 제한 위치", "Result limit parameter (optional)": "결과 제한 매개변수 (선택 사항)", @@ -2380,11 +2391,13 @@ "System": "시스템", "System permission": "시스템 권한", "System permission request": "시스템 권한 요청", + "System permissions": "시스템 권한", "System permissions granted": "시스템 권한 허용됨", "System tray icon": "시스템 트레이 아이콘", "TLS CA certificate path": "TLS CA 인증서 경로", "TLS certificate SHA-256": "TLS 인증서 SHA-256", "Table of contents": "목차", + "Take a screenshot": "스크린샷 찍기", "Take a seat hint": "@ 멘션으로 멤버를 참여시키세요", "Taken by another app": "다른 앱에서 사용 중", "Target conversation": "대화", @@ -2892,6 +2905,18 @@ "orphaned": "연결 끊김", "other": "기타", "path and descendants": "이 경로 및 하위 경로", + "permissionGuide.drag": "아이콘을 목록에 끌어 놓거나 +를 누르고 Finder에 표시된 앱을 선택하세요.", + "permissionGuide.finderFailed": "Finder에서 앱을 표시할 수 없습니다.", + "permissionGuide.pending": "권한을 허용했지만 {application}에는 아직 적용되지 않았습니다.", + "permissionGuide.recheck": "다시 확인", + "permissionGuide.restart": "Maka 다시 시작", + "permissionGuide.restartFailed": "Maka를 다시 시작할 수 없습니다. 종료 확인이나 업데이트를 마친 뒤 다시 시도하세요.", + "permissionGuide.restartHint": "스위치를 켰다면 Maka를 다시 시작해 변경 사항을 적용하세요.", + "permissionGuide.switch": "목록에 {application}이(가) 있으면 스위치를 켜세요.", + "permissionSettings.filesInfo": "파일 접근은 macOS 시스템 설정에서 관리합니다. Maka는 권한 확인을 위해 보호된 폴더를 스캔하지 않습니다.", + "permissionSettings.go": "시스템 설정 열기", + "permissionSettings.hostInfo": "Maka Host는 Maka의 백그라운드 구성 요소입니다. 컴퓨터 제어 권한은 시스템 설정에서 별도로 허용합니다.", + "permissionSettings.unsupported": "이 호스트에서는 권한 상태를 확인할 수 없습니다.", "permissionSetup.accessibilityPurpose": "허용한 응용 프로그램에서 인터페이스 요소를 읽고 클릭하며 입력합니다.", "permissionSetup.application": "권한 부여 대상 앱", "permissionSetup.cancel": "설정 취소", diff --git a/products/maka/workbench/locales/pt-BR.json b/products/maka/workbench/locales/pt-BR.json index a6672f98f38..44a2314fccf 100644 --- a/products/maka/workbench/locales/pt-BR.json +++ b/products/maka/workbench/locales/pt-BR.json @@ -25,6 +25,7 @@ "Access allowed · {scope}": "Acesso permitido · {scope}", "Access denied": "Acesso negado", "Access key ID": "ID da chave de acesso", + "Access protected data when a task requires it.": "Acesse dados protegidos quando a tarefa exigir.", "Access stopped for this turn": "Acesso interrompido neste turno", "Accessibility": "Acessibilidade", "Account": "Conta", @@ -79,6 +80,7 @@ "After a reply": "Após uma resposta", "After the current turn": "Após o turno atual", "Agent": "Agente", + "Agent computer control": "Controle do computador pelo agente", "Agent conversation": "Conversa do agente", "Agent message": "Mensagem do agente", "Agent messages": "Mensagens do agente", @@ -472,6 +474,7 @@ "Connect {name}": "Conectar {name}", "Connected": "Conectado", "Connected relays": "Relays conectados", + "Connected to a remote device.": "Conectado a um dispositivo remoto.", "Connecting to terminal…": "Conectando ao terminal…", "Connecting…": "Conectando…", "Connection ID": "ID da conexão", @@ -735,6 +738,8 @@ "Deployment change saved": "Alteração de implantação salva", "Deployment conflict": "Conflito de implantação", "Description": "Descrição", + "Desktop features": "Recursos da área de trabalho", + "Desktop, Documents and Downloads": "Mesa, Documentos e Downloads", "Detached HEAD": "HEAD desanexado", "Details": "Detalhes", "Details for skill {name} at {path}": "Detalhes da habilidade {name} em {path}", @@ -961,6 +966,7 @@ "Fetch the provider’s catalog or add its exact model ID.": "Busque o catálogo do provedor ou adicione o ID exato do modelo.", "Fetching models…": "Buscando modelos…", "File": "Arquivo", + "File access": "Acesso a arquivos", "File actions": "Ações de arquivo", "File changed on disk.": "Arquivo alterado no disco.", "File changes": "Alterações de arquivo", @@ -974,6 +980,7 @@ "File updates ended. Retry to reconnect.": "As atualizações de arquivo foram encerradas. Tente novamente para reconectar.", "Files": "Arquivos", "Files already changed": "Arquivos já alterados", + "Files and folders": "Arquivos e pastas", "Filesystem: no additional access": "Sistema de arquivos: sem acesso adicional", "Filter branches…": "Filtrar branches…", "Filter commits…": "Filtrar commits…", @@ -1034,6 +1041,7 @@ "From {title}": "De {title}", "Full access": "Acesso total", "Full access · Sandbox off": "Acesso total · Sandbox desativada", + "Full disk access": "Acesso total ao disco", "Full screen image viewer": "Visualizador de imagem em tela cheia", "General": "Geral", "Generating answer…": "Gerando resposta…", @@ -1499,6 +1507,7 @@ "Not completed": "Não concluído", "Not installed": "Não instalado", "Not loaded": "Não carregado", + "Not requested": "Ainda não solicitado", "Not sent. Choose a workspace, then retry.": "Não enviado. Escolha um espaço de trabalho e tente novamente.", "Not set": "Não definido", "Not signed in": "Não conectado", @@ -1529,6 +1538,7 @@ "Open Maka": "Abrir Maka", "Open Maka Bot": "Abrir Maka Bot", "Open System Settings": "Abrir Ajustes do Sistema", + "Open System Settings → Privacy & Security → {permission}.": "Abra Ajustes do Sistema → Privacidade e Segurança → {permission}.", "Open a location, then choose a workspace folder.": "Abra um local e escolha uma pasta de workspace.", "Open a plugin in this group to edit its settings.": "Abra um plugin neste grupo para editar suas configurações.", "Open as a conversation": "Abrir como conversa", @@ -1953,6 +1963,7 @@ "Restore room": "Restaurar sala", "Restore this conversation to continue it.": "Restaure esta conversa para continuá-la.", "Restoring attachment drafts…": "Restaurando rascunhos de anexos…", + "Restricted": "Restrito", "Result URL path": "Caminho da URL do resultado", "Result limit location": "Local do limite de resultados", "Result limit parameter (optional)": "Parâmetro de limite de resultados (opcional)", @@ -2380,11 +2391,13 @@ "System": "Sistema", "System permission": "Permissão do sistema", "System permission request": "Solicitação de permissão do sistema", + "System permissions": "Permissões do sistema", "System permissions granted": "Permissões do sistema concedidas", "System tray icon": "Ícone na bandeja do sistema", "TLS CA certificate path": "Caminho do certificado da CA TLS", "TLS certificate SHA-256": "SHA-256 do certificado TLS", "Table of contents": "Sumário", + "Take a screenshot": "Capturar a tela", "Take a seat hint": "@ alguém para entrar na sala", "Taken by another app": "Usado por outro aplicativo", "Target conversation": "Conversa", @@ -2892,6 +2905,18 @@ "orphaned": "órfão", "other": "outro", "path and descendants": "caminho e descendentes", + "permissionGuide.drag": "Arraste o ícone para a lista ou clique em + e selecione o app mostrado no Finder.", + "permissionGuide.finderFailed": "Não foi possível mostrar o aplicativo no Finder.", + "permissionGuide.pending": "Permissão concedida. Ela ainda não entrou em vigor em {application}.", + "permissionGuide.recheck": "Verificar novamente", + "permissionGuide.restart": "Reiniciar o Maka", + "permissionGuide.restartFailed": "Não foi possível reiniciar o Maka. Conclua a confirmação de saída ou a atualização e tente novamente.", + "permissionGuide.restartHint": "Se você já ativou a opção, reinicie o Maka para aplicar a alteração.", + "permissionGuide.switch": "Se {application} estiver na lista, ative a opção.", + "permissionSettings.filesInfo": "Gerencie o acesso a arquivos nos Ajustes do Sistema do macOS. O Maka não examina pastas protegidas para verificar permissões.", + "permissionSettings.go": "Abrir Ajustes do Sistema", + "permissionSettings.hostInfo": "O Maka Host controla o computador em segundo plano e tem permissões próprias nos Ajustes do Sistema.", + "permissionSettings.unsupported": "O estado das permissões não está disponível neste host.", "permissionSetup.accessibilityPurpose": "Leia elementos da interface, clique e digite nos aplicativos que você permitir.", "permissionSetup.application": "Aplicativo de permissão", "permissionSetup.cancel": "Cancelar configuração", diff --git a/products/maka/workbench/locales/ru.json b/products/maka/workbench/locales/ru.json index f66de6fff96..5b458877859 100644 --- a/products/maka/workbench/locales/ru.json +++ b/products/maka/workbench/locales/ru.json @@ -25,6 +25,7 @@ "Access allowed · {scope}": "Доступ разрешён · {scope}", "Access denied": "Доступ запрещён", "Access key ID": "ID ключа доступа", + "Access protected data when a task requires it.": "Доступ к защищённым данным по необходимости.", "Access stopped for this turn": "Доступ остановлен для этого хода", "Accessibility": "Универсальный доступ", "Account": "Аккаунт", @@ -79,6 +80,7 @@ "After a reply": "После ответа", "After the current turn": "После текущего хода", "Agent": "Агент", + "Agent computer control": "Управление компьютером агентом", "Agent conversation": "Диалог с агентом", "Agent message": "Сообщение агента", "Agent messages": "Сообщения агента", @@ -472,6 +474,7 @@ "Connect {name}": "Подключить {name}", "Connected": "Подключено", "Connected relays": "Подключённые ретрансляторы", + "Connected to a remote device.": "Подключено удалённое устройство.", "Connecting to terminal…": "Подключение к терминалу…", "Connecting…": "Подключение…", "Connection ID": "ID подключения", @@ -735,6 +738,8 @@ "Deployment change saved": "Изменение развёртывания сохранено", "Deployment conflict": "Конфликт развёртывания", "Description": "Описание", + "Desktop features": "Функции приложения", + "Desktop, Documents and Downloads": "Рабочий стол, Документы и Загрузки", "Detached HEAD": "Отсоединённый HEAD", "Details": "Подробности", "Details for skill {name} at {path}": "Подробности навыка {name} в {path}", @@ -961,6 +966,7 @@ "Fetch the provider’s catalog or add its exact model ID.": "Загрузите каталог провайдера или добавьте точный ID модели.", "Fetching models…": "Загрузка моделей…", "File": "Файл", + "File access": "Доступ к файлам", "File actions": "Действия с файлом", "File changed on disk.": "Файл изменён на диске.", "File changes": "Изменения файла", @@ -974,6 +980,7 @@ "File updates ended. Retry to reconnect.": "Обновления файлов завершены. Повторите для переподключения.", "Files": "Файлы", "Files already changed": "Уже изменённые файлы", + "Files and folders": "Файлы и папки", "Filesystem: no additional access": "Файловая система: без дополнительного доступа", "Filter branches…": "Фильтр веток…", "Filter commits…": "Фильтр коммитов…", @@ -1034,6 +1041,7 @@ "From {title}": "Из «{title}»", "Full access": "Полный доступ", "Full access · Sandbox off": "Полный доступ · Песочница выключена", + "Full disk access": "Полный доступ к диску", "Full screen image viewer": "Полноэкранный просмотр изображения", "General": "Основные", "Generating answer…": "Генерация ответа…", @@ -1499,6 +1507,7 @@ "Not completed": "Не завершено", "Not installed": "Не установлено", "Not loaded": "Не загружается", + "Not requested": "Не запрашивалось", "Not sent. Choose a workspace, then retry.": "Не отправлено. Выберите рабочую область и повторите попытку.", "Not set": "Не задано", "Not signed in": "Вход не выполнен", @@ -1529,6 +1538,7 @@ "Open Maka": "Открыть Maka", "Open Maka Bot": "Открыть Maka Bot", "Open System Settings": "Открыть Системные настройки", + "Open System Settings → Privacy & Security → {permission}.": "Откройте Системные настройки → Конфиденциальность и безопасность → {permission}.", "Open a location, then choose a workspace folder.": "Откройте расположение, затем выберите папку рабочей области.", "Open a plugin in this group to edit its settings.": "Откройте плагин в этой группе, чтобы изменить его настройки.", "Open as a conversation": "Открыть как беседу", @@ -1953,6 +1963,7 @@ "Restore room": "Восстановить комнату", "Restore this conversation to continue it.": "Восстановите этот диалог, чтобы продолжить его.", "Restoring attachment drafts…": "Восстановление черновиков вложений…", + "Restricted": "Ограничено", "Result URL path": "Путь к URL результата", "Result limit location": "Расположение лимита результатов", "Result limit parameter (optional)": "Параметр лимита результатов (необязательно)", @@ -2380,11 +2391,13 @@ "System": "Системный", "System permission": "Системное разрешение", "System permission request": "Запрос системного разрешения", + "System permissions": "Системные разрешения", "System permissions granted": "Системные разрешения выданы", "System tray icon": "Значок в системном трее", "TLS CA certificate path": "Путь к сертификату CA TLS", "TLS certificate SHA-256": "SHA-256 сертификата TLS", "Table of contents": "Содержание", + "Take a screenshot": "Создание снимков экрана", "Take a seat hint": "Упомяните @ кого-нибудь, чтобы пригласить", "Taken by another app": "Занято другим приложением", "Target conversation": "Диалог", @@ -2892,6 +2905,18 @@ "orphaned": "потеряна связь", "other": "другое", "path and descendants": "путь и вложенные элементы", + "permissionGuide.drag": "Перетащите значок в список или нажмите + и выберите приложение, показанное в Finder.", + "permissionGuide.finderFailed": "Не удалось показать приложение в Finder.", + "permissionGuide.pending": "Разрешение предоставлено, но пока не действует в {application}.", + "permissionGuide.recheck": "Проверить снова", + "permissionGuide.restart": "Перезапустить Maka", + "permissionGuide.restartFailed": "Не удалось перезапустить Maka. Завершите обновление или подтвердите выход и повторите попытку.", + "permissionGuide.restartHint": "Если переключатель включён, перезапустите Maka, чтобы применить изменение.", + "permissionGuide.switch": "Если {application} есть в списке, включите переключатель.", + "permissionSettings.filesInfo": "Доступ к файлам регулируется в Системных настройках macOS. Maka не сканирует защищённые папки для проверки разрешений.", + "permissionSettings.go": "Открыть Системные настройки", + "permissionSettings.hostInfo": "Maka Host управляет компьютером в фоновом режиме. Разрешения для него задаются отдельно в Системных настройках.", + "permissionSettings.unsupported": "На этом узле нельзя проверить состояние разрешений.", "permissionSetup.accessibilityPurpose": "Чтение элементов интерфейса, нажатия и ввод текста в разрешённых вами приложениях.", "permissionSetup.application": "Приложение для разрешения", "permissionSetup.cancel": "Отменить настройку", diff --git a/products/maka/workbench/locales/zh-CN.json b/products/maka/workbench/locales/zh-CN.json index 6605869ddf7..039c0c4acf4 100644 --- a/products/maka/workbench/locales/zh-CN.json +++ b/products/maka/workbench/locales/zh-CN.json @@ -25,6 +25,7 @@ "Access allowed · {scope}": "已允许访问 · {scope}", "Access denied": "权限已拒绝", "Access key ID": "访问密钥 ID", + "Access protected data when a task requires it.": "任务需要读写受系统保护的数据时使用。", "Access stopped for this turn": "本轮访问已停止", "Accessibility": "辅助功能", "Account": "账号", @@ -79,6 +80,7 @@ "After a reply": "回复完成后", "After the current turn": "当前轮次结束后", "Agent": "助手", + "Agent computer control": "Agent 电脑控制", "Agent conversation": "Agent 会话", "Agent message": "Agent 消息", "Agent messages": "Agent 消息", @@ -472,6 +474,7 @@ "Connect {name}": "连接 {name}", "Connected": "已连接", "Connected relays": "已连接的中继", + "Connected to a remote device.": "当前连接的是远端设备。", "Connecting to terminal…": "正在连接终端…", "Connecting…": "正在连接…", "Connection ID": "连接标识", @@ -735,6 +738,8 @@ "Deployment change saved": "已保存部署更改", "Deployment conflict": "部署更改冲突", "Description": "描述", + "Desktop features": "桌面功能", + "Desktop, Documents and Downloads": "桌面、文稿和下载等目录", "Detached HEAD": "游离 HEAD", "Details": "详情", "Details for skill {name} at {path}": "查看 {path} 中的技能 {name}", @@ -961,6 +966,7 @@ "Fetch the provider’s catalog or add its exact model ID.": "获取提供商的模型目录,或添加准确的模型 ID。", "Fetching models…": "正在拉取模型…", "File": "文件", + "File access": "文件访问", "File actions": "文件操作", "File changed on disk.": "文件已被外部修改。", "File changes": "文件变更", @@ -974,6 +980,7 @@ "File updates ended. Retry to reconnect.": "文件更新已结束。请重试以重新连接。", "Files": "文件", "Files already changed": "已更改的文件", + "Files and folders": "文件与文件夹", "Filesystem: no additional access": "文件系统:无额外访问权限", "Filter branches…": "筛选分支…", "Filter commits…": "搜索提交记录…", @@ -1034,6 +1041,7 @@ "From {title}": "来自 {title}", "Full access": "完全访问", "Full access · Sandbox off": "完全访问 · 沙箱已关闭", + "Full disk access": "完全磁盘访问", "Full screen image viewer": "全屏图片查看器", "General": "常规", "Generating answer…": "正在生成回答…", @@ -1499,6 +1507,7 @@ "Not completed": "未完成", "Not installed": "未安装", "Not loaded": "未加载", + "Not requested": "尚未请求", "Not sent. Choose a workspace, then retry.": "未发送。请先选择工作区,然后重试。", "Not set": "未设置", "Not signed in": "未登录", @@ -1529,6 +1538,7 @@ "Open Maka": "打开 Maka", "Open Maka Bot": "打开 Maka Bot", "Open System Settings": "打开系统设置", + "Open System Settings → Privacy & Security → {permission}.": "请打开系统设置 → 隐私与安全性 → {permission}。", "Open a location, then choose a workspace folder.": "打开一个位置,然后选择工作区文件夹。", "Open a plugin in this group to edit its settings.": "打开此分组中的插件以编辑其设置。", "Open as a conversation": "作为对话打开", @@ -1953,6 +1963,7 @@ "Restore room": "恢复房间", "Restore this conversation to continue it.": "恢复这个对话后才能继续。", "Restoring attachment drafts…": "正在恢复附件草稿…", + "Restricted": "受限制", "Result URL path": "结果 URL 路径", "Result limit location": "结果数量参数位置", "Result limit parameter (optional)": "结果数量参数(选填)", @@ -2380,11 +2391,13 @@ "System": "系统", "System permission": "系统权限", "System permission request": "系统权限请求", + "System permissions": "系统权限", "System permissions granted": "系统权限已开启", "System tray icon": "系统托盘图标", "TLS CA certificate path": "TLS CA 证书路径", "TLS certificate SHA-256": "TLS 证书 SHA-256", "Table of contents": "目录", + "Take a screenshot": "截取桌面画面", "Take a seat hint": "@ 谁,谁就入座", "Taken by another app": "已被其他应用占用", "Target conversation": "目标会话", @@ -2892,6 +2905,18 @@ "orphaned": "已失联", "other": "其他文件", "path and descendants": "此路径及其子路径", + "permissionGuide.drag": "把图标拖进列表,或点列表下方的 +,选择访达中显示的应用。", + "permissionGuide.finderFailed": "无法在访达中显示该应用。", + "permissionGuide.pending": "权限已授予,当前 {application} 尚未生效。", + "permissionGuide.recheck": "重新检查", + "permissionGuide.restart": "重新启动 Maka", + "permissionGuide.restartFailed": "Maka 暂时无法重启。请先完成退出确认或更新,再试一次。", + "permissionGuide.restartHint": "如果你已打开开关,请重新启动 Maka 使权限生效。", + "permissionGuide.switch": "如果列表中已有 {application},请打开它的开关。", + "permissionSettings.filesInfo": "这两项权限由 macOS 系统设置管理。Maka 不会扫描受保护目录来检查权限。", + "permissionSettings.go": "前往系统设置", + "permissionSettings.hostInfo": "Maka Host 是 Maka 自带的后台组件,电脑控制权限需在系统设置中单独授予。", + "permissionSettings.unsupported": "当前 Host 不支持查询系统权限。", "permissionSetup.accessibilityPurpose": "读取界面元素,并在你允许的应用中点击和输入。", "permissionSetup.application": "获得权限的应用", "permissionSetup.cancel": "取消设置", diff --git a/products/maka/workbench/locales/zh-HK.json b/products/maka/workbench/locales/zh-HK.json index 7defd43b131..eb7c021dfce 100644 --- a/products/maka/workbench/locales/zh-HK.json +++ b/products/maka/workbench/locales/zh-HK.json @@ -6,6 +6,7 @@ "Abandon unconfirmed upload": "放棄未確認的上載", "Absolute folder path on this Host": "此主機上的檔案夾絕對路徑", "Access key ID": "存取密鑰 ID", + "Access protected data when a task requires it.": "工作需要讀寫受系統保護的資料時使用。", "Account": "帳戶", "Account sign-in": "帳戶登入", "Action feedback": "操作反饋", @@ -15,6 +16,7 @@ "Add connections, API keys and models": "新增連線、API 密鑰和模型", "Add or update the usage access key": "新增或更新用量查詢密鑰", "Add to queue": "加入隊列", + "Agent computer control": "Agent 電腦控制", "Allow Accessibility to snap to the controls inside windows.": "允許輔助使用後,可以吸附視窗內的控制項。", "Allow Maka to read Downloads in System Settings > Privacy & Security > Files and Folders.": "請在系統設定的「私隱與保安 → 檔案與檔案夾」中允許 Maka 讀取下載項目。", "Allow Maka under Screen & System Audio Recording in System Settings, then take the screenshot again.": "請在系統設定的「熒幕與系統錄音」中允許 Maka,然後重新截圖。", @@ -64,6 +66,7 @@ "Connect to a relay before pairing a device.": "配對裝置前請先連接至中繼。", "Connected": "已連接", "Connected relays": "已連接的中繼", + "Connected to a remote device.": "目前連接至遙距裝置。", "Connecting…": "正在連接…", "Connection and API key saved.": "連線和 API 密鑰已儲存。", "Connection saved; saving API key…": "連線已儲存;正在儲存 API 密鑰…", @@ -90,6 +93,8 @@ "Cron expression": "Cron 表達式", "Current queued message": "目前隊列訊息", "Delete discovery plan?": "刪除此計劃?", + "Desktop features": "桌面功能", + "Desktop, Documents and Downloads": "桌面、文件及下載項目等資料夾", "Details": "詳細資料", "Dictation uses the API key from this connection.": "聽寫使用此連線的 API 密鑰。", "Diff truncated; {count} binary or large files omitted.": "差異已截斷,省略了 {count} 個二進制或超大檔案。", @@ -126,7 +131,9 @@ "Entries kept": "保留條數", "Exit fullscreen": "退出全熒幕", "Fetching models…": "正在取得模型…", + "File access": "檔案取用", "File list": "檔案列表", + "Files and folders": "檔案與資料夾", "Filter commits…": "搜尋提交記錄…", "Find compatible plugins": "尋找兼容插件", "Folder": "檔案夾", @@ -136,6 +143,7 @@ "Fork created. Open it in Sessions.": "分支對話已建立,可在對話列表中開啟。", "From room agent": "{room} · 由 {sender} 在房間內 @", "From room human": "{room} · 你在房間內 @ 了此會話", + "Full disk access": "完整磁碟取用權", "Full screen image viewer": "全熒幕圖片檢視器", "GitHub authentication": "GitHub 身份驗證", "Goal checkpoint": "進度記錄", @@ -188,7 +196,9 @@ "No token": "無令牌", "No turn is running. This message remains queued.": "目前沒有正在執行的輪次,訊息仍在隊列中。", "No usage limits reported": "供應商未傳回用量限制", + "Not requested": "尚未要求", "Only the user can change permissions": "只有用戶可以變更權限", + "Open System Settings → Privacy & Security → {permission}.": "請開啟系統設定 → 私隱與保安 → {permission}。", "Open a location, then choose a workspace folder.": "開啟一個位置,然後選擇工作區檔案夾。", "Open a plugin in this group to edit its settings.": "開啟此群組中的插件以編輯其設定。", "Open diagram full screen": "全熒幕檢視圖表", @@ -266,6 +276,7 @@ "Replace plugin deployment": "取代插件部署", "Requests needing attention ({count})": "有 {count} 項請求待處理", "Responses": "Responses 兼容介面", + "Restricted": "受限制", "Retry attachment metadata": "重試附件資料", "Retry folder": "重試檔案夾", "Retry loading providers": "重試載入供應商", @@ -302,7 +313,9 @@ "Stop the current run and clear any queued messages before changing workspaces.": "請先停止目前的執行並清除排隊中的訊息,再更改工作區。", "Stored API key": "已儲存的 API 密鑰", "Stored provider credential removed.": "已移除儲存的供應商憑據。", + "System permissions": "系統權限", "System tray icon": "系統托盤圖示", + "Take a screenshot": "擷取桌面畫面", "Terminal observation interrupted.": "終端機連接已中斷。", "The Host closed the terminal list.": "Host 已關閉終端列表。", "The Host did not accept this queue change.": "Host 未接受此次隊列變更。", @@ -377,6 +390,18 @@ "launcher.keywords.dictation": "聽寫,語音輸入", "launcher.keywords.file_search": "檔案,檔案搜尋", "launcher.keywords.screenshot": "截圖,截取熒幕,熒幕截圖", + "permissionGuide.drag": "將圖示拖入列表,或按列表下方的 +,選擇 Finder 中顯示的應用程式。", + "permissionGuide.finderFailed": "無法在 Finder 中顯示此程式。", + "permissionGuide.pending": "權限已授予,目前在 {application} 尚未生效。", + "permissionGuide.recheck": "重新檢查", + "permissionGuide.restart": "重新啟動 Maka", + "permissionGuide.restartFailed": "Maka 暫時無法重新啟動。請先完成結束確認或更新,再試一次。", + "permissionGuide.restartHint": "如果已開啟開關,請重新啟動 Maka 讓權限生效。", + "permissionGuide.switch": "如果列表中已有 {application},請開啟其開關。", + "permissionSettings.filesInfo": "這兩項權限由 macOS 系統設定管理。Maka 不會掃描受保護的資料夾來檢查權限。", + "permissionSettings.go": "前往系統設定", + "permissionSettings.hostInfo": "Maka Host 是 Maka 內置的背景元件,電腦控制權限須在系統設定中單獨授予。", + "permissionSettings.unsupported": "目前的 Host 不支援查詢系統權限。", "permissionSetup.closedBody": "此請求已不再等待授權。這裏不會再發起任何變更。", "permissionSetup.helpBody": "如果私隱列表中沒有此 App,請按「在 Finder 中顯示」,將選取的 App 拖入系統設定。", "permissionSetup.screenPurpose": "查看你分享的 App 和熒幕截圖。", diff --git a/products/maka/workbench/locales/zh-TW.json b/products/maka/workbench/locales/zh-TW.json index 2a349f50dfb..1d2a4fa39fd 100644 --- a/products/maka/workbench/locales/zh-TW.json +++ b/products/maka/workbench/locales/zh-TW.json @@ -25,6 +25,7 @@ "Access allowed · {scope}": "已允許存取 · {scope}", "Access denied": "權限已拒絕", "Access key ID": "存取金鑰 ID", + "Access protected data when a task requires it.": "工作需要讀寫受系統保護的資料時使用。", "Access stopped for this turn": "本輪存取已停止", "Accessibility": "輔助使用", "Account": "帳號", @@ -79,6 +80,7 @@ "After a reply": "回覆完成後", "After the current turn": "目前輪次結束後", "Agent": "助理", + "Agent computer control": "Agent 電腦控制", "Agent conversation": "Agent 工作階段", "Agent message": "Agent 訊息", "Agent messages": "Agent 訊息", @@ -472,6 +474,7 @@ "Connect {name}": "連線至 {name}", "Connected": "已連線", "Connected relays": "已連線的中繼", + "Connected to a remote device.": "目前連線至遠端裝置。", "Connecting to terminal…": "正在連線終端…", "Connecting…": "正在連線…", "Connection ID": "連線識別碼", @@ -735,6 +738,8 @@ "Deployment change saved": "已儲存部署變更", "Deployment conflict": "部署變更衝突", "Description": "描述", + "Desktop features": "桌面功能", + "Desktop, Documents and Downloads": "桌面、文件及下載項目等資料夾", "Detached HEAD": "分離 HEAD", "Details": "詳細資訊", "Details for skill {name} at {path}": "檢視 {path} 中的技能 {name}", @@ -961,6 +966,7 @@ "Fetch the provider’s catalog or add its exact model ID.": "取得供應商的模型目錄,或新增正確的模型 ID。", "Fetching models…": "正在擷取模型…", "File": "檔案", + "File access": "檔案取用", "File actions": "檔案操作", "File changed on disk.": "檔案已被外部修改。", "File changes": "檔案變更", @@ -974,6 +980,7 @@ "File updates ended. Retry to reconnect.": "檔案更新已結束。請重試以重新連線。", "Files": "檔案", "Files already changed": "已變更的檔案", + "Files and folders": "檔案與檔案夾", "Filesystem: no additional access": "檔案系統:無額外存取權限", "Filter branches…": "篩選分支…", "Filter commits…": "搜尋提交紀錄…", @@ -1034,6 +1041,7 @@ "From {title}": "來自 {title}", "Full access": "完整存取", "Full access · Sandbox off": "完整存取 · 沙箱已關閉", + "Full disk access": "完整磁碟取用權", "Full screen image viewer": "全螢幕圖片檢視器", "General": "一般", "Generating answer…": "正在產生回答…", @@ -1499,6 +1507,7 @@ "Not completed": "未完成", "Not installed": "未安裝", "Not loaded": "未載入", + "Not requested": "尚未要求", "Not sent. Choose a workspace, then retry.": "未傳送。請先選擇工作區,然後重試。", "Not set": "未設定", "Not signed in": "未登入", @@ -1529,6 +1538,7 @@ "Open Maka": "打開 Maka", "Open Maka Bot": "開啟 Maka Bot", "Open System Settings": "打開系統設定", + "Open System Settings → Privacy & Security → {permission}.": "請打開系統設定 → 隱私權與安全性 → {permission}。", "Open a location, then choose a workspace folder.": "開啟一個位置,然後選擇工作區資料夾。", "Open a plugin in this group to edit its settings.": "開啟此群組中的外掛以編輯其設定。", "Open as a conversation": "以對話開啟", @@ -1953,6 +1963,7 @@ "Restore room": "還原房間", "Restore this conversation to continue it.": "還原這個對話後才能繼續。", "Restoring attachment drafts…": "正在恢復附件草稿…", + "Restricted": "受限制", "Result URL path": "結果 URL 路徑", "Result limit location": "結果數量參數位置", "Result limit parameter (optional)": "結果數量參數(選填)", @@ -2380,11 +2391,13 @@ "System": "系統", "System permission": "系統權限", "System permission request": "系統權限請求", + "System permissions": "系統權限", "System permissions granted": "系統權限已開啟", "System tray icon": "系統匣圖示", "TLS CA certificate path": "TLS CA 憑證路徑", "TLS certificate SHA-256": "TLS 憑證 SHA-256", "Table of contents": "目錄", + "Take a screenshot": "擷取桌面畫面", "Take a seat hint": "@ 誰,誰就入座", "Taken by another app": "已被其他 App 佔用", "Target conversation": "目標對話", @@ -2892,6 +2905,18 @@ "orphaned": "已失聯", "other": "其他檔案", "path and descendants": "此路徑及其子路徑", + "permissionGuide.drag": "將圖示拖入列表,或按列表下方的 +,選擇 Finder 中顯示的 App。", + "permissionGuide.finderFailed": "無法在 Finder 中顯示此應用程式。", + "permissionGuide.pending": "已授予權限,目前在 {application} 尚未生效。", + "permissionGuide.recheck": "重新檢查", + "permissionGuide.restart": "重新啟動 Maka", + "permissionGuide.restartFailed": "Maka 暫時無法重新啟動。請先完成結束確認或更新,再試一次。", + "permissionGuide.restartHint": "如果已打開開關,請重新啟動 Maka 讓權限生效。", + "permissionGuide.switch": "如果清單中已有 {application},請打開它的開關。", + "permissionSettings.filesInfo": "這兩項權限由 macOS 系統設定管理。Maka 不會掃描受保護的資料夾來檢查權限。", + "permissionSettings.go": "前往系統設定", + "permissionSettings.hostInfo": "Maka Host 是 Maka 內建的背景元件,電腦控制權限需在系統設定中個別授予。", + "permissionSettings.unsupported": "目前的 Host 不支援查詢系統權限。", "permissionSetup.accessibilityPurpose": "讀取介面元素,並在你允許的 App 中點按和輸入。", "permissionSetup.application": "取得權限的 App", "permissionSetup.cancel": "取消設定", diff --git a/products/maka/workbench/src/bindings.rs b/products/maka/workbench/src/bindings.rs index acdd40a5752..e5b4f2cac83 100644 --- a/products/maka/workbench/src/bindings.rs +++ b/products/maka/workbench/src/bindings.rs @@ -27,6 +27,7 @@ mod file_search; mod files; mod links; mod mutation; +mod permission_settings; mod permission_window; mod plugins; mod quick_tools; @@ -39,7 +40,7 @@ mod ui_services; mod uploads; pub use mutation::OriginalMutation; -pub use permission_window::SystemPermissionWindow; +pub use permission_window::{PermissionGuide, SystemPermissionWindow}; use maka_app_client::{Client, Subscription, SubscriptionEvent}; use maka_plugin_core::contract::{Contract, Interface}; @@ -62,13 +63,17 @@ const EDITOR: &str = "composer"; pub struct Bindings { owner: Arc, } +type RestartReply = tokio::sync::oneshot::Sender>; +type RestartHandler = Box; struct Owner { + restart: std::sync::OnceLock, client: Client, runtime: Handle, tasks: StdMutex>, plugins: plugins::Packages, reload: crate::reload::UiReload, staged_images: StdMutex>>, + guide: StdMutex>, permission_windows: StdMutex>>, } @@ -192,6 +197,8 @@ impl Bindings { plugins: Default::default(), reload: Default::default(), staged_images: Default::default(), + restart: Default::default(), + guide: Default::default(), permission_windows: Default::default(), }), } @@ -210,6 +217,10 @@ impl Bindings { self.owner.reload.clone() } + pub fn set_permission_restart(&self, handler: impl Fn(RestartReply) + Send + Sync + 'static) { + let _ = self.owner.restart.set(Box::new(handler)); + } + /// Installs the shell's dedicated system-permission window presenter. pub fn set_system_permission_windows( &self, @@ -230,8 +241,15 @@ impl Bindings { }) } + /// Invalidate file drags before detaching this connection. + pub fn close_permission_guide(&self) { + if let Some(old) = self.owner.guide.lock().unwrap().take() { + old.close(); + } + } /// Fence new native tasks, close the original Host session and finish admitted IO. pub async fn close(&self) -> Result<(), String> { + self.close_permission_guide(); self.close_with(self.owner.client.close()).await } @@ -873,6 +891,171 @@ impl ApplicationHost { Ok(Instance::new(original)) } + pub async fn desktop_permission_settings(this: Instance) -> Result { + let owner = this.with(|host| host.owner.clone()); + drop(this); + let can_restart = owner.restart.get().is_some(); + execute(owner, async move { + let mut value = tokio::task::spawn_blocking(permission_settings::desktop) + .await + .map_err(|e| e.to_string())??; + value["canRestart"] = can_restart.into(); + Ok(value) + }) + .await + } + + pub async fn host_permission_settings(this: Instance) -> Result { + let (owner, source) = this.with(|host| (host.owner.clone(), host.client.clone())); + drop(this); + execute(owner.clone(), async move { + let client = source.resolve(&owner).await?; + let snapshot = permission_settings::host(&client, None).await?; + let local = permission_settings::local(&client, &owner.client, &snapshot).await; + Ok(serde_json::json!({"local": local, "status": snapshot})) + }) + .await + } + + pub async fn perform_permission_setting( + this: Instance, + subject: String, + action: String, + grant: String, + ) -> Result<(), String> { + let (owner, source) = this.with(|host| (host.owner.clone(), host.client.clone())); + drop(this); + execute(owner.clone(), async move { + let ApplicationClient::Ui(services) = &source else { + return Err("System permission actions require the Settings page".into()); + }; + services.require_settings_page()?; + if action == "restart" { + if subject != "desktop" + || !matches!(grant.as_str(), "accessibility" | "screen_recording") + { + return Err("Invalid restart target".into()); + } + let handler = owner + .restart + .get() + .ok_or("This launcher cannot restart Maka")?; + let (send, recv) = tokio::sync::oneshot::channel(); + handler(send); + return recv.await.map_err(|_| "Restart cancelled")?; + } + if action == "end" { + if let Some(g) = owner + .guide + .lock() + .unwrap() + .as_ref() + .filter(|g| g.matches(&subject, &grant)) + { + g.close(); + } + return Ok(()); + } + let guiding = matches!(grant.as_str(), "accessibility" | "screen_recording") + && matches!(action.as_str(), "open" | "request"); + let guide = if action == "guide" { + let lease = owner.guide.lock().unwrap().clone(); + let Some(lease) = lease.filter(|g| g.matches(&subject, &grant) && g.active()) + else { + return Ok(()); + }; + Some(lease) + } else if guiding { + Some(PermissionGuide::begin( + &owner.guide, + &subject, + &grant, + services.guide_scope()?, + )) + } else { + None + }; + if guide.is_none() && action != "reveal" { + if let Some(old) = owner.guide.lock().unwrap().take() { + old.close(); + } + } + let action = if action == "guide" { "open" } else { &action }; + let application = if subject == "desktop" { + permission_settings::desktop_action(action, &grant).await?; + permission_settings::desktop_app() + } else { + if subject != "host" { + return Err("Unknown permission subject".into()); + } + let client = source.resolve(&owner).await?; + let snapshot = permission_settings::host(&client, Some(&grant)).await?; + if !permission_settings::local(&client, &owner.client, &snapshot).await { + return Err("Computer permission actions require the local Host".into()); + } + let application = ( + snapshot.application.clone(), + snapshot.bundle_path.as_ref().map(std::path::PathBuf::from), + ); + permission_settings::host_action(&client, snapshot, action, &grant).await?; + application + }; + if let Some(guide) = guide + && action == "open" + { + permission_window::show_guide(&owner, source, guide, application.0, application.1) + .await?; + } + Ok(()) + }) + .await + } + + pub async fn observe_permission_setting( + this: Instance, + subject: String, + grant: String, + ) -> Result { + let (owner, source) = this.with(|host| (host.owner.clone(), host.client.clone())); + drop(this); + execute(owner.clone(), async move { + if let ApplicationClient::Ui(services) = &source { + services.require_settings_page()?; + } else { + return Err("Requires Settings".into()); + } + let guide = owner.guide.lock().unwrap().clone(); + let Some(guide) = guide.filter(|g| g.active() && g.matches(&subject, &grant)) else { + return Ok(JsonValue::Null); + }; + let (effective, pending_host) = if subject == "desktop" { + ( + tokio::task::spawn_blocking(move || permission_settings::desktop_grant(&grant)) + .await + .map_err(|e| e.to_string())??, + false, + ) + } else { + let client = source.resolve(&owner).await?; + let snapshot = permission_settings::host(&client, Some(&grant)).await?; + if !permission_settings::local(&client, &owner.client, &snapshot).await { + guide.close(); + return Ok(JsonValue::Null); + } + let item = snapshot + .grants + .first() + .ok_or("Unsupported Host permission")?; + (item.effective, item.pending_host) + }; + if !guide.active() { + return Ok(JsonValue::Null); + } + Ok(serde_json::json!({"effective":effective,"pendingHost":pending_host})) + }) + .await + } + /// Whether this shell presents system permissions in a dedicated window. #[getter] pub fn system_permission_window(&self) -> bool { diff --git a/products/maka/workbench/src/bindings/dictation.m b/products/maka/workbench/src/bindings/dictation.m index 8990959424a..00f588037ae 100644 --- a/products/maka/workbench/src/bindings/dictation.m +++ b/products/maka/workbench/src/bindings/dictation.m @@ -17,6 +17,7 @@ * under the License. */ +#import #import #import #import @@ -295,3 +296,28 @@ void maka_record_message(const char *path, const char *uid, bool modelConnection done(context, NULL, "dictation.error.model_connection_required"); }); } + +int maka_microphone_status(void) { + return (int)[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]; +} + +// Called from a blocking worker. Wait for the decision before refreshing the UI. +bool maka_request_microphone(void) { + if (![NSBundle.mainBundle objectForInfoDictionaryKey:@"NSMicrophoneUsageDescription"]) + return false; + if (maka_microphone_status() != AVAuthorizationStatusNotDetermined) + return true; + dispatch_semaphore_t done = dispatch_semaphore_create(0); + [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL allowed) { + (void)allowed; + dispatch_semaphore_signal(done); + }]; + dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER); + return true; +} + +void maka_request_accessibility(void) { + AXIsProcessTrustedWithOptions((__bridge CFDictionaryRef)@{ + (__bridge NSString *)kAXTrustedCheckOptionPrompt: @YES + }); +} diff --git a/products/maka/workbench/src/bindings/permission_settings.rs b/products/maka/workbench/src/bindings/permission_settings.rs new file mode 100644 index 00000000000..5b745a1abb1 --- /dev/null +++ b/products/maka/workbench/src/bindings/permission_settings.rs @@ -0,0 +1,282 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +use maka_agent_api::contract::HostPermissions; +use maka_app_client::Client; +use serde_json::{Value, json}; +use std::path::PathBuf; + +pub(super) async fn host(client: &Client, grant: Option<&str>) -> Result { + super::require_contract( + super::AGENT, + "hostPermissions", + &client.describe(super::AGENT).await?.contract, + )?; + serde_json::from_value( + client + .query(super::AGENT, "hostPermissions", json!({"grant":grant})) + .await?, + ) + .map_err(|error| error.to_string()) +} + +pub(super) async fn local(client: &Client, root: &Client, snapshot: &HostPermissions) -> bool { + local_subject( + &snapshot.state_domain, + &client.source().state_domain, + &root.source().state_domain, + client.is_local_owner().await, + ) +} +fn local_subject(subject: &str, source: &str, root: &str, owner: bool) -> bool { + owner && subject == source && source == root +} + +#[cfg(target_os = "macos")] +unsafe extern "C" { + fn maka_microphone_status() -> i32; + fn maka_request_microphone() -> bool; + fn maka_request_accessibility(); + fn AXIsProcessTrusted() -> bool; + fn CGPreflightScreenCaptureAccess() -> bool; + fn CGRequestScreenCaptureAccess() -> bool; +} + +#[cfg(any(target_os = "macos", test))] +fn microphone_state(status: i32) -> &'static str { + match status { + 0 => "notDetermined", + 1 => "restricted", + 2 => "denied", + 3 => "granted", + _ => "unknown", + } +} + +#[cfg(target_os = "macos")] +pub(super) fn desktop_app() -> (String, Option) { + let app = objc2_app_kit::NSRunningApplication::currentApplication(); + let path = app + .bundleURL() + .and_then(|url| url.path()) + .map(|p| PathBuf::from(p.to_string())) + .filter(|p| p.extension().is_some_and(|ext| ext == "app")); + ( + app.localizedName() + .map(|n| n.to_string()) + .unwrap_or_else(|| "Maka".into()), + path, + ) +} + +#[cfg(not(target_os = "macos"))] +pub(super) fn desktop_app() -> (String, Option) { + (String::new(), None) +} + +pub(super) fn desktop_grant(grant: &str) -> Result { + #[cfg(target_os = "macos")] + // SAFETY: preflight only; these functions have no arguments. + unsafe { + match grant { + "accessibility" => Ok(AXIsProcessTrusted()), + "screen_recording" => Ok(CGPreflightScreenCaptureAccess()), + _ => Err("Unsupported permission".into()), + } + } + #[cfg(not(target_os = "macos"))] + { + let _ = grant; + Err("Requires macOS".into()) + } +} + +pub(super) fn desktop() -> Result { + #[cfg(target_os = "macos")] + { + let (application, path) = desktop_app(); + // SAFETY: these argument-free preflight calls only observe the calling process. + let (mic, screen, ax) = unsafe { + ( + maka_microphone_status(), + CGPreflightScreenCaptureAccess(), + AXIsProcessTrusted(), + ) + }; + Ok( + json!({"supported":true,"application":application,"canReveal":path.is_some(), + "microphone": microphone_state(mic), "screen_recording": screen, "accessibility": ax}), + ) + } + #[cfg(not(target_os = "macos"))] + Ok(json!({"supported":false})) +} + +pub(super) fn panel_url(grant: &str) -> Result { + let pane = match grant { + "microphone" => "Privacy_Microphone", + "accessibility" => "Privacy_Accessibility", + "screen_recording" => "Privacy_ScreenCapture", + "files" => "Privacy_FilesAndFolders", + "disk" => "Privacy_AllFiles", + _ => return Err("Unknown privacy panel".into()), + }; + Ok(format!( + "x-apple.systempreferences:com.apple.preference.security?{pane}" + )) +} + +async fn open(grant: &str) -> Result<(), String> { + launch(vec![panel_url(grant)?]).await +} + +async fn reveal(path: Option) -> Result<(), String> { + let path = path.ok_or("Application bundle unavailable")?; + launch(vec![ + "-R".into(), + path.into_os_string() + .into_string() + .map_err(|_| "Invalid application path")?, + ]) + .await +} + +async fn launch(args: Vec) -> Result<(), String> { + let status = tokio::process::Command::new("/usr/bin/open") + .args(args) + .status() + .await + .map_err(|e| e.to_string())?; + if status.success() { + Ok(()) + } else { + Err(format!("open: {status}")) + } +} + +pub(super) async fn desktop_action(action: &str, grant: &str) -> Result<(), String> { + #[cfg(not(target_os = "macos"))] + { + let _ = (action, grant); + Err("Requires macOS".into()) + } + #[cfg(target_os = "macos")] + match action { + "open" => open(grant).await, + "reveal" => reveal(desktop_app().1).await, + "request" => { + let grant = grant.to_owned(); + // SAFETY: these APIs take no borrowed arguments. Authorization is requested only on explicit action. + tokio::task::spawn_blocking(move || unsafe { + match grant.as_str() { + "microphone" if !maka_request_microphone() => { + Err("Missing microphone usage description".into()) + } + "microphone" => Ok(()), + "screen_recording" => { + CGRequestScreenCaptureAccess(); + Ok(()) + } + "accessibility" => { + maka_request_accessibility(); + Ok(()) + } + _ => Err("Unknown desktop grant".into()), + } + }) + .await + .map_err(|e| e.to_string())? + } + _ => Err("Unknown permission action".into()), + } +} + +pub(super) async fn host_action( + client: &Client, + snapshot: HostPermissions, + action: &str, + grant: &str, +) -> Result<(), String> { + use maka_host_runtime::application::host::protocol::{Request, Response}; + if !cfg!(target_os = "macos") { + return Err("Requires macOS".into()); + } + if !matches!(grant, "accessibility" | "screen_recording") { + return Err("Unknown Host grant".into()); + } + match action { + "open" => open(grant).await, + "reveal" => reveal(snapshot.bundle_path.map(PathBuf::from)).await, + "request" => { + let grant = serde_json::from_value(json!(grant)).map_err(|e| e.to_string())?; + match client + .local_owner_control(Request::RequestComputerPermission { grant }) + .await? + { + Response::ComputerPermissionRequested(result) => result, + _ => Err("Unexpected Host permission response".into()), + } + } + _ => Err("Unknown permission action".into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn guide_requires_local_transport_and_the_admitted_state_domain() { + assert!(local_subject("a", "a", "a", true)); + assert!(!local_subject("a", "a", "a", false)); + assert!(!local_subject("b", "b", "a", true)); + assert!(!local_subject("a", "b", "a", true)); + } + #[test] + fn microphone_preserves_decisions() { + assert_eq!( + [0, 1, 2, 3, 99].map(microphone_state), + [ + "notDetermined", + "restricted", + "denied", + "granted", + "unknown" + ] + ); + } + #[test] + fn file_panels_are_fixed() { + assert_eq!( + panel_url("files").unwrap(), + "x-apple.systempreferences:com.apple.preference.security?Privacy_FilesAndFolders" + ); + assert_eq!( + panel_url("disk").unwrap(), + "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles" + ); + assert!(panel_url("file:///tmp").is_err()); + } + #[cfg(not(target_os = "macos"))] + #[test] + fn unsupported_desktop() { + assert_eq!(desktop().unwrap(), json!({"supported":false})); + assert!(desktop_grant("accessibility").is_err()); + assert!(desktop_app().1.is_none()); + } +} diff --git a/products/maka/workbench/src/bindings/permission_window.rs b/products/maka/workbench/src/bindings/permission_window.rs index 3e09cf448b0..4163abf4c7a 100644 --- a/products/maka/workbench/src/bindings/permission_window.rs +++ b/products/maka/workbench/src/bindings/permission_window.rs @@ -27,6 +27,7 @@ pub struct SystemPermissionWindow { key: String, config: EngineConfig, application: Option, + pub guide: Option, } impl SystemPermissionWindow { @@ -98,6 +99,29 @@ pub(super) async fn open( )) .map_err(|error| error.to_string())?; let source = ApplicationClient::Permission(client); + let config = configuration( + &owner, + source, + "systemPermission", + serde_json::json!({"sessionId":session_id,"requestId":request_id,"request":record.request}), + ) + .await?; + sender + .send(SystemPermissionWindow { + key, + config, + application, + guide: None, + }) + .map_err(|_| "The system-permission window is unavailable".to_owned()) +} + +async fn configuration( + owner: &Arc, + source: ApplicationClient, + parameter: &str, + value: JsonValue, +) -> Result { let preferences = owner .client .query("settings", "assistantPreferences", serde_json::json!({})) @@ -126,21 +150,121 @@ pub(super) async fn open( let mut config = crate::configuration(registry, owner.runtime.clone()); config.app = crate::system_permission_bundle().into(); config.assets = Some(Arc::new(assets::HostAssets(owner.clone()))); - config.host.set_params(serde_json::Map::from_iter([ - ( - "systemPermission".into(), - serde_json::json!({"sessionId": session_id, "requestId": request_id, "request": record.request}), - ), - ( - "languagePreference".into(), - serde_json::json!({"preference": language, "revision": revision, "resolvedLanguage": resolved_language}), - ), - ])); - sender - .send(SystemPermissionWindow { - key, - config, - application, - }) - .map_err(|_| "The system-permission window is unavailable".to_owned()) + let mut params = serde_json::Map::new(); + params.insert("languagePreference".into(), serde_json::json!({"preference": language, "revision":revision,"resolvedLanguage":resolved_language})); + params.insert(parameter.into(), value); + config.host.set_params(params); + Ok(config) +} + +/// A settings guide is scoped to one observation on the admitted connection. +#[derive(Clone)] +pub struct PermissionGuide { + pub id: Uuid, + subject: String, + grant: String, + live: tokio::sync::watch::Sender, + valid: Arc bool + Send + Sync>, +} + +impl PermissionGuide { + pub fn active(&self) -> bool { + if !(self.valid)() { + self.close(); + } + *self.live.borrow() + } + pub fn close(&self) { + self.live.send_replace(false); + } + pub async fn closed(&self) { + let _ = self.live.subscribe().wait_for(|live| !*live).await; + } + pub(super) fn matches(&self, subject: &str, grant: &str) -> bool { + self.subject == subject && self.grant == grant + } + pub(super) fn begin( + slot: &StdMutex>, + subject: &str, + grant: &str, + valid: Arc bool + Send + Sync>, + ) -> Self { + let guide = Self { + valid, + id: Uuid::new_v4(), + subject: subject.into(), + grant: grant.into(), + live: tokio::sync::watch::channel(true).0, + }; + if let Some(old) = slot.lock().unwrap().replace(guide.clone()) { + old.close(); + } + guide + } +} + +pub(super) async fn show_guide( + owner: &Arc, + source: ApplicationClient, + guide: PermissionGuide, + name: String, + application: Option, +) -> Result<(), String> { + let sender = owner.permission_windows.lock().unwrap().clone(); + let sender = sender.ok_or("Desktop permission guide window is unavailable")?; + let application = application + .filter(|p| p.is_absolute() && p.extension().is_some_and(|ext| ext == "app") && p.is_dir()); + let config = configuration( + owner, + source, + "settingsGuide", + serde_json::json!({"application":name,"grant":guide.grant}), + ) + .await?; + if let Some(path) = application.clone() { + let alive = guide.clone(); + config.host.handle("permissionGuide.reveal", move |call| { + if !alive.active() { + call.reject("Permission guide expired"); + return; + } + match std::process::Command::new("/usr/bin/open") + .arg("-R") + .arg(&path) + .status() + { + Ok(status) if status.success() => call.resolve(JsonValue::Null), + _ => call.reject("Finder could not reveal the application"), + } + }); + } + if guide.active() { + sender + .send(SystemPermissionWindow { + key: guide.id.to_string(), + config, + application, + guide: Some(guide), + }) + .map_err(|_| "Permission guide unavailable")?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn replacement_and_disconnect_invalidate_previous_drag_source() { + let slot = StdMutex::default(); + let first = PermissionGuide::begin(&slot, "host", "screen_recording", Arc::new(|| true)); + let second = PermissionGuide::begin(&slot, "desktop", "accessibility", Arc::new(|| true)); + first.closed().await; + assert!(!first.active()); + assert!(second.active()); + assert!(!second.matches("host", "accessibility")); + slot.lock().unwrap().take().unwrap().close(); + second.closed().await; + assert!(!second.active()); + } } diff --git a/products/maka/workbench/src/bindings/system_permission.rs b/products/maka/workbench/src/bindings/system_permission.rs index 531c3364117..e9f90f7f5d6 100644 --- a/products/maka/workbench/src/bindings/system_permission.rs +++ b/products/maka/workbench/src/bindings/system_permission.rs @@ -82,15 +82,8 @@ fn command( } let mut command = tokio::process::Command::new("/usr/bin/open"); match action { - "accessibility" => { - command.arg( - "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility", - ); - } - "screen_recording" => { - command.arg( - "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture", - ); + "accessibility" | "screen_recording" => { + command.arg(super::permission_settings::panel_url(action)?); } "reveal_application" => { let InteractionRequest::SystemPermission { diff --git a/products/maka/workbench/src/bindings/ui_services.rs b/products/maka/workbench/src/bindings/ui_services.rs index ed10759d1ff..e1b45c760d8 100644 --- a/products/maka/workbench/src/bindings/ui_services.rs +++ b/products/maka/workbench/src/bindings/ui_services.rs @@ -123,6 +123,29 @@ impl Services { super::assets::scoped_uri(&self.instance, &self.definition_basis, uri) } + pub(super) fn require_settings_page(&self) -> Result<(), String> { + let (_, instance) = self.current_source()?; + if instance.package.id != "maka.agent.settings" { + return Err("System permission actions require the Settings page".into()); + } + Ok(()) + } + + pub(super) fn guide_scope( + self: &Arc, + ) -> Result bool + Send + Sync>, String> { + let (source, instance) = self.current_source()?; + let basis = instance.binding_basis.clone(); + let weak = Arc::downgrade(self); + Ok(Arc::new(move || { + weak.upgrade().is_some_and(|services| { + services.current_source().is_ok_and(|(current, metadata)| { + current == source && metadata.binding_basis == basis + }) + }) + })) + } + fn ensure_open(&self) -> Result<(), String> { if self.closed.load(Ordering::Acquire) { return Err("UI service scope is closed".into()); @@ -269,6 +292,9 @@ impl Services { pub(super) async fn close(&self) -> Result<(), String> { self.closed.store(true, Ordering::Release); + if let Some(guide) = self.owner.guide.lock().unwrap().as_ref() { + guide.active(); + } self.cleanup .get_or_init(|| async { let client = self diff --git a/products/maka/workbench/src/lib.rs b/products/maka/workbench/src/lib.rs index 03af98e58d9..3260b64d3d7 100644 --- a/products/maka/workbench/src/lib.rs +++ b/products/maka/workbench/src/lib.rs @@ -73,6 +73,7 @@ fn system_permission_bundle() -> Bundle { let mut capabilities = Capabilities::all(); capabilities.host = vec![ "computerPermissions.close".into(), + "permissionGuide.reveal".into(), "appearance.textSize".into(), ]; Bundle::source(bundle_source(include_bytes!(concat!( @@ -121,6 +122,13 @@ mod tests { } } + #[test] + fn permission_guide_may_reveal_its_application() { + let access = super::system_permission_bundle().policy.access(); + assert!(nsh_core::host_channel::check_call(&access, "permissionGuide.reveal").is_ok()); + assert!(nsh_core::host_channel::check_call(&access, "workspace.chooseFolder").is_err()); + } + fn fixture(entry: &str) -> nsh_testing::Headless { headless_fixture( &format!("tests/fixtures/{entry}"), @@ -508,6 +516,91 @@ mod tests { ) } + #[test] + fn permission_settings_hide_file_access_for_unsupported_desktops() { + let mut app = headless_fixture( + "tests/fixtures/permission-settings-unsupported.tsx", + Size::new(px(760.0), px(1200.0)), + false, + ); + app.wait_for("text:Remote Host").unwrap(); + app.wait_for("text:Allowed").unwrap(); + for selector in [ + "text:File access", + "role:button[Open Files and folders settings…]", + "role:button[Open Full disk access settings…]", + ] { + assert_eq!(app.screen().count(selector).unwrap(), 0, "{selector}"); + } + } + + #[test] + fn permission_settings_show_only_local_actions_for_a_remote_host() { + let mut app = headless_fixture( + "tests/fixtures/permission-settings.tsx", + Size::new(px(760.0), px(1200.0)), + false, + ); + app.wait_for("text:Connected to a remote device.").unwrap(); + app.wait_for("text:Maka Dev").unwrap(); + assert_eq!( + app.screen().count("role:button[Show in Finder]").unwrap(), + 1 + ); + app.wait_for("role:button[Allow · Microphone]").unwrap(); + app.wait_for("text:Remote Host").unwrap(); + app.wait_for("text:Allowed").unwrap(); + let screen = app.screen(); + let bounds = |selector| screen.layout(selector).unwrap().unwrap().bounds; + let allow = bounds("role:button[Allow · Microphone]"); + let allowed = bounds("text:Allowed"); + let microphone_settings = bounds("role:button[Open Microphone settings…]"); + let accessibility_settings = bounds("role:button[Open Accessibility settings…]"); + assert!((allow.right().0 - allowed.right().0).abs() <= 1.0); + assert!((allow.center().y.0 - microphone_settings.center().y.0).abs() <= 1.0); + assert!((allowed.center().y.0 - accessibility_settings.center().y.0).abs() <= 1.0); + assert!((0.0..=8.0).contains(&(microphone_settings.origin.x.0 - allow.right().0))); + assert_eq!( + microphone_settings.origin.x, + accessibility_settings.origin.x + ); + + assert_eq!(app.screen().count("text:Not enabled yet").unwrap(), 1); + app.wait_for("text:Permission granted. It hasn’t taken effect in Remote Host yet.") + .unwrap(); + app.wait_for("role:button[Check again]").unwrap(); + assert_eq!( + app.screen().count("text:Check in System Settings").unwrap(), + 0 + ); + assert_eq!( + app.screen() + .count("role:button[Open Accessibility settings…]") + .unwrap(), + 1 + ); + app.press("role:button[Allow · Microphone]").unwrap(); + app.wait_for("text:Denied").unwrap(); + assert_eq!( + app.screen() + .count("role:button[Allow · Microphone]") + .unwrap(), + 0 + ); + app.press("role:button[Open Screen & System Audio Recording settings…]") + .unwrap(); + app.wait_for("role:button[Restart Maka]").unwrap(); + app.press("role:button[Restart Maka]").unwrap(); + app.wait_for( + "text:Maka could not restart. Finish any pending quit or update, then try again.", + ) + .unwrap(); + app.press("role:button[Open Full disk access settings…]") + .unwrap(); + app.wait_for("text:Open System Settings → Privacy & Security → Full disk access.") + .unwrap(); + } + #[test] fn stopping_an_agent_terminal_requires_confirmation() { let mut app = fixture("terminal-sidebar.tsx"); diff --git a/products/maka/workbench/tests/fixtures/permission-settings-unsupported.tsx b/products/maka/workbench/tests/fixtures/permission-settings-unsupported.tsx new file mode 100644 index 00000000000..a999d3b7fc1 --- /dev/null +++ b/products/maka/workbench/tests/fixtures/permission-settings-unsupported.tsx @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { cleanup, mount } from 'nsh'; +import { installWorkbenchLocaleCatalog } from '../../app/localeCatalog'; +import { createPermissionSettings } from '../../app/permissionSettingsState'; +import { SystemPermissionSettings } from '../../app/SystemPermissionSettings'; + +mount(() => { + installWorkbenchLocaleCatalog(); + const owner = createPermissionSettings({ + desktopPermissionSettings: async () => ({ supported: false }), + hostPermissionSettings: async () => ({ + local: false, + status: { + supported: true, + application: 'Remote Host', + bundlePath: null, + stateDomain: 'remote', + grants: [{ grant: 'accessibility', effective: true }], + }, + }), + observePermissionSetting: async () => null, + performPermissionSetting: async () => { + throw Error('unexpected permission action'); + }, + }); + owner.activate(); + cleanup(owner.deactivate); + return ; +}); diff --git a/products/maka/workbench/tests/fixtures/permission-settings.tsx b/products/maka/workbench/tests/fixtures/permission-settings.tsx new file mode 100644 index 00000000000..dde91628012 --- /dev/null +++ b/products/maka/workbench/tests/fixtures/permission-settings.tsx @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { cleanup, mount } from 'nsh'; +import { installWorkbenchLocaleCatalog } from '../../app/localeCatalog'; +import { createPermissionSettings } from '../../app/permissionSettingsState'; +import { SystemPermissionSettings } from '../../app/SystemPermissionSettings'; + +mount(() => { + installWorkbenchLocaleCatalog(); + let microphone: 'notDetermined' | 'denied' = 'notDetermined'; + const owner = createPermissionSettings({ + observePermissionSetting: async () => ({ effective: false, pendingHost: false }), + desktopPermissionSettings: async () => ({ + supported: true, + application: 'Maka Dev', + canReveal: true, + canRestart: true, + microphone, + screen_recording: false, + accessibility: true, + }), + hostPermissionSettings: async () => ({ + local: false, + status: { + supported: true, + application: 'Remote Host', + bundlePath: '/Remote.app', + stateDomain: 'remote', + grants: [ + { grant: 'accessibility', effective: false }, + { grant: 'screen_recording', effective: false, pendingHost: true }, + ], + }, + }), + performPermissionSetting: async (_subject, action, grant) => { + if (action === 'request' && grant === 'microphone') { + microphone = 'denied'; + return; + } + if (action === 'open' && grant === 'screen_recording') return; + throw Error('fixture: unavailable'); + }, + }); + owner.activate(); + cleanup(owner.deactivate); + return ; +}); diff --git a/products/maka/workbench/tests/permission-settings.test.mjs b/products/maka/workbench/tests/permission-settings.test.mjs new file mode 100644 index 00000000000..3e51e7292f6 --- /dev/null +++ b/products/maka/workbench/tests/permission-settings.test.mjs @@ -0,0 +1,240 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import assert from 'node:assert/strict'; +import { registerHooks } from 'node:module'; +import test from 'node:test'; + +const modules = { + nsh: 'export function signal(v){return Object.assign(()=>v,{set(n){v=n;}})}', + './locale': 'export const tr=(key,args)=>args?key.replace("{permission}",args.permission):key', +}; +const hook = registerHooks({ + resolve(specifier, context, next) { + return Object.hasOwn(modules, specifier) + ? { + url: 'data:text/javascript,' + encodeURIComponent(modules[specifier]), + shortCircuit: true, + } + : next(specifier, context); + }, +}); +const { createPermissionSettings, statusLabel } = await import('../app/permissionSettingsState.ts'); +hook.deregister(); +const flush = () => new Promise((resolve) => setImmediate(resolve)); + +function setup(local = true) { + const calls = []; + const client = { + desktopPermissionSettings: async () => { + calls.push('desktop'); + return { supported: true, microphone: 'denied', accessibility: false }; + }, + hostPermissionSettings: async () => { + calls.push('host'); + return { local, status: { supported: true, grants: [] } }; + }, + performPermissionSetting: async (...args) => { + calls.push(args); + }, + }; + return { owner: createPermissionSettings(client), calls, client }; +} +test('opening and foreground refresh only read status, including after a request', async () => { + const { owner, calls } = setup(); + owner.activate(); + await flush(); + await owner.refresh(); + assert.deepEqual(calls, ['desktop', 'host', 'desktop', 'host']); + await owner.act('desktop', 'request', 'accessibility'); + assert.equal(owner.desktop().accessibility, false); + assert.deepEqual(calls.slice(-3), [['desktop', 'request', 'accessibility'], 'desktop', 'host']); + await owner.act('desktop', 'open', 'microphone'); + assert.equal(owner.desktop().microphone, 'denied'); + assert.deepEqual(calls.slice(-3), [['desktop', 'open', 'microphone'], 'desktop', 'host']); + owner.deactivate(); + await owner.refresh(); + assert.equal(owner.desktop(), null); +}); +test('remote Host offers no local actions', async () => { + const { owner, calls } = setup(false); + owner.activate(); + await flush(); + for (const action of ['open', 'reveal', 'request']) + await owner.act('host', action, 'accessibility'); + assert.deepEqual(calls, ['desktop', 'host']); +}); +test('file rows are settings-only and failed links name the manual path', async () => { + assert.deepEqual( + ['unknown', 'denied', 'granted', 'restricted', 'notDetermined', true, false].map(statusLabel), + [ + 'Unknown', + 'Denied', + 'Allowed', + 'Restricted', + 'Not requested', + 'Allowed', + 'permissionSetup.notEnabled', + ], + ); + const { owner, client } = setup(); + client.performPermissionSetting = async () => { + throw Error('open failed'); + }; + owner.activate(); + await flush(); + await owner.act('desktop', 'open', 'disk'); + assert.match(owner.actionError(), /Privacy & Security → Full disk access/); +}); +test('late observations cannot restore an old Host after leaving', async () => { + const { owner, client } = setup(); + let resolve; + client.hostPermissionSettings = () => + new Promise((done) => { + resolve = done; + }); + owner.activate(); + owner.deactivate(); + resolve({ local: true }); + await flush(); + assert.equal(owner.host(), null); +}); + +test('only the selected grant is polled until effective or dismissed', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const { owner, calls, client } = setup(); + let result = { effective: false, pendingHost: false }; + client.observePermissionSetting = async (subject, grant) => { + calls.push(['observe', subject, grant]); + return result; + }; + client.desktopPermissionSettings = async () => ({ + supported: true, + accessibility: false, + canRestart: true, + }); + owner.activate(); + await flush(); + t.mock.timers.tick(2500); + assert.equal(owner.restartHint(), null); + await owner.act('desktop', 'open', 'accessibility'); + calls.length = 0; + t.mock.timers.tick(1250); + await flush(); + assert.deepEqual(calls, [['observe', 'desktop', 'accessibility']]); + assert.equal(owner.restartHint(), 'accessibility'); + await owner.act('desktop', 'restart', 'accessibility'); + assert.ok(calls.some((c) => Array.isArray(c) && c[1] === 'restart')); + result = { effective: true, pendingHost: false }; + t.mock.timers.tick(1250); + await flush(); + assert.equal(owner.restartHint(), null); + calls.length = 0; + t.mock.timers.tick(5000); + assert.deepEqual(calls, []); + await owner.act('desktop', 'open', 'screen_recording'); + owner.deactivate(); + calls.length = 0; + t.mock.timers.tick(5000); + await flush(); + assert.deepEqual(calls, []); +}); + +test('microphone and remote settings never start a local guide or offer a restart', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const { owner, client, calls } = setup(false); + client.observePermissionSetting = async () => assert.fail('unexpected preflight'); + owner.activate(); + await flush(); + await owner.act('desktop', 'open', 'microphone'); + calls.length = 0; + await owner.act('host', 'open', 'screen_recording'); + await owner.act('host', 'restart', 'screen_recording'); + await owner.act('desktop', 'restart', 'microphone'); + t.mock.timers.tick(5000); + await flush(); + assert.deepEqual(calls, []); + assert.equal(owner.restartHint(), null); + owner.deactivate(); +}); + +test('an already granted Settings guide survives foreground refresh and observation', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const { owner, client, calls } = setup(); + client.desktopPermissionSettings = async () => ({ supported: true, accessibility: true }); + client.observePermissionSetting = async () => ({ effective: true, pendingHost: false }); + owner.activate(); + await flush(); + await owner.act('desktop', 'open', 'accessibility'); + await owner.refresh(); + t.mock.timers.tick(1250); + await flush(); + assert.deepEqual(calls.filter(Array.isArray), [['desktop', 'open', 'accessibility']]); + owner.deactivate(); +}); +test('a still ineffective request opens settings once using the current lease', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const { owner, client, calls } = setup(); + client.observePermissionSetting = async () => ({ effective: false, pendingHost: false }); + owner.activate(); + await flush(); + await owner.act('desktop', 'request', 'accessibility'); + t.mock.timers.tick(1750); + await flush(); + t.mock.timers.tick(1250); + await flush(); + assert.deepEqual(calls.filter(Array.isArray), [ + ['desktop', 'request', 'accessibility'], + ['desktop', 'guide', 'accessibility'], + ]); + owner.deactivate(); +}); + +test('Host pending propagation keeps the guide until the resident Host observes the grant', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const { owner, client, calls } = setup(); + let effective = false; + client.hostPermissionSettings = async () => ({ + local: true, + status: { grants: [{ grant: 'accessibility', effective }] }, + }); + client.observePermissionSetting = async () => ({ effective, pendingHost: !effective }); + owner.activate(); + await flush(); + await owner.act('host', 'open', 'accessibility'); + t.mock.timers.tick(1250); + await flush(); + assert.deepEqual(calls.filter(Array.isArray), [['host', 'open', 'accessibility']]); + effective = true; + t.mock.timers.tick(1250); + await flush(); + assert.deepEqual(calls.at(-1), ['host', 'end', 'accessibility']); + owner.deactivate(); +}); + +test('unsupported desktops never open macOS file permission settings', async () => { + const { owner, client, calls } = setup(); + client.desktopPermissionSettings = async () => ({ supported: false }); + owner.activate(); + await flush(); + await owner.act('desktop', 'open', 'files'); + await owner.act('desktop', 'open', 'disk'); + assert.deepEqual(calls.filter(Array.isArray), []); + owner.deactivate(); +}); diff --git a/scripts/rust/build-cli.mjs b/scripts/rust/build-cli.mjs index 0a917120032..01d2936836d 100644 --- a/scripts/rust/build-cli.mjs +++ b/scripts/rust/build-cli.mjs @@ -155,6 +155,8 @@ export async function compileCli({ repositoryRoot, join(directory, 'maka-desktop-shell'), join(directory, 'Maka.app'), + [], + { development: !isRelease }, ); } return { @@ -220,8 +222,13 @@ export async function stageDesktopBundle( shell, destination, resources = [], - { executables = [], version: versionOverride } = {}, + { executables = [], version: versionOverride, development = false } = {}, ) { + // TCC keys the grant by bundle ID and verifies its stored code requirement. + // An ad-hoc dev build cannot satisfy the installed release's requirement. + const app = development + ? { ...desktopApp, id: 'org.apache.maka.desktop.dev', name: 'Maka Preview' } + : desktopApp; const version = versionOverride ?? workspaceVersion(await readFile(join(repositoryRoot, 'Cargo.toml'), 'utf8')); const localizations = await readBundleLocalizations(repositoryRoot); @@ -236,10 +243,7 @@ export async function stageDesktopBundle( const contents = join(stage, 'Contents'); await mkdir(join(contents, 'Resources'), { recursive: true }); await writeFile(join(contents, 'Resources', 'Maka.icns'), icon); - await writeFile( - join(contents, 'Info.plist'), - infoPlist({ ...desktopApp, version, localizations }), - ); + await writeFile(join(contents, 'Info.plist'), infoPlist({ ...app, version, localizations })); await mkdir(join(contents, 'MacOS')); const executable = join(contents, 'MacOS', 'maka-desktop-shell'); for (const resource of resources) { @@ -254,13 +258,13 @@ export async function stageDesktopBundle( const target = join(contents, 'MacOS', basename(extra)); await copyFile(extra, target, constants.COPYFILE_FICLONE); await chmod(target, 0o755); - signMachO(target, `${desktopApp.id}.${basename(extra)}`, { + signMachO(target, `${app.id}.${basename(extra)}`, { entitlements: basename(extra) === 'maka' ? entitlements : undefined, }); } await stageHostBundle(join(dirname(shell), 'maka-host-shell'), contents, localizations); await chmod(stage, 0o755); - signBundle(stage, desktopApp.id, { entitlements }); + signBundle(stage, app.id, { entitlements }); } finally { await rm(entitlements, { force: true }); } diff --git a/scripts/rust/build-cli.test.mjs b/scripts/rust/build-cli.test.mjs index 060f700ad3c..c010e9011d6 100644 --- a/scripts/rust/build-cli.test.mjs +++ b/scripts/rust/build-cli.test.mjs @@ -272,6 +272,10 @@ test('CLI builds use the requested target and artifact path', async (t) => { ).binary, executable, ); + if (process.platform === 'darwin') { + const plist = await readFile(join(development, 'Maka.app/Contents/Info.plist'), 'utf8'); + assert.match(plist, /org\.apache\.maka\.desktop\.dev<\/string>/u); + } assert.deepEqual(invocation.args, [ 'build', '--locked', @@ -425,6 +429,20 @@ test('the Host app has a valid stable bundle signature', { }; await stageDesktopBundle(root, shell, destination); const first = identity(); + const plist = join(destination, 'Contents', 'Info.plist'); + assert.match(await readFile(plist, 'utf8'), /org\.apache\.maka\.desktop<\/string>/u); + await stageDesktopBundle(root, shell, destination, [], { development: true }); + assert.match(await readFile(plist, 'utf8'), /Maka Preview<\/string>/u); + assert.equal( + childProcess.spawnSync('/usr/bin/codesign', [ + '--verify', + '--strict', + '-R=identifier "org.apache.maka.desktop.dev"', + destination, + ]).status, + 0, + ); + assert.equal(identity(), first); await writeFile(join(root, 'Cargo.toml'), manifest.replace('1.2.3-beta.1', '1.2.4')); await stageDesktopBundle(root, shell, destination); assert.equal( diff --git a/third-party/nsh/crates/nsh-platform-macos/src/app.rs b/third-party/nsh/crates/nsh-platform-macos/src/app.rs index 1ba84dcf744..ebf71d20059 100644 --- a/third-party/nsh/crates/nsh-platform-macos/src/app.rs +++ b/third-party/nsh/crates/nsh-platform-macos/src/app.rs @@ -1168,6 +1168,29 @@ pub fn quit_app() { }); } +fn relaunch_allowed(asks_quit: bool, pending: Option) -> bool { + !asks_quit && pending.is_none() +} + +/// Attempt a synchronous, ordinary quit for an embedding launcher that will relaunch +/// only after a clean exit. If an application owns asynchronous quit confirmation, +/// leave it running: that owner must coordinate the relaunch itself. +pub fn try_quit_for_relaunch(mtm: MainThreadMarker) -> bool { + let can_quit = RUNNING.with(|state| { + state.borrow().as_ref().is_some_and(|running| { + relaunch_allowed( + running.view.surface().chrome.asks_quit.get(), + running.quit_requests.pending, + ) + }) + }); + if !can_quit { + return false; + } + NSApplication::sharedApplication(mtm).terminate(None); + RUNNING.with(|state| state.borrow().is_none()) +} + /// Quits the standalone runner as [`quit_app`] does, and starts the app /// again once this process has exited ([`nsh_core::restart`]). With no /// standalone runner this has no effect. @@ -1644,6 +1667,15 @@ fn secondary(frames: &[NSRect]) -> Option { #[cfg(test)] mod tests { + #[test] + fn relaunch_defers_to_async_or_pending_quit() { + assert!(super::relaunch_allowed(false, None)); + assert!(!super::relaunch_allowed(true, None)); + for pending in [Some(true), Some(false)] { + assert!(!super::relaunch_allowed(false, pending)); + } + } + use objc2_app_kit::NSApplicationActivationPolicy; use objc2_foundation::{NSPoint, NSRect, NSSize}; diff --git a/third-party/nsh/crates/nsh-platform-macos/src/lib.rs b/third-party/nsh/crates/nsh-platform-macos/src/lib.rs index af6960d7a68..60fe1d27947 100644 --- a/third-party/nsh/crates/nsh-platform-macos/src/lib.rs +++ b/third-party/nsh/crates/nsh-platform-macos/src/lib.rs @@ -92,7 +92,7 @@ pub use crate::app::set_root; pub use crate::{ app::{ ActivationPolicy, AppOptions, AppSource, AppView, WindowDisplay, quit_app, run_app, - run_app_with_config, set_components, set_ui_sets, with_running_view, + run_app_with_config, set_components, set_ui_sets, try_quit_for_relaunch, with_running_view, }, image::AssetBase, native::{ComponentContext, ComponentFactory, Components, NativeComponent},