enya-plugin 0.1.7

Plugin system for Enya editor
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! Core types for the plugin system.
//!
//! These types are designed to be independent of any specific editor implementation,
//! allowing the plugin system to be used in different contexts.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use std::collections::BTreeMap;

use rustc_hash::FxHashMap;

/// Notification level for user-facing messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotificationLevel {
    Info,
    Warning,
    Error,
}

impl NotificationLevel {
    /// Parse a notification level from a string.
    pub fn parse(s: &str) -> Self {
        match s {
            "error" => Self::Error,
            "warn" | "warning" => Self::Warning,
            _ => Self::Info,
        }
    }
}

/// Log level for plugin logging.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
    Debug,
    Info,
    Warn,
    Error,
}

impl LogLevel {
    /// Parse a log level from a string (case-insensitive).
    pub fn parse(s: &str) -> Self {
        match s.to_ascii_lowercase().as_str() {
            "debug" => Self::Debug,
            "warn" | "warning" => Self::Warn,
            "error" => Self::Error,
            _ => Self::Info,
        }
    }
}

/// Application theme.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Theme {
    #[default]
    Dark,
    Light,
    /// Custom theme identified by name
    Custom,
}

/// A boxed future for async operations.
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;

/// HTTP response returned from http_get/http_post.
#[derive(Debug, Clone)]
pub struct HttpResponse {
    /// HTTP status code (e.g., 200, 404, 500)
    pub status: u16,
    /// Response body as a string
    pub body: String,
    /// Response headers
    pub headers: FxHashMap<String, String>,
}

/// HTTP request error.
#[derive(Debug, Clone)]
pub struct HttpError {
    /// Error message
    pub message: String,
}

// ==================== Custom Pane Types ====================

/// Column configuration for a custom table pane.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TableColumnConfig {
    /// Column header name
    pub name: String,
    /// Key to look up in row data (optional, defaults to name)
    pub key: Option<String>,
    /// Optional fixed width in pixels (as integer for Hash/Eq)
    pub width: Option<u32>,
}

impl TableColumnConfig {
    /// Create a new column configuration.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            key: None,
            width: None,
        }
    }

    /// Set the data key for this column.
    pub fn with_key(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }

    /// Set the width for this column (in pixels).
    pub fn with_width(mut self, width: u32) -> Self {
        self.width = Some(width);
        self
    }

    /// Get the width as f32 for rendering.
    pub fn width_f32(&self) -> Option<f32> {
        self.width.map(|w| w as f32)
    }

    /// Get the key to use for looking up data (falls back to name).
    pub fn data_key(&self) -> &str {
        self.key.as_deref().unwrap_or(&self.name)
    }
}

/// Configuration for a custom table pane type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CustomTableConfig {
    /// Unique identifier for this pane type
    pub name: String,
    /// Display title for the pane
    pub title: String,
    /// Column definitions
    pub columns: Vec<TableColumnConfig>,
    /// Auto-refresh interval in seconds (0 = manual only)
    pub refresh_interval: u32,
    /// Plugin that registered this pane type
    pub plugin_name: String,
}

/// A single row of data for a custom table.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct CustomTableRow {
    /// Cell values keyed by column key (BTreeMap for deterministic ordering and Hash)
    pub cells: BTreeMap<String, String>,
}

impl CustomTableRow {
    /// Create a new empty row.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a cell value.
    pub fn with_cell(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.cells.insert(key.into(), value.into());
        self
    }

    /// Get a cell value by key.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.cells.get(key).map(|s| s.as_str())
    }
}

/// Data returned by a custom table pane's fetch function.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CustomTableData {
    /// Rows of data
    pub rows: Vec<CustomTableRow>,
    /// Error message if fetch failed
    pub error: Option<String>,
}

impl CustomTableData {
    /// Create successful table data with rows.
    pub fn with_rows(rows: Vec<CustomTableRow>) -> Self {
        Self { rows, error: None }
    }

