tauri-plugin-phyto 0.1.24

Tauri plugin that exposes an HTTP automation server for Phyto end-to-end testing
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use tauri::{
    plugin::{Builder, TauriPlugin},
    Manager, Runtime, WebviewWindow,
};
use tiny_http::{Header, Response, Server};
use uuid::Uuid;

/// Wire protocol version. Kept manually in lockstep with the
/// `PROTOCOL_VERSION` constants in `crates/phyto-core/src/protocol.rs` and
/// the TS packages. The driver fetches this via `GET /info` and exits cleanly
/// on mismatch — see `packages/driver-tauri/src/index.ts`. Bump only on
/// breaking wire-format changes.
pub const PROTOCOL_VERSION: u32 = 1;

/// `Cargo.toml`-defined version of this crate. Returned alongside
/// `protocol_version` on `GET /info` so the driver can surface it in error
/// messages when versions mismatch.
const PLUGIN_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Configuration for the Phyto automation server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhytoConfig {
    /// Port for the HTTP automation server (default: 9876)
    #[serde(default = "default_port")]
    pub port: u16,
}

impl Default for PhytoConfig {
    fn default() -> Self {
        Self {
            port: default_port(),
        }
    }
}

fn default_port() -> u16 {
    9876
}

/// Response body for command results
#[derive(Debug, Serialize)]
struct CommandResponse {
    ok: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    value: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

/// Callback result received from the webview via Tauri IPC
#[derive(Debug, Clone, Deserialize)]
struct CallbackResult {
    ok: bool,
    #[serde(default)]
    value: Option<serde_json::Value>,
    #[serde(default)]
    error: Option<String>,
}

/// Shared state for pending command callbacks.
/// Wrapped in Arc so both the HTTP server thread and Tauri command can share it.
#[derive(Clone)]
pub struct PendingCallbacks {
    inner: Arc<Mutex<HashMap<String, std::sync::mpsc::Sender<CallbackResult>>>>,
}

impl PendingCallbacks {
    fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    fn insert(&self, id: String, sender: std::sync::mpsc::Sender<CallbackResult>) {
        self.inner.lock().unwrap().insert(id, sender);
    }

    fn remove(&self, id: &str) {
        self.inner.lock().unwrap().remove(id);
    }

