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
//! Studio's routes: the page that hosts its interface, the JSON API behind it, the live event
//! stream, the endpoints written for coding agents, and the MCP server.

use std::collections::HashMap;
use std::time::Duration;

use http::{Method, StatusCode};
use laravel::axum::Json as Body;
use laravel::axum::extract::Query;
use laravel::container::Inject;
use laravel::http::middleware::PreventRequestForgery;
use laravel::http::sse::{Event, EventStream};
use laravel::http::{IntoResponse, Json, Middleware, MiddlewareGroup, Next, Request, Response};
use laravel::routing::{Params, Router};
use laravel::view::Html;
use serde::Deserialize;
use serde_json::{Value, json};
use tokio::sync::broadcast::error::RecvError;

use crate::agent::{self, WaitFor};
use crate::config::StudioGate;
use crate::store::{QueryFilter, StudioStore, TraceFilter};
use crate::types::{
    ActionResult, OverviewResponse, QueuesOverviewResponse, SystemInfoResponse, WorkflowRunDetail,
    WorkflowsListResponse,
};
use crate::workflows::{self, WorkflowFilter};
use crate::{docs, markdown, mcp, queues};

type QueryString = Query<HashMap<String, String>>;

/// Decides who reaches Studio, turns away requests that another site's page made a browser send,
/// and brings in what other processes captured before a route reads it.
#[derive(Clone, Debug)]
pub struct StudioAccess {
    gate: StudioGate,
    store: StudioStore,
}

impl Middleware for StudioAccess {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        if !self.gate.enabled {
            return Err(laravel::abort(404));
        }
        if !self.gate.is_authorized(&request) {
            return Err(laravel::abort_with(
                403,
                "Studio answers only in the local environment. To open it here, give `StudioServiceProvider` an \
                 `authorize` callback, or set `STUDIO_ALLOW_IN_PRODUCTION=true`.",
            ));
        }

        // Studio's API takes no CSRF token, so that `curl` and agents can call it. A browser says
        // where a request comes from, and that keeps another site's page from calling it...
        if !matches!(*request.method(), Method::GET | Method::HEAD | Method::OPTIONS) {
            let cross_origin = request
                .header("origin")
                .is_some_and(|origin| !origin.eq_ignore_ascii_case(&request.origin()));
            let cross_site = request
                .header("sec-fetch-site")
                .is_some_and(|site| !matches!(site, "same-origin" | "none"));
            if cross_origin || cross_site {
                return Err(laravel::abort_with(
                    403,
                    "Studio doesn't take requests from other sites.",
                ));
            }
        }

        agent::sync(&self.store).await;

        Ok(next.run(request).await)
    }
}

/// Register Studio's routes under `mount`.
pub(crate) fn register_routes(
    route: &mut Router,
    mount: &str,
    gate: StudioGate,
    middleware: MiddlewareGroup,
    store: StudioStore,
    mcp_enabled: bool,
) {
    route
        .prefix(mount)
        .middleware((StudioAccess { gate, store }, middleware))
        .group(|route| {
            route.get("/", index);
            route.get("/llms.txt", llms_txt);
            route.get("/skill.md", skill_md);
            if mcp_enabled {
                route.post("/mcp", mcp).without_middleware::<PreventRequestForgery>();
            }

            route
                .prefix("/api")
                .without_middleware::<PreventRequestForgery>()
                .group(api_routes);

            // The interface routes itself in the browser, so each of its URLs serves the page...
            route.get("/{*path}", index);
        });
}