    /// Create error result.
    pub fn with_error(message: impl Into<String>) -> Self {
        Self {
            rows: Vec::new(),
            error: Some(message.into()),
        }
    }
}

// ==================== Custom Chart Pane Types ====================

/// A single data point in a chart series.
#[derive(Debug, Clone, PartialEq)]
pub struct ChartDataPoint {
    /// Unix timestamp in seconds
    pub timestamp: f64,
    /// Value at this timestamp
    pub value: f64,
}

impl ChartDataPoint {
    /// Create a new data point.
    pub fn new(timestamp: f64, value: f64) -> Self {
        Self { timestamp, value }
    }
}

/// A single series in a chart (line).
#[derive(Debug, Clone, PartialEq)]
pub struct ChartSeries {
    /// Display name for the series
    pub name: String,
    /// Tags/labels for the series (BTreeMap for deterministic ordering)
    pub tags: BTreeMap<String, String>,
    /// Data points in the series
    pub points: Vec<ChartDataPoint>,
}

impl ChartSeries {
    /// Create a new series with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            tags: BTreeMap::new(),
            points: Vec::new(),
        }
    }

    /// Add a tag/label to the series.
    pub fn with_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.tags.insert(key.into(), value.into());
        self
    }

    /// Add a data point to the series.
    pub fn with_point(mut self, timestamp: f64, value: f64) -> Self {
        self.points.push(ChartDataPoint::new(timestamp, value));
        self
    }

    /// Add multiple data points to the series.
    pub fn with_points(mut self, points: Vec<ChartDataPoint>) -> Self {
        self.points.extend(points);
        self
    }
}

/// Configuration for a custom chart pane type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CustomChartConfig {
    /// Unique identifier for this pane type
    pub name: String,
    /// Display title for the pane
    pub title: String,
    /// Unit label for the Y-axis (e.g., "ms", "bytes", "%")
    pub y_unit: Option<String>,
    /// Auto-refresh interval in seconds (0 = manual only)
    pub refresh_interval: u32,
    /// Plugin that registered this pane type
    pub plugin_name: String,
}

/// Data to display in a custom chart pane.
#[derive(Debug, Clone, PartialEq)]
pub struct CustomChartData {
    /// Series to display
    pub series: Vec<ChartSeries>,
    /// Error message if fetch failed
    pub error: Option<String>,
}

impl CustomChartData {
    /// Create chart data with series.
    pub fn with_series(series: Vec<ChartSeries>) -> Self {
        Self {
            series,
            error: None,
        }
    }

    /// Create error result.
    pub fn with_error(message: impl Into<String>) -> Self {
        Self {
            series: Vec::new(),
            error: Some(message.into()),
        }
    }
}

// ==================== Custom Stat Pane Types ====================

/// Threshold configuration for stat/gauge visualizations.
#[derive(Debug, Clone, PartialEq)]
pub struct ThresholdConfig {
    /// Value at which this threshold applies
    pub value: f64,
    /// Color name: "green", "yellow", "red", "blue", or hex "#RRGGBB"
    pub color: String,
    /// Optional label for the threshold
    pub label: Option<String>,
}

impl ThresholdConfig {
    /// Create a new threshold.
    pub fn new(value: f64, color: impl Into<String>) -> Self {
        Self {
            value,
            color: color.into(),
            label: None,
        }
    }

    /// Set a label for this threshold.
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }
}

/// Configuration for a custom stat pane type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StatPaneConfig {
    /// Unique identifier for this pane type
    pub name: String,
    /// Display title for the pane
    pub title: String,
    /// Unit label (e.g., "jobs", "ms", "%")
    pub unit: Option<String>,
    /// Auto-refresh interval in seconds (0 = manual only)
    pub refresh_interval: u32,
    /// Plugin that registered this pane type
    pub plugin_name: String,
}