    fn send(&self, id: &str, result: CallbackResult) {
        let callbacks = self.inner.lock().unwrap();
        if let Some(sender) = callbacks.get(id) {
            let _ = sender.send(result);
        }
    }
}

/// Shared readiness flag. Managed as Tauri state so both the HTTP server
/// thread and the `signal_ready` IPC command can access it.
#[derive(Clone)]
struct ReadinessFlag(Arc<AtomicBool>);

// ─── Tauri command: receives command results from the webview via IPC ───

#[tauri::command]
fn eval_callback(
    state: tauri::State<'_, PendingCallbacks>,
    id: String,
    ok: bool,
    value: Option<serde_json::Value>,
    error: Option<String>,
) -> Result<(), String> {
    let result = CallbackResult { ok, value, error };
    state.send(&id, result);
    Ok(())
}

/// Tauri IPC command called by the readiness probe script.
/// Uses Tauri IPC instead of HTTP fetch to avoid mixed-content blocks
/// when the app runs under `tauri://localhost` (custom-protocol).
#[tauri::command]
fn signal_ready(state: tauri::State<'_, ReadinessFlag>) -> Result<(), String> {
    log::info!("[phyto] Readiness signal received via IPC — marking ready");
    state.0.store(true, Ordering::SeqCst);
    Ok(())
}

// ─── HTTP helpers ───────────────────────────────────────────────────

fn cors_headers() -> Vec<Header> {
    vec![
        Header::from_bytes("Access-Control-Allow-Origin", "*").unwrap(),
        Header::from_bytes("Access-Control-Allow-Methods", "GET, POST, OPTIONS").unwrap(),
        Header::from_bytes("Access-Control-Allow-Headers", "Content-Type").unwrap(),
        Header::from_bytes("Content-Type", "application/json").unwrap(),
    ]
}

fn json_response(status: u16, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
    let data = body.as_bytes().to_vec();
    let mut response = Response::from_data(data).with_status_code(status);
    for header in cors_headers() {
        response.add_header(header);
    }
    response
}

/// Start the HTTP automation server in a background thread.
///
/// The server includes an IPC readiness probe: before `/health` returns 200,
/// it verifies that the webview's Tauri IPC bridge is functional by sending
/// a test eval and waiting for the callback. This prevents the harness from
/// thinking the app is ready when the page hasn't fully loaded yet
/// (common under QEMU + Xvfb where WebKitGTK init is slow).
fn start_server<R: Runtime>(
    ipc_ready: Arc<AtomicBool>,
    pending: PendingCallbacks,
    webview: WebviewWindow<R>,
) {
    let port = {
        let config = webview.state::<PhytoConfig>();
        config.port
    };

    let addr = format!("0.0.0.0:{}", port);
    let server = match Server::http(&addr) {
        Ok(s) => {
            log::info!("[phyto] Automation server listening on http://localhost:{}", port);
            s
        }
        Err(e) => {
            log::error!("[phyto] Failed to start automation server on {}: {}", addr, e);
            return;
        }
    };

    // Readiness probe thread: injects JS into the webview that signals
    // readiness via Tauri IPC (not HTTP fetch, which is blocked by
    // mixed-content policies when the app uses custom-protocol / tauri://).
    {
        let ipc_ready = ipc_ready.clone();
        let webview = webview.clone();
        thread::spawn(move || {
            let deadline = Instant::now() + Duration::from_secs(120);
            let mut probe_count = 0u32;
            while Instant::now() < deadline {
                // The probe checks three conditions:
                //  1. Page navigated away from about:blank
                //  2. Tauri IPC bridge available
                //  3. Phyto harness loaded
                // When all are true, signals readiness via Tauri IPC.
                let script = format!(
                    r#"try {{
  var __phyto_loc = location.href !== 'about:blank';
  var __phyto_tauri = !!window.__TAURI_INTERNALS__;
  var __phyto_harness = !!window.__phyto_harness__;
  var __phyto_loaded = __phyto_loc && __phyto_tauri && __phyto_harness;
  if ({probe_count} % 10 === 0) console.log('[phyto-probe] loc=' + __phyto_loc + ' tauri=' + __phyto_tauri + ' harness=' + __phyto_harness + ' loaded=' + __phyto_loaded);
  if (__phyto_loaded && __phyto_tauri) {{
    window.__TAURI_INTERNALS__.invoke('plugin:phyto|signal_ready');
  }}
}} catch(e) {{ if ({probe_count} % 10 === 0) console.log('[phyto-probe] error: ' + e.message); }}"#,
                    probe_count = probe_count,
                );

                let _ = webview.eval(&script);
                probe_count += 1;
                thread::sleep(Duration::from_millis(500));

                if ipc_ready.load(Ordering::SeqCst) {
                    log::info!("[phyto] Readiness probe succeeded after {} probes", probe_count);
                    return;
                }
            }
            log::error!("[phyto] Readiness probe timed out after 120s ({} probes)", probe_count);
        });
    }

    thread::spawn(move || {
        for mut request in server.incoming_requests() {
            let method_str = request.method().to_string();
            let url = request.url().to_string();

            // Handle CORS preflight
            if method_str == "OPTIONS" {
                let _ = request.respond(json_response(204, ""));
                continue;
            }

            // POST /__ready_probe — legacy HTTP-based readiness signal (kept for
            // apps that serve from http:// origins where fetch works fine).
            if method_str == "POST" && url == "/__ready_probe" {
                let mut probe_body = String::new();
                let _ = request.as_reader().read_to_string(&mut probe_body);

                let is_loaded = probe_body.contains("\"loaded\":true");
                if is_loaded {
                    log::info!("[phyto] Readiness probe received loaded=true via HTTP — marking ready");
                    ipc_ready.store(true, Ordering::SeqCst);
                }
                let _ = request.respond(json_response(200, r#"{"ok":true}"#));
                continue;
            }

            // GET /health — only returns 200 once webview JS context is confirmed working
            if method_str == "GET" && url == "/health" {
                if ipc_ready.load(Ordering::SeqCst) {
                    let body = serde_json::json!({ "status": "ok" }).to_string();
                    let _ = request.respond(json_response(200, &body));
                } else {
                    let body = serde_json::json!({ "status": "loading" }).to_string();
                    let _ = request.respond(json_response(503, &body));
                }
                continue;
            }

            // GET /info — returns wire-protocol and plugin metadata so the
            // external driver can verify compatibility before issuing any
            // commands. Always responds (no readiness gate) — the protocol
            // version doesn't change at runtime.
            if method_str == "GET" && url == "/info" {
                let body = serde_json::json!({
                    "protocol_version": PROTOCOL_VERSION,
                    "plugin_version": PLUGIN_VERSION,
                    "plugin": "tauri-plugin-phyto",
                })
                .to_string();
                let _ = request.respond(json_response(200, &body));
                continue;
            }

            // POST /command — forward a declarative command to the in-page harness
            if method_str == "POST" && url == "/command" {
                let mut body = String::new();
                if request.as_reader().read_to_string(&mut body).is_err() {
                    let _ = request.respond(json_response(
                        400,
                        r#"{"ok":false,"error":"Failed to read request body"}"#,
                    ));
                    continue;
                }

                // Validate it's valid JSON (the harness will handle the rest)
                let command_json: serde_json::Value = match serde_json::from_str(&body) {
                    Ok(v) => v,
                    Err(e) => {
                        let err = serde_json::json!({
                            "ok": false,
                            "error": format!("Invalid JSON: {}", e)
                        });
                        let _ = request.respond(json_response(400, &err.to_string()));
                        continue;
                    }
                };

                // Build a script that calls the harness's execute() method
                // and sends the result back via the existing IPC callback channel
                let callback_id = Uuid::new_v4().to_string();
                let (tx, rx) = std::sync::mpsc::channel::<CallbackResult>();
                pending.insert(callback_id.clone(), tx);

                let command_str = serde_json::to_string(&command_json).unwrap();
                let wrapped_script = format!(
                    r#"(async () => {{
    const __phyto_id = "{}";
    try {{
        if (!window.__phyto_harness__) {{
            throw new Error("Phyto harness not available — is the vite plugin installed?");
        }}
        const __phyto_result = await window.__phyto_harness__.execute({});
        await window.__TAURI_INTERNALS__.invoke('plugin:phyto|eval_callback', {{
            id: __phyto_id,
            ok: true,
            value: __phyto_result,
            error: null
        }});
    }} catch (__phyto_err) {{
        await window.__TAURI_INTERNALS__.invoke('plugin:phyto|eval_callback', {{
            id: __phyto_id,
            ok: false,
            value: null,
            error: __phyto_err.message || String(__phyto_err)
        }});
    }}
}})()"#,
                    callback_id, command_str
                );

                let webview_clone = webview.clone();
                let eval_result = webview_clone.eval(&wrapped_script);

                if let Err(e) = eval_result {
                    pending.remove(&callback_id);
                    let err = serde_json::json!({
                        "ok": false,
                        "error": format!("Failed to evaluate command in webview: {}", e)
                    });
                    let _ = request.respond(json_response(500, &err.to_string()));
                    continue;
                }

                match rx.recv_timeout(std::time::Duration::from_secs(30)) {
                    Ok(result) => {
                        pending.remove(&callback_id);
                        let response = CommandResponse {
                            ok: result.ok,
                            value: result.value,
                            error: result.error,
                        };
                        let body = serde_json::to_string(&response).unwrap();
                        let _ = request.respond(json_response(200, &body));
                    }
                    Err(_) => {
                        pending.remove(&callback_id);
                        let err = serde_json::json!({
                            "ok": false,
                            "error": "Command timed out after 30 seconds"
                        });
                        let _ = request.respond(json_response(500, &err.to_string()));
                    }
                }
                continue;
            }

            // 404 for everything else
            let _ = request.respond(json_response(
                404,
                r#"{"ok":false,"error":"Not found"}"#,
            ));
        }
    });
}