fn api_routes(route: &mut Router) {
    route.get("/overview", overview);
    route.get("/system", system);
    route.get("/stream", stream);
    route.post("/clear", clear);

    route.get("/traces", traces);
    route.get("/traces/{id}", trace);
    route.get("/queries", queries);
    route.get("/logs", logs);
    route.get("/exceptions", exceptions);
    route.get("/exceptions/{id}", exception);
    route.get("/mail", mails);
    route.get("/mail/{id}", mail);
    route.get("/http-client", http_client);
    route.get("/cache", cache);

    route.get("/workflows", workflow_runs);
    route.post("/workflows/resume", resume_workflow);
    route.post("/workflows/recover", recover_workflows);
    route.post("/workflows/prune", prune_workflows);
    route.get("/workflows/{id}", workflow_run);
    route.post("/workflows/{id}/cancel", cancel_workflow);
    route.post("/workflows/{id}/retry", retry_workflow);

    route.get("/queues", queue_overview);
    route.get("/queues/failed", failed_jobs);
    route.post("/queues/failed/retry-all", retry_all_failed_jobs);
    route.post("/queues/failed/flush", flush_failed_jobs);
    route.post("/queues/failed/{id}/retry", retry_failed_job);
    route.delete("/queues/failed/{id}", forget_failed_job);
    route.post("/queues/batches/{id}/cancel", cancel_batch);
    route.post("/queues/pause", pause_queue);
    route.post("/queues/continue", continue_queue);
    route.post("/queues/restart", restart_workers);

    route.get("/agent/summary", agent_summary);
    route.get("/agent/diagnose", agent_diagnose);
    route.get("/agent/last-request", agent_last_request);
    route.get("/agent/last-error", agent_last_error);
    route.get("/agent/last-mail", agent_last_mail);
    route.get("/agent/wait", agent_wait);
}

// ---- The page, and the documents for agents ----

/// `GET /studio` and every path under it that the API doesn't take: the page that loads Studio's
/// interface.
pub async fn index(store: Inject<StudioStore>) -> Html {
    let config = store.config();
    let app = &laravel::config().app;
    let boot = json!({
        "basePath": config.mount_path(),
        "appName": app.name,
        "appEnv": app.env.to_string(),
        "hasDatabase": cfg!(feature = "database"),
        "mcpEnabled": config.mcp_enabled,
        "slowQueryMs": config.slow_query_ms,
        "slowRequestMs": config.slow_request_ms,
        "version": env!("CARGO_PKG_VERSION"),
    });
    // `</script>` inside a string would end the script element...
    let boot = boot.to_string().replace("</", "<\\/");

    Html::raw(format!(
        r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Studio — {title}</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%23f53003'/%3E%3Cpath d='M13 2 4 14h7l-1 8 9-12h-7z' transform='translate(7.4 7) scale(.75)' fill='%23fff' stroke='%23fff' stroke-width='1.6' stroke-linejoin='round'/%3E%3C/svg%3E">
<link rel="stylesheet" href="{style}">
</head>
<body>
<div id="root"></div>
<script>window.__STUDIO__ = {boot};</script>
<script type="module" src="{script}"></script>
</body>
</html>
"#,
        title = escape_html(&app.name),
        style = laravel::url::vendor_asset("studio", "style.css"),
        script = laravel::url::vendor_asset("studio", "app.js"),
    ))
}

/// The URL Studio is served at, as the request reached it.
fn studio_url(store: &StudioStore, request: &Request) -> String {
    format!("{}{}", request.origin(), store.config().mount_path())
}

/// `GET /studio/llms.txt`
pub async fn llms_txt(store: Inject<StudioStore>, request: Request) -> Response {
    let body = docs::render_llms_txt(
        &studio_url(&store, &request),
        &laravel::config().app.name,
        store.config().mcp_enabled,
    );

    body.with_header("content-type", "text/plain; charset=utf-8")
}

/// `GET /studio/skill.md`
pub async fn skill_md(store: Inject<StudioStore>, request: Request) -> Response {
    docs::render_skill(&studio_url(&store, &request)).with_header("content-type", "text/markdown; charset=utf-8")
}

/// `POST /studio/mcp`: the Model Context Protocol over its Streamable HTTP transport.
pub async fn mcp(store: Inject<StudioStore>, Body(message): Body<Value>) -> Response {
    match mcp::handle(&store, message).await {
        Some(answer) => Json(answer).into_response(),
        None => StatusCode::ACCEPTED.into_response(),
    }
}