/// Data to display in a stat pane.
#[derive(Debug, Clone, PartialEq)]
pub struct StatPaneData {
    /// Current value to display
    pub value: f64,
    /// Sparkline data (recent history)
    pub sparkline: Vec<f64>,
    /// Change from previous period (percentage)
    pub change_value: Option<f64>,
    /// Description of change period (e.g., "vs last hour")
    pub change_period: Option<String>,
    /// Thresholds for coloring the value
    pub thresholds: Vec<ThresholdConfig>,
    /// Error message if fetch failed
    pub error: Option<String>,
}

impl Default for StatPaneData {
    fn default() -> Self {
        Self {
            value: 0.0,
            sparkline: Vec::new(),
            change_value: None,
            change_period: None,
            thresholds: Vec::new(),
            error: None,
        }
    }
}

impl StatPaneData {
    /// Create stat data with a value.
    pub fn with_value(value: f64) -> Self {
        Self {
            value,
            ..Default::default()
        }
    }

    /// Create error result.
    pub fn with_error(message: impl Into<String>) -> Self {
        Self {
            error: Some(message.into()),
            ..Default::default()
        }
    }

    /// Set sparkline data.
    pub fn sparkline(mut self, data: Vec<f64>) -> Self {
        self.sparkline = data;
        self
    }

    /// Set change indicator.
    pub fn change(mut self, value: f64, period: impl Into<String>) -> Self {
        self.change_value = Some(value);
        self.change_period = Some(period.into());
        self
    }

    /// Add a threshold.
    pub fn threshold(mut self, threshold: ThresholdConfig) -> Self {
        self.thresholds.push(threshold);
        self
    }
}

// ==================== Focused Pane Info ====================

/// Information about the currently focused pane.
/// Used for sharing context to external services like Slack/Discord.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FocusedPaneInfo {
    /// Type of the pane (e.g., "query", "logs", "tracing", "terminal", "sql", "custom_table")
    pub pane_type: String,
    /// Display title of the pane (if any)
    pub title: Option<String>,
    /// Query string (for query panes)
    pub query: Option<String>,
    /// Metric name (for query panes, extracted from PromQL)
    pub metric_name: Option<String>,
}

impl FocusedPaneInfo {
    /// Create a new focused pane info.
    pub fn new(pane_type: impl Into<String>) -> Self {
        Self {
            pane_type: pane_type.into(),
            title: None,
            query: None,
            metric_name: None,
        }
    }

    /// Set the title.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the query.
    pub fn with_query(mut self, query: impl Into<String>) -> Self {
        self.query = Some(query.into());
        self
    }

    /// Set the metric name.
    pub fn with_metric_name(mut self, metric_name: impl Into<String>) -> Self {
        self.metric_name = Some(metric_name.into());
        self
    }
}

// ==================== Custom Gauge Pane Types ====================

/// Configuration for a custom gauge pane type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GaugePaneConfig {
    /// Unique identifier for this pane type
    pub name: String,
    /// Display title for the pane
    pub title: String,
    /// Unit label (e.g., "%", "MB", "req/s")
    pub unit: Option<String>,
    /// Minimum value of the gauge range (stored as scaled i64 for Hash)
    pub min_scaled: i64,
    /// Maximum value of the gauge range (stored as scaled i64 for Hash)
    pub max_scaled: i64,
    /// Auto-refresh interval in seconds (0 = manual only)
    pub refresh_interval: u32,
    /// Plugin that registered this pane type
    pub plugin_name: String,
}

/// Scale factor for converting f64 to i64 for hashable storage.
const GAUGE_SCALE_FACTOR: f64 = 1_000_000.0;

impl GaugePaneConfig {
    /// Get minimum value as f64.
    pub fn min(&self) -> f64 {
        self.min_scaled as f64 / GAUGE_SCALE_FACTOR
    }

    /// Get maximum value as f64.
    pub fn max(&self) -> f64 {
        self.max_scaled as f64 / GAUGE_SCALE_FACTOR
    }

    /// Set range from f64 values.
    /// Values are clamped to representable range to avoid overflow.
    pub fn set_range(&mut self, min: f64, max: f64) {
        self.min_scaled = scale_f64_to_i64(min);
        self.max_scaled = scale_f64_to_i64(max);
    }
}

