eguidev 0.1.0

AI-assisted development tooling and in-process instrumentation for egui apps
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
//! Diagnostic provider registry for app-owned automation state.

use std::{
    any::Any,
    collections::{BTreeMap, VecDeque},
    fmt,
    panic::{AssertUnwindSafe, catch_unwind},
    sync::{
        Arc, Mutex,
        mpsc::{self, RecvTimeoutError},
    },
    time::Duration,
};

use egui::Context;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

use crate::registry::lock;

/// Result returned by an app diagnostic provider.
pub type DiagnosticResult = Result<Value, DiagnosticError>;

/// Structured failure returned by an app diagnostic provider.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticError {
    /// Stable machine-readable error code.
    pub code: String,
    /// Human-readable error message.
    pub message: String,
    /// Optional machine-readable error details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<Value>,
}

impl DiagnosticError {
    /// Create a diagnostic error.
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            details: None,
        }
    }

    /// Attach structured error details.
    pub fn with_details(mut self, details: Value) -> Self {
        self.details = Some(details);
        self
    }

    fn provider_panic(name: &str, panic: &(dyn Any + Send)) -> Self {
        Self::new(
            "panic",
            format!(
                "diagnostic provider {name:?} panicked: {}",
                panic_message(panic)
            ),
        )
    }

    fn disconnected(name: &str) -> Self {
        Self::new(
            "internal",
            format!("diagnostic provider {name:?} did not return a result"),
        )
    }

    fn not_found(name: &str) -> Self {
        Self::new("not_found", format!("unknown diagnostic provider: {name}"))
    }
}

/// Configuration error returned while building a [`crate::DevMcp`] handle.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Error)]
#[error("{message}")]
pub struct DevMcpConfigError {
    /// Stable machine-readable error code.
    pub code: String,
    /// Human-readable error message.
    pub message: String,
    /// Optional machine-readable error details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<Value>,
}

impl DevMcpConfigError {
    pub(crate) fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            details: None,
        }
    }

    pub(crate) fn duplicate_diagnostic(name: &str) -> Self {
        Self::new(
            "duplicate_diagnostic",
            format!("duplicate diagnostic provider: {name}"),
        )
    }

    pub(crate) fn empty_diagnostic_name() -> Self {
        Self::new(
            "empty_diagnostic_name",
            "diagnostic provider name must not be empty",
        )
    }

    pub(crate) fn empty_script_prelude_namespace() -> Self {
        Self::new(
            "empty_script_prelude_namespace",
            "script prelude namespace must not be empty",
        )
    }

    pub(crate) fn invalid_script_prelude_namespace(namespace: &str) -> Self {
        Self::new(
            "invalid_script_prelude_namespace",
            format!("script prelude namespace must be a Luau identifier: {namespace}"),
        )
    }

    pub(crate) fn reserved_script_prelude_namespace(namespace: &str) -> Self {
        Self::new(
            "reserved_script_prelude_namespace",
            format!("script prelude namespace collides with built-in global: {namespace}"),
        )
    }

    pub(crate) fn duplicate_script_prelude_namespace(namespace: &str) -> Self {
        Self::new(
            "duplicate_script_prelude_namespace",
            format!("duplicate script prelude namespace: {namespace}"),
        )
    }
}

type RuntimeDiagnosticProvider = Arc<dyn Fn() -> DiagnosticResult + Send + Sync>;
type UiDiagnosticProvider = Arc<Mutex<Box<dyn FnMut(&Context) -> DiagnosticResult + Send>>>;

#[derive(Clone)]
enum DiagnosticProvider {
    Runtime(RuntimeDiagnosticProvider),
    Ui(UiDiagnosticProvider),
}

struct UiDiagnosticRequest {
    name: String,
    provider: UiDiagnosticProvider,
    sender: mpsc::Sender<DiagnosticResult>,
}

/// Pending UI-thread diagnostic result.
pub struct DiagnosticReceiver {
    name: String,
    receiver: mpsc::Receiver<DiagnosticResult>,
}

impl DiagnosticReceiver {
    /// Wait until the UI-thread provider returns or the caller's timeout expires.
    pub fn recv_timeout(self, timeout: Duration) -> DiagnosticResult {
        match self.receiver.recv_timeout(timeout) {
            Ok(result) => result,
            Err(RecvTimeoutError::Timeout) => Err(DiagnosticError::new(
                "timeout",
                format!("diagnostic provider {:?} timed out", self.name),
            )),
            Err(RecvTimeoutError::Disconnected) => Err(DiagnosticError::disconnected(&self.name)),
        }
    }
}