// ---- Telemetry ----

/// `GET /studio/api/overview`
pub async fn overview(store: Inject<StudioStore>) -> Json<OverviewResponse> {
    let snapshot = agent::snapshot(&store).await;
    let metrics = store.compute_metrics();
    let counts = store.buffer_counts();

    Json(OverviewResponse {
        uptime_seconds: store.uptime_seconds(),
        total_requests: metrics.total_requests,
        total_errors: metrics.total_errors,
        error_rate_pct: metrics.error_rate_pct,
        avg_request_ms: metrics.avg_request_ms,
        p95_request_ms: metrics.p95_request_ms,
        total_queries: metrics.total_queries,
        slow_queries: metrics.slow_queries,
        duplicate_query_traces: metrics.duplicate_query_traces,
        total_exceptions: counts.exceptions,
        total_mails: counts.mails,
        total_http_client: counts.http_client,
        cache_hit_rate_pct: metrics.cache_hit_rate_pct,
        workflow_counts: snapshot.workflows.counts,
        failed_jobs_count: snapshot.queues.failed_jobs.len(),
        pending_jobs_count: snapshot
            .queues
            .queues
            .iter()
            .map(|queue| queue.pending + queue.delayed + queue.reserved)
            .sum(),
        recent_traces: store.list_traces(&TraceFilter::default(), 12),
        recent_exceptions: store.list_exceptions(None, 5),
        diagnostics: snapshot.diagnostics,
        latency_series: metrics.latency_series,
    })
}

/// `GET /studio/api/system`
pub async fn system(store: Inject<StudioStore>) -> Json<SystemInfoResponse> {
    let config = laravel::config();
    let studio = store.config();

    Json(SystemInfoResponse {
        app_name: config.app.name.clone(),
        app_env: config.app.env.to_string(),
        app_debug: config.app.debug,
        studio_version: env!("CARGO_PKG_VERSION").to_owned(),
        studio_path: studio.mount_path(),
        mcp_enabled: studio.mcp_enabled,
        database_feature: cfg!(feature = "database"),
        #[cfg(feature = "database")]
        default_db_connection: config.database.default.clone(),
        #[cfg(not(feature = "database"))]
        default_db_connection: String::new(),
        default_queue_connection: config.queue.default.clone(),
        default_cache_store: config.cache.default.clone(),
        default_workflow_store: config.workflow.default.clone(),
        uptime_seconds: store.uptime_seconds(),
        slow_query_ms: studio.slow_query_ms,
        slow_request_ms: studio.slow_request_ms,
        buffer_counts: store.buffer_counts(),
        process: store.process().role.clone(),
        pid: store.process().pid,
        journal_dir: store.journal_dir().map(|dir| dir.display().to_string()),
    })
}

/// `GET /studio/api/stream`: each record as it's captured, as a `studio` server-sent event.
pub async fn stream(store: Inject<StudioStore>) -> EventStream {
    let store = (*store).clone();
    let mut events = store.subscribe();

    EventStream::channel(async move |sse| {
        sse.send(Event::new("ready", "{}")).await?;

        let mut sync = tokio::time::interval(Duration::from_secs(1));
        let mut ping = tokio::time::interval(Duration::from_secs(10));
        loop {
            tokio::select! {
                // Other processes' records come through the journal, which only a read brings in...
                _ = sync.tick() => agent::sync(&store).await,
                // A send is how the stream learns that the browser left...
                _ = ping.tick() => sse.send(Event::new("ping", "{}")).await?,
                event = events.recv() => match event {
                    Ok(event) => sse.send(Event::new("studio", serde_json::to_string(&event)?)).await?,
                    Err(RecvError::Lagged(missed)) => {
                        sse.send(Event::new("lagged", json!({ "missed": missed }).to_string())).await?;
                    }
                    Err(RecvError::Closed) => return Ok(()),
                },
            }
        }
    })
    .without_end_event()
}