/// Safely scale an f64 value to i64, clamping to representable range.
/// Handles NaN, infinity, and values that would overflow after scaling.
fn scale_f64_to_i64(value: f64) -> i64 {
    if value.is_nan() {
        return 0;
    }
    let scaled = value * GAUGE_SCALE_FACTOR;
    if scaled >= i64::MAX as f64 {
        i64::MAX
    } else if scaled <= i64::MIN as f64 {
        i64::MIN
    } else {
        scaled as i64
    }
}

/// Data to display in a gauge pane.
#[derive(Debug, Clone, PartialEq)]
pub struct GaugePaneData {
    /// Current value
    pub value: f64,
    /// Thresholds for coloring
    pub thresholds: Vec<ThresholdConfig>,
    /// Error message if fetch failed
    pub error: Option<String>,
}

impl Default for GaugePaneData {
    fn default() -> Self {
        Self {
            value: 0.0,
            thresholds: Vec::new(),
            error: None,
        }
    }
}

impl GaugePaneData {
    /// Create gauge data with a value.
    pub fn with_value(value: f64) -> Self {
        Self {
            value,
            ..Default::default()
        }
    }

    /// Create error result.
    pub fn with_error(message: impl Into<String>) -> Self {
        Self {
            error: Some(message.into()),
            ..Default::default()
        }
    }

    /// Add a threshold.
    pub fn threshold(mut self, threshold: ThresholdConfig) -> Self {
        self.thresholds.push(threshold);
        self
    }
}

/// Trait for the host application to implement.
///
/// This provides the interface that plugins use to interact with the host
/// (typically the Enya editor). The host implements this trait and provides
/// it to plugins via the `PluginContext`.
pub trait PluginHost: Send + Sync {
    /// Send a notification to the user.
    fn notify(&self, level: NotificationLevel, message: &str);

    /// Request a UI repaint.
    fn request_repaint(&self);

    /// Log a message.
    fn log(&self, level: LogLevel, message: &str);

    /// Get the host application version.
    fn version(&self) -> &'static str;

    /// Check if running in WASM environment.
    fn is_wasm(&self) -> bool;

    /// Get the current theme.
    fn theme(&self) -> Theme;

    /// Get the current theme name as a string (e.g., "tokyo-night", "catppuccin").
    fn theme_name(&self) -> &'static str;

    /// Write text to the system clipboard.
    /// Returns true if successful, false if clipboard is unavailable.
    fn clipboard_write(&self, text: &str) -> bool;

    /// Read text from the system clipboard.
    /// Returns None if clipboard is empty or unavailable.
    fn clipboard_read(&self) -> Option<String>;

    /// Spawn an async task (may not be available in all environments).
    fn spawn(&self, future: BoxFuture<()>);

    /// Perform an HTTP GET request.
    /// Returns the response or an error message.
    fn http_get(
        &self,
        url: &str,
        headers: &FxHashMap<String, String>,
    ) -> Result<HttpResponse, HttpError>;

    /// Perform an HTTP POST request.
    /// Returns the response or an error message.
    fn http_post(
        &self,
        url: &str,
        body: &str,
        headers: &FxHashMap<String, String>,
    ) -> Result<HttpResponse, HttpError>;

    // ==================== Pane Management ====================

    /// Add a query pane with the given PromQL query and optional title.
    fn add_query_pane(&self, query: &str, title: Option<&str>);

    /// Add a logs pane.
    fn add_logs_pane(&self);

    /// Add a tracing pane, optionally pre-filled with a trace ID.
    fn add_tracing_pane(&self, trace_id: Option<&str>);

    /// Add a terminal pane (native only, no-op on WASM).
    fn add_terminal_pane(&self);

    /// Add a SQL pane.
    fn add_sql_pane(&self);

    /// Close the currently focused pane.
    fn close_focused_pane(&self);

    /// Focus pane in the given direction ("left", "right", "up", "down").
    fn focus_pane(&self, direction: &str);

    // ==================== Time Range ====================