/// Started diagnostic execution.
pub enum DiagnosticExecution {
    /// The provider completed immediately.
    Ready(DiagnosticResult),
    /// The provider must be awaited after the UI thread drains the request.
    Queued(DiagnosticReceiver),
}

/// Registry of named app diagnostic providers.
#[derive(Clone, Default)]
pub struct DiagnosticRegistry {
    providers: Arc<Mutex<BTreeMap<String, DiagnosticProvider>>>,
    pending_ui: Arc<Mutex<VecDeque<UiDiagnosticRequest>>>,
}

impl fmt::Debug for DiagnosticRegistry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DiagnosticRegistry")
            .field(
                "providers",
                &lock(&self.providers, "diagnostic providers lock").len(),
            )
            .field(
                "pending_ui",
                &lock(&self.pending_ui, "pending diagnostic lock").len(),
            )
            .finish()
    }
}

impl DiagnosticRegistry {
    /// Create an empty diagnostic registry.
    pub fn new() -> Self {
        Self::default()
    }

    pub(crate) fn set_providers_from(&self, other: &Self) {
        let providers = lock(&other.providers, "diagnostic providers lock").clone();
        *lock(&self.providers, "diagnostic providers lock") = providers;
    }

    pub(crate) fn insert_runtime<F>(
        &self,
        name: String,
        provider: F,
    ) -> Result<(), DevMcpConfigError>
    where
        F: Fn() -> DiagnosticResult + Send + Sync + 'static,
    {
        self.insert_provider(name, DiagnosticProvider::Runtime(Arc::new(provider)))
    }

    pub(crate) fn insert_ui<F>(&self, name: String, provider: F) -> Result<(), DevMcpConfigError>
    where
        F: FnMut(&Context) -> DiagnosticResult + Send + 'static,
    {
        self.insert_provider(
            name,
            DiagnosticProvider::Ui(Arc::new(Mutex::new(Box::new(provider)))),
        )
    }

    fn insert_provider(
        &self,
        name: String,
        provider: DiagnosticProvider,
    ) -> Result<(), DevMcpConfigError> {
        if name.is_empty() {
            return Err(DevMcpConfigError::empty_diagnostic_name());
        }
        let mut providers = lock(&self.providers, "diagnostic providers lock");
        if providers.contains_key(&name) {
            return Err(DevMcpConfigError::duplicate_diagnostic(&name));
        }
        providers.insert(name, provider);
        Ok(())
    }

    /// Return sorted diagnostic provider names.
    pub fn names(&self) -> Vec<String> {
        lock(&self.providers, "diagnostic providers lock")
            .keys()
            .cloned()
            .collect()
    }

    /// Start one diagnostic provider by name.
    pub fn start(&self, name: &str) -> DiagnosticExecution {
        let provider = lock(&self.providers, "diagnostic providers lock")
            .get(name)
            .cloned();
        match provider {
            Some(DiagnosticProvider::Runtime(provider)) => {
                DiagnosticExecution::Ready(run_runtime_provider(name, &provider))
            }
            Some(DiagnosticProvider::Ui(provider)) => {
                let (sender, receiver) = mpsc::channel();
                lock(&self.pending_ui, "pending diagnostic lock").push_back(UiDiagnosticRequest {
                    name: name.to_string(),
                    provider,
                    sender,
                });
                DiagnosticExecution::Queued(DiagnosticReceiver {
                    name: name.to_string(),
                    receiver,
                })
            }
            None => DiagnosticExecution::Ready(Err(DiagnosticError::not_found(name))),
        }
    }

    /// Run every queued UI-thread diagnostic provider against the current root context.
    pub fn drain_ui(&self, ctx: &Context) {
        let requests = {
            let mut pending = lock(&self.pending_ui, "pending diagnostic lock");
            pending.drain(..).collect::<Vec<_>>()
        };
        for request in requests {
            let result = run_ui_provider(&request.name, &request.provider, ctx);
            if request.sender.send(result).is_err() {}
        }
    }
}

fn run_runtime_provider(name: &str, provider: &RuntimeDiagnosticProvider) -> DiagnosticResult {
    catch_unwind(AssertUnwindSafe(|| provider()))
        .unwrap_or_else(|panic| Err(DiagnosticError::provider_panic(name, panic.as_ref())))
}

