victauri-plugin 0.9.0

Tauri plugin for Victauri — embedded MCP server with full-stack introspection
Documentation
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
//! Round-5 tool-result regressions (R5B-*): expression wrapping, `undefined` in assertions,
//! `wait_for` edge cases, `logs slow_ipc` window targeting, `explain diff` accounting, and
//! page-reported failures surfacing as tool errors. Each drives the real `execute_tool`
//! dispatch with a bridge that answers the page's side of the protocol.

use std::sync::Mutex as StdMutex;
use std::time::{Duration, Instant};

use serde_json::json;
use victauri_core::WindowState;

use super::*;

/// What the page answers for one eval wrapper: `(target label, wrapper script) -> callback body`
/// (`None` leaves the eval unanswered).
type Responder = Arc<dyn Fn(Option<&str>, &str) -> Option<String> + Send + Sync>;

/// A bridge that answers the liveness probe, and every eval wrapper through a [`Responder`].
#[derive(Clone)]
struct ScriptBridge {
    pending: crate::PendingCallbacks,
    respond: Responder,
    /// `(label, script)` of every eval delivered.
    evals: Arc<StdMutex<Vec<(Option<String>, String)>>>,
}

impl ScriptBridge {
    fn new(state: &Arc<VictauriState>, respond: Responder) -> Self {
        Self {
            pending: state.pending_evals.clone(),
            respond,
            evals: Arc::default(),
        }
    }

    /// A bridge that answers every eval with the same callback body.
    fn answering(state: &Arc<VictauriState>, body: &str) -> Self {
        let body = body.to_string();
        Self::new(state, Arc::new(move |_, _| Some(body.clone())))
    }

    fn answer(&self, id: String, body: String) {
        let pending = self.pending.clone();
        std::thread::spawn(move || {
            if let Some(tx) = pending.blocking_lock().remove(&id) {
                let _ = tx.send(body);
            }
        });
    }

    /// Labels of every eval whose script contains `needle`.
    fn labels_of(&self, needle: &str) -> Vec<Option<String>> {
        self.evals
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .iter()
            .filter(|(_, s)| s.contains(needle))
            .map(|(l, _)| l.clone())
            .collect()
    }
}

/// The quoted 36-char id right after `marker`.
fn quoted_id_after(script: &str, marker: &str) -> Option<String> {
    let start = script.find(marker)? + marker.len();
    script.get(start..start + 36).map(str::to_string)
}

impl WebviewBridge for ScriptBridge {
    fn eval_webview(&self, label: Option<&str>, script: &str) -> Result<(), String> {
        self.evals
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .push((label.map(str::to_string), script.to_string()));
        if script.contains("probe_ok") {
            if let Some(id) = quoted_id_after(script, "id:\"") {
                self.answer(id, "\"probe_ok:page-1\"".to_string());
            }
        } else if let Some(id) = quoted_id_after(script, "__vic = { id: \"")
            && let Some(body) = (self.respond)(label, script)
        {
            self.answer(id, body);
        }
        Ok(())
    }
    fn get_window_states(&self, _l: Option<&str>) -> Vec<WindowState> {
        Vec::new()
    }
    fn list_window_labels(&self) -> Vec<String> {
        vec!["main".to_string(), "popup".to_string()]
    }
    fn get_native_handle(&self, _l: Option<&str>) -> Result<isize, String> {
        Err("no handle".to_string())
    }
    fn manage_window(&self, _l: Option<&str>, _a: &str) -> Result<String, String> {
        Err("no window".to_string())
    }
    fn resize_window(&self, _l: Option<&str>, _w: u32, _h: u32) -> Result<(), String> {
        Ok(())
    }
    fn move_window(&self, _l: Option<&str>, _x: i32, _y: i32) -> Result<(), String> {
        Ok(())
    }
    fn set_window_title(&self, _l: Option<&str>, _t: &str) -> Result<(), String> {
        Ok(())
    }
}

fn state() -> Arc<VictauriState> {
    let mut s = VictauriState::for_tests();
    s.eval_timeout = Duration::from_secs(5);
    Arc::new(s)
}

