axterminator 0.8.0

macOS GUI testing framework with background testing, sub-millisecond element access, and self-healing locators
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Read handlers for MCP resources.
//!
//! This module contains every `read_*` function invoked by [`super::resources::read_resource`]
//! together with the helper routines they depend on.  It is intentionally
//! `pub(super)` so that only [`resources`](super::resources) can call in;
//! external callers go through the public `read_resource` dispatcher.

use std::sync::Arc;

use base64::Engine as _;
use serde_json::{json, Value};

use crate::display;
use crate::mcp::protocol::{ResourceContents, ResourceReadResult};
use crate::mcp::tools::AppRegistry;

use super::resources::ResourceError;

// ---------------------------------------------------------------------------
// Static resource handlers
// ---------------------------------------------------------------------------

pub(super) fn read_system_status(
    uri: &str,
    registry: &Arc<AppRegistry>,
) -> Result<ResourceReadResult, ResourceError> {
    let accessibility_enabled = crate::accessibility::check_accessibility_enabled();
    let connected = registry.connected_names();
    let payload = json!({
        "accessibility_enabled": accessibility_enabled,
        "server_version": env!("CARGO_PKG_VERSION"),
        "protocol_version": "2025-11-05",
        "connected_apps": connected,
        "connected_count": connected.len(),
    });

    Ok(ResourceReadResult {
        contents: vec![ResourceContents::text(
            uri,
            "application/json",
            payload.to_string(),
        )],
    })
}

pub(super) fn read_running_apps(
    uri: &str,
    _registry: &Arc<AppRegistry>,
) -> Result<ResourceReadResult, ResourceError> {
    let apps = list_running_apps();
    let payload = json!({ "apps": apps });

    Ok(ResourceReadResult {
        contents: vec![ResourceContents::text(
            uri,
            "application/json",
            payload.to_string(),
        )],
    })
}

/// Read the `axterminator://system/displays` resource.
///
/// Returns the complete list of connected displays with id, bounds
/// (in global logical-point coordinates — may have negative origin for
/// secondary monitors), scale factor, and is_primary flag.
pub(super) fn read_system_displays(uri: &str) -> Result<ResourceReadResult, ResourceError> {
    let displays = display::list_displays()
        .map_err(|e| ResourceError::operation_failed(format!("Display enumeration failed: {e}")))?;

    let display_values: Vec<Value> = displays
        .iter()
        .map(|d| {
            json!({
                "id": d.id,
                "bounds": {
                    "x": d.bounds.x,
                    "y": d.bounds.y,
                    "width": d.bounds.width,
                    "height": d.bounds.height,
                },
                "scale_factor": d.scale_factor,
                "is_primary": d.is_primary,
            })
        })
        .collect();

    let payload = json!({
        "display_count": display_values.len(),
        "displays": display_values,
    });

    Ok(ResourceReadResult {
        contents: vec![ResourceContents::text(
            uri,
            "application/json",
            payload.to_string(),
        )],
    })
}

/// Read the `axterminator://clipboard` resource.
///
/// Invokes `osascript -e 'the clipboard'` to retrieve the current pasteboard text.
/// Returns an empty string for the `text` field when the clipboard contains
/// non-text content or when the AppleScript invocation fails.
pub(super) fn read_clipboard(uri: &str) -> Result<ResourceReadResult, ResourceError> {
    let text = read_clipboard_text();
    let payload = serde_json::json!({ "text": text });
    Ok(ResourceReadResult {
        contents: vec![ResourceContents::text(
            uri,
            "application/json",
            payload.to_string(),
        )],
    })
}

/// Retrieve the current pasteboard text via `osascript`.
///
/// Returns an empty string on any failure so callers never see an error for
/// clipboard operations — the clipboard may simply contain non-text data.
fn read_clipboard_text() -> String {
    std::process::Command::new("osascript")
        .arg("-e")
        .arg("the clipboard")
        .output()
        .ok()
        .filter(|out| out.status.success())
        .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_owned())
        .unwrap_or_default()
}

/// Read the `axterminator://workflows` resource.
///
/// Locks the global `WORKFLOW_TRACKER` and returns aggregate stats plus every
/// detected cross-app workflow pattern (min frequency = 2).  An empty `workflows`
/// array is valid when fewer than two transitions have been recorded.
pub(super) fn read_workflows(uri: &str) -> Result<ResourceReadResult, ResourceError> {
    let payload = crate::mcp::tools_innovation::workflow_tracking_data();
    let body = serde_json::to_string(&payload)
        .map_err(|e| ResourceError::operation_failed(format!("Serialization failed: {e}")))?;
    Ok(ResourceReadResult {
        contents: vec![ResourceContents::text(uri, "application/json", body)],
    })
}

