laravel-rust-studio 0.1.1

See what a running Laravel for Rust application did: requests with their queries, errors with their source lines, mail, queued jobs, and durable workflows. For you in the browser, and for coding agents over MCP.
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
//! What Studio captures and what its API answers with. The interface's `types.ts` mirrors these.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// What a trace is of.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TraceKind {
    Request,
    Job,
    Workflow,
    Command,
    Schedule,
    Tick,
    Background,
    Custom,
}

impl TraceKind {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Request => "request",
            Self::Job => "job",
            Self::Workflow => "workflow",
            Self::Command => "command",
            Self::Schedule => "schedule",
            Self::Tick => "tick",
            Self::Background => "background",
            Self::Custom => "custom",
        }
    }
}

/// What a span did, which decides how its trace's timeline shows it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SpanCategory {
    Request,
    Db,
    Cache,
    Redis,
    HttpClient,
    Job,
    Workflow,
    WorkflowStep,
    Mail,
    Sms,
    Command,
    Schedule,
    Tick,
    Background,
    Custom,
}

/// One span of a trace: a query, a cache operation, a workflow step, and so on.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpanRecord {
    pub id: u64,
    pub parent_id: Option<u64>,
    pub name: String,
    pub target: String,
    pub category: SpanCategory,
    pub level: String,
    pub start_offset_ms: f64,
    pub duration_ms: f64,
    pub started_at_ms: i64,
    pub is_error: bool,
    pub error: Option<String>,
    pub fields: BTreeMap<String, Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
    /// The dependency whose code built the query, such as `laravel-rust-workflow`, or `None` when
    /// the application's own code did.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vendor: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bindings: Vec<QueryBinding>,
    /// Whether the query read back the row that the write before it, from the same line, had just
    /// written. Creating a model does that on MySQL, which can't return the row from its `INSERT`.
    /// Such a read repeats as often as its write does, and isn't an N+1 query.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub read_back: bool,
}

/// One unit of the application's work, with everything that happened inside it: a request, a
/// queued job's attempt, a workflow run's advance, a console command, or a scheduled task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceRecord {
    pub id: String,
    pub kind: TraceKind,
    pub name: String,
    /// The command of the process that captured the trace, such as `serve` or `queue:work`.
    #[serde(default)]
    pub process: String,
    #[serde(default)]
    pub pid: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub route: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_code: Option<u16>,
    pub duration_ms: f64,
    /// How long a request took to answer, when its response then went on streaming: an event
    /// stream, a download, or a WebSocket. `duration_ms` is how long the whole of it lasted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub responded_ms: Option<f64>,
    pub started_at_ms: i64,
    pub finished_at_ms: i64,
    pub is_error: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    pub query_count: usize,
    pub total_query_ms: f64,
    pub duplicate_query_count: usize,
    pub slow_query_count: usize,
    pub cache_hits: usize,
    pub cache_misses: usize,
    pub http_client_count: usize,
    pub mail_count: usize,
    pub log_count: usize,
    pub exception_count: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow_run_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queue: Option<String>,
    pub fields: BTreeMap<String, Value>,
    pub spans: Vec<SpanRecord>,
    /// How many spans were left out because the trace had more than Studio keeps of one trace.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub dropped_spans: usize,
}

#[expect(clippy::trivially_copy_pass_by_ref, reason = "serde passes the field by reference")]
const fn is_zero(count: &usize) -> bool {
    *count == 0
}

/// A trace without its spans, as lists show it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceSummary {
    pub id: String,
    pub kind: TraceKind,
    pub name: String,
    #[serde(default)]
    pub process: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub route: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_code: Option<u16>,
    pub duration_ms: f64,
    /// How long a request took to answer, when its response then went on streaming: an event
    /// stream, a download, or a WebSocket. `duration_ms` is how long the whole of it lasted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub responded_ms: Option<f64>,
    pub started_at_ms: i64,
    pub is_error: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    pub span_count: usize,
    pub query_count: usize,
    pub total_query_ms: f64,
    pub duplicate_query_count: usize,
    pub slow_query_count: usize,
    pub cache_hits: usize,
    pub cache_misses: usize,
    pub http_client_count: usize,
    pub mail_count: usize,
    pub exception_count: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow_run_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queue: Option<String>,
}

impl TraceRecord {
    /// How long the application took to answer, which is what makes a request slow. A response
    /// that streams for minutes isn't slow for it.
    #[must_use]
    pub fn response_ms(&self) -> f64 {
        self.responded_ms.unwrap_or(self.duration_ms)
    }
}