    /// Set time range to a preset (e.g., "5m", "15m", "1h", "6h", "24h", "7d").
    fn set_time_range_preset(&self, preset: &str);

    /// Set absolute time range (start and end in seconds since Unix epoch).
    fn set_time_range_absolute(&self, start_secs: f64, end_secs: f64);

    /// Get the current time range as (start_secs, end_secs).
    /// Note: This returns cached values; may not reflect real-time updates.
    fn get_time_range(&self) -> (f64, f64);

    // ==================== Custom Panes ====================

    /// Register a custom table pane type.
    fn register_custom_table_pane(&self, config: CustomTableConfig);

    /// Add an instance of a custom table pane.
    fn add_custom_table_pane(&self, pane_type: &str);

    /// Update data for a custom table pane by pane ID.
    /// Called by plugins when they have new data to display.
    fn update_custom_table_data(&self, pane_id: usize, data: CustomTableData);

    /// Update data for all custom table panes of a given type.
    /// Called by plugins when they have new data to display.
    fn update_custom_table_data_by_type(&self, pane_type: &str, data: CustomTableData);

    // ==================== Custom Chart Panes ====================

    /// Register a custom chart pane type.
    fn register_custom_chart_pane(&self, config: CustomChartConfig);

    /// Add an instance of a custom chart pane.
    fn add_custom_chart_pane(&self, pane_type: &str);

    /// Update data for all custom chart panes of a given type.
    fn update_custom_chart_data_by_type(&self, pane_type: &str, data: CustomChartData);

    // ==================== Custom Stat Panes ====================

    /// Register a custom stat pane type.
    fn register_stat_pane(&self, config: StatPaneConfig);

    /// Add an instance of a stat pane.
    fn add_stat_pane(&self, pane_type: &str);

    /// Update data for all stat panes of a given type.
    fn update_stat_data_by_type(&self, pane_type: &str, data: StatPaneData);

    // ==================== Custom Gauge Panes ====================

    /// Register a custom gauge pane type.
    fn register_gauge_pane(&self, config: GaugePaneConfig);

    /// Add an instance of a gauge pane.
    fn add_gauge_pane(&self, pane_type: &str);

    /// Update data for all gauge panes of a given type.
    fn update_gauge_data_by_type(&self, pane_type: &str, data: GaugePaneData);

    // ==================== Focused Pane ====================

    /// Get information about the currently focused pane.
    /// Returns None if no pane is focused.
    fn get_focused_pane_info(&self) -> Option<FocusedPaneInfo>;
}

/// Reference-counted plugin host.
pub type PluginHostRef = Arc<dyn PluginHost>;

/// Context provided to plugins for interacting with the host.
pub struct PluginContext {
    host: PluginHostRef,
}

impl PluginContext {
    /// Create a new plugin context with the given host.
    pub fn new(host: PluginHostRef) -> Self {
        Self { host }
    }

    /// Send a notification to the user.
    pub fn notify(&self, level: &str, message: &str) {
        self.host.notify(NotificationLevel::parse(level), message);
    }

    /// Request a UI repaint.
    pub fn request_repaint(&self) {
        self.host.request_repaint();
    }

    /// Log a message.
    pub fn log(&self, level: LogLevel, message: &str) {
        self.host.log(level, message);
    }

