cueward-adapter-macos 0.3.1

macOS adapter for Cueward with Safari, Notes, Messages, Reminders, Calendar, Screenshot, Clipboard, and OCR integrations.
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
use std::thread;
use std::time::{Duration, Instant};

use crate::MacosError;
use crate::safari_guard::with_safari_session;

use super::run_capture;
use super::script::{
    build_active_tab_script, build_close_script, build_exec_script_for_profile, build_open_script,
    build_tabs_script, decode_field, escape_js_string, extract_profile, parse_tab_line,
    parse_tabs_output, selector_click_js, selector_exists_js, selector_fill_js, selector_text_js,
};
use super::types::{
    SafariClickResult, SafariCloseResult, SafariEvalResult, SafariFillResult, SafariReadResult,
    SafariScrollReadChunk, SafariScrollReadResult, SafariScrollReadSnapshot, SafariScrollResult,
    SafariSourceResult, SafariTab, SafariWaitResult,
};

pub(super) fn execute_js(js_code: &str, context: &str) -> Result<String, MacosError> {
    execute_js_for_profile(js_code, None, context)
}

pub(super) fn execute_js_for_profile(
    js_code: &str,
    profile_filter: Option<&str>,
    context: &str,
) -> Result<String, MacosError> {
    let stdout = run_capture(
        &build_exec_script_for_profile(js_code, profile_filter),
        context,
    )?;
    Ok(decode_field(stdout.trim()))
}

pub(crate) fn doctor_live_probe() -> Result<String, MacosError> {
    with_safari_session(|| execute_js("1 + 1", "safari_doctor_live"))
}

pub fn tabs(profile_filter: Option<&str>) -> Result<Vec<SafariTab>, MacosError> {
    with_safari_session(|| {
        let stdout = run_capture(&build_tabs_script(), "safari_tabs")?;
        let mut tabs = parse_tabs_output(&stdout);
        if let Some(profile) = profile_filter {
            tabs.retain(|tab| tab.profile.as_deref() == Some(profile));
        }
        Ok(tabs)
    })
}

pub fn active(profile_filter: Option<&str>) -> Result<Option<SafariTab>, MacosError> {
    with_safari_session(|| {
        let stdout = run_capture(&build_active_tab_script(profile_filter), "safari_active")?;
        Ok(parse_tab_line(stdout.trim()).map(|mut tab| {
            tab.profile = extract_profile(&tab.window_name, &tab.title);
            tab
        }))
    })
}

pub fn open(url: &str, profile_filter: Option<&str>) -> Result<Option<SafariTab>, MacosError> {
    with_safari_session(|| {
        let stdout = run_capture(&build_open_script(url, profile_filter), "safari_open")?;
        Ok(parse_tab_line(stdout.trim()).map(|mut tab| {
            tab.profile = extract_profile(&tab.window_name, &tab.title);
            tab
        }))
    })
}

/// Focus a specific tab by index or by matching URL/title substring.
/// This sets the matched tab as the current tab so subsequent operations target it.
pub fn focus_tab(
    tab_selector: &str,
    profile_filter: Option<&str>,
) -> Result<SafariTab, MacosError> {
    with_safari_session(|| {
        let all_tabs = tabs(profile_filter)?;
        if all_tabs.is_empty() {
            return Err(MacosError::Other("no Safari tabs found".to_string()));
        }

        let matched = if let Ok(index) = tab_selector.parse::<usize>() {
            all_tabs.into_iter().nth(index)
        } else {
            let query = tab_selector.to_lowercase();
            all_tabs.into_iter().find(|t| {
                t.url.to_lowercase().contains(&query) || t.title.to_lowercase().contains(&query)
            })
        };

        let tab = matched
            .ok_or_else(|| MacosError::Other(format!("no tab matching '{tab_selector}'")))?;

        let script = format!(
            r#"
        tell application "Safari"
            repeat with w in every window
                if (id of w) is {window_id} then
                    set current tab of w to tab {one_based} of w
                    set index of w to 1
                    return "true"
                end if
            end repeat
            return "false"
        end tell
        "#,
            window_id = tab.window_id,
            one_based = tab.index + 1,
        );
        let result = run_capture(&script, "safari_focus_tab")?;
        if result.trim() != "true" {
            return Err(MacosError::Other(format!(
                "failed to focus tab '{}'",
                tab_selector
            )));
        }

        Ok(tab)
    })
}