/// Read the `axterminator://profiles` resource.
///
/// Instantiates a [`ProfileRegistry`](crate::electron_profiles::ProfileRegistry)
/// with all built-in profiles and serialises each one to JSON, including
/// capabilities, selectors, shortcuts, and CDP port.
pub(super) fn read_profiles(uri: &str) -> Result<ResourceReadResult, ResourceError> {
    let profiles: Vec<Value> = crate::electron_profiles::builtin_profiles()
        .iter()
        .map(profile_to_json)
        .collect();

    let payload = json!({
        "profile_count": profiles.len(),
        "profiles":      profiles,
    });

    let body = serde_json::to_string(&payload)
        .map_err(|e| ResourceError::operation_failed(format!("Serialization failed: {e}")))?;

    Ok(ResourceReadResult {
        contents: vec![ResourceContents::text(uri, "application/json", body)],
    })
}

/// Serialise a single [`AppProfile`](crate::electron_profiles::AppProfile) to JSON.
fn profile_to_json(profile: &crate::electron_profiles::AppProfile) -> Value {
    use crate::electron_profiles::AppCapability;

    let capabilities: Vec<&str> = profile
        .capabilities
        .iter()
        .map(|cap| match cap {
            AppCapability::Chat => "chat",
            AppCapability::Email => "email",
            AppCapability::Calendar => "calendar",
            AppCapability::CodeEditor => "code_editor",
            AppCapability::Browser => "browser",
            AppCapability::Terminal => "terminal",
            AppCapability::FileManager => "file_manager",
            AppCapability::Custom(_) => "custom",
        })
        .collect();

    let selectors: Value = profile.selectors.iter().fold(json!({}), |mut acc, (k, v)| {
        acc[k] = json!(v);
        acc
    });

    let shortcuts: Value = profile.shortcuts.iter().fold(json!({}), |mut acc, (k, v)| {
        acc[k] = json!(v);
        acc
    });

    json!({
        "name":         profile.name,
        "app_id":       profile.app_id,
        "cdp_port":     profile.cdp_port,
        "capabilities": capabilities,
        "selectors":    selectors,
        "shortcuts":    shortcuts,
    })
}

/// Read the `axterminator://spaces` virtual desktop resource.
///
/// Lists all Spaces with id, type, active flag, and agent-created status.
/// Requires the `spaces` feature flag.
#[cfg(feature = "spaces")]
pub(super) fn read_spaces(uri: &str) -> Result<ResourceReadResult, ResourceError> {
    use crate::spaces::SpaceManager;

    let mgr = SpaceManager::new();
    let spaces = mgr
        .list_spaces()
        .map_err(|e| ResourceError::operation_failed(format!("Space enumeration failed: {e}")))?;

    let space_values: Vec<Value> = spaces
        .iter()
        .map(|s| {
            json!({
                "id": s.id,
                "type": format!("{:?}", s.space_type).to_lowercase(),
                "is_active": s.is_active,
                "is_agent_created": s.is_agent_created,
            })
        })
        .collect();

    let payload = json!({
        "space_count": space_values.len(),
        "spaces": space_values,
    });

    Ok(ResourceReadResult {
        contents: vec![ResourceContents::text(
            uri,
            "application/json",
            payload.to_string(),
        )],
    })
}

/// Read the `axterminator://audio/devices` resource.
///
/// Returns all CoreAudio input/output devices with name, ID, sample rate,
/// and default-device flags. Requires the `audio` cargo feature.
///
/// # Errors
///
/// Returns [`ResourceError::operation_failed`] when serialization fails
/// (should never occur in practice).
#[cfg(feature = "audio")]
pub(super) fn read_audio_devices(uri: &str) -> Result<ResourceReadResult, ResourceError> {
    let devices = crate::audio::list_audio_devices();
    let payload = json!({
        "device_count": devices.len(),
        "devices": devices,
    });
    let body = serde_json::to_string(&payload)
        .map_err(|e| ResourceError::operation_failed(format!("Serialization failed: {e}")))?;
    Ok(ResourceReadResult {
        contents: vec![ResourceContents::text(uri, "application/json", body)],
    })
}

/// Read `axterminator://camera/devices`.
///
/// Enumerates available video capture devices via AVFoundation. No TCC permission
/// is required for device enumeration — only capture operations need it.
#[cfg(feature = "camera")]
pub(super) fn read_camera_devices(uri: &str) -> Result<ResourceReadResult, ResourceError> {
    let payload = crate::mcp::tools_extended::camera_devices_payload();
    Ok(ResourceReadResult {
        contents: vec![ResourceContents::text(uri, "application/json", payload)],
    })
}

