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
//! Application event types and a thread-safe ring-buffer event log.
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
/// A single Tauri IPC call with timing, result, and source webview.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct IpcCall {
/// Unique call identifier for correlation.
pub id: String,
/// Name of the Tauri command that was invoked.
pub command: String,
/// When the call was initiated.
pub timestamp: DateTime<Utc>,
/// Round-trip duration in milliseconds, if completed.
pub duration_ms: Option<u64>,
/// Current outcome of the call (pending, ok, or error).
pub result: IpcResult,
/// Size of the serialized arguments in bytes.
pub arg_size_bytes: usize,
/// Label of the webview that initiated the call.
pub webview_label: String,
/// The call never reached the backend: a `route` rule fulfilled or blocked it in the
/// webview. `recording replay` skips such calls — replaying a mocked call would turn a
/// fake success into a real invocation.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub mocked: bool,
}
/// Outcome of an IPC call: pending, success with a JSON value, or error.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum IpcResult {
/// Call is still in flight, awaiting a response.
Pending,
/// Call completed successfully with a JSON return value.
Ok(serde_json::Value),
/// Call failed with an error message.
Err(String),
}
impl IpcCall {
/// Creates an IPC call record.
///
/// `IpcCall` is `#[non_exhaustive]`, so code outside this crate (bridges,
/// mocks, tests) builds it through this constructor rather than a struct
/// literal; fields added later get a default here instead of breaking callers.
///
/// # Examples
///
/// ```
/// use victauri_core::{IpcCall, IpcResult};
///
/// let call = IpcCall::new(
/// "c1",
/// "greet",
/// chrono::Utc::now(),
/// IpcResult::Pending,
/// None,
/// 0,
/// "main",
/// );
/// assert_eq!(call.command, "greet");
/// ```
#[must_use]
pub fn new(
id: impl Into<String>,
command: impl Into<String>,
timestamp: DateTime<Utc>,
result: IpcResult,
duration_ms: Option<u64>,
arg_size_bytes: usize,
webview_label: impl Into<String>,
) -> Self {
Self {
id: id.into(),
command: command.into(),
timestamp,
duration_ms,
result,
arg_size_bytes,
webview_label: webview_label.into(),
mocked: false,
}
}
/// Mark the call as answered by a route rule instead of the backend.
#[must_use]
pub fn with_mocked(mut self, mocked: bool) -> Self {
self.mocked = mocked;
self
}
}
impl fmt::Display for IpcResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Pending => f.write_str("pending"),
Self::Ok(_) => f.write_str("ok"),
Self::Err(msg) => write!(f, "error: {msg}"),
}
}
}
impl fmt::Display for IpcCall {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} [{}] \u{2192} {}", self.command, self.id, self.result)
}
}
impl From<IpcCall> for AppEvent {
fn from(call: IpcCall) -> Self {
Self::Ipc(call)
}
}
/// The kind of user interaction captured from the DOM.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum InteractionKind {
/// Mouse click on an element.
Click,
/// Double-click on an element.
DoubleClick,
/// Text typed into an input field.
Fill,
/// Individual key press event.
KeyPress,
/// Option selected from a dropdown.
Select,
/// Page navigation (URL change).
Navigate,
/// Scroll to element or position.
Scroll,
}
impl fmt::Display for InteractionKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Click => f.write_str("click"),
Self::DoubleClick => f.write_str("double_click"),
Self::Fill => f.write_str("fill"),
Self::KeyPress => f.write_str("key_press"),
Self::Select => f.write_str("select"),
Self::Navigate => f.write_str("navigate"),
Self::Scroll => f.write_str("scroll"),
}
}
}
/// Application event captured by the introspection layer.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum AppEvent {
/// An IPC call between webview and Rust backend.
Ipc(IpcCall),
/// A change to application state in the backend.
#[non_exhaustive]
StateChange {
/// State key that changed.
key: String,
/// When the change occurred.
timestamp: DateTime<Utc>,
/// Command or action that triggered the change, if known.
caused_by: Option<String>,
},
/// A batch of DOM mutations observed in a webview.
#[non_exhaustive]
DomMutation {
/// Webview where the mutations were observed.
webview_label: String,
/// When the mutations were observed.
timestamp: DateTime<Utc>,
/// Number of individual DOM mutations in this batch.
mutation_count: u32,
},
/// A user interaction captured from the DOM during recording.
#[non_exhaustive]
DomInteraction {
/// What kind of interaction occurred.
action: InteractionKind,
/// Best available selector for the target element (data-testid, id, CSS path).
selector: String,
/// Value associated with the interaction (typed text, selected option, URL, key name).
value: Option<String>,
/// When the interaction occurred.
timestamp: DateTime<Utc>,
/// Label of the webview where the interaction happened.
webview_label: String,
},
/// A native window lifecycle event (e.g. focus, resize, close).
#[non_exhaustive]
WindowEvent {
/// Tauri window label that emitted the event.
label: String,
/// Event name (e.g. "focus", "resize").
event: String,
/// When the event occurred.
timestamp: DateTime<Utc>,
},
/// A console log/warn/error message captured from the webview.
#[non_exhaustive]
Console {
/// Severity level: "log", "warn", or "error".
level: String,
/// The log message text.
message: String,
/// When the message was captured.
timestamp: DateTime<Utc>,
},
}
impl AppEvent {
/// Builds an [`AppEvent::StateChange`].
#[must_use]
pub fn state_change(
key: impl Into<String>,
timestamp: DateTime<Utc>,
caused_by: Option<String>,
) -> Self {
Self::StateChange {
key: key.into(),
timestamp,
caused_by,
}
}
/// Builds an [`AppEvent::DomMutation`].
#[must_use]
pub fn dom_mutation(
webview_label: impl Into<String>,
timestamp: DateTime<Utc>,
mutation_count: u32,
) -> Self {
Self::DomMutation {
webview_label: webview_label.into(),
timestamp,
mutation_count,
}
}
/// Builds an [`AppEvent::DomInteraction`].
#[must_use]
pub fn dom_interaction(
action: InteractionKind,
selector: impl Into<String>,
value: Option<String>,
timestamp: DateTime<Utc>,
webview_label: impl Into<String>,
) -> Self {
Self::DomInteraction {
action,
selector: selector.into(),
value,
timestamp,
webview_label: webview_label.into(),
}
}
/// Builds an [`AppEvent::WindowEvent`].
#[must_use]
pub fn window_event(
label: impl Into<String>,
event: impl Into<String>,
timestamp: DateTime<Utc>,
) -> Self {
Self::WindowEvent {
label: label.into(),
event: event.into(),
timestamp,
}
}
/// Builds an [`AppEvent::Console`].
///
/// # Examples
///
/// ```
/// use victauri_core::AppEvent;
///
/// let ev = AppEvent::console("warn", "deprecated", chrono::Utc::now());
/// assert!(matches!(ev, AppEvent::Console { .. }));
/// ```
#[must_use]
pub fn console(
level: impl Into<String>,
message: impl Into<String>,
timestamp: DateTime<Utc>,
) -> Self {
Self::Console {
level: level.into(),
message: message.into(),
timestamp,
}
}
/// Returns the timestamp of this event, regardless of variant.
#[must_use]
pub fn timestamp(&self) -> DateTime<Utc> {
match self {
Self::Ipc(call) => call.timestamp,
Self::StateChange { timestamp, .. }
| Self::DomMutation { timestamp, .. }
| Self::DomInteraction { timestamp, .. }
| Self::WindowEvent { timestamp, .. }
| Self::Console { timestamp, .. } => *timestamp,
}
}
/// Returns true if this event was generated by Victauri's own infrastructure
/// rather than the application under observation.
#[must_use]
pub fn is_internal(&self) -> bool {
match self {
Self::Ipc(call) => call.command.starts_with("plugin:victauri|"),
_ => false,
}
}
}
/// Thread-safe ring-buffer event log. Automatically evicts the oldest events
/// when capacity is reached. All operations recover from mutex poisoning.
#[derive(Debug, Clone)]
pub struct EventLog {
events: Arc<Mutex<VecDeque<AppEvent>>>,
max_capacity: usize,
}
impl EventLog {
/// Creates a new event log with the given maximum capacity.
///
/// ```
/// use victauri_core::EventLog;
///
/// let log = EventLog::new(100);
/// assert!(log.is_empty());
/// assert_eq!(log.capacity(), 100);
/// ```
#[must_use]
pub fn new(max_capacity: usize) -> Self {
Self {
events: Arc::new(Mutex::new(VecDeque::with_capacity(max_capacity))),
max_capacity,
}
}
/// Returns the maximum number of events this log can hold.
#[must_use]
pub fn capacity(&self) -> usize {
self.max_capacity
}
/// Appends an event, evicting the oldest if at capacity.
///
/// # Examples
///
/// ```
/// use victauri_core::{EventLog, AppEvent};
/// use chrono::Utc;
///
/// let log = EventLog::new(100);
/// log.push(AppEvent::state_change("theme", Utc::now(), None));
/// assert_eq!(log.len(), 1);
/// assert_eq!(log.snapshot().len(), 1);
/// ```
pub fn push(&self, event: AppEvent) {
let mut events = crate::acquire_lock(&self.events, "EventLog");
if events.len() >= self.max_capacity {
events.pop_front();
}
events.push_back(event);
}
/// Returns a clone of all events currently in the log.
#[must_use]
pub fn snapshot(&self) -> Vec<AppEvent> {
crate::acquire_lock(&self.events, "EventLog")
.iter()
.cloned()
.collect()
}
/// Returns a paginated slice of events starting at `offset`, up to `limit` items.
#[must_use]
pub fn snapshot_range(&self, offset: usize, limit: usize) -> Vec<AppEvent> {
crate::acquire_lock(&self.events, "EventLog")
.iter()
.skip(offset)
.take(limit)
.cloned()
.collect()
}
/// Returns all events with a timestamp at or after the given time.
#[must_use]
pub fn since(&self, timestamp: DateTime<Utc>) -> Vec<AppEvent> {
crate::acquire_lock(&self.events, "EventLog")
.iter()
.filter(|e| e.timestamp() >= timestamp)
.cloned()
.collect()
}
/// Returns all IPC call events, filtering out non-IPC events.
///
/// # Examples
///
/// ```
/// use victauri_core::{EventLog, AppEvent, IpcCall, IpcResult};
/// use chrono::Utc;
///
/// let log = EventLog::new(100);
/// log.push(AppEvent::Ipc(IpcCall::new(
/// "c1",
/// "greet",
/// Utc::now(),
/// IpcResult::Ok(serde_json::json!("hi")),
/// Some(5),
/// 0,
/// "main",
/// )));
/// assert_eq!(log.ipc_calls().len(), 1);
/// ```
#[must_use]
pub fn ipc_calls(&self) -> Vec<IpcCall> {
crate::acquire_lock(&self.events, "EventLog")
.iter()
.filter_map(|e| match e {
AppEvent::Ipc(call) => Some(call.clone()),
_ => None,
})
.collect()
}
/// Returns the newest `limit` IPC calls, oldest first.
///
/// Unlike [`ipc_calls`](Self::ipc_calls) this clones only the calls it returns (a call
/// carries its whole request/response body), so its cost is bounded by `limit`, not by the
/// size of the log.
#[must_use]
pub fn recent_ipc_calls(&self, limit: usize) -> Vec<IpcCall> {
let events = crate::acquire_lock(&self.events, "EventLog");
let mut calls: Vec<IpcCall> = events
.iter()
.rev()
.filter_map(|e| match e {
AppEvent::Ipc(call) => Some(call),
_ => None,
})
.take(limit)
.cloned()
.collect();
drop(events);
calls.reverse();
calls
}
/// Returns the distinct command names of the IPC calls in the log, without cloning the
/// calls themselves.
#[must_use]
pub fn ipc_command_names(&self) -> std::collections::BTreeSet<String> {
let events = crate::acquire_lock(&self.events, "EventLog");
let mut names = std::collections::BTreeSet::new();
for event in events.iter() {
if let AppEvent::Ipc(call) = event
&& !names.contains(call.command.as_str())
{
names.insert(call.command.clone());
}
}
names
}
/// Calls `f` on every IPC call in the log, in order, under the log's lock (so `f` must be
/// quick and must not touch the log). Nothing is cloned.
pub(crate) fn for_each_ipc_call(&self, mut f: impl FnMut(&IpcCall)) {
for event in crate::acquire_lock(&self.events, "EventLog").iter() {
if let AppEvent::Ipc(call) = event {
f(call);
}
}
}
/// Returns IPC calls with a timestamp at or after the given time.
#[must_use]
pub fn ipc_calls_since(&self, timestamp: DateTime<Utc>) -> Vec<IpcCall> {
crate::acquire_lock(&self.events, "EventLog")
.iter()
.filter_map(|e| match e {
AppEvent::Ipc(call) if call.timestamp >= timestamp => Some(call.clone()),
_ => None,
})
.collect()
}
/// Returns the number of events currently in the log.
#[must_use]
pub fn len(&self) -> usize {
crate::acquire_lock(&self.events, "EventLog").len()
}
/// Returns true if the log contains no events.
#[must_use]
pub fn is_empty(&self) -> bool {
crate::acquire_lock(&self.events, "EventLog").is_empty()
}
/// Removes all events from the log.
pub fn clear(&self) {
crate::acquire_lock(&self.events, "EventLog").clear();
}
}