/// `POST /studio/api/clear`
pub async fn clear(store: Inject<StudioStore>) -> Json<ActionResult> {
    store.clear();

    Json(ActionResult {
        ok: true,
        message: "The captured telemetry was cleared.".to_owned(),
        detail: None,
    })
}

/// `GET /studio/api/traces`
pub async fn traces(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
    let filter = TraceFilter {
        kind: text(&query, "kind"),
        status: text(&query, "status"),
        search: text(&query, "search"),
        slow: flag(&query, "slow"),
        errors: flag(&query, "errors"),
    };
    let traces = store.list_traces(&filter, limit(&query, 100, 500));

    Json(json!({ "traces": traces }))
}

/// `GET /studio/api/traces/{id}`: a trace with everything captured during it.
pub async fn trace(store: Inject<StudioStore>, Params(id): Params<String>) -> laravel::Result<Json<Value>> {
    let Some(trace) = store.get_trace(&id) else {
        return Err(laravel::abort_with(404, format!("No trace has the ID `{id}`.")));
    };

    Ok(Json(trace_details(&store, &trace)))
}

fn trace_details(store: &StudioStore, trace: &crate::types::TraceRecord) -> Value {
    let id = trace.id.as_str();
    let during = |trace_id: &Option<String>| trace_id.as_deref() == Some(id);

    json!({
        "trace": trace,
        "queries": store.list_queries(&QueryFilter { trace_id: Some(id), ..QueryFilter::default() }, 1000),
        "logs": store.list_logs(Some(id), None, None, 500),
        "exceptions": store.list_exceptions(None, usize::MAX).into_iter().filter(|e| during(&e.trace_id)).collect::<Vec<_>>(),
        "mails": store.list_mails(None, None, usize::MAX).into_iter().filter(|m| during(&m.trace_id)).collect::<Vec<_>>(),
        "http_client": store.list_http_client(Some(id), 200),
        "cache": store.list_cache(Some(id), 500),
    })
}

/// `GET /studio/api/queries`
pub async fn queries(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
    let filter = QueryFilter {
        trace_id: text(&query, "trace_id"),
        slow: flag(&query, "slow"),
        writes: flag(&query, "writes"),
        duplicates: flag(&query, "duplicates"),
        app_only: flag(&query, "app"),
        search: text(&query, "search"),
    };
    let queries = store.list_queries(&filter, limit(&query, 150, 1000));

    Json(json!({ "queries": queries, "slow_threshold_ms": store.config().slow_query_ms }))
}

/// `GET /studio/api/logs`
pub async fn logs(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
    let logs = store.list_logs(
        text(&query, "trace_id"),
        text(&query, "level"),
        text(&query, "search"),
        limit(&query, 200, 1000),
    );

    Json(json!({ "logs": logs }))
}

/// `GET /studio/api/exceptions`
pub async fn exceptions(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
    let exceptions = store.list_exceptions(text(&query, "search"), limit(&query, 100, 500));

    Json(json!({ "exceptions": exceptions }))
}

/// `GET /studio/api/exceptions/{id}`
pub async fn exception(store: Inject<StudioStore>, Params(id): Params<u64>) -> laravel::Result<Json<Value>> {
    let Some(exception) = store.get_exception(id) else {
        return Err(laravel::abort_with(404, format!("No error has the ID `{id}`.")));
    };

    Ok(Json(json!({ "exception": exception })))
}

/// `GET /studio/api/mail`
pub async fn mails(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
    let mails = store.list_mails(text(&query, "kind"), text(&query, "search"), limit(&query, 100, 200));

    Json(json!({ "mails": mails }))
}

/// `GET /studio/api/mail/{id}`
pub async fn mail(store: Inject<StudioStore>, Params(id): Params<u64>) -> laravel::Result<Json<Value>> {
    let Some(mail) = store.get_mail(id) else {
        return Err(laravel::abort_with(404, format!("No message has the ID `{id}`.")));
    };

    Ok(Json(json!({ "mail": mail })))
}