pub fn close(index: Option<usize>) -> Result<SafariCloseResult, MacosError> {
    with_safari_session(|| {
        let stdout = run_capture(&build_close_script(index), "safari_close")?;
        Ok(SafariCloseResult {
            closed: stdout.trim() == "true",
            index,
        })
    })
}

pub fn close_tabs(
    profile_filter: Option<&str>,
    url_pattern: Option<&str>,
) -> Result<usize, MacosError> {
    with_safari_session(|| {
        let all_tabs = tabs(profile_filter)?;
        let to_close: Vec<&SafariTab> = all_tabs
            .iter()
            .filter(|tab| match url_pattern {
                Some(pattern) => tab.url.contains(pattern),
                None => true,
            })
            .collect();

        let mut closed = 0;
        for tab in to_close.iter().rev() {
            let script = format!(
                r#"
            tell application "Safari"
                repeat with w in every window
                    if (id of w) is {window_id} then
                        set tabIdx to {tab_index} + 1
                        if tabIdx ≤ (count of tabs of w) then
                            close tab tabIdx of w
                        end if
                        exit repeat
                    end if
                end repeat
            end tell
            "#,
                window_id = tab.window_id,
                tab_index = tab.index,
            );
            if run_capture(&script, "safari_close_tab").is_ok() {
                closed += 1;
            }
        }

        Ok(closed)
    })
}

pub fn source(profile_filter: Option<&str>) -> Result<SafariSourceResult, MacosError> {
    with_safari_session(|| {
        let result = execute_js_for_profile(
            "document.documentElement.outerHTML",
            profile_filter,
            "safari_source",
        )?;
        Ok(SafariSourceResult { html: result })
    })
}

pub fn read(
    selector: Option<&str>,
    profile_filter: Option<&str>,
) -> Result<SafariReadResult, MacosError> {
    with_safari_session(|| {
        let js = match selector {
            Some(selector) => selector_text_js(selector),
            None => "(document.body.innerText ?? \"\").trim()".to_string(),
        };
        let content = execute_js_for_profile(&js, profile_filter, "safari_read")?;
        Ok(SafariReadResult {
            selector: selector.map(ToOwned::to_owned),
            content,
        })
    })
}

pub fn exec(js_code: &str, profile_filter: Option<&str>) -> Result<SafariEvalResult, MacosError> {
    with_safari_session(|| {
        let result = execute_js_for_profile(js_code, profile_filter, "safari_exec")?;
        Ok(SafariEvalResult { result })
    })
}

pub fn click(selector: &str) -> Result<SafariClickResult, MacosError> {
    with_safari_session(|| {
        let result = execute_js(&selector_click_js(selector), "safari_click")?;
        if result.trim() != "true" {
            return Err(MacosError::Other(result));
        }
        Ok(SafariClickResult {
            clicked: true,
            selector: selector.to_string(),
        })
    })
}

pub fn fill(selector: &str, text: &str) -> Result<SafariFillResult, MacosError> {
    with_safari_session(|| {
        let result = execute_js(&selector_fill_js(selector, text), "safari_fill")?;
        if result.trim() != "true" {
            return Err(MacosError::Other(result));
        }
        Ok(SafariFillResult {
            filled: true,
            selector: selector.to_string(),
            text: text.to_string(),
        })
    })
}

pub fn wait(selector: &str, timeout_seconds: u64) -> Result<SafariWaitResult, MacosError> {
    with_safari_session(|| {
        let deadline = Instant::now() + Duration::from_secs(timeout_seconds);
        let js = selector_exists_js(selector);
        loop {
            let exists = execute_js(&js, "safari_wait")?;
            if exists.is_empty() {
                return Err(MacosError::Other(
                    "no Safari window or active tab available".to_string(),
                ));
            }
            if exists.trim() == "true" {
                return Ok(SafariWaitResult {
                    found: true,
                    selector: selector.to_string(),
                    timeout_seconds,
                });
            }
            if Instant::now() >= deadline {
                return Err(MacosError::Other(format!(
                    "timeout waiting for selector: {selector}"
                )));
            }
            thread::sleep(Duration::from_millis(250));
        }
    })
}