// ---------------------------------------------------------------------------
// Dynamic resource handlers
// ---------------------------------------------------------------------------

pub(super) fn read_dynamic(
    uri: &str,
    registry: &Arc<AppRegistry>,
) -> Result<ResourceReadResult, ResourceError> {
    // Expected pattern: axterminator://app/{name}/{resource}
    let name = super::resources::parse_app_name(uri)?;

    if uri.ends_with("/tree") {
        read_app_tree(uri, name, registry)
    } else if uri.ends_with("/screenshot") {
        read_app_screenshot(uri, name, registry)
    } else if uri.ends_with("/state") {
        read_app_state(uri, name, registry)
    } else if let Some(question) = parse_query_question(uri, name) {
        read_app_query(uri, name, question, registry)
    } else {
        Err(ResourceError::invalid_uri(uri))
    }
}

/// Extract the `{question}` segment from a `query` template URI.
///
/// Expected form: `axterminator://app/{name}/query/{question}`.
/// Returns `None` when the URI does not match this pattern or the question
/// segment is empty.
fn parse_query_question<'a>(uri: &'a str, app_name: &str) -> Option<&'a str> {
    let prefix = format!("axterminator://app/{app_name}/query/");
    let question = uri.strip_prefix(prefix.as_str())?;
    if question.is_empty() {
        None
    } else {
        Some(question)
    }
}

fn read_app_tree(
    uri: &str,
    app_name: &str,
    registry: &Arc<AppRegistry>,
) -> Result<ResourceReadResult, ResourceError> {
    registry
        .with_app(app_name, |app| {
            let tree = build_element_tree(app, 3);
            let payload = json!({
                "app": app_name,
                "depth_limit": 3,
                "tree": tree,
            });
            ResourceReadResult {
                contents: vec![ResourceContents::text(
                    uri,
                    "application/json",
                    payload.to_string(),
                )],
            }
        })
        .map_err(|_| ResourceError::not_connected(app_name))
}

fn read_app_screenshot(
    uri: &str,
    app_name: &str,
    registry: &Arc<AppRegistry>,
) -> Result<ResourceReadResult, ResourceError> {
    registry
        .with_app(app_name, |app| {
            app.screenshot_native()
                .map_err(|e| ResourceError::operation_failed(format!("Screenshot failed: {e}")))
                .map(|bytes| {
                    let b64 = base64::engine::general_purpose::STANDARD.encode::<&[u8]>(&bytes);
                    ResourceReadResult {
                        contents: vec![ResourceContents::blob(uri, "image/png", b64)],
                    }
                })
        })
        .map_err(|_| ResourceError::not_connected(app_name))?
}

fn read_app_state(
    uri: &str,
    app_name: &str,
    registry: &Arc<AppRegistry>,
) -> Result<ResourceReadResult, ResourceError> {
    // Enumerate displays once so we can annotate each window with its display.
    let displays = display::list_displays().unwrap_or_default();

    registry
        .with_app(app_name, |app| {
            let windows = app
                .windows_native()
                .unwrap_or_default()
                .iter()
                .map(|w| window_state_json(w, &displays))
                .collect::<Vec<_>>();

            let payload = json!({
                "app": app_name,
                "pid": app.pid,
                "windows": windows,
                "window_count": windows.len(),
            });

            ResourceReadResult {
                contents: vec![ResourceContents::text(
                    uri,
                    "application/json",
                    payload.to_string(),
                )],
            }
        })
        .map_err(|_| ResourceError::not_connected(app_name))
}

/// Read `axterminator://app/{name}/query/{question}`.
///
/// Builds a live [`SceneGraph`](crate::scene::SceneGraph) from the app's
/// accessibility tree and answers a percent-encoded natural-language question.
/// The `{question}` segment should be percent-encoded (spaces as `%20`).
///
/// # Errors
///
/// - [`ResourceError::not_connected`] when the app has not been registered.
/// - [`ResourceError::operation_failed`] when the accessibility scan fails.
fn read_app_query(
    uri: &str,
    app_name: &str,
    question: &str,
    registry: &Arc<AppRegistry>,
) -> Result<ResourceReadResult, ResourceError> {
    let decoded = percent_decode(question);

    registry
        .with_app(app_name, |app| {
            let scene = crate::intent::scan_scene(app.element)
                .map_err(|e| ResourceError::operation_failed(format!("scan_scene failed: {e}")))?;

            let result = crate::scene::SceneEngine::new().query(&decoded, &scene);

            let matches_json: Vec<Value> = result
                .matches
                .iter()
                .map(|m| {
                    json!({
                        "role":         m.element_role,
                        "label":        m.element_label,
                        "path":         m.element_path,
                        "match_score":  m.match_score,
                        "match_reason": m.match_reason,
                        "bounds": m.bounds.map(|(x, y, w, h)| json!([x, y, w, h])),
                    })
                })
                .collect();

            let payload = json!({
                "app":               app_name,
                "question":          decoded,
                "confidence":        result.confidence,
                "scene_description": result.scene_description,
                "matches":           matches_json,
            });

            Ok(ResourceReadResult {
                contents: vec![ResourceContents::text(
                    uri,
                    "application/json",
                    payload.to_string(),
                )],
            })
        })
        .map_err(|_| ResourceError::not_connected(app_name))?
}