/// `GET /studio/api/http-client`
pub async fn http_client(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
    let requests = store.list_http_client(text(&query, "trace_id"), limit(&query, 100, 500));

    Json(json!({ "requests": requests }))
}

/// `GET /studio/api/cache`
pub async fn cache(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
    let operations = store.list_cache(text(&query, "trace_id"), limit(&query, 150, 1000));

    Json(json!({ "operations": operations }))
}

// ---- Workflows ----

/// `GET /studio/api/workflows`
pub async fn workflow_runs(store: Inject<StudioStore>, Query(query): QueryString) -> Json<WorkflowsListResponse> {
    let filter = WorkflowFilter {
        status: text(&query, "status").map(str::to_owned),
        workflow: text(&query, "workflow").map(str::to_owned),
        attribute: text(&query, "attribute")
            .and_then(|attribute| attribute.split_once('='))
            .map(|(name, value)| (name.to_owned(), value.to_owned())),
        search: text(&query, "search").map(str::to_owned),
        limit: limit(&query, 50, 200),
    };

    Json(workflows::list_workflows(&store, filter).await)
}

/// `GET /studio/api/workflows/{id}`
pub async fn workflow_run(
    Params(id): Params<String>,
    Query(query): QueryString,
    request: Request,
) -> laravel::Result<Response> {
    let Some(run) = workflows::get_workflow(&id).await? else {
        return Err(laravel::abort_with(404, format!("No workflow run has the ID `{id}`.")));
    };
    if wants_markdown(&query, &request) {
        return Ok(markdown(markdown::render_workflow_markdown(&run)));
    }

    Ok(Json::<WorkflowRunDetail>(run).into_response())
}

#[derive(Deserialize)]
pub struct Resume {
    pub token: String,
    #[serde(default)]
    pub value: Value,
}

/// `POST /studio/api/workflows/resume`
pub async fn resume_workflow(Body(resume): Body<Resume>) -> laravel::Result<Json<ActionResult>> {
    Ok(Json(workflows::resume_workflow(resume.token, resume.value).await?))
}

#[derive(Deserialize, Default)]
pub struct Cancel {
    pub reason: Option<String>,
}

/// `POST /studio/api/workflows/{id}/cancel`
pub async fn cancel_workflow(
    Params(id): Params<String>,
    cancel: Option<Body<Cancel>>,
) -> laravel::Result<Json<ActionResult>> {
    let reason = cancel.and_then(|Body(cancel)| cancel.reason);

    Ok(Json(workflows::cancel_workflow(&id, reason).await?))
}

/// `POST /studio/api/workflows/{id}/retry`
pub async fn retry_workflow(Params(id): Params<String>) -> laravel::Result<Json<ActionResult>> {
    Ok(Json(workflows::retry_workflow(&id).await?))
}

/// `POST /studio/api/workflows/recover`
pub async fn recover_workflows() -> laravel::Result<Json<ActionResult>> {
    Ok(Json(workflows::recover_workflows().await?))
}

#[derive(Deserialize)]
pub struct Prune {
    pub hours: Option<u32>,
}

/// `POST /studio/api/workflows/prune`
pub async fn prune_workflows(prune: Option<Body<Prune>>) -> laravel::Result<Json<ActionResult>> {
    let hours = prune.and_then(|Body(prune)| prune.hours).unwrap_or(24);

    Ok(Json(workflows::prune_workflows(hours).await?))
}

// ---- Queues ----

/// `GET /studio/api/queues`
pub async fn queue_overview(store: Inject<StudioStore>) -> Json<QueuesOverviewResponse> {
    Json(queues::queue_overview(&store).await)
}

/// `GET /studio/api/queues/failed`
pub async fn failed_jobs(Query(query): QueryString) -> Json<Value> {
    let jobs = queues::list_failed_jobs(limit(&query, 100, 500), text(&query, "search")).await;

    Json(json!({ "failed_jobs": jobs }))
}