    /// Get the host application version.
    pub fn editor_version(&self) -> &'static str {
        self.host.version()
    }

    /// Check if running in WASM environment.
    pub fn is_wasm(&self) -> bool {
        self.host.is_wasm()
    }

    /// Get the current theme.
    pub fn theme(&self) -> Theme {
        self.host.theme()
    }

    /// Get the current theme name as a string.
    pub fn theme_name(&self) -> &'static str {
        self.host.theme_name()
    }

    /// Write text to the system clipboard.
    pub fn clipboard_write(&self, text: &str) -> bool {
        self.host.clipboard_write(text)
    }

    /// Read text from the system clipboard.
    pub fn clipboard_read(&self) -> Option<String> {
        self.host.clipboard_read()
    }

    /// Spawn an async task.
    pub fn spawn<F>(&self, future: F)
    where
        F: Future<Output = ()> + Send + 'static,
    {
        self.host.spawn(Box::pin(future));
    }

    /// Get a reference to the underlying host.
    pub fn host(&self) -> &PluginHostRef {
        &self.host
    }

    /// Perform an HTTP GET request.
    pub fn http_get(
        &self,
        url: &str,
        headers: &FxHashMap<String, String>,
    ) -> Result<HttpResponse, HttpError> {
        self.host.http_get(url, headers)
    }

    /// Perform an HTTP POST request.
    pub fn http_post(
        &self,
        url: &str,
        body: &str,
        headers: &FxHashMap<String, String>,
    ) -> Result<HttpResponse, HttpError> {
        self.host.http_post(url, body, headers)
    }

    // ==================== Pane Management ====================

    /// Add a query pane with the given PromQL query and optional title.
    pub fn add_query_pane(&self, query: &str, title: Option<&str>) {
        self.host.add_query_pane(query, title);
    }

    /// Add a logs pane.
    pub fn add_logs_pane(&self) {
        self.host.add_logs_pane();
    }

    /// Add a tracing pane, optionally pre-filled with a trace ID.
    pub fn add_tracing_pane(&self, trace_id: Option<&str>) {
        self.host.add_tracing_pane(trace_id);
    }

    /// Add a terminal pane (native only, no-op on WASM).
    pub fn add_terminal_pane(&self) {
        self.host.add_terminal_pane();
    }

    /// Add a SQL pane.
    pub fn add_sql_pane(&self) {
        self.host.add_sql_pane();
    }

    /// Close the currently focused pane.
    pub fn close_focused_pane(&self) {
        self.host.close_focused_pane();
    }

    /// Focus pane in the given direction ("left", "right", "up", "down").
    pub fn focus_pane(&self, direction: &str) {
        self.host.focus_pane(direction);
    }

    // ==================== Time Range ====================

    /// Set time range to a preset (e.g., "5m", "15m", "1h", "6h", "24h", "7d").
    pub fn set_time_range_preset(&self, preset: &str) {
        self.host.set_time_range_preset(preset);
    }

    /// Set absolute time range (start and end in seconds since Unix epoch).
    pub fn set_time_range_absolute(&self, start_secs: f64, end_secs: f64) {
        self.host.set_time_range_absolute(start_secs, end_secs);
    }

    /// Get the current time range as (start_secs, end_secs).
    pub fn get_time_range(&self) -> (f64, f64) {
        self.host.get_time_range()
    }

    // ==================== Custom Panes ====================

    /// Register a custom table pane type.
    pub fn register_custom_table_pane(&self, config: CustomTableConfig) {
        self.host.register_custom_table_pane(config);
    }

    /// Add an instance of a custom table pane.
    pub fn add_custom_table_pane(&self, pane_type: &str) {
        self.host.add_custom_table_pane(pane_type);
    }

    /// Update data for a custom table pane.
    pub fn update_custom_table_data(&self, pane_id: usize, data: CustomTableData) {
        self.host.update_custom_table_data(pane_id, data);
    }

    /// Update data for all custom table panes of a given type.
    pub fn update_custom_table_data_by_type(&self, pane_type: &str, data: CustomTableData) {
        self.host.update_custom_table_data_by_type(pane_type, data);
    }

    // ==================== Custom Chart Panes ====================

    /// Register a custom chart pane type.
    pub fn register_custom_chart_pane(&self, config: CustomChartConfig) {
        self.host.register_custom_chart_pane(config);
    }

    /// Add an instance of a custom chart pane.
    pub fn add_custom_chart_pane(&self, pane_type: &str) {
        self.host.add_custom_chart_pane(pane_type);
    }

    /// Update data for all custom chart panes of a given type.
    pub fn update_custom_chart_data_by_type(&self, pane_type: &str, data: CustomChartData) {
        self.host.update_custom_chart_data_by_type(pane_type, data);
    }

    // ==================== Custom Stat Panes ====================

    /// Register a custom stat pane type.
    pub fn register_stat_pane(&self, config: StatPaneConfig) {
        self.host.register_stat_pane(config);
    }

    /// Add an instance of a stat pane.
    pub fn add_stat_pane(&self, pane_type: &str) {
        self.host.add_stat_pane(pane_type);
    }

    /// Update data for all stat panes of a given type.
    pub fn update_stat_data_by_type(&self, pane_type: &str, data: StatPaneData) {
        self.host.update_stat_data_by_type(pane_type, data);
    }

    // ==================== Custom Gauge Panes ====================

    /// Register a custom gauge pane type.
    pub fn register_gauge_pane(&self, config: GaugePaneConfig) {
        self.host.register_gauge_pane(config);
    }

    /// Add an instance of a gauge pane.
    pub fn add_gauge_pane(&self, pane_type: &str) {
        self.host.add_gauge_pane(pane_type);
    }

    /// Update data for all gauge panes of a given type.
    pub fn update_gauge_data_by_type(&self, pane_type: &str, data: GaugePaneData) {
        self.host.update_gauge_data_by_type(pane_type, data);
    }

    // ==================== Focused Pane ====================

    /// Get information about the currently focused pane.
    pub fn get_focused_pane_info(&self) -> Option<FocusedPaneInfo> {
        self.host.get_focused_pane_info()
    }
}