impl From<&TraceRecord> for TraceSummary {
    fn from(t: &TraceRecord) -> Self {
        Self {
            id: t.id.clone(),
            kind: t.kind,
            name: t.name.clone(),
            process: t.process.clone(),
            method: t.method.clone(),
            path: t.path.clone(),
            route: t.route.clone(),
            status_code: t.status_code,
            duration_ms: t.duration_ms,
            responded_ms: t.responded_ms,
            started_at_ms: t.started_at_ms,
            is_error: t.is_error,
            error: t.error.clone(),
            span_count: t.spans.len(),
            query_count: t.query_count,
            total_query_ms: t.total_query_ms,
            duplicate_query_count: t.duplicate_query_count,
            slow_query_count: t.slow_query_count,
            cache_hits: t.cache_hits,
            cache_misses: t.cache_misses,
            http_client_count: t.http_client_count,
            mail_count: t.mail_count,
            exception_count: t.exception_count,
            workflow_run_id: t.workflow_run_id.clone(),
            workflow_name: t.workflow_name.clone(),
            job_name: t.job_name.clone(),
            queue: t.queue.clone(),
        }
    }
}

/// A value bound to a query. `value` is `None` unless the query bound it with `bind_visible`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryBinding {
    pub type_name: String,
    pub value: Option<String>,
}

/// A query the application ran.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryRecord {
    pub id: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_id: Option<String>,
    pub sql: String,
    pub normalized_sql: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operation: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub table: Option<String>,
    pub connection: String,
    pub driver: String,
    pub duration_ms: f64,
    pub is_slow: bool,
    pub is_write: bool,
    pub joined_transaction: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bindings: Vec<QueryBinding>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
    /// The dependency whose code built the query, such as `laravel-rust-workflow`, or `None` when
    /// the application's own code did.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vendor: Option<String>,
    /// Whether the query read back the row that the write before it, from the same line, had just
    /// written. Creating a model does that on MySQL, which can't return the row from its `INSERT`.
    /// Such a read repeats as often as its write does, and isn't an N+1 query.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub read_back: bool,
    pub started_at_ms: i64,
    pub is_error: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// A log line.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogRecord {
    pub id: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub span_id: Option<u64>,
    pub level: String,
    pub target: String,
    pub message: String,
    pub fields: BTreeMap<String, Value>,
    pub timestamp_ms: i64,
}

/// An error or a panic that the application reported.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExceptionRecord {
    pub id: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_id: Option<String>,
    pub error_type: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
    pub causes: Vec<String>,
    pub context: BTreeMap<String, Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub route: Option<String>,
    pub timestamp_ms: i64,
}

/// An email or a text message. The `log` mailer and SMS sender show a message's body, and a real
/// transport only that it was sent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MailRecord {
    pub id: u64,
    pub message_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_id: Option<String>,
    /// `mail` or `sms`.
    pub kind: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mailer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transport: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cc: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bcc: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub html: Option<String>,
    pub attachments: usize,
    /// The links in the message, such as a verification link or a workflow's resume URL.
    pub extracted_urls: Vec<String>,
    /// The sign-in and verification codes in the message.
    pub extracted_codes: Vec<String>,
    pub timestamp_ms: i64,
    pub is_error: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// A request the application's HTTP client sent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpClientRecord {
    pub id: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_id: Option<String>,
    pub method: String,
    pub url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub host: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<u16>,
    pub duration_ms: f64,
    pub retries: u64,
    pub is_error: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    pub timestamp_ms: i64,
}

/// A read from or a write to the cache.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheRecord {
    pub id: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_id: Option<String>,
    pub operation: String,
    pub store: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hit: Option<bool>,
    pub duration_ms: f64,
    pub is_error: bool,
    pub timestamp_ms: i64,
}

/// A workflow run advancing, completing, failing, or being cancelled, as Studio saw it happen.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowActivityRecord {
    pub run_id: String,
    pub workflow: String,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    pub updated_at_ms: i64,
}

/// One attempt of a queued job, as a worker reported it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobActivityRecord {
    pub id: u64,
    pub job_id: String,
    pub name: String,
    pub connection: String,
    pub queue: String,
    pub attempt: u32,
    pub outcome: String,
    pub duration_ms: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    pub timestamp_ms: i64,
}