fn block_fingerprint(text: &str) -> String {
    text.chars().take(120).collect()
}

pub(super) fn scroll_read_new_content_blocks(content: &str, seen: &[String]) -> Vec<String> {
    let seen_fps: Vec<String> = seen.iter().map(|s| block_fingerprint(s)).collect();
    let mut new_blocks = Vec::new();
    let mut new_fps = Vec::new();
    for block in content
        .split("\n\n")
        .map(str::trim)
        .filter(|block| !block.is_empty())
    {
        let fp = block_fingerprint(block);
        if seen_fps.iter().any(|existing| *existing == fp)
            || new_fps.iter().any(|existing: &String| *existing == fp)
        {
            continue;
        }
        new_fps.push(fp);
        new_blocks.push(block.to_string());
    }
    new_blocks
}

pub(super) fn scroll_read_snapshot_blocks(
    snapshot: &SafariScrollReadSnapshot,
    seen: &[String],
) -> Vec<String> {
    if !snapshot.blocks.is_empty() {
        let seen_fps: Vec<String> = seen.iter().map(|s| block_fingerprint(s)).collect();
        let mut new_blocks = Vec::new();
        let mut new_fps = Vec::new();
        for block in &snapshot.blocks {
            let trimmed = block.trim();
            if trimmed.is_empty() {
                continue;
            }
            let fp = block_fingerprint(trimmed);
            if seen_fps.iter().any(|existing| *existing == fp)
                || new_fps.iter().any(|existing: &String| *existing == fp)
            {
                continue;
            }
            new_fps.push(fp);
            new_blocks.push(trimmed.to_string());
        }
        return new_blocks;
    }

    scroll_read_new_content_blocks(&snapshot.content, seen)
}

pub(super) fn scroll_read_detects_new_content(
    previous_text: &str,
    previous_count: usize,
    current_text: &str,
    current_count: usize,
) -> bool {
    current_count > previous_count || current_text.trim() != previous_text.trim()
}

pub fn scroll(
    direction: &str,
    amount: Option<i64>,
    profile_filter: Option<&str>,
) -> Result<SafariScrollResult, MacosError> {
    with_safari_session(|| {
        let pixels = amount.unwrap_or(500).unsigned_abs();
        let js = match direction {
            "down" => format!("(function(){{ window.scrollBy(0, {pixels}); return JSON.stringify({{ x: Math.round(window.scrollX), y: Math.round(window.scrollY) }}); }})()"),
            "up" => format!("(function(){{ window.scrollBy(0, -{pixels}); return JSON.stringify({{ x: Math.round(window.scrollX), y: Math.round(window.scrollY) }}); }})()"),
            "top" => "(function(){ window.scrollTo(0, 0); return JSON.stringify({ x: 0, y: 0 }); })()".to_string(),
            "bottom" => "(function(){ window.scrollTo(0, document.body.scrollHeight); return JSON.stringify({ x: Math.round(window.scrollX), y: Math.round(window.scrollY) }); })()".to_string(),
            _ => return Err(MacosError::Other(format!("unknown scroll direction: {direction}. Use: up, down, top, bottom"))),
        };
        let raw = execute_js_for_profile(&js, profile_filter, "safari_scroll")?;
        let value: serde_json::Value = serde_json::from_str(&raw)
            .map_err(|e| MacosError::Other(format!("failed to parse scroll result: {e}")))?;
        Ok(SafariScrollResult {
            scroll_x: value.get("x").and_then(|v| v.as_i64()).unwrap_or(0),
            scroll_y: value.get("y").and_then(|v| v.as_i64()).unwrap_or(0),
        })
    })
}