/// Reference-counted plugin context.
pub type PluginContextRef = Arc<PluginContext>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_notification_level_parse() {
        assert_eq!(NotificationLevel::parse("error"), NotificationLevel::Error);
        assert_eq!(NotificationLevel::parse("warn"), NotificationLevel::Warning);
        assert_eq!(
            NotificationLevel::parse("warning"),
            NotificationLevel::Warning
        );
        assert_eq!(NotificationLevel::parse("info"), NotificationLevel::Info);
        // Unknown values default to Info
        assert_eq!(NotificationLevel::parse("unknown"), NotificationLevel::Info);
        assert_eq!(NotificationLevel::parse(""), NotificationLevel::Info);
        assert_eq!(NotificationLevel::parse("ERROR"), NotificationLevel::Info); // case sensitive
    }

    #[test]
    fn test_log_level_parse() {
        assert_eq!(LogLevel::parse("debug"), LogLevel::Debug);
        assert_eq!(LogLevel::parse("info"), LogLevel::Info);
        assert_eq!(LogLevel::parse("warn"), LogLevel::Warn);
        assert_eq!(LogLevel::parse("warning"), LogLevel::Warn);
        assert_eq!(LogLevel::parse("error"), LogLevel::Error);
        // Unknown values default to Info
        assert_eq!(LogLevel::parse("unknown"), LogLevel::Info);
        assert_eq!(LogLevel::parse(""), LogLevel::Info);
        // Case-insensitive parsing
        assert_eq!(LogLevel::parse("DEBUG"), LogLevel::Debug);
        assert_eq!(LogLevel::parse("WARN"), LogLevel::Warn);
        assert_eq!(LogLevel::parse("Error"), LogLevel::Error);
    }

    #[test]
    fn test_theme_default() {
        assert_eq!(Theme::default(), Theme::Dark);
    }

    #[test]
    fn test_http_response_clone() {
        let mut headers = FxHashMap::default();
        headers.insert("Content-Type".to_string(), "application/json".to_string());

        let response = HttpResponse {
            status: 200,
            body: "test body".to_string(),
            headers,
        };

        let cloned = response.clone();
        assert_eq!(cloned.status, 200);
        assert_eq!(cloned.body, "test body");
        assert_eq!(
            cloned.headers.get("Content-Type"),
            Some(&"application/json".to_string())
        );
    }

    #[test]
    fn test_http_error_clone() {
        let error = HttpError {
            message: "Network error".to_string(),
        };

        let cloned = error.clone();
        assert_eq!(cloned.message, "Network error");
    }
}