/// A workflow run without its steps, as lists show it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowRunSummary {
    pub id: String,
    pub workflow: String,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queue: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wake_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finished_at: Option<String>,
    pub duration_ms: Option<f64>,
    pub step_count: usize,
    pub waiting_tokens: Vec<String>,
    pub attributes: BTreeMap<String, String>,
    pub purged: bool,
}

/// A workflow run with its input, output, steps, waits, and the values it was resumed with.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowRunDetail {
    pub id: String,
    pub workflow: String,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queue: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wake_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finished_at: Option<String>,
    pub duration_ms: Option<f64>,
    pub attributes: BTreeMap<String, String>,
    pub purged: bool,
    pub steps: Vec<WorkflowStepDetail>,
    pub waits: Vec<WorkflowWaitDetail>,
    pub resumes: Vec<WorkflowResumeMessage>,
    pub can_retry: bool,
    pub can_cancel: bool,
    pub source: String,
}

/// A step, a sleep, a wait, or an inbox read of a workflow run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowStepDetail {
    pub kind: String,
    pub name: String,
    pub status: String,
    pub tries: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wake_at: Option<String>,
    pub started_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finished_at: Option<String>,
    pub duration_ms: Option<f64>,
    pub timed_out: bool,
}

/// A token a run owns, and whether the run waits for a value on it now.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowWaitDetail {
    pub token: String,
    pub number: Option<i64>,
    pub resumed_at: Option<String>,
    pub is_waiting: bool,
}

/// A value a run was resumed with.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowResumeMessage {
    pub token: String,
    pub number: i64,
    pub value: Value,
    pub created_at: String,
}

/// The answer of `GET /studio/api/workflows`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowsListResponse {
    pub source: String,
    pub store_driver: String,
    pub database_enabled: bool,
    pub table_ready: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    pub counts: BTreeMap<String, usize>,
    pub runs: Vec<WorkflowRunSummary>,
}

/// How many jobs a queue holds, and whether it's paused.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueDepth {
    pub connection: String,
    pub driver: String,
    pub queue: String,
    pub pending: u64,
    pub reserved: u64,
    pub delayed: u64,
    pub oldest_pending: Option<String>,
    pub approximate: bool,
    pub paused: bool,
    /// Why the queue's depth couldn't be read, such as a Redis server that's down.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// A job on a database queue: waiting, reserved by a worker, or delayed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingJobRecord {
    pub id: i64,
    pub connection: String,
    pub queue: String,
    pub job_id: Option<String>,
    pub job_name: String,
    pub display_name: Option<String>,
    pub state: String,
    pub attempts: i64,
    pub available_at: String,
    pub reserved_at: Option<String>,
    pub created_at: String,
    pub batch_id: Option<String>,
    pub data: Value,
}

/// A job that failed for good.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailedJobRecord {
    pub id: i64,
    pub job_id: String,
    pub connection: String,
    pub queue: String,
    pub job_name: String,
    pub display_name: Option<String>,
    pub error: String,
    pub failed_at: String,
    pub batch_id: Option<String>,
    pub data: Value,
}

/// A batch of jobs and how far it has come.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchRecord {
    pub id: String,
    pub name: Option<String>,
    pub total_jobs: i64,
    pub pending_jobs: i64,
    pub failed_jobs: i64,
    pub processed_jobs: i64,
    pub progress_pct: f64,
    pub status: String,
    pub created_at: String,
    pub cancelled_at: Option<String>,
    pub finished_at: Option<String>,
}

/// The answer of `GET /studio/api/queues`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueuesOverviewResponse {
    pub default_connection: String,
    pub all_paused: bool,
    pub database_enabled: bool,
    pub queues: Vec<QueueDepth>,
    pub pending_jobs: Vec<PendingJobRecord>,
    pub failed_jobs: Vec<FailedJobRecord>,
    pub batches: Vec<BatchRecord>,
    pub recent_activity: Vec<JobActivityRecord>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

/// The application's name, environment, and drivers, and Studio's settings. It holds no secrets.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemInfoResponse {
    pub app_name: String,
    pub app_env: String,
    pub app_debug: bool,
    pub studio_version: String,
    pub studio_path: String,
    pub mcp_enabled: bool,
    pub database_feature: bool,
    pub default_db_connection: String,
    pub default_queue_connection: String,
    pub default_cache_store: String,
    pub default_workflow_store: String,
    pub uptime_seconds: u64,
    pub slow_query_ms: u64,
    pub slow_request_ms: u64,
    pub buffer_counts: BufferCounts,
    /// The command of the process that answered, such as `serve`.
    pub process: String,
    pub pid: u32,
    /// Where processes share what they capture, or `None` when the journal is off.
    pub journal_dir: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BufferCounts {
    pub traces: usize,
    pub queries: usize,
    pub logs: usize,
    pub exceptions: usize,
    pub mails: usize,
    pub http_client: usize,
    pub cache: usize,
}