pub(super) fn scroll_read_poll_js(selector: Option<&str>) -> String {
    let scope_expr = match selector {
        Some(selector) => format!("document.querySelector(\"{}\")", escape_js_string(selector)),
        None => "document.body".to_string(),
    };
    format!(
        r#"(() => {{
            const scope = {scope_expr};
            if (!scope) return JSON.stringify({{ item_count: 0, content: "", blocks: [] }});
            const text = (scope.innerText || scope.textContent || "").trim();
            const isVisible = (node) => {{
              const rect = node.getBoundingClientRect();
              return rect.bottom > 0 && rect.top < window.innerHeight;
            }};
            let itemNodes = [
              ...scope.querySelectorAll("shreddit-post"),
              ...scope.querySelectorAll("[data-testid='post-container']"),
              ...scope.querySelectorAll("article"),
              ...scope.querySelectorAll("[role='article']")
            ];
            if (itemNodes.length === 0) {{
              const MIN_TEXT = 50;
              const MAX_TEXT = 3000;
              itemNodes = [...scope.querySelectorAll("div")].filter(el => {{
                const t = (el.innerText || "").trim();
                if (t.length < MIN_TEXT || t.length > MAX_TEXT) return false;
                const kids = el.querySelectorAll(":scope > div");
                for (const c of kids) {{
                  if ((c.innerText || "").trim().length > t.length * 0.8) return false;
                }}
                return true;
              }});
            }}
            const visibleItemNodes = itemNodes.filter(isVisible);
            const blocks = [];
            const seen = new Set();
            for (const node of visibleItemNodes) {{
              const block = (node.innerText || node.textContent || "").trim();
              if (!block || block.length < 20) continue;
              const key = block.slice(0, 120);
              if (seen.has(key)) continue;
              seen.add(key);
              blocks.push(block);
            }}
            const itemCount = visibleItemNodes.length
              || scope.querySelectorAll("li").length
              || scope.children.length
              || 0;
            return JSON.stringify({{
              item_count: itemCount,
              content: text,
              blocks
            }});
        }})()"#
    )
}

fn parse_scroll_read_snapshot(payload: &str) -> Result<SafariScrollReadSnapshot, MacosError> {
    serde_json::from_str(payload).map_err(|error| {
        MacosError::Other(format!("invalid scroll/read payload: {error}: {payload}"))
    })
}

fn poll_scroll_read_snapshot(
    selector: Option<&str>,
    previous: &SafariScrollReadSnapshot,
    profile_filter: Option<&str>,
    timeout: Duration,
) -> Result<SafariScrollReadSnapshot, MacosError> {
    let deadline = Instant::now() + timeout;
    let js = scroll_read_poll_js(selector);

    while Instant::now() < deadline {
        thread::sleep(Duration::from_millis(500));
        let payload = execute_js_for_profile(&js, profile_filter, "safari_scroll_read_poll")?;
        let snapshot = parse_scroll_read_snapshot(&payload)?;
        if scroll_read_detects_new_content(
            &previous.content,
            previous.item_count,
            &snapshot.content,
            snapshot.item_count,
        ) {
            return Ok(snapshot);
        }
    }

    let payload = execute_js_for_profile(&js, profile_filter, "safari_scroll_read_poll")?;
    parse_scroll_read_snapshot(&payload)
}

pub fn scroll_and_read(
    times: u64,
    amount: Option<i64>,
    selector: Option<&str>,
    profile_filter: Option<&str>,
) -> Result<SafariScrollReadResult, MacosError> {
    with_safari_session(|| {
        let js = scroll_read_poll_js(selector);
        let payload = execute_js_for_profile(&js, profile_filter, "safari_scroll_read_initial")?;
        let mut snapshot = parse_scroll_read_snapshot(&payload)?;
        let mut seen = scroll_read_snapshot_blocks(&snapshot, &[]);
        let mut chunks = Vec::new();

        for iteration in 1..=times {
            scroll("down", amount, profile_filter)?;
            snapshot = poll_scroll_read_snapshot(
                selector,
                &snapshot,
                profile_filter,
                Duration::from_secs(5),
            )?;
            let new_blocks = scroll_read_snapshot_blocks(&snapshot, &seen);
            if new_blocks.is_empty() {
                continue;
            }
            seen.extend(new_blocks.iter().cloned());
            chunks.push(SafariScrollReadChunk {
                iteration,
                content: new_blocks.join("\n\n"),
            });
        }

        Ok(SafariScrollReadResult {
            selector: selector.map(ToOwned::to_owned),
            times,
            chunks,
        })
    })
}