/// `POST /studio/api/queues/failed/{id}/retry`
pub async fn retry_failed_job(Params(id): Params<String>) -> laravel::Result<Json<ActionResult>> {
    Ok(Json(queues::retry_failed_job(&id).await?))
}

/// `POST /studio/api/queues/failed/retry-all`
pub async fn retry_all_failed_jobs() -> laravel::Result<Json<ActionResult>> {
    Ok(Json(queues::retry_all_failed_jobs().await?))
}

/// `DELETE /studio/api/queues/failed/{id}`
pub async fn forget_failed_job(Params(id): Params<String>) -> laravel::Result<Json<ActionResult>> {
    Ok(Json(queues::forget_failed_job(&id).await?))
}

#[derive(Deserialize, Default)]
pub struct Flush {
    pub hours: Option<u32>,
}

/// `POST /studio/api/queues/failed/flush`
pub async fn flush_failed_jobs(flush: Option<Body<Flush>>) -> laravel::Result<Json<ActionResult>> {
    let hours = flush.and_then(|Body(flush)| flush.hours);

    Ok(Json(queues::flush_failed_jobs(hours).await?))
}

/// `POST /studio/api/queues/batches/{id}/cancel`
pub async fn cancel_batch(Params(id): Params<String>) -> laravel::Result<Json<ActionResult>> {
    Ok(Json(queues::cancel_batch(&id).await?))
}

#[derive(Deserialize, Default)]
pub struct QueueName {
    pub connection: Option<String>,
    pub queue: Option<String>,
    #[serde(default)]
    pub all: bool,
}

/// `POST /studio/api/queues/pause`
pub async fn pause_queue(queue: Option<Body<QueueName>>) -> laravel::Result<Json<ActionResult>> {
    let Body(queue) = queue.unwrap_or_default();

    Ok(Json(
        queues::pause_queue(queue.connection, queue.queue, queue.all).await?,
    ))
}

/// `POST /studio/api/queues/continue`
pub async fn continue_queue(queue: Option<Body<QueueName>>) -> laravel::Result<Json<ActionResult>> {
    let Body(queue) = queue.unwrap_or_default();

    Ok(Json(
        queues::continue_queue(queue.connection, queue.queue, queue.all).await?,
    ))
}

/// `POST /studio/api/queues/restart`
pub async fn restart_workers() -> laravel::Result<Json<ActionResult>> {
    Ok(Json(queues::restart_workers().await?))
}

// ---- For agents: JSON, or Markdown with `?format=markdown` ----

/// `GET /studio/api/agent/summary`
pub async fn agent_summary(store: Inject<StudioStore>, Query(query): QueryString, request: Request) -> Response {
    let summary = agent::build_agent_summary(&store).await;
    if wants_markdown(&query, &request) {
        return markdown(markdown::render_summary_markdown(
            &summary,
            &store.config().mount_path(),
        ));
    }

    Json(summary).into_response()
}

/// `GET /studio/api/agent/diagnose`
pub async fn agent_diagnose(store: Inject<StudioStore>, Query(query): QueryString, request: Request) -> Response {
    // `?since=60` keeps the problems seen in the last minute. A number no duration can hold, such
    // as a negative one, counts as not given...
    let within = seconds(&query, "since").and_then(|seconds| Duration::try_from_secs_f64(seconds).ok());
    let diagnostics = agent::diagnose(&store, within).await;
    if wants_markdown(&query, &request) {
        return markdown(markdown::render_diagnostics_markdown(&diagnostics));
    }

    Json(diagnostics).into_response()
}

