Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(spaces): classify host access by route; collapse and page the This machine log (#4540)
ddupontab8239a076c5
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swiftindex e69f6484af..f575646ead 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swift@@ -13,6 +13,8 @@ struct ThisMachineView: View {@Bindable var host: HostModel/// A button waiting for the user's confirmation (the core's `confirm`).@State private var confirming: AppHostAction?+ /// The log open in full ("Show All…").+ @State private var fullLog: HostLog?var body: some View {let panel = host.panel@@ -99,14 +101,12 @@ struct ThisMachineView: View {}if let title = panel.recentTitle, !panel.recent.isEmpty {Section(title) {- ForEach(Array(panel.recent.enumerated()), id: \.offset) { _, row in- LabeledContent {- Text(Date(timeIntervalSince1970: Double(row.atMs) / 1000),- format: .relative(presentation: .named))- .foregroundStyle(.secondary)- } label: {- Text(row.text).lineLimit(1).truncationMode(.middle)- }+ // The newest few (repeats collapsed); the rest+ // in a sheet, so the page never grows with it.+ TimedRows(rows: panel.recent)+ if let more = panel.recentMore {+ ShowAllButton(label: more) { fullLog = .access }+ .accessibilityIdentifier("host-recent-access-more")}}.accessibilityIdentifier("host-recent-access")@@ -116,8 +116,14 @@ struct ThisMachineView: View {.accessibilityIdentifier("host-activity-warning")}if let title = panel.activityTitle, !panel.activity.isEmpty {- Section(title) { TimedRows(rows: panel.activity) }- .accessibilityIdentifier("host-activity")+ Section(title) {+ TimedRows(rows: panel.activity)+ if let more = panel.activityMore {+ ShowAllButton(label: more) { fullLog = .activity }+ .accessibilityIdentifier("host-activity-more")+ }+ }+ .accessibilityIdentifier("host-activity")}if let title = panel.permissionsTitle {Section(title) {@@ -133,30 +139,25 @@ struct ThisMachineView: View {} else if let error = host.error {Text(error).foregroundStyle(.red).lineLimit(1).help(error)}- if panel.setupChoices.isEmpty {- Section {- HStack {- ForEach(Array(panel.actions.enumerated()), id: \.offset) { index, action in- let button = Button(action.label, role: action.destructive ? .destructive : nil) {- if action.confirm != nil {- confirming = action- } else {- Task { await host.run(action.id) }- }- }- .disabled(host.busy)- .accessibilityIdentifier("host-action-\(index)")- if index == 0 {- button.buttonStyle(.borderedProminent).tint(action.destructive ? .red : .accentColor)- } else {- button- }- }- }- }- }}.formStyle(.grouped)+ .safeAreaInset(edge: .bottom, spacing: 0) {+ // Pinned under the page: Stop sharing and Remove stay+ // in view however long the logs get.+ if panel.setupChoices.isEmpty, !panel.actions.isEmpty {+ actionBar(panel.actions)+ }+ }+ }+ }+ .sheet(item: $fullLog) { log in+ switch log {+ case .access:+ HostLogSheet(title: panel.recentTitle ?? "", rows: panel.recentAll,+ backgroundRows: panel.recentWithBackground) { fullLog = nil }+ case .activity:+ HostLogSheet(title: panel.activityTitle ?? "", rows: panel.activityAll,+ backgroundRows: nil) { fullLog = nil }}}.navigationTitle(host.form == nil ? panel.title : (host.formView?.title ?? panel.title))@@ -182,6 +183,101 @@ struct ThisMachineView: View {Text(confirming?.confirm?.message ?? "")}}++ /// The page's buttons, primary first, in a bar pinned to the bottom.+ private func actionBar(_ actions: [AppHostAction]) -> some View {+ VStack(spacing: 0) {+ Divider()+ HStack {+ ForEach(Array(actions.enumerated()), id: \.offset) { index, action in+ let button = Button(action.label, role: action.destructive ? .destructive : nil) {+ if action.confirm != nil {+ confirming = action+ } else {+ Task { await host.run(action.id) }+ }+ }+ .disabled(host.busy)+ .accessibilityIdentifier("host-action-\(index)")+ if index == 0 {+ button.buttonStyle(.borderedProminent).tint(action.destructive ? .red : .accentColor)+ } else {+ button+ }+ }+ Spacer()+ }+ .padding(.horizontal, 20)+ .padding(.vertical, 12)+ }+ .background(.bar)+ .accessibilityIdentifier("host-actions")+ }+}++/// A "This machine" log shown in full.+enum HostLog: String, Identifiable {+ case access, activity+ var id: String { rawValue }+}++/// "Show All…" under a log section.+struct ShowAllButton: View {+ let label: String+ let action: () -> Void++ var body: some View {+ HStack {+ Spacer()+ Button(label, action: action)+ .buttonStyle(.link)+ .controlSize(.small)+ }+ }+}++/// A log in full: every row (repeats collapsed), newest first, and for the+/// access log a switch that adds the background probes.+struct HostLogSheet: View {+ let title: String+ let rows: [AppHostAccessRow]+ /// Every row with background activity too (`nil`: no switch).+ let backgroundRows: [AppHostAccessRow]?+ let done: () -> Void+ @State private var withBackground = false++ var body: some View {+ VStack(spacing: 0) {+ HStack {+ Text(title).font(.headline)+ Spacer()+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 12)+ Divider()+ List {+ TimedRows(rows: withBackground ? (backgroundRows ?? rows) : rows)+ }+ .listStyle(.inset(alternatesRowBackgrounds: true))+ .accessibilityIdentifier("host-log-rows")+ Divider()+ HStack {+ if backgroundRows != nil {+ Toggle("Include background activity", isOn: $withBackground)+ .toggleStyle(.checkbox)+ .accessibilityIdentifier("host-log-background")+ }+ Spacer()+ Button("Done", action: done)+ .keyboardShortcut(.defaultAction)+ .accessibilityIdentifier("host-log-done")+ }+ .padding(12)+ }+ .frame(minWidth: 520, idealWidth: 560, minHeight: 360, idealHeight: 460)+ .navigationTitle(title)+ .accessibilityIdentifier("host-log-sheet")+ }}/// Rows with a relative time after them (provided Spaces, activity).diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/this-machine.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/this-machine.pngindex 07c668fb48..aedf309ab8 100644Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/this-machine.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/this-machine.png differdiff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swiftindex f5c98b954b..5ff5be4856 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift@@ -325,6 +325,33 @@ struct ViewModelTests {#expect(panel.accessWarning != nil)}+ /// A spammed log: background probes and the owner's thumbnails are+ /// left out, repeats collapse into one row with a count, the page+ /// shows five rows and "Show All…", and the buttons stay.+ @Test func aSpammedAccessLogCollapsesAndShowsFive() {+ var log = (0..<12).map {+ HostAccessRecord(atMs: Int64(1_000 - $0), via: "relay", who: "Mac mini (a1)",+ what: "refused ComputerService (desktop not shared)")+ }+ log += ["SystemService/Health (background)", "ComputerService/Screenshot (thumbnail)", "StreamService",+ "FilesystemService", "ProcessService", "TeleportService", "MCP"].enumerated().map {+ HostAccessRecord(atMs: Int64(900 - $0.offset), via: "relay", who: "Mac mini (a1)", what: $0.element)+ }+ let status = HostStatus(+ configured: true, mode: "relay", relayUrl: "https://relay.cua.ai", directUrl: nil, envTokenPath: nil,+ machineId: nil, name: "Studio", sharing: true, serviceInstalled: true, serviceRunning: true,+ serviceKind: "launchd", online: true, clients: [], allow: [], permissions: [], error: nil,+ recentAccess: log, accessLogError: nil)+ let panel = appHostPanel(state: appHostState(status: status))+ #expect(panel.recent.count == 5)+ #expect(panel.recent.first?.text == "Mac mini (a1) \u{b7} Screen and input refused (desktop not shared) \u{d7}12")+ #expect(panel.recentMore == "Show All\u{2026}")+ #expect(panel.recentAll.count == 6)+ #expect(panel.recentWithBackground.count == 8)+ #expect(!panel.recentAll.contains { $0.text.contains("background") })+ #expect(panel.actions.map(\.label) == ["Stop sharing", "Remove host setup"])+ }+@Test func aFailedHostSetupKeepsTheFormWithTheReason() async {let host = FixtureHost()host.failSetup = "launchctl bootstrap failed\nmore"diff --git a/libs/cua-spacesd/crates/cua-spacesd-desktop/src/grpc/computer.rs b/libs/cua-spacesd/crates/cua-spacesd-desktop/src/grpc/computer.rsindex a757c92688..798efbd393 100644--- a/libs/cua-spacesd/crates/cua-spacesd-desktop/src/grpc/computer.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-desktop/src/grpc/computer.rs@@ -356,6 +356,9 @@ impl ComputerService for Computer {&self,request: Request<ScreenshotRequest>,) -> Result<Response<ScreenshotResponse>, Status> {+ // The access log says whether this was a thumbnail or a screen+ // read (the auth layer leaves screenshots to us).+ cua_spacesd_server::auth::record_screenshot(&request, request.get_ref().max_dimension);let request = request.into_inner();let state = self.0.clone();let (source, window) = match &request.source {diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/access_log.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/access_log.rsindex 5fd4715f82..24f4a6bb54 100644--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/access_log.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/access_log.rs@@ -49,7 +49,11 @@ pub struct AccessBody {pub via: String,/// Who: the verified identity, or `token` (plus a claimed name).pub who: String,- /// What: the gRPC service (`ProcessService`, ...) or `MCP`.+ /// What: the gRPC service (`ProcessService`, ...) or `MCP`; a+ /// background call as `<Service>/<Method> (background)`, a thumbnail+ /// as `ComputerService/Screenshot (thumbnail[, not owner])`, a refusal+ /// as `refused <Service> (<why>)` (see `auth::call_what`). Readers+ /// classify by these forms; the host decides them, never the caller.pub what: String,/// The previous entry's `hash` (or [`GENESIS`]).pub prev: String,diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rsindex 7220df685a..37c17bb3cf 100644--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rs@@ -310,6 +310,33 @@ impl Auth {}}+ /// Records an authorized gRPC call to `path` ([`call_what`]); a+ /// screenshot is left to its handler ([`record_screenshot`]), which+ /// knows whether it is a thumbnail. `owner`: the caller is the+ /// machine's owner (the token, or the owner's relay account).+ pub fn record_call(+ &self,+ extensions: &mut http::Extensions,+ via: &str,+ who: &str,+ path: &str,+ owner: bool,+ ) {+ if path == SCREENSHOT_METHOD {+ let log = self.access_log.read().expect("access log lock").clone();+ if let Some(log) = log {+ extensions.insert(PendingAccess {+ log,+ via: via.into(),+ who: who.into(),+ owner,+ });+ }+ return;+ }+ self.record_access(via, who, &call_what(path));+ }+/// Records the access `headers` were authorized with for `what`: the/// relay-asserted identity, else the token (with any client-claimed/// name marked as claimed). Nothing without a token (a loopback server@@ -653,6 +680,104 @@ pub fn grpc_service(path: &str) -> &str {service.rsplit('.').next().unwrap_or(service)}+/// Read-only, low-impact calls (capability and health probes, status+/// polls, presence, listings) that clients make on their own. The access+/// log records them as `<Service>/<Method> (background)` so readers can+/// leave them out of "connected now"; the classification is the route's,+/// decided here on the host, never anything the caller says about itself.+/// Every other call (a stream, input, a shell, files, an agent, teleport,+/// a share or the volume) is recorded by its service name, as before.+pub const BACKGROUND_GRPC_METHODS: &[&str] = &[+ "/cua.env.v1.SystemService/GetCapabilities",+ "/cua.env.v1.SystemService/Health",+ "/cua.env.v1.SystemService/Metrics",+ "/cua.env.v1.PresenceService/Join",+ "/cua.env.v1.PresenceService/UpdateCursor",+ "/cua.env.v1.PresenceService/Leave",+ "/cua.env.v1.StreamService/ListTargets",+ "/cua.env.v1.ComputerService/ListDisplays",+ "/cua.env.v1.HostSpacesService/GetHostSpaces",+ "/cua.env.v1.TunnelService/ListForwards",+ "/cua.env.v1.TunnelService/GetHotspotStatus",+ "/cua.env.v1.VolumeService/GetVolumeStatus",+ "/cua.env.v1.DriverService/ListTools",+];++/// The suffix of a background call's `what` in the access log.+pub const BACKGROUND_TAG: &str = " (background)";++/// `ComputerService.Screenshot`: recorded by the handler once it knows the+/// size asked for ([`record_screenshot`]).+pub const SCREENSHOT_METHOD: &str = "/cua.env.v1.ComputerService/Screenshot";++/// A screenshot no larger than this (long edge, pixels) is a thumbnail.+pub const THUMBNAIL_MAX_DIMENSION: u32 = 480;++/// What the access log records for an authorized gRPC call to `path`.+pub fn call_what(path: &str) -> String {+ let route = path.trim_start_matches('/');+ let route = route.rsplit_once('.').map_or(route, |(_, r)| r);+ if BACKGROUND_GRPC_METHODS.contains(&path) {+ return format!("{route}{BACKGROUND_TAG}");+ }+ let service = grpc_service(path);+ // Older drivers wrote these services bare, and readers take a bare+ // one as background; their other calls (a viewer ticket, shutdown)+ // name the method so they still count.+ if LEGACY_BACKGROUND_SERVICES.contains(&service) {+ return route.to_string();+ }+ service.to_string()+}++/// Services older drivers recorded without the method, which readers take+/// as background when bare ([`call_what`] names the method for the rest).+pub const LEGACY_BACKGROUND_SERVICES: &[&str] = &["SystemService", "PresenceService"];++/// What the access log records for a screenshot of at most+/// `max_dimension` pixels (0: full size): a thumbnail (background for the+/// machine's owner, surfaced for anyone else) or a screen read.+pub fn screenshot_what(max_dimension: u32, owner: bool) -> String {+ if (1..=THUMBNAIL_MAX_DIMENSION).contains(&max_dimension) {+ if owner {+ "ComputerService/Screenshot (thumbnail)".into()+ } else {+ "ComputerService/Screenshot (thumbnail, not owner)".into()+ }+ } else {+ "ComputerService".into()+ }+}++/// An authorized screenshot not yet recorded: the handler records it with+/// the size it was asked for ([`record_screenshot`]).+#[derive(Clone)]+pub struct PendingAccess {+ log: Arc<crate::access_log::AccessLog>,+ via: String,+ who: String,+ owner: bool,+}++impl std::fmt::Debug for PendingAccess {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("PendingAccess")+ .field("via", &self.via)+ .field("who", &self.who)+ .field("owner", &self.owner)+ .finish()+ }+}++/// Records the screenshot `request` asks for (`ComputerService.Screenshot`+/// handlers call it first): a thumbnail or a screen read, by its size.+pub fn record_screenshot<T>(request: &tonic::Request<T>, max_dimension: u32) {+ if let Some(p) = request.extensions().get::<PendingAccess>() {+ p.log+ .record(&p.via, &p.who, &screenshot_what(max_dimension, p.owner));+ }+}+/// How the gRPC surface treats callers when no token is configured.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum AccessMode {@@ -793,7 +918,8 @@ where.into_http::<R>();return Box::pin(async move { Ok(response) });}- self.auth.record_access("relay", &who, grpc_service(&path));+ self.auth+ .record_call(req.extensions_mut(), "relay", &who, &path, false);let viewer = Arc::new(grant.viewer_grant());req.extensions_mut().insert(CallerIdentity {principal: Some(grant.principal),@@ -828,10 +954,13 @@ where.into_http::<R>();return Box::pin(async move { Ok(response) });}- self.auth.record_access(+ let owner = grant.account.as_ref().is_some_and(|a| a.role == "owner");+ self.auth.record_call(+ req.extensions_mut(),"relay",&principal_label(&grant.principal),- grpc_service(&path),+ &path,+ owner,);req.extensions_mut().insert(CallerIdentity {principal: Some(grant.principal),@@ -865,10 +994,12 @@ wherelet path = req.uri().path().to_owned();let refusal = match viewer {Ok(grant) if cua_proto::metadata::VIEWER_GRPC_METHODS.contains(&path.as_str()) => {- self.auth.record_access(+ self.auth.record_call(+ req.extensions_mut(),"viewer",&principal_label(&grant.principal()),- grpc_service(&path),+ &path,+ false,);req.extensions_mut().insert(CallerIdentity {principal: Some(grant.principal()),@@ -938,10 +1069,13 @@ whereOk(token_verified) => {let principal = principal_from_headers(req.headers());if token_verified {- self.auth.record_access(+ let path = req.uri().path().to_owned();+ self.auth.record_call(+ req.extensions_mut(),"token",&token_label(principal.clone()),- grpc_service(req.uri().path()),+ &path,+ true,);}req.extensions_mut().insert(CallerIdentity {@@ -978,6 +1112,53 @@ pub fn caller<T>(request: &tonic::Request<T>) -> CallerIdentity {mod tests {use super::*;+ #[test]+ fn screenshots_are_recorded_as_thumbnails_or_screen_reads() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("access.log");+ let auth = Auth::new(Some("t".into()));+ auth.set_access_log(Arc::new(crate::access_log::AccessLog::open(&path)));+ let shot = |who: &str, owner: bool, max_dimension: u32| {+ let mut ext = http::Extensions::new();+ auth.record_call(&mut ext, "relay", who, SCREENSHOT_METHOD, owner);+ let req = tonic::Request::from_parts(tonic::metadata::MetadataMap::new(), ext, ());+ record_screenshot(&req, max_dimension);+ };+ shot("owner", true, 320);+ shot("guest", false, 320);+ shot("owner", true, 0);+ let text = std::fs::read_to_string(&path).unwrap();+ let what: Vec<String> = text+ .lines()+ .map(|l| {+ serde_json::from_str::<crate::access_log::AccessEntry>(l)+ .unwrap()+ .body+ .what+ })+ .collect();+ assert_eq!(+ what,+ [+ "ComputerService/Screenshot (thumbnail)",+ "ComputerService/Screenshot (thumbnail, not owner)",+ "ComputerService",+ ]+ );+ assert_eq!(+ call_what("/cua.env.v1.SystemService/Health"),+ "SystemService/Health (background)"+ );+ assert_eq!(+ call_what("/cua.env.v1.SystemService/CreateViewerTicket"),+ "SystemService/CreateViewerTicket"+ );+ assert_eq!(+ call_what("/cua.env.v1.TeleportService/ImportSession"),+ "TeleportService"+ );+ }+#[test]fn claim_token_installs_only_the_first_token() {let auth = Auth::new(None);diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/tests/access_log.rs b/libs/cua-spacesd/crates/cua-spacesd-server/tests/access_log.rsindex 8d00d8ef85..46d42e3e98 100644--- a/libs/cua-spacesd/crates/cua-spacesd-server/tests/access_log.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-server/tests/access_log.rs@@ -61,7 +61,8 @@ async fn token_calls_are_recorded_and_refusals_are_not() {assert_eq!(e.len(), 1, "{e:?}");assert_eq!(e[0].body.via, "token");assert_eq!(e[0].body.who, "token");- assert_eq!(e[0].body.what, "SystemService");+ // A capabilities probe is background, by its route.+ assert_eq!(e[0].body.what, "SystemService/GetCapabilities (background)");let text = std::fs::read_to_string(ctx.config().access_log_path()).unwrap();assert!(!text.contains("s3cret"), "never the credential");@@ -295,6 +296,49 @@ async fn view_only_shares_need_desktop_sharing_on() {assert_eq!(status(&resp).as_deref(), Some("7"));}+/// Background calls are classified by their route on the host: probes,+/// status and presence are tagged `(background)`; a stream, a shell or+/// files are recorded by service; a screenshot waits for its handler.+/// Nothing the caller sends changes that.+#[tokio::test]+async fn calls_are_classified_by_route_not_by_the_caller() {+ let (r, ctx, _d) = server(Some("s3cret"), true);+ ctx.auth().set_external(std::sync::Arc::new(Relay));+ let call = |path: &str| {+ let mut req = grpc(path, None);+ req.headers_mut()+ .insert("x-test-relay", http::HeaderValue::from_static("1"));+ // A client claiming its call is background changes nothing.+ req.headers_mut().insert(+ "x-cua-purpose",+ http::HeaderValue::from_static("background"),+ );+ req+ };+ for path in [+ "/cua.env.v1.SystemService/Health",+ "/cua.env.v1.PresenceService/UpdateCursor",+ "/cua.env.v1.HostSpacesService/GetHostSpaces",+ "/cua.env.v1.StreamService/OpenMedia",+ "/cua.env.v1.ProcessService/StartProcess",+ "/cua.env.v1.ComputerService/Screenshot",+ ] {+ r.clone().oneshot(call(path)).await.unwrap();+ }+ let what: Vec<String> = entries(&ctx).into_iter().map(|e| e.body.what).collect();+ assert_eq!(+ what,+ [+ "SystemService/Health (background)",+ "PresenceService/UpdateCursor (background)",+ "HostSpacesService/GetHostSpaces (background)",+ "StreamService",+ "ProcessService",+ ],+ "the screenshot is recorded by its handler, with its size"+ );+}+fn percent_decode(s: &str) -> String {let b = s.as_bytes();let mut out = Vec::new();diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex fa0e97d6ef..eb9b9824e5 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -1127,11 +1127,25 @@ fn render_access(s: &HostStatus, now_ms: u64, out: &mut dyn Write) {format!(" access log: does not verify ({e}); it may have been altered"),);}- if s.recent_access.is_empty() {+ // Background probes and the owner's own thumbnails stay in the log+ // (and `--json`), not in this list.+ use cua_host::access::AccessKind;+ let shown: Vec<_> = s+ .recent_access+ .iter()+ .filter(|r| {+ !matches!(+ r.kind(),+ AccessKind::Background | AccessKind::OwnerThumbnail+ )+ })+ .take(8)+ .collect();+ if shown.is_empty() {return;}line(out, " recent access:");- for r in s.recent_access.iter().take(8) {+ for r in shown {line(out,format!(diff --git a/libs/cua/crates/cua-host/src/access.rs b/libs/cua/crates/cua-host/src/access.rsindex 8a89e77168..829248a404 100644--- a/libs/cua/crates/cua-host/src/access.rs+++ b/libs/cua/crates/cua-host/src/access.rs@@ -14,6 +14,13 @@ use sha2::{Digest as _, Sha256};/// Accesses shown by default.pub const RECENT_LIMIT: usize = 20;+/// Accesses a status reads (the app classifies, collapses and pages them;+/// background probes make most of the lines).+pub const STATUS_LIMIT: usize = 1000;+/// A caller whose session started with a connection this recent stays+/// connected while it keeps calling (background calls included, such as+/// presence while a stream is open), at most this long after it.+pub const SESSION_WINDOW_MS: u64 = 10 * 60_000;/// A caller with an access this recent counts as connected now. The driver/// writes at most one line per caller and service per minute while the/// caller keeps using it, so two minutes covers an active session.@@ -63,6 +70,64 @@ pub struct AccessRecord {pub what: String,}+impl AccessRecord {+ /// What it was ([`classify`]).+ pub fn kind(&self) -> AccessKind {+ classify(&self.who, &self.what)+ }+}++/// What an access was, as the host classified it when it wrote the line+/// (`cua-spacesd-server`'s `auth::call_what`; keep in sync). Never from+/// anything the caller said about itself.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum AccessKind {+ /// Someone used the machine: a stream, input, a shell, files, an+ /// agent, teleport, a share, the volume. Counts as a connection.+ Connection,+ /// A read-only probe clients make on their own (capabilities, health,+ /// status, presence, listings). Never a connection.+ Background,+ /// A thumbnail-sized screenshot by the machine's owner.+ OwnerThumbnail,+ /// A thumbnail-sized screenshot by anyone else: shown, not a+ /// connection.+ Thumbnail,+ /// Refused (the desktop is not shared, a view-only share, a bad+ /// assertion). Shown, never a connection.+ Refused,+}++impl AccessKind {+ /// Whether it makes the caller "connected now".+ pub fn is_connection(self) -> bool {+ self == Self::Connection+ }+}++/// The suffix the driver gives a background call.+const BACKGROUND_TAG: &str = " (background)";++/// Classifies an access line. Lines from drivers that predate the+/// classification name only the service: their `SystemService` and+/// `PresenceService` lines are background, the rest connections.+pub fn classify(who: &str, what: &str) -> AccessKind {+ if who == "refused" || what.starts_with("refused ") {+ AccessKind::Refused+ } else if what.ends_with(BACKGROUND_TAG) {+ AccessKind::Background+ } else if what.ends_with("(thumbnail, not owner)") {+ AccessKind::Thumbnail+ } else if what.ends_with("(thumbnail)") {+ AccessKind::OwnerThumbnail+ } else if matches!(what, "SystemService" | "PresenceService") {+ AccessKind::Background+ } else {+ AccessKind::Connection+ }+}+/// The log's recent entries and whether its chain verified.#[derive(Clone, Debug, Default, PartialEq, Eq)]pub struct AccessReport {@@ -130,15 +195,71 @@ pub fn read(path: &Path, limit: usize) -> AccessReport {report}-/// The distinct callers with an access in the last [`ACTIVE_WINDOW_MS`]-/// before `now_ms` (newest first).+/// The distinct callers connected at `now_ms` (newest first, each as its+/// latest connection): a connection ([`AccessKind::Connection`]) in the+/// last [`ACTIVE_WINDOW_MS`], or one in the last [`SESSION_WINDOW_MS`]+/// followed by calls of any kind with no gap longer than+/// [`ACTIVE_WINDOW_MS`] up to now (a stream kept open, with presence).+/// Background probes, thumbnails and refusals alone never count.pub fn active(recent: &[AccessRecord], now_ms: u64) -> Vec<&AccessRecord> {let mut seen = std::collections::HashSet::new();- recent+ let mut out = vec![];+ for r in recent {+ let key = (r.via.as_str(), r.who.as_str());+ if !r.kind().is_connection() || seen.contains(&key) {+ continue;+ }+ let age = now_ms.saturating_sub(r.at_ms);+ if age > SESSION_WINDOW_MS {+ continue;+ }+ let live = age <= ACTIVE_WINDOW_MS || {+ // The caller's calls since then (newest first, refusals+ // aside) must leave no gap longer than the active window.+ let mut last = now_ms;+ let mut ok = true;+ for c in recent.iter().filter(|c| {+ (c.via.as_str(), c.who.as_str()) == key+ && c.at_ms >= r.at_ms+ && c.kind() != AccessKind::Refused+ }) {+ if last.saturating_sub(c.at_ms) > ACTIVE_WINDOW_MS {+ ok = false;+ break;+ }+ last = c.at_ms;+ }+ ok && last.saturating_sub(r.at_ms) <= ACTIVE_WINDOW_MS+ };+ if live {+ seen.insert(key);+ out.push(r);+ }+ }+ out+}++/// Whether a relay-reported client (account `id`, its presence since+/// `since_ms`) made a connection on this machine: one since its presence+/// began, or in the last [`ACTIVE_WINDOW_MS`]. `None` when the log has+/// nothing from that account at all (no log, or a driver that does not+/// write one): the relay's word stands then.+pub fn relay_client_connected(+ recent: &[AccessRecord],+ id: &str,+ since_ms: u64,+ now_ms: u64,+) -> Option<bool> {+ let suffix = format!("({id})");+ let mut theirs = recent.iter()- .filter(|r| now_ms.saturating_sub(r.at_ms) <= ACTIVE_WINDOW_MS)- .filter(|r| seen.insert((r.via.as_str(), r.who.as_str())))- .collect()+ .filter(|r| r.via == "relay" && (r.who == id || r.who.ends_with(&suffix)))+ .peekable();+ theirs.peek()?;+ Some(theirs.any(|r| {+ r.kind().is_connection()+ && (r.at_ms + 5_000 >= since_ms || now_ms.saturating_sub(r.at_ms) <= ACTIVE_WINDOW_MS)+ }))}#[cfg(test)]@@ -230,6 +351,175 @@ mod tests {assert!(read(&path, 5).error.unwrap().contains("chain broken"));}+ fn rec(at_ms: u64, via: &str, who: &str, what: &str) -> AccessRecord {+ AccessRecord {+ at_ms,+ via: via.into(),+ who: who.into(),+ what: what.into(),+ }+ }++ #[test]+ fn classifies_by_the_hosts_tags() {+ use AccessKind::*;+ for (who, what, want) in [+ ("Ada (a1)", "SystemService/Health (background)", Background),+ (+ "Ada (a1)",+ "HostSpacesService/GetHostSpaces (background)",+ Background,+ ),+ (+ "Ada (a1)",+ "PresenceService/UpdateCursor (background)",+ Background,+ ),+ (+ "Ada (a1)",+ "ComputerService/Screenshot (thumbnail)",+ OwnerThumbnail,+ ),+ (+ "Bob (b1)",+ "ComputerService/Screenshot (thumbnail, not owner)",+ Thumbnail,+ ),+ (+ "Ada (a1)",+ "refused ComputerService (desktop not shared)",+ Refused,+ ),+ ("refused", "bad assertion", Refused),+ ("Ada (a1)", "StreamService", Connection),+ ("Ada (a1)", "ProcessService", Connection),+ ("Ada (a1)", "FilesystemService", Connection),+ ("Ada (a1)", "TeleportService", Connection),+ ("Ada (a1)", "VolumeService", Connection),+ ("token", "MCP", Connection),+ ("Ada (a1)", "ComputerService", Connection),+ ("Ada (a1)", "SystemService/CreateViewerTicket", Connection),+ // An older driver's bare probe services are background.+ ("token", "SystemService", Background),+ ("token", "PresenceService", Background),+ ] {+ assert_eq!(classify(who, what), want, "{what}");+ }+ }++ #[test]+ fn background_alone_is_never_connected() {+ let now = 10_000_000;+ let rows = [+ rec(+ now - 1_000,+ "relay",+ "Mac mini (a1)",+ "SystemService/Health (background)",+ ),+ rec(+ now - 2_000,+ "relay",+ "Mac mini (a1)",+ "ComputerService/Screenshot (thumbnail)",+ ),+ rec(+ now - 3_000,+ "relay",+ "Mac mini (a1)",+ "refused ComputerService (desktop not shared)",+ ),+ rec(+ now - 4_000,+ "relay",+ "Bob (b1)",+ "ComputerService/Screenshot (thumbnail, not owner)",+ ),+ ];+ assert!(active(&rows, now).is_empty());+ // A user-started call does count.+ let mut rows = rows.to_vec();+ rows.insert(0, rec(now - 500, "relay", "Mac mini (a1)", "StreamService"));+ let a = active(&rows, now);+ assert_eq!(a.len(), 1);+ assert_eq!(a[0].what, "StreamService");+ }++ #[test]+ fn a_session_stays_connected_while_it_keeps_calling() {+ let now = 10_000_000;+ // A stream opened six minutes ago, presence every minute since.+ let mut rows: Vec<AccessRecord> = (0..6)+ .map(|m| {+ rec(+ now - m * 60_000,+ "relay",+ "Ada (a1)",+ "PresenceService/UpdateCursor (background)",+ )+ })+ .collect();+ rows.push(rec(now - 6 * 60_000, "relay", "Ada (a1)", "StreamService"));+ assert_eq!(active(&rows, now).len(), 1);+ // A gap longer than the active window ends it.+ rows.remove(2);+ rows.remove(2);+ assert!(active(&rows, now).is_empty());+ // So does the session window, however busy the poller.+ let rows: Vec<AccessRecord> = (0..20)+ .map(|m| {+ rec(+ now - m * 60_000,+ "relay",+ "Ada (a1)",+ "SystemService/Health (background)",+ )+ })+ .chain([rec(+ now - 20 * 60_000,+ "relay",+ "Ada (a1)",+ "ProcessService",+ )])+ .collect();+ assert!(active(&rows, now).is_empty());+ }++ #[test]+ fn relay_presence_needs_a_connection_in_the_log() {+ let now = 10_000_000;+ let polls = [rec(+ now - 1_000,+ "relay",+ "Mac mini (acct-1)",+ "SystemService/Health (background)",+ )];+ assert_eq!(+ relay_client_connected(&polls, "acct-1", now - 60_000, now),+ Some(false)+ );+ assert_eq!(+ relay_client_connected(&polls, "acct-2", now - 60_000, now),+ None+ );+ let used = [rec(+ now - 30_000,+ "relay",+ "Mac mini (acct-1)",+ "StreamService",+ )];+ assert_eq!(+ relay_client_connected(&used, "acct-1", now - 60_000, now),+ Some(true)+ );+ // An auto-connect opens a real session, so it counts like any other.+ let auto = [rec(now - 400_000, "relay", "acct-1", "ProcessService")];+ assert_eq!(+ relay_client_connected(&auto, "acct-1", now - 401_000, now),+ Some(true)+ );+ }+#[test]fn active_is_recent_and_distinct() {let rows = [diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex b7e8baa4db..f7ceefc8ed 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -1244,9 +1244,20 @@ impl Host {/// active right now to `clients`: every one in direct mode (there is no/// relay presence), and in relay mode the ones the relay cannot see/// (token and viewer callers) or all of them when the relay did not- /// answer.+ /// answer. Only connections count ([`crate::access::AccessKind`]): a+ /// relay client whose calls this machine logged as background probes,+ /// thumbnails or refusals only is not "connected now".fn add_access(&self, status: &mut HostStatus, now_ms: u64) {- let report = crate::access::read(&self.paths.access_log(), crate::access::RECENT_LIMIT);+ let report = crate::access::read(&self.paths.access_log(), crate::access::STATUS_LIMIT);+ status.clients.retain(|c| {+ crate::access::relay_client_connected(+ &report.recent,+ &c.id,+ c.since.saturating_mul(1000),+ now_ms,+ )+ .unwrap_or(true)+ });let relay_answered = status.online.is_some();let active: Vec<ConnectedClient> = crate::access::active(&report.recent, now_ms).into_iter()diff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rsindex 361e28a0f0..5035002fa8 100644--- a/libs/cua/crates/cua-host/src/tests.rs+++ b/libs/cua/crates/cua-host/src/tests.rs@@ -117,6 +117,45 @@ async fn relay_setup_registers_writes_policy_and_installs_the_service() {assert_eq!(status.online, Some(true));assert_eq!(status.clients.len(), 1);+ // A relay client this machine logged only background probes and+ // thumbnails from (an app polling it) is not connected now; one that+ // opened something is.+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_millis() as u64;+ let log = host.paths().access_log();+ std::fs::create_dir_all(log.parent().unwrap()).unwrap();+ crate::access::write_log(+ &log,+ &[+ (+ now - 2_000,+ "relay",+ "[email protected] (user-2)",+ "SystemService/Health (background)",+ ),+ (+ now - 1_000,+ "relay",+ "[email protected] (user-2)",+ "ComputerService/Screenshot (thumbnail)",+ ),+ ],+ );+ assert!(host.status().await.unwrap().clients.is_empty());+ crate::access::write_log(+ &log,+ &[(+ now - 1_000,+ "relay",+ "[email protected] (user-2)",+ "StreamService",+ )],+ );+ assert_eq!(host.status().await.unwrap().clients.len(), 1);+ std::fs::remove_file(&log).unwrap();+// Stop sharing: relay cuts clients, policy refuses, service keeps running.let status = host.stop_sharing().await.unwrap();assert!(!status.sharing);@@ -333,6 +372,35 @@ async fn status_shows_recent_access_and_who_is_connected_in_direct_mode() {let text = std::fs::read_to_string(host.paths().access_log()).unwrap();std::fs::write(host.paths().access_log(), text.replace("Bob", "Eve")).unwrap();assert!(host.status().await.unwrap().access_log_error.is_some());++ // Background probes and thumbnails, however recent, are not a+ // connection; they stay in the log.+ crate::access::write_log(+ &host.paths().access_log(),+ &[+ (+ now - 9_000,+ "relay",+ "Mac mini (acct-1)",+ "SystemService/Health (background)",+ ),+ (+ now - 8_000,+ "relay",+ "Mac mini (acct-1)",+ "ComputerService/Screenshot (thumbnail)",+ ),+ (+ now - 7_000,+ "token",+ "token",+ "SystemService/GetCapabilities (background)",+ ),+ ],+ );+ let status = host.status().await.unwrap();+ assert!(status.clients.is_empty(), "{:?}", status.clients);+ assert_eq!(status.recent_access.len(), 3);}/// Every file under `dir`, recursively.diff --git a/libs/cua/crates/cua-spaces-app-core/src/host.rs b/libs/cua/crates/cua-spaces-app-core/src/host.rsindex 6e9e78793c..4690bcf686 100644--- a/libs/cua/crates/cua-spaces-app-core/src/host.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/host.rs@@ -622,8 +622,53 @@ pub struct HostAccessRow {pub at_ms: i64,}+/// Rows a "This machine" log section shows before "Show All…".+pub const LOG_PREVIEW_ROWS: usize = 5;+/// The button under a log section with more rows than it shows.+pub const SHOW_ALL_LABEL: &str = "Show All\u{2026}";++/// What an access was, as the host classified it when it logged it (the+/// mirror of `cua-host`'s `access::classify`; keep in sync). Never from+/// anything the caller said about itself.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum HostAccessKind {+ /// Someone used the machine (a stream, input, a shell, files, an+ /// agent, teleport, a share, the volume).+ Connection,+ /// A read-only probe a client made on its own (capabilities, health,+ /// status, presence, listings).+ Background,+ /// A thumbnail-sized screenshot by the owner (background).+ OwnerThumbnail,+ /// A thumbnail-sized screenshot by someone else (shown).+ Thumbnail,+ /// Refused.+ Refused,+}++/// Classifies an access line ([`HostAccessKind`]).+pub fn access_kind(who: &str, what: &str) -> HostAccessKind {+ if who == "refused" || what.starts_with("refused ") {+ HostAccessKind::Refused+ } else if what.ends_with(" (background)") {+ HostAccessKind::Background+ } else if what.ends_with("(thumbnail, not owner)") {+ HostAccessKind::Thumbnail+ } else if what.ends_with("(thumbnail)") {+ HostAccessKind::OwnerThumbnail+ } else if matches!(what, "SystemService" | "PresenceService") {+ // An older driver's bare probe services.+ HostAccessKind::Background+ } else {+ HostAccessKind::Connection+ }+}+/// What an access used, in words.pub fn access_what(what: &str) -> String {+ // `Service/Method (tag)` → `Service`.+ let what = what.split(" (").next().unwrap_or(what);+ let what = what.split('/').next().unwrap_or(what);match what {"ProcessService" => "Terminal and processes","FilesystemService" => "Files",@@ -631,7 +676,10 @@ pub fn access_what(what: &str) -> String {"TunnelService" => "Network tunnel","DriverService" | "MCP" => "Automation tools","SystemService" => "Status",+ "HostSpacesService" => "Spaces",+ "VolumeService" => "Cua Volume","ComputerService"+ | "StreamService"| "DesktopService"| "MediaService"| "WindowsService"@@ -657,21 +705,89 @@ pub fn access_who(via: &str, who: &str) -> String {who.to_string()}-/// "Recent access" rows, newest first.+/// One access, in words: "Ada · Files", "Bob viewed thumbnails",+/// "Mac mini · Screen and input refused (desktop not shared)".+pub fn access_text(a: &HostAccess) -> String {+ let who = access_who(&a.via, &a.who);+ match access_kind(&a.who, &a.what) {+ HostAccessKind::Refused if a.who == "refused" => {+ format!("Refused sign-in \u{b7} {}", a.what)+ }+ HostAccessKind::Refused => {+ let rest = a.what.trim_start_matches("refused ");+ let (service, why) = match rest.split_once(" (") {+ Some((service, why)) => (service, format!(" ({why}")),+ None => (rest, String::new()),+ };+ format!("{who} \u{b7} {} refused{why}", access_what(service))+ }+ HostAccessKind::Thumbnail | HostAccessKind::OwnerThumbnail => {+ format!("{who} viewed thumbnails")+ }+ HostAccessKind::Background => {+ format!("{who} \u{b7} {} (background)", access_what(&a.what))+ }+ HostAccessKind::Connection => format!("{who} \u{b7} {}", access_what(&a.what)),+ }+}++/// "Recent access" rows, newest first: connections, refusals and other+/// people's thumbnails, with consecutive repeats collapsed ("×12").+/// Background probes and the owner's own thumbnails are left out (see+/// [`access_rows_with_background`]).pub fn access_rows(recent: &[HostAccess]) -> Vec<HostAccessRow> {- recent- .iter()- .map(|a| HostAccessRow {- text: format!(- "{} \u{b7} {}",- access_who(&a.via, &a.who),- access_what(&a.what)- ),- at_ms: a.at_ms,+ collapse_repeats(+ recent+ .iter()+ .filter(|a| {+ !matches!(+ access_kind(&a.who, &a.what),+ HostAccessKind::Background | HostAccessKind::OwnerThumbnail+ )+ })+ .map(|a| HostAccessRow {+ text: access_text(a),+ at_ms: a.at_ms,+ }),+ )+}++/// Every access, background included, newest first, repeats collapsed.+pub fn access_rows_with_background(recent: &[HostAccess]) -> Vec<HostAccessRow> {+ collapse_repeats(recent.iter().map(|a| HostAccessRow {+ text: access_text(a),+ at_ms: a.at_ms,+ }))+}++/// Collapses consecutive rows with the same text into one, newest first,+/// with the count: "Mac mini · Screen and input refused ×12".+pub fn collapse_repeats(rows: impl IntoIterator<Item = HostAccessRow>) -> Vec<HostAccessRow> {+ let mut out: Vec<(HostAccessRow, u32)> = vec![];+ for row in rows {+ match out.last_mut() {+ Some((last, n)) if last.text == row.text => *n += 1,+ _ => out.push((row, 1)),+ }+ }+ out.into_iter()+ .map(|(mut row, n)| {+ if n > 1 {+ row.text.push_str(&format!(" \u{d7}{n}"));+ }+ row}).collect()}+/// The first [`LOG_PREVIEW_ROWS`] of `all`, and "Show All…" when there are+/// more.+pub fn log_preview(all: &[HostAccessRow]) -> (Vec<HostAccessRow>, Option<String>) {+ let shown = all.iter().take(LOG_PREVIEW_ROWS).cloned().collect();+ let more = (all.len() > LOG_PREVIEW_ROWS).then(|| SHOW_ALL_LABEL.to_string());+ (shown, more)+}+/// A permission row: the pane's title and "Open Settings".#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -707,9 +823,21 @@ pub struct HostPanelView {/// "Recent access" (configured, when the log has any).#[serde(default, skip_serializing_if = "Option::is_none")]pub recent_title: Option<String>,- /// Who reached this machine recently, newest first.+ /// Who reached this machine recently, newest first: the first+ /// [`LOG_PREVIEW_ROWS`] of [`Self::recent_all`].#[serde(default, skip_serializing_if = "Vec::is_empty")]pub recent: Vec<HostAccessRow>,+ /// "Show All…" when `recent_all` has more than `recent` shows.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub recent_more: Option<String>,+ /// Every recent access (connections, refusals, other people's+ /// thumbnails), repeats collapsed: the "Show All" sheet.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub recent_all: Vec<HostAccessRow>,+ /// The same with background probes and the owner's thumbnails too+ /// (the sheet's "Include background activity").+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub recent_with_background: Vec<HostAccessRow>,/// Set when the access log does not verify.#[serde(default, skip_serializing_if = "Option::is_none")]pub access_warning: Option<String>,@@ -732,9 +860,16 @@ pub struct HostPanelView {/// "Spaces activity" (when the audit has any).#[serde(default, skip_serializing_if = "Option::is_none")]pub activity_title: Option<String>,- /// Remote creates, deletes and refusals, newest first.+ /// Remote creates, deletes and refusals, newest first: the first+ /// [`LOG_PREVIEW_ROWS`] of [`Self::activity_all`].#[serde(default, skip_serializing_if = "Vec::is_empty")]pub activity: Vec<HostAccessRow>,+ /// "Show All…" when `activity_all` has more than `activity` shows.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub activity_more: Option<String>,+ /// The whole Spaces activity, repeats collapsed.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub activity_all: Vec<HostAccessRow>,/// Set when the Spaces audit does not verify.#[serde(default, skip_serializing_if = "Option::is_none")]pub activity_warning: Option<String>,@@ -819,6 +954,9 @@ pub fn panel(state: Option<&HostState>) -> HostPanelView {clients_empty: None,recent_title: None,recent: vec![],+ recent_more: None,+ recent_all: vec![],+ recent_with_background: vec![],access_warning: None,toggles: vec![],limits: None,@@ -827,6 +965,8 @@ pub fn panel(state: Option<&HostState>) -> HostPanelView {provided_empty: None,activity_title: None,activity: vec![],+ activity_more: None,+ activity_all: vec![],activity_warning: None,permissions_title: None,permissions: vec![],@@ -915,7 +1055,9 @@ pub fn panel(state: Option<&HostState>) -> HostPanelView {}).collect();v.clients_empty = s.clients.is_empty().then(|| "Nobody".into());- v.recent = access_rows(&s.recent_access);+ v.recent_all = access_rows(&s.recent_access);+ (v.recent, v.recent_more) = log_preview(&v.recent_all);+ v.recent_with_background = access_rows_with_background(&s.recent_access);v.recent_title = (!v.recent.is_empty()).then(|| "Recent access".into());v.access_warning = s.access_log_error@@ -958,7 +1100,8 @@ pub fn panel(state: Option<&HostState>) -> HostPanelView {v.provided = provided_rows(&s.provided_spaces);v.provided_empty = s.provided_spaces.is_empty().then(|| "None yet".into());}- v.activity = activity_rows(&s.spaces_audit);+ v.activity_all = collapse_repeats(activity_rows(&s.spaces_audit));+ (v.activity, v.activity_more) = log_preview(&v.activity_all);v.activity_title = (!v.activity.is_empty()).then(|| "Spaces activity".into());v.activity_warning = s.spaces_audit_error@@ -1677,6 +1820,180 @@ mod tests {);}+ fn access(at_ms: i64, who: &str, what: &str) -> HostAccess {+ HostAccess {+ at_ms,+ via: "relay".into(),+ who: who.into(),+ what: what.into(),+ }+ }++ #[test]+ fn accesses_are_classified_by_the_hosts_tags() {+ use HostAccessKind::*;+ for (who, what, want) in [+ (+ "Mac mini (a1)",+ "SystemService/Health (background)",+ Background,+ ),+ (+ "Mac mini (a1)",+ "SystemService/GetCapabilities (background)",+ Background,+ ),+ (+ "Mac mini (a1)",+ "HostSpacesService/GetHostSpaces (background)",+ Background,+ ),+ (+ "Mac mini (a1)",+ "PresenceService/Join (background)",+ Background,+ ),+ (+ "Mac mini (a1)",+ "ComputerService/Screenshot (thumbnail)",+ OwnerThumbnail,+ ),+ (+ "Bob (b1)",+ "ComputerService/Screenshot (thumbnail, not owner)",+ Thumbnail,+ ),+ (+ "Mac mini (a1)",+ "refused ComputerService (desktop not shared)",+ Refused,+ ),+ ("refused", "assertion expired", Refused),+ // Opening the desktop, files, a shell, agents, teleport, an+ // auto-connect's session: connections.+ ("Mac mini (a1)", "StreamService", Connection),+ ("Mac mini (a1)", "FilesystemService", Connection),+ ("Mac mini (a1)", "ProcessService", Connection),+ ("Mac mini (a1)", "DriverService", Connection),+ ("Mac mini (a1)", "TeleportService", Connection),+ ("token", "MCP", Connection),+ (+ "Mac mini (a1)",+ "SystemService/CreateViewerTicket",+ Connection,+ ),+ // An older driver's bare probe services.+ ("token", "SystemService", Background),+ ] {+ assert_eq!(access_kind(who, what), want, "{what}");+ }+ }++ #[test]+ fn repeats_collapse_and_the_log_shows_five_then_show_all() {+ // Twelve refusals in a row, then a mix.+ let mut log: Vec<HostAccess> = (0..12)+ .map(|i| {+ access(+ 1_000 - i,+ "Mac mini (a1)",+ "refused ComputerService (desktop not shared)",+ )+ })+ .collect();+ for (i, what) in [+ "SystemService/Health (background)",+ "ComputerService/Screenshot (thumbnail)",+ "StreamService",+ "FilesystemService",+ "ProcessService",+ "TeleportService",+ "DriverService",+ "ComputerService/Screenshot (thumbnail, not owner)",+ ]+ .iter()+ .enumerate()+ {+ log.push(access(900 - i as i64, "Mac mini (a1)", what));+ }+ let state = HostState {+ configured: true,+ sharing: true,+ recent_access: log,+ ..Default::default()+ };+ let v = panel(Some(&state));+ let texts: Vec<&str> = v.recent_all.iter().map(|r| r.text.as_str()).collect();+ assert_eq!(+ texts,+ [+ "Mac mini (a1) \u{b7} Screen and input refused (desktop not shared) \u{d7}12",+ "Mac mini (a1) \u{b7} Screen and input",+ "Mac mini (a1) \u{b7} Files",+ "Mac mini (a1) \u{b7} Terminal and processes",+ "Mac mini (a1) \u{b7} Teleport",+ "Mac mini (a1) \u{b7} Automation tools",+ "Mac mini (a1) viewed thumbnails",+ ],+ "background probes and the owner's thumbnails are left out"+ );+ // The newest of a collapsed run is its time.+ assert_eq!(v.recent_all[0].at_ms, 1_000);+ assert_eq!(v.recent.len(), LOG_PREVIEW_ROWS);+ assert_eq!(v.recent[..], v.recent_all[..LOG_PREVIEW_ROWS]);+ assert_eq!(v.recent_more.as_deref(), Some("Show All\u{2026}"));+ // With background: everything, still collapsed.+ assert_eq!(v.recent_with_background.len(), 9);+ assert!(+ v.recent_with_background[1]+ .text+ .ends_with("Status (background)")+ );+ // Five or fewer: no "Show All".+ let few = panel(Some(&HostState {+ recent_access: state.recent_access[..12].to_vec(),+ ..state.clone()+ }));+ assert_eq!(few.recent.len(), 1);+ assert!(few.recent_more.is_none());+ // The buttons are always there, whatever the log's length.+ assert_eq!(v.actions[0].id, HostActionId::StopSharing);+ assert_eq!(v.actions[1].id, HostActionId::Remove);+ }++ #[test]+ fn spaces_activity_collapses_and_pages_too() {+ let audit: Vec<HostSpacesAudit> = (0..9)+ .map(|i| HostSpacesAudit {+ at_ms: 100 - i,+ action: "refused".into(),+ who: "Bob".into(),+ space: "space-2".into(),+ detail: "already runs 2 macOS VMs".into(),+ })+ .chain((0..6).map(|i| HostSpacesAudit {+ at_ms: 50 - i,+ action: "create".into(),+ who: "Ada".into(),+ space: format!("space-{i}"),+ detail: String::new(),+ }))+ .collect();+ let v = panel(Some(&HostState {+ configured: true,+ spaces_audit: audit,+ ..Default::default()+ }));+ assert_eq!(v.activity_all.len(), 7);+ assert!(+ v.activity_all[0].text.ends_with("\u{d7}9"),+ "{}",+ v.activity_all[0].text+ );+ assert_eq!(v.activity.len(), LOG_PREVIEW_ROWS);+ assert_eq!(v.activity_more.as_deref(), Some(SHOW_ALL_LABEL));+ }+#[test]fn connected_now_reads_back_the_entry_the_core_built() {let input = HostSummaryInput {diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rsindex 0a2f595423..0226a96fea 100644--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs@@ -6854,8 +6854,17 @@ pub struct AppHostPanelView {pub clients_empty: Option<String>,/// "Recent access" (configured, when the log has any).pub recent_title: Option<String>,- /// Who reached this machine recently, newest first.+ /// Who reached this machine recently, newest first: the first+ /// [`LOG_PREVIEW_ROWS`] of [`Self::recent_all`].pub recent: Vec<AppHostAccessRow>,+ /// "Show All…" when `recent_all` has more than `recent` shows.+ pub recent_more: Option<String>,+ /// Every recent access (connections, refusals, other people's+ /// thumbnails), repeats collapsed: the "Show All" sheet.+ pub recent_all: Vec<AppHostAccessRow>,+ /// The same with background probes and the owner's thumbnails too+ /// (the sheet's "Include background activity").+ pub recent_with_background: Vec<AppHostAccessRow>,/// Set when the access log does not verify.pub access_warning: Option<String>,/// The two settings (configured only).@@ -6871,8 +6880,13 @@ pub struct AppHostPanelView {pub provided_empty: Option<String>,/// "Spaces activity" (when the audit has any).pub activity_title: Option<String>,- /// Remote creates, deletes and refusals, newest first.+ /// Remote creates, deletes and refusals, newest first: the first+ /// [`LOG_PREVIEW_ROWS`] of [`Self::activity_all`].pub activity: Vec<AppHostAccessRow>,+ /// "Show All…" when `activity_all` has more than `activity` shows.+ pub activity_more: Option<String>,+ /// The whole Spaces activity, repeats collapsed.+ pub activity_all: Vec<AppHostAccessRow>,/// Set when the Spaces audit does not verify.pub activity_warning: Option<String>,/// Heading over the permission rows, when any is left to grant.diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rsindex 1711d5e800..2a5ad088e7 100644--- a/libs/cua/crates/cua-spaces/src/spaces.rs+++ b/libs/cua/crates/cua-spaces/src/spaces.rs@@ -2530,14 +2530,37 @@ impl Spaces {{return Ok(t.clone());}+ // A Space whose capture failed is not asked again until its+ // backoff passes (a host that does not share its desktop refuses+ // every capture; asking each refresh only fills its access log).+ if let Some(f) = cache.backing_off(&id, std::time::Instant::now()) {+ return cached.ok_or_else(|| thumbnail_failure(&f));+ }match self.capture_thumbnail(&id).await {Ok(t) => Ok(t),Err(e) => cached.ok_or(e),}}- /// Captures and caches the Space's thumbnail now.+ /// Captures and caches the Space's thumbnail now; a failure starts the+ /// Space's backoff ([`crate::thumbnails::ThumbnailCache::fail`]).async fn capture_thumbnail(&self, id: &str) -> Result<crate::thumbnails::Thumbnail> {+ let result = self.capture_thumbnail_once(id).await;+ if let Err(e) = &result {+ let denied = matches!(+ e,+ Error::Env(cua_spacesd_client::Error::PermissionDenied(_))+ | Error::Env(cua_spacesd_client::Error::FeatureUnsupported { .. })+ | Error::CapabilityMissing { .. }+ );+ self.inner+ .thumbnails+ .fail(id, std::time::Instant::now(), denied, e.to_string());+ }+ result+ }++ async fn capture_thumbnail_once(&self, id: &str) -> Result<crate::thumbnails::Thumbnail> {use crate::thumbnails::{MAX_DIMENSION, QUALITY, Thumbnail};let space = self.space(id).await?;let shot = space@@ -2582,7 +2605,13 @@ impl Spaces {let mut captured = 0;for info in spaces {let off = matches!(info.power_state.as_str(), "suspended" | "stopped");- if off || info.spacesd_version.is_empty() || !cache.due(&info.id, now) {+ if off+ || info.spacesd_version.is_empty()+ || !cache.due(&info.id, now)+ || cache+ .backing_off(&info.id, std::time::Instant::now())+ .is_some()+ {continue;}match tokio::time::timeout(Duration::from_secs(10), self.capture_thumbnail(&info.id))@@ -2877,6 +2906,21 @@ pub fn sized_pool_key(format!("{image}\n{key}")}+/// The error a thumbnail request gets while the Space's capture backs off+/// (and nothing is cached).+fn thumbnail_failure(f: &crate::thumbnails::CaptureFailure) -> Error {+ let details = cua_spacesd_client::ErrorDetails {+ code: if f.denied { 7 } else { 14 },+ message: format!("{} (not retried for a while)", f.message),+ metadata: Default::default(),+ };+ if f.denied {+ Error::Env(cua_spacesd_client::Error::PermissionDenied(details))+ } else {+ Error::Env(cua_spacesd_client::Error::Transport(details.message))+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/libs/cua/crates/cua-spaces/src/thumbnails.rs b/libs/cua/crates/cua-spaces/src/thumbnails.rsindex fba83ab5b0..34bffb53a7 100644--- a/libs/cua/crates/cua-spaces/src/thumbnails.rs+++ b/libs/cua/crates/cua-spaces/src/thumbnails.rs@@ -36,6 +36,14 @@ pub const MAX_DIMENSION: u32 = 320;pub const QUALITY: u32 = 70;/// Disk cap for the whole cache.pub const DISK_BYTES: u64 = 32 * 1024 * 1024;+/// After a refused capture (a host that does not share its desktop, a+/// view-only share) nobody asks that Space again for this long.+pub const DENIED_BACKOFF: Duration = Duration::from_secs(15 * 60);+/// After another failed capture: the first wait, doubled per failure up to+/// [`MAX_FAILURE_BACKOFF`].+pub const FAILURE_BACKOFF: Duration = Duration::from_secs(30);+/// The longest wait after failed captures.+pub const MAX_FAILURE_BACKOFF: Duration = Duration::from_secs(10 * 60);/// One Space's latest thumbnail.#[derive(Clone, Debug, PartialEq, Eq)]@@ -83,11 +91,38 @@ struct Meta {captured_at_ms: u64,}+/// The last failed capture of a Space (cleared by a good one).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CaptureFailure {+ /// When it failed.+ pub at: Instant,+ /// Failures in a row.+ pub attempts: u32,+ /// Refused (permission denied): not retried for [`DENIED_BACKOFF`].+ pub denied: bool,+ /// Why.+ pub message: String,+}++impl CaptureFailure {+ /// How long after `at` no capture is tried.+ pub fn backoff(&self) -> Duration {+ if self.denied {+ return DENIED_BACKOFF;+ }+ let doublings = self.attempts.saturating_sub(1).min(16);+ FAILURE_BACKOFF+ .saturating_mul(1 << doublings)+ .min(MAX_FAILURE_BACKOFF)+ }+}+#[derive(Default)]struct State {entries: HashMap<String, Thumbnail>,loaded: bool,interest: Option<Instant>,+ failures: HashMap<String, CaptureFailure>,}/// The cache. Cheap to share behind the runtime's `Arc`.@@ -161,13 +196,41 @@ impl ThumbnailCache {tracing::debug!(space, error = %e, "thumbnail not written");}s.entries.insert(space.to_string(), t);+ s.failures.remove(space);self.enforce_cap(&mut s);}+ /// Notes a failed capture of the Space at `now`: it is not tried again+ /// until its backoff passes ([`Self::backing_off`]), so a host that+ /// refuses (its desktop is not shared) is not asked every tick.+ pub fn fail(&self, space: &str, now: Instant, denied: bool, message: String) {+ let mut s = self.state.lock().expect("thumbnail cache");+ let attempts = s.failures.get(space).map_or(0, |f| f.attempts) + 1;+ s.failures.insert(+ space.to_string(),+ CaptureFailure {+ at: now,+ attempts,+ denied,+ message,+ },+ );+ }++ /// The Space's last failure while its backoff runs at `now`.+ pub fn backing_off(&self, space: &str, now: Instant) -> Option<CaptureFailure> {+ let s = self.state.lock().expect("thumbnail cache");+ s.failures+ .get(space)+ .filter(|f| now.saturating_duration_since(f.at) < f.backoff())+ .cloned()+ }+/// Forgets the Space's thumbnail (a deleted or forgotten Space).pub fn remove(&self, space: &str) {let mut s = self.state();s.entries.remove(space);+ s.failures.remove(space);if let Some(dir) = &self.dir {unlink(dir, space);}@@ -335,6 +398,57 @@ mod tests {assert!(cache.due("local:a", now + BACKGROUND_INTERVAL));}+ /// A host that refuses captures (its desktop is not shared) is not+ /// asked again for [`DENIED_BACKOFF`]; other failures back off+ /// exponentially; a good capture clears it.+ #[test]+ fn failed_captures_back_off() {+ let cache = ThumbnailCache::new(None, DISK_BYTES);+ let t0 = Instant::now();+ assert!(cache.backing_off("relay:mac", t0).is_none());+ cache.fail("relay:mac", t0, true, "desktop not shared".into());+ let f = cache+ .backing_off("relay:mac", t0 + Duration::from_secs(60))+ .unwrap();+ assert!(f.denied && f.message == "desktop not shared");+ assert!(+ cache+ .backing_off("relay:mac", t0 + DENIED_BACKOFF - Duration::from_secs(1))+ .is_some()+ );+ assert!(+ cache+ .backing_off("relay:mac", t0 + DENIED_BACKOFF)+ .is_none()+ );++ for (n, want) in [+ (1, 30),+ (2, 60),+ (3, 120),+ (4, 240),+ (5, 480),+ (6, 600),+ (9, 600),+ ] {+ let f = CaptureFailure {+ at: t0,+ attempts: n,+ denied: false,+ message: String::new(),+ };+ assert_eq!(f.backoff(), Duration::from_secs(want), "{n}");+ }+ cache.fail("local:a", t0, false, "unreachable".into());+ cache.fail("local:a", t0, false, "unreachable".into());+ assert_eq!(cache.backing_off("local:a", t0).unwrap().attempts, 2);+ cache.put("local:a", shot(10, 1));+ assert!(+ cache.backing_off("local:a", t0).is_none(),+ "a good capture clears it"+ );+ }+#[test]fn interest_lapses_after_the_window() {let cache = ThumbnailCache::new(None, DISK_BYTES);diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swiftindex 4d997feaef..66a01bfb7e 100644--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift@@ -14414,9 +14414,24 @@ public struct AppHostPanelView: Equatable, Hashable {*/public var recentTitle: String?/**- * Who reached this machine recently, newest first.+ * Who reached this machine recently, newest first: the first+ * [`LOG_PREVIEW_ROWS`] of [`Self::recent_all`].*/public var recent: [AppHostAccessRow]+ /**+ * "Show All…" when `recent_all` has more than `recent` shows.+ */+ public var recentMore: String?+ /**+ * Every recent access (connections, refusals, other people's+ * thumbnails), repeats collapsed: the "Show All" sheet.+ */+ public var recentAll: [AppHostAccessRow]+ /**+ * The same with background probes and the owner's thumbnails too+ * (the sheet's "Include background activity").+ */+ public var recentWithBackground: [AppHostAccessRow]/*** Set when the access log does not verify.*/@@ -14447,9 +14462,18 @@ public struct AppHostPanelView: Equatable, Hashable {*/public var activityTitle: String?/**- * Remote creates, deletes and refusals, newest first.+ * Remote creates, deletes and refusals, newest first: the first+ * [`LOG_PREVIEW_ROWS`] of [`Self::activity_all`].*/public var activity: [AppHostAccessRow]+ /**+ * "Show All…" when `activity_all` has more than `activity` shows.+ */+ public var activityMore: String?+ /**+ * The whole Spaces activity, repeats collapsed.+ */+ public var activityAll: [AppHostAccessRow]/*** Set when the Spaces audit does not verify.*/@@ -14507,8 +14531,20 @@ public struct AppHostPanelView: Equatable, Hashable {* "Recent access" (configured, when the log has any).*/recentTitle: String?,/**- * Who reached this machine recently, newest first.+ * Who reached this machine recently, newest first: the first+ * [`LOG_PREVIEW_ROWS`] of [`Self::recent_all`].*/recent: [AppHostAccessRow],+ /**+ * "Show All…" when `recent_all` has more than `recent` shows.+ */recentMore: String?,+ /**+ * Every recent access (connections, refusals, other people's+ * thumbnails), repeats collapsed: the "Show All" sheet.+ */recentAll: [AppHostAccessRow],+ /**+ * The same with background probes and the owner's thumbnails too+ * (the sheet's "Include background activity").+ */recentWithBackground: [AppHostAccessRow],/*** Set when the access log does not verify.*/accessWarning: String?,@@ -14532,8 +14568,15 @@ public struct AppHostPanelView: Equatable, Hashable {* "Spaces activity" (when the audit has any).*/activityTitle: String?,/**- * Remote creates, deletes and refusals, newest first.+ * Remote creates, deletes and refusals, newest first: the first+ * [`LOG_PREVIEW_ROWS`] of [`Self::activity_all`].*/activity: [AppHostAccessRow],+ /**+ * "Show All…" when `activity_all` has more than `activity` shows.+ */activityMore: String?,+ /**+ * The whole Spaces activity, repeats collapsed.+ */activityAll: [AppHostAccessRow],/*** Set when the Spaces audit does not verify.*/activityWarning: String?,@@ -14564,6 +14607,9 @@ public struct AppHostPanelView: Equatable, Hashable {self.clientsEmpty = clientsEmptyself.recentTitle = recentTitleself.recent = recent+ self.recentMore = recentMore+ self.recentAll = recentAll+ self.recentWithBackground = recentWithBackgroundself.accessWarning = accessWarningself.toggles = togglesself.limits = limits@@ -14572,6 +14618,8 @@ public struct AppHostPanelView: Equatable, Hashable {self.providedEmpty = providedEmptyself.activityTitle = activityTitleself.activity = activity+ self.activityMore = activityMore+ self.activityAll = activityAllself.activityWarning = activityWarningself.permissionsTitle = permissionsTitleself.permissions = permissions@@ -14606,6 +14654,9 @@ public struct FfiConverterTypeAppHostPanelView: FfiConverterRustBuffer {clientsEmpty: FfiConverterOptionString.read(from: &buf),recentTitle: FfiConverterOptionString.read(from: &buf),recent: FfiConverterSequenceTypeAppHostAccessRow.read(from: &buf),+ recentMore: FfiConverterOptionString.read(from: &buf),+ recentAll: FfiConverterSequenceTypeAppHostAccessRow.read(from: &buf),+ recentWithBackground: FfiConverterSequenceTypeAppHostAccessRow.read(from: &buf),accessWarning: FfiConverterOptionString.read(from: &buf),toggles: FfiConverterSequenceTypeAppHostToggle.read(from: &buf),limits: FfiConverterOptionString.read(from: &buf),@@ -14614,6 +14665,8 @@ public struct FfiConverterTypeAppHostPanelView: FfiConverterRustBuffer {providedEmpty: FfiConverterOptionString.read(from: &buf),activityTitle: FfiConverterOptionString.read(from: &buf),activity: FfiConverterSequenceTypeAppHostAccessRow.read(from: &buf),+ activityMore: FfiConverterOptionString.read(from: &buf),+ activityAll: FfiConverterSequenceTypeAppHostAccessRow.read(from: &buf),activityWarning: FfiConverterOptionString.read(from: &buf),permissionsTitle: FfiConverterOptionString.read(from: &buf),permissions: FfiConverterSequenceTypeAppPermissionRow.read(from: &buf),@@ -14634,6 +14687,9 @@ public struct FfiConverterTypeAppHostPanelView: FfiConverterRustBuffer {FfiConverterOptionString.write(value.clientsEmpty, into: &buf)FfiConverterOptionString.write(value.recentTitle, into: &buf)FfiConverterSequenceTypeAppHostAccessRow.write(value.recent, into: &buf)+ FfiConverterOptionString.write(value.recentMore, into: &buf)+ FfiConverterSequenceTypeAppHostAccessRow.write(value.recentAll, into: &buf)+ FfiConverterSequenceTypeAppHostAccessRow.write(value.recentWithBackground, into: &buf)FfiConverterOptionString.write(value.accessWarning, into: &buf)FfiConverterSequenceTypeAppHostToggle.write(value.toggles, into: &buf)FfiConverterOptionString.write(value.limits, into: &buf)@@ -14642,6 +14698,8 @@ public struct FfiConverterTypeAppHostPanelView: FfiConverterRustBuffer {FfiConverterOptionString.write(value.providedEmpty, into: &buf)FfiConverterOptionString.write(value.activityTitle, into: &buf)FfiConverterSequenceTypeAppHostAccessRow.write(value.activity, into: &buf)+ FfiConverterOptionString.write(value.activityMore, into: &buf)+ FfiConverterSequenceTypeAppHostAccessRow.write(value.activityAll, into: &buf)FfiConverterOptionString.write(value.activityWarning, into: &buf)FfiConverterOptionString.write(value.permissionsTitle, into: &buf)FfiConverterSequenceTypeAppPermissionRow.write(value.permissions, into: &buf)