/// Decode percent-encoded characters in a URI path segment.
///
/// Only replaces `%XX` sequences; non-ASCII pass through unchanged.
/// Invalid sequences are left as-is rather than returning an error.
fn percent_decode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c != '%' {
            out.push(c);
            continue;
        }
        let hi = chars.next();
        let lo = chars.next();
        match (hi, lo) {
            (Some(h), Some(l)) => {
                let hex = format!("{h}{l}");
                if let Ok(byte) = u8::from_str_radix(&hex, 16) {
                    out.push(byte as char);
                } else {
                    out.push('%');
                    out.push(h);
                    out.push(l);
                }
            }
            (Some(h), None) => {
                out.push('%');
                out.push(h);
            }
            _ => out.push('%'),
        }
    }
    out
}

/// Build the JSON state object for a single window, annotated with display info.
fn window_state_json(w: &crate::element::AXElement, displays: &[display::Display]) -> Value {
    let bounds = w.bounds();

    let display_id =
        bounds.and_then(|(x, y, _, _)| display::display_for_point(x, y, displays).map(|d| d.id));

    // For windows spanning multiple displays, include both display IDs.
    let spanning_displays: Vec<u32> = bounds
        .map(|(x, y, w_size, h_size)| {
            let rect = display::Rect {
                x,
                y,
                width: w_size,
                height: h_size,
            };
            display::displays_for_rect(&rect, displays)
                .iter()
                .map(|d| d.id)
                .collect()
        })
        .unwrap_or_default();

    json!({
        "title": w.title(),
        "role": w.role(),
        "bounds": bounds.map(|(x, y, w_size, h_size)| json!({
            "x": x, "y": y, "width": w_size, "height": h_size
        })),
        "display_id": display_id,
        "spanning_displays": spanning_displays,
    })
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Build a depth-limited element tree rooted at `app`'s accessibility element.
///
/// Returns a `Value::Null` if the tree cannot be accessed (accessibility
/// denied, app not responding, etc.). Callers should treat `null` as an
/// empty tree rather than an error, since accessibility state is inherently
/// transient.
fn build_element_tree(app: &crate::AXApp, max_depth: u32) -> Value {
    use crate::accessibility;

    let root = app.element;
    build_node(root, max_depth, 0, &accessibility::get_children)
}

/// Recursively build one tree node up to `max_depth`.
fn build_node(
    element: crate::accessibility::AXUIElementRef,
    max_depth: u32,
    current_depth: u32,
    get_children: &dyn Fn(
        crate::accessibility::AXUIElementRef,
    ) -> crate::error::AXResult<Vec<crate::accessibility::AXUIElementRef>>,
) -> Value {
    use crate::accessibility;

    let role =
        accessibility::get_string_attribute_value(element, accessibility::attributes::AX_ROLE);
    let title =
        accessibility::get_string_attribute_value(element, accessibility::attributes::AX_TITLE);
    let identifier = accessibility::get_string_attribute_value(
        element,
        accessibility::attributes::AX_IDENTIFIER,
    );

    let children = if current_depth < max_depth {
        get_children(element)
            .unwrap_or_default()
            .into_iter()
            .map(|child| build_node(child, max_depth, current_depth + 1, get_children))
            .collect::<Vec<_>>()
    } else {
        vec![]
    };

    json!({
        "role": role,
        "title": title,
        "identifier": identifier,
        "children": children,
    })
}

/// Enumerate running applications via `sysinfo`.
fn list_running_apps() -> Vec<Value> {
    use sysinfo::System;

    let mut sys = System::new();
    sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);

    sys.processes()
        .values()
        .filter_map(|proc| {
            let name = proc.name().to_string_lossy().into_owned();
            // Filter out kernel threads and very short names
            if name.is_empty() || proc.pid().as_u32() == 0 {
                return None;
            }
            Some(json!({
                "name": name,
                "pid": proc.pid().as_u32(),
            }))
        })
        .collect()
}