/// The totals and the series the overview page draws.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OverviewResponse {
    pub uptime_seconds: u64,
    pub total_requests: u64,
    pub total_errors: u64,
    pub error_rate_pct: f64,
    pub avg_request_ms: f64,
    pub p95_request_ms: f64,
    pub total_queries: u64,
    pub slow_queries: u64,
    pub duplicate_query_traces: usize,
    pub total_exceptions: usize,
    pub total_mails: usize,
    pub total_http_client: usize,
    pub cache_hit_rate_pct: Option<f64>,
    pub workflow_counts: BTreeMap<String, usize>,
    pub failed_jobs_count: usize,
    pub pending_jobs_count: u64,
    pub recent_traces: Vec<TraceSummary>,
    pub recent_exceptions: Vec<ExceptionRecord>,
    pub diagnostics: DiagnosticsReport,
    pub latency_series: Vec<LatencyPoint>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LatencyPoint {
    pub trace_id: String,
    pub timestamp_ms: i64,
    pub duration_ms: f64,
    pub status_code: Option<u16>,
    pub label: String,
    pub is_error: bool,
}

/// The problems Studio found in what it captured.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagnosticsReport {
    /// `healthy`, `degraded`, or `critical`, as the problems in `issues` make it.
    pub status: String,
    pub generated_at_ms: i64,
    pub issue_count: usize,
    pub critical_count: usize,
    pub warning_count: usize,
    pub issues: Vec<DiagnosticIssue>,
    /// The problems last seen before the server last started, and not since. A change to the code
    /// restarts the application, so the code that runs now hasn't shown them, and they count
    /// toward neither the status nor the totals.
    #[serde(default)]
    pub before_restart: Vec<DiagnosticIssue>,
    /// When the process that made the report started.
    #[serde(default)]
    pub started_at_ms: i64,
    /// How many requests, queued jobs, and workflow advances were captured since then. With none,
    /// an empty `issues` says nothing yet about the code that runs now.
    #[serde(default)]
    pub traces_since_start: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagnosticIssue {
    /// `critical`, `warning`, or `info`.
    pub severity: String,
    /// `exception`, `n_plus_one`, `slow_query`, `slow_request`, `http_client_error`,
    /// `workflow_failed`, `workflow_overdue`, `job_failed`, `queue_unreachable`, or `queue_paused`.
    pub category: String,
    pub title: String,
    pub detail: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource_id: Option<String>,
    /// What to do about it.
    pub hint: String,
    /// The API call that shows more, or acts on it, for a coding agent to make.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next: Option<String>,
    /// When the problem last showed: its latest error, the latest trace that repeated the query,
    /// the latest slow run, or when the job or the workflow run failed. `None` for a condition
    /// that holds now, such as a paused queue.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_seen_ms: Option<i64>,
}

/// The application's state in one answer, which a coding agent starts from.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentSummary {
    pub app_name: String,
    pub app_env: String,
    pub uptime_seconds: u64,
    pub health: String,
    pub metrics: AgentMetrics,
    pub diagnostics: DiagnosticsReport,
    pub latest_requests: Vec<TraceSummary>,
    pub latest_exceptions: Vec<ExceptionRecord>,
    pub workflows: WorkflowsListResponse,
    pub failed_jobs: Vec<FailedJobRecord>,
    pub latest_mails: Vec<MailRecord>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentMetrics {
    pub total_requests: u64,
    pub total_errors: u64,
    pub avg_request_ms: f64,
    pub total_queries: u64,
    pub slow_queries: u64,
    pub exceptions_in_buffer: usize,
    pub failed_jobs: usize,
    pub waiting_workflows: usize,
    pub failed_workflows: usize,
}

/// A record as the live stream at `GET /studio/api/stream` carries it.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum StudioEvent {
    Trace(TraceSummary),
    Query(QueryRecord),
    Exception(ExceptionRecord),
    Log(LogRecord),
    Mail(MailRecord),
    Workflow(WorkflowActivityRecord),
    Job(JobActivityRecord),
    Cleared,
}

/// How an action went, in words to show the person or the agent that asked for it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionResult {
    pub ok: bool,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<Value>,
}