fn run_ui_provider(name: &str, provider: &UiDiagnosticProvider, ctx: &Context) -> DiagnosticResult {
    catch_unwind(AssertUnwindSafe(|| {
        let mut provider = lock(provider, "ui diagnostic provider lock");
        provider(ctx)
    }))
    .unwrap_or_else(|panic| Err(DiagnosticError::provider_panic(name, panic.as_ref())))
}

fn panic_message(panic: &(dyn Any + Send)) -> String {
    if let Some(message) = panic.downcast_ref::<&str>() {
        return (*message).to_string();
    }
    if let Some(message) = panic.downcast_ref::<String>() {
        return message.clone();
    }
    "non-string panic payload".to_string()
}

#[cfg(test)]
mod tests {
    use std::{
        sync::{
            Arc,
            atomic::{AtomicUsize, Ordering},
        },
        time::Duration,
    };

    use serde_json::json;

    use super::{DiagnosticExecution, DiagnosticRegistry};

    #[test]
    fn registry_rejects_empty_and_duplicate_names() {
        let registry = DiagnosticRegistry::new();

        let empty = registry
            .insert_runtime(String::new(), || Ok(json!(null)))
            .expect_err("empty name");
        assert_eq!(
            empty.to_string(),
            "diagnostic provider name must not be empty"
        );

        registry
            .insert_runtime("ready".to_string(), || Ok(json!(true)))
            .expect("first provider");
        let duplicate = registry
            .insert_runtime("ready".to_string(), || Ok(json!(false)))
            .expect_err("duplicate name");
        assert_eq!(
            duplicate.to_string(),
            "duplicate diagnostic provider: ready"
        );
    }

    #[test]
    fn runtime_provider_panics_become_diagnostic_errors() {
        let registry = DiagnosticRegistry::new();
        registry
            .insert_runtime("panic".to_string(), || panic!("boom"))
            .expect("provider");

        let DiagnosticExecution::Ready(result) = registry.start("panic") else {
            panic!("runtime provider should complete immediately");
        };
        let error = result.expect_err("panic error");
        assert_eq!(error.code, "panic");
        assert!(error.message.contains("boom"));
    }

    #[test]
    fn missing_provider_returns_not_found() {
        let registry = DiagnosticRegistry::new();

        let DiagnosticExecution::Ready(result) = registry.start("missing") else {
            panic!("missing provider should complete immediately");
        };
        let error = result.expect_err("missing error");
        assert_eq!(error.code, "not_found");
        assert_eq!(error.message, "unknown diagnostic provider: missing");
    }

    #[test]
    fn ui_provider_runs_when_root_frame_drains_queue() {
        let registry = DiagnosticRegistry::new();
        let calls = Arc::new(AtomicUsize::new(0));
        let calls_for_provider = Arc::clone(&calls);
        registry
            .insert_ui("ui".to_string(), move |ctx| {
                calls_for_provider.fetch_add(1, Ordering::SeqCst);
                Ok(json!({ "pixels_per_point": ctx.pixels_per_point() }))
            })
            .expect("provider");

        let DiagnosticExecution::Queued(receiver) = registry.start("ui") else {
            panic!("ui provider should queue");
        };
        registry.drain_ui(&egui::Context::default());

        let value = receiver
            .recv_timeout(Duration::from_millis(10))
            .expect("ui result");
        assert_eq!(value, json!({ "pixels_per_point": 1.0 }));
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn syncing_providers_does_not_cancel_pending_ui_requests() {
        let registry = DiagnosticRegistry::new();
        registry
            .insert_ui("ui".to_string(), |_ctx| Ok(json!({ "ready": true })))
            .expect("provider");
        let DiagnosticExecution::Queued(receiver) = registry.start("ui") else {
            panic!("ui provider should queue");
        };

        let replacement = DiagnosticRegistry::new();
        replacement
            .insert_runtime("runtime".to_string(), || Ok(json!({ "ready": true })))
            .expect("replacement");
        registry.set_providers_from(&replacement);
        registry.drain_ui(&egui::Context::default());

        let value = receiver
            .recv_timeout(Duration::from_millis(10))
            .expect("ui result");
        assert_eq!(value, json!({ "ready": true }));
        assert_eq!(registry.names(), vec!["runtime"]);
    }
}