/// `GET /studio/api/agent/last-request`
pub async fn agent_last_request(
    store: Inject<StudioStore>,
    Query(query): QueryString,
    request: Request,
) -> laravel::Result<Response> {
    let Some(trace) = agent::latest_request(&store, text(&query, "path"), text(&query, "method")) else {
        return Err(laravel::abort_with(404, "No such request has been captured yet."));
    };
    if wants_markdown(&query, &request) {
        let mut out = markdown::render_trace_markdown(&trace);
        markdown::append_trace_details(&store, &trace, &mut out);
        return Ok(markdown(out));
    }

    Ok(Json(trace_details(&store, &trace)).into_response())
}

/// `GET /studio/api/agent/last-error`
pub async fn agent_last_error(
    store: Inject<StudioStore>,
    Query(query): QueryString,
    request: Request,
) -> laravel::Result<Response> {
    let Some(exception) = store.latest_exception() else {
        return Err(laravel::abort_with(404, "No error has been captured yet."));
    };
    if wants_markdown(&query, &request) {
        return Ok(markdown(markdown::render_exception_markdown(
            &exception,
            &store.config().mount_path(),
        )));
    }

    Ok(Json(exception).into_response())
}

/// `GET /studio/api/agent/last-mail`
pub async fn agent_last_mail(
    store: Inject<StudioStore>,
    Query(query): QueryString,
    request: Request,
) -> laravel::Result<Response> {
    let recipient = text(&query, "to").map(str::to_lowercase);
    let mail = store
        .list_mails(text(&query, "kind"), None, usize::MAX)
        .into_iter()
        .find(|mail| {
            recipient.as_ref().is_none_or(|to| {
                mail.to
                    .as_ref()
                    .is_some_and(|sent_to| sent_to.to_lowercase().contains(to))
            })
        });
    let Some(mail) = mail else {
        return Err(laravel::abort_with(404, "No such message has been captured yet."));
    };
    if wants_markdown(&query, &request) {
        return Ok(markdown(markdown::render_mail_markdown(&mail)));
    }

    Ok(Json(mail).into_response())
}

/// `GET /studio/api/agent/wait`: answers when a matching record is captured, or with
/// `{"matched": false}` when the time runs out.
pub async fn agent_wait(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
    let lasting = |name: &str, default: f64, max: f64| {
        Duration::from_secs_f64(seconds(&query, name).unwrap_or(default).clamp(0.0, max))
    };
    let wait = WaitFor {
        kind: text(&query, "for").unwrap_or_default().to_owned(),
        contains: text(&query, "contains").map(str::to_owned),
        timeout: lasting("timeout", 15.0, 120.0),
        lookback: lasting("lookback", 10.0, 3600.0),
    };

    match agent::wait_for_event(&store, wait).await {
        Some(event) => Json(json!({ "matched": true, "event": event })),
        None => Json(json!({ "matched": false })),
    }
}

// ---- Helpers ----

fn markdown(body: String) -> Response {
    body.with_header("content-type", "text/markdown; charset=utf-8")
}

fn wants_markdown(query: &HashMap<String, String>, request: &Request) -> bool {
    match text(query, "format") {
        Some(format) => matches!(format, "md" | "markdown" | "text"),
        None => request
            .header("accept")
            .is_some_and(|accept| accept.contains("text/markdown")),
    }
}

fn text<'a>(query: &'a HashMap<String, String>, name: &str) -> Option<&'a str> {
    query.get(name).map(String::as_str).filter(|value| !value.is_empty())
}

/// A number of seconds in the query string. `NaN` parses as a number, and no duration can hold
/// it, so it counts as not given.
fn seconds(query: &HashMap<String, String>, name: &str) -> Option<f64> {
    text(query, name)?
        .parse::<f64>()
        .ok()
        .filter(|seconds| !seconds.is_nan())
}

fn flag(query: &HashMap<String, String>, name: &str) -> bool {
    matches!(text(query, name), Some("1" | "true" | "yes"))
}

fn limit(query: &HashMap<String, String>, default: usize, max: usize) -> usize {
    text(query, "limit")
        .and_then(|limit| limit.parse::<usize>().ok())
        .map_or(default, |limit| limit.clamp(1, max))
}

fn escape_html(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}