/// Initialize the Phyto plugin.
///
/// # Usage in your Tauri app
///
/// ```rust,ignore
/// tauri::Builder::default()
///     .plugin(tauri_plugin_phyto::init(Default::default()))
/// ```
pub fn init<R: Runtime>(config: PhytoConfig) -> TauriPlugin<R> {
    Builder::new("phyto")
        .invoke_handler(tauri::generate_handler![eval_callback, signal_ready])
        .setup(move |app, _api| {
            let pending = PendingCallbacks::new();
            let ipc_ready = Arc::new(AtomicBool::new(false));

            // Share state so Tauri commands and HTTP server can access it
            app.manage(pending.clone());
            app.manage(ReadinessFlag(ipc_ready.clone()));
            app.manage(config.clone());

            let app_handle = app.clone();
            let pending_clone = pending.clone();

            // Start the HTTP server once the main window is ready.
            // Poll for the window with retries to handle slow WebKitGTK init
            // (e.g. inside QEMU + Xvfb where startup can take several seconds).
            thread::spawn(move || {
                let deadline = Instant::now() + Duration::from_secs(10);
                loop {
                    if let Some(window) = app_handle.get_webview_window("main") {
                        start_server(ipc_ready, pending_clone, window);
                        return;
                    }
                    // Fallback: try any available window
                    let windows = app_handle.webview_windows();
                    if let Some((_label, window)) = windows.into_iter().next() {
                        start_server(ipc_ready, pending_clone, window);
                        return;
                    }
                    if Instant::now() >= deadline {
                        log::error!("[phyto] No webview window found after 10s — automation server not started");
                        return;
                    }
                    thread::sleep(Duration::from_millis(250));
                }
            });

            Ok(())
        })
        .build()
}