fn handler(state: &Arc<VictauriState>, bridge: &ScriptBridge) -> VictauriMcpHandler {
    VictauriMcpHandler::new(Arc::clone(state), Arc::new(bridge.clone()))
}

async fn call(h: &VictauriMcpHandler, tool: &str, args: serde_json::Value) -> CallToolResult {
    tokio::time::timeout(Duration::from_secs(30), h.execute_tool(tool, args))
        .await
        .unwrap_or_else(|_| panic!("{tool} did not return within 30s"))
        .unwrap_or_else(|_| panic!("{tool}: dispatch rejected the arguments"))
}

fn text(r: &CallToolResult) -> String {
    r.content
        .iter()
        .filter_map(|c| match c {
            ContentBlock::Text(t) => Some(t.text.clone()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn ok_json(r: &CallToolResult) -> serde_json::Value {
    assert_ne!(r.is_error, Some(true), "unexpected tool error: {}", text(r));
    serde_json::from_str(&text(r)).unwrap_or_else(|e| panic!("not JSON ({e}): {}", text(r)))
}

// ── R5B-EXPR1: expression wrapping ─────────────────────────────────────────────────────────

/// The code the eval engine finally runs for `code` — the same `return` auto-prepend as
/// `eval_outcome`.
fn engine_code(code: &str) -> String {
    let body = strip_leading_js_comments(code.trim());
    if should_prepend_return(body) {
        format!("return {body}")
    } else {
        code.trim().to_string()
    }
}

/// Every expression in `cases` runs (in Node, inside the same async-function body the eval
/// wrapper uses) and yields 2; the invalid one is a syntax error.
#[test]
fn expression_tools_accept_trailing_semicolons_and_comments() {
    let cases = [
        "1+1",
        "1+1;",
        "1+1 // note",
        "1+1;  // note",
        "1+1; /* note */",
        "1+1;;  ",
        "1+1 /* a */ // b",
        "/* lead */ 1+1",
        "// lead\n1+1",
        "1 +\n1",
        "(1\n+ 1)",
        "[1,\n 1]\n  .length",
        "  \n 1+1 \n ",
        "'a//b'.length - 2",
        "\"x;\".length",
        "{a: 2}.a",
        "({a: 2}).a;",
        "await Promise.resolve(2)",
        "await Promise.resolve(2); // done",
    ];
    let bodies: Vec<String> = cases
        .iter()
        .map(|c| engine_code(&expression_eval_code(c)))
        .collect();
    let invalid = engine_code(&expression_eval_code("1 +"));
    let script = format!(
        "const AF = Object.getPrototypeOf(async function(){{}}).constructor;
         (async () => {{
           const out = [];
           for (const body of {bodies}) {{
             try {{ out.push(await new AF(body + '\\n')()); }}
             catch (e) {{ out.push('ERR ' + e.name + ': ' + e.message); }}
           }}
           let invalid;
           try {{ new AF({invalid} + '\\n'); invalid = 'parsed'; }}
           catch (e) {{ invalid = e.name; }}
           console.log('OUT:' + JSON.stringify({{ out, invalid }}));
         }})();",
        bodies = serde_json::to_string(&bodies).unwrap(),
        invalid = serde_json::to_string(&invalid).unwrap(),
    );
    let Ok(out) = std::process::Command::new("node")
        .arg("-e")
        .arg(&script)
        .output()
    else {
        eprintln!("SKIP: node not installed");
        return;
    };
    let stdout = String::from_utf8_lossy(&out.stdout);
    let line = stdout
        .lines()
        .find_map(|l| l.strip_prefix("OUT:"))
        .unwrap_or_else(|| {
            panic!(
                "no output: {stdout} {}",
                String::from_utf8_lossy(&out.stderr)
            )
        });
    let v: serde_json::Value = serde_json::from_str(line).unwrap();
    for (i, case) in cases.iter().enumerate() {
        assert_eq!(
            v["out"][i],
            json!(2),
            "{case:?} -> {:?}: {}",
            bodies[i],
            v["out"][i]
        );
    }
    assert_eq!(v["invalid"], "SyntaxError", "{invalid:?}");
}

/// A genuine syntax error in a `wait_for` expression fails at once, not after polling to the
/// timeout (it can never start matching).
#[tokio::test]
async fn wait_for_expression_with_a_syntax_error_fails_fast() {
    let state = state();
    let bridge = ScriptBridge::answering(
        &state,
        r#"{"__victauri_not_run":"the code did not begin executing — this almost always means a syntax/parse error in the submitted code"}"#,
    );
    let h = handler(&state, &bridge);
    let started = Instant::now();
    let r = call(
        &h,
        "wait_for",
        json!({"condition": "expression", "value": "1 +", "timeout_ms": 10_000}),
    )
    .await;
    assert_eq!(r.is_error, Some(true), "{}", text(&r));
    assert!(text(&r).contains("parse error"), "{}", text(&r));
    assert!(
        started.elapsed() < Duration::from_secs(3),
        "polled for {:?}",
        started.elapsed()
    );
}

/// A page-side exception (the target may not exist yet during startup) is still "not yet
/// met": `wait_for` keeps polling and surfaces it on timeout.
#[tokio::test]
async fn wait_for_expression_keeps_polling_through_a_page_exception() {
    let state = state();
    let bridge = ScriptBridge::answering(&state, r#"{"__victauri_err":"x is not defined"}"#);
    let h = handler(&state, &bridge);
    let r = ok_json(
        &call(
            &h,
            "wait_for",
            json!({"condition": "expression", "value": "x.ready", "timeout_ms": 300,
                   "poll_ms": 50}),
        )
        .await,
    );
    assert_eq!(r["ok"], false, "{r}");
    assert!(
        r["last_error"]
            .as_str()
            .is_some_and(|e| e.contains("x is not defined")),
        "{r}"
    );
    assert!(bridge.labels_of("x.ready").len() > 1, "did not poll");
}

// ── R5B-ASSERT1: `undefined` is a value assertions can test ────────────────────────────────

const UNDEFINED: &str = r#"{"__victauri_ok":null,"__victauri_type":"undefined"}"#;

/// An expression that evaluates to `undefined` (a missing property, an absent global) used to
/// fail with "not valid JSON", so `exists` / `falsy` could not be asserted against it. It is
/// now read as `null` — what JSON makes of it, and what JavaScript's `x == null` says.
#[tokio::test]
async fn assert_semantic_treats_undefined_as_null() {
    let state = state();
    let bridge = ScriptBridge::answering(&state, UNDEFINED);
    let h = handler(&state, &bridge);
    for (condition, expected, passes) in [
        ("exists", json!(null), false),
        ("falsy", json!(null), true),
        ("truthy", json!(null), false),
        ("equals", json!(null), true),
        ("not_equals", json!(null), false),
        ("type_is", json!("null"), true),
    ] {
        let r = ok_json(
            &call(
                &h,
                "assert_semantic",
                json!({"expression": "window.nothingHere", "condition": condition,
                       "expected": expected}),
            )
            .await,
        );
        assert_eq!(r["passed"], passes, "{condition}: {r}");
        assert_eq!(r["actual"], json!(null), "{condition}: {r}");
    }
}

/// `verify_state` reads an `undefined` frontend value the same way: it is compared (as `null`)
/// instead of failing the call.
#[tokio::test]
async fn verify_state_treats_undefined_as_null() {
    let state = state();
    let bridge = ScriptBridge::answering(&state, UNDEFINED);
    let h = handler(&state, &bridge);
    let r = ok_json(
        &call(
            &h,
            "verify_state",
            json!({"frontend_expr": "window.nothingHere", "backend_state": {"a": 1}}),
        )
        .await,
    );
    assert_eq!(r["passed"], false, "{r}");
    assert_eq!(r["frontend_state"], json!(null), "{r}");
}

// ── R5B-WAIT0: `timeout_ms: 0` is a single immediate check ─────────────────────────────────

/// The server-side conditions check exactly once with `timeout_ms: 0` (the page-side ones are
/// covered by `tests/bridge_r5b_tests.rs`), and the page-side wait is given time to answer.
#[tokio::test]
async fn wait_for_with_a_zero_timeout_checks_once() {
    let state = state();
    let bridge = ScriptBridge::new(
        &state,
        Arc::new(|_, script: &str| {
            Some(if script.contains("waitFor(") {
                json!({"__victauri_ok": {"ok": false, "error": "timeout after 0ms"},
                       "__victauri_type": "value"})
                .to_string()
            } else {
                json!({"__victauri_ok": script.contains("isReady"), "__victauri_type": "value"})
                    .to_string()
            })
        }),
    );
    let h = handler(&state, &bridge);
    let started = Instant::now();
    let met = ok_json(
        &call(
            &h,
            "wait_for",
            json!({"condition": "expression", "value": "isReady", "timeout_ms": 0}),
        )
        .await,
    );
    assert_eq!(met["ok"], true, "{met}");
    let unmet = ok_json(
        &call(
            &h,
            "wait_for",
            json!({"condition": "expression", "value": "notYet", "timeout_ms": 0}),
        )
        .await,
    );
    assert_eq!(unmet["ok"], false, "{unmet}");
    assert_eq!(
        bridge.labels_of("notYet").len(),
        1,
        "must check exactly once"
    );
    let event = ok_json(
        &call(
            &h,
            "wait_for",
            json!({"condition": "event", "value": "never", "timeout_ms": 0}),
        )
        .await,
    );
    assert_eq!(event["ok"], false, "{event}");
    let page = ok_json(
        &call(
            &h,
            "wait_for",
            json!({"condition": "selector", "value": "#x", "timeout_ms": 0}),
        )
        .await,
    );
    assert_eq!(page["ok"], false, "{page}");
    assert!(
        bridge
            .evals
            .lock()
            .unwrap()
            .iter()
            .any(|(_, s)| s.contains("timeout_ms: 0,")),
        "the page must be told 0, not a default"
    );
    assert!(
        started.elapsed() < Duration::from_secs(3),
        "{:?}",
        started.elapsed()
    );
}

// ── R5B-SLOWIPC1: `logs slow_ipc` reads the window it is asked about ───────────────────────

#[tokio::test]
async fn logs_slow_ipc_honours_webview_label() {
    let state = state();
    let bridge = ScriptBridge::answering(
        &state,
        &json!({"__victauri_ok": {"threshold_ms": 10, "count": 0, "calls": []},
                "__victauri_type": "value"})
        .to_string(),
    );
    let h = handler(&state, &bridge);
    let r = ok_json(
        &call(
            &h,
            "logs",
            json!({"action": "slow_ipc", "threshold_ms": 10, "webview_label": "popup"}),
        )
        .await,
    );
    assert_eq!(r["count"], 0, "{r}");
    assert_eq!(
        bridge.labels_of("duration_ms || 0) > 10"),
        vec![Some("popup".to_string())],
        "slow_ipc read the wrong window"
    );
}

// ── R5B-EXPLAIN1: `explain diff` counts calls and lists each command once ──────────────────

#[tokio::test]
async fn explain_diff_counts_calls_and_lists_unique_commands() {
    use victauri_core::{AppEvent, IpcCall, IpcResult};
    let state = state();
    state.recorder.start("s-1".to_string()).unwrap();
    for (i, cmd) in ["zeta", "zeta", "alpha", "zeta", "mid", "alpha", "zeta"]
        .iter()
        .enumerate()
    {
        state.event_log.push(AppEvent::Ipc(IpcCall::new(
            format!("c-{i}"),
            (*cmd).to_string(),
            chrono::Utc::now(),
            IpcResult::Ok(json!(true)),
            Some(1),
            0,
            "main".to_string(),
        )));
    }
    let bridge = ScriptBridge::answering(&state, "null");
    let h = handler(&state, &bridge);
    let r = ok_json(&call(&h, "explain", json!({"action": "diff", "seconds": 60})).await);
    assert_eq!(r["ipc_calls_made"], 7, "{r}");
    assert_eq!(r["unique_commands"], json!(["zeta", "alpha", "mid"]), "{r}");
}

// ── R5B-ISERR1: a page-reported failure is a tool error ────────────────────────────────────

fn page_value(value: &serde_json::Value) -> String {
    json!({"__victauri_ok": value, "__victauri_type": "value"}).to_string()
}

/// `interact` / `input` / `inspect` / `route add` returned the page's `{ok:false, error}` (or
/// `{error}`) as a SUCCESS result, so a refused click read as done. They now come back as
/// `isError` with the page's message and recovery hint — like `find_elements` already did.
#[tokio::test]
async fn page_reported_failures_are_tool_errors() {
    let refused = json!({"ok": false, "error": "element is covered by div.modal at (10,20)",
                         "hint": "RETRY_LATER"});
    let not_found = json!({"error": "ref not found: e9"});
    let cases = [
        (
            json!({"action": "click", "ref_id": "e9"}),
            "interact",
            refused.clone(),
        ),
        (
            json!({"action": "double_click", "ref_id": "e9"}),
            "interact",
            refused.clone(),
        ),
        (
            json!({"action": "hover", "ref_id": "e9"}),
            "interact",
            refused.clone(),
        ),
        (
            json!({"action": "focus", "ref_id": "e9"}),
            "interact",
            refused.clone(),
        ),
        (
            json!({"action": "scroll_into_view", "ref_id": "e9"}),
            "interact",
            refused.clone(),
        ),
        (
            json!({"action": "select_option", "ref_id": "e9", "value": "a"}),
            "interact",
            json!({"ok": false, "error": "element is not a <select>", "hint": "CHECK_INPUT"}),
        ),
        (
            json!({"action": "fill", "ref_id": "e9", "value": "x"}),
            "input",
            refused.clone(),
        ),
        (
            json!({"action": "type_text", "ref_id": "e9", "text": "x"}),
            "input",
            refused.clone(),
        ),
        (
            json!({"action": "press_key", "key": "Enter"}),
            "input",
            refused.clone(),
        ),
        (
            json!({"action": "get_styles", "ref_id": "e9"}),
            "inspect",
            not_found.clone(),
        ),
        (
            json!({"action": "highlight", "ref_id": "e9"}),
            "inspect",
            not_found.clone(),
        ),
        (
            json!({"action": "add", "pattern": "/api"}),
            "route",
            json!({"ok": false, "error": "fulfill status must be an integer in 200-599"}),
        ),
    ];
    for (args, tool, answer) in cases {
        let state = state();
        let bridge = ScriptBridge::answering(&state, &page_value(&answer));
        let h = handler(&state, &bridge);
        let r = call(&h, tool, args.clone()).await;
        let t = text(&r);
        assert_eq!(r.is_error, Some(true), "{tool} {args}: {t}");
        let want = answer["error"].as_str().unwrap();
        assert!(t.starts_with(want), "{tool} {args}: {t}");
        if let Some(hint) = answer["hint"].as_str() {
            assert!(
                t.ends_with(&format!("[hint: {hint}]")),
                "{tool} {args}: {t}"
            );
        }
    }
}

/// Success shapes stay successes — including partial per-item errors inside an array and
/// results that merely CONTAIN an `error` field below the top level.
#[tokio::test]
async fn page_successes_stay_successes() {
    let cases = [
        (
            json!({"action": "click", "ref_id": "e1"}),
            "interact",
            json!({"ok": true}),
        ),
        (
            json!({"action": "focus", "ref_id": "e1"}),
            "interact",
            json!({"ok": true, "tag": "input"}),
        ),
        (
            json!({"action": "get_bounding_boxes", "ref_ids": ["e1", "e2"]}),
            "inspect",
            json!([{"ref_id": "e1", "x": 1}, {"ref_id": "e2", "error": "ref not found"}]),
        ),
        (
            json!({"action": "audit_accessibility"}),
            "inspect",
            json!({"violations": [{"error": "x"}], "warnings": [], "summary": {}}),
        ),
        (
            json!({"action": "add", "pattern": "/api"}),
            "route",
            json!({"ok": true, "id": 3}),
        ),
    ];
    for (args, tool, answer) in cases {
        let state = state();
        let bridge = ScriptBridge::answering(&state, &page_value(&answer));
        let h = handler(&state, &bridge);
        let r = ok_json(&call(&h, tool, args.clone()).await);
        assert_eq!(r, answer, "{tool} {args}");
    }
}