swimmers 0.2.0

Axum server plus TUI for orchestrating Claude Code and Codex agents across tmux panes
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
use super::*;
use swimmers::openrouter_models::{
    cached_or_default_openrouter_candidates, refresh_openrouter_model_cache,
};
use swimmers::thought::probe::{run_thought_config_probe, ThoughtConfigProbeResult};
pub(crate) use swimmers::types::ThoughtConfigResponse;

pub(crate) type ThoughtConfigTestResponse = ThoughtConfigProbeResult;

pub(crate) struct ApiClient {
    pub(crate) http: Client,
    pub(crate) startup_http: Client,
    pub(crate) base_url: String,
    pub(crate) auth_token: Option<String>,
    pub(crate) startup_wait_timeout: Duration,
    pub(crate) startup_retry_interval: Duration,
}

enum StartupAccessError {
    Retryable(String),
    Fatal(String),
}

impl StartupAccessError {
    fn into_string(self) -> String {
        match self {
            Self::Retryable(message) | Self::Fatal(message) => message,
        }
    }
}

impl ApiClient {
    fn build_http_client(timeout: Duration) -> Result<Client, String> {
        Client::builder()
            .connect_timeout(API_CONNECT_TIMEOUT)
            .timeout(timeout)
            .build()
            .map_err(|err| format!("failed to build http client: {err}"))
    }

    pub(crate) fn from_env() -> Result<Self, String> {
        let config = Config::from_env();
        let base_url = std::env::var("SWIMMERS_TUI_URL")
            .unwrap_or_else(|_| format!("http://127.0.0.1:{}", config.port));
        let auth_token = match config.auth_mode {
            AuthMode::Token => config.auth_token,
            AuthMode::LocalTrust => None,
        };
        let http = Self::build_http_client(API_REQUEST_TIMEOUT)?;
        let startup_http = Self::build_http_client(API_STARTUP_REQUEST_TIMEOUT)?;

        Ok(Self {
            http,
            startup_http,
            base_url,
            auth_token,
            startup_wait_timeout: API_STARTUP_WAIT_TIMEOUT,
            startup_retry_interval: API_STARTUP_RETRY_INTERVAL,
        })
    }

    pub(crate) fn with_auth(&self, builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        match &self.auth_token {
            Some(token) => builder.bearer_auth(token),
            None => builder,
        }
    }

    pub(crate) fn transport_error(&self, action: &str, err: reqwest::Error) -> String {
        let detail = root_error_message(&err);
        tracing::warn!(
            url = %self.base_url,
            action,
            is_timeout = err.is_timeout(),
            is_connect = err.is_connect(),
            is_request = err.is_request(),
            status = ?err.status(),
            detail = %detail,
            "tui http transport error"
        );
        friendly_transport_error_with_detail(&self.base_url, action, &err, &detail)
    }

    pub(crate) fn targets_local_backend(&self) -> bool {
        let Ok(url) = reqwest::Url::parse(&self.base_url) else {
            return false;
        };
        match url.host_str() {
            Some("localhost") => true,
            Some(host) => host
                .parse::<std::net::IpAddr>()
                .map(|ip| ip.is_loopback())
                .unwrap_or(false),
            None => false,
        }
    }

    pub(crate) fn startup_access_error(&self, path: &str, status: reqwest::StatusCode) -> String {
        match status {
            reqwest::StatusCode::UNAUTHORIZED => format!(
                "backend at {} requires valid auth for {}. Set AUTH_MODE=token and AUTH_TOKEN to match the target API.",
                self.base_url, path
            ),
            reqwest::StatusCode::FORBIDDEN => format!(
                "backend at {} denied startup access to {}. Use a token with the required session scope for this TUI instance.",
                self.base_url, path
            ),
            _ => format!(
                "backend at {} rejected startup access to {} ({status})",
                self.base_url, path
            ),
        }
    }

    fn startup_transport_error(&self, action: &str, err: reqwest::Error) -> StartupAccessError {
        let retryable = err.is_connect() || err.is_timeout();
        // transport_error already emits a structured warn; this just labels
        // whether the preflight loop will retry or give up.
        tracing::debug!(action, retryable, "startup transport error classified");
        let message = self.transport_error(action, err);
        if retryable {
            StartupAccessError::Retryable(message)
        } else {
            StartupAccessError::Fatal(message)
        }
    }

    async fn ensure_startup_access_probe(
        &self,
        response: reqwest::Response,
        path: &str,
    ) -> Result<(), StartupAccessError> {
        if response.status().is_success() {
            return Ok(());
        }

        let status = response.status();
        match status {
            reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN => Err(
                StartupAccessError::Fatal(self.startup_access_error(path, status)),
            ),
            _ => Err(StartupAccessError::Fatal(read_error(response).await)),
        }
    }

    async fn preflight_session_refresh_access_with_client(
        &self,
        http: &Client,
    ) -> Result<(), StartupAccessError> {
        let url = format!("{}/v1/sessions", self.base_url);
        tracing::debug!(url = %url, "preflight: GET /v1/sessions");
        let response = self
            .with_auth(http.get(url))
            .send()
            .await
            .map_err(|err| self.startup_transport_error("refresh sessions", err))?;

        self.ensure_startup_access_probe(response, "/v1/sessions")
            .await
    }

    async fn preflight_session_refresh_access(&self) -> Result<(), String> {
        self.preflight_session_refresh_access_with_client(&self.http)
            .await
            .map_err(StartupAccessError::into_string)
    }

    async fn preflight_selection_sync_access_with_client(
        &self,
        http: &Client,
    ) -> Result<(), StartupAccessError> {
        let url = format!("{}/v1/selection", self.base_url);
        tracing::debug!(url = %url, "preflight: PUT /v1/selection (clear)");
        let response = self
            .with_auth(http.put(url))
            .json(&PublishSelectionRequest { session_id: None })
            .send()
            .await
            .map_err(|err| self.startup_transport_error("clear the published selection", err))?;

        self.ensure_startup_access_probe(response, "/v1/selection")
            .await
    }

    async fn preflight_selection_sync_access(&self) -> Result<(), String> {
        self.preflight_selection_sync_access_with_client(&self.http)
            .await
            .map_err(StartupAccessError::into_string)
    }

    async fn wait_for_local_startup_probe<F, Fut>(
        &self,
        deadline: Instant,
        mut probe: F,
    ) -> Result<(), String>
    where
        F: FnMut() -> Fut,
        Fut: std::future::Future<Output = Result<(), StartupAccessError>>,
    {
        let started = Instant::now();
        let mut attempt: u32 = 0;
        loop {
            attempt += 1;
            match probe().await {
                Ok(()) => {
                    tracing::info!(
                        attempt,
                        elapsed_ms = started.elapsed().as_millis() as u64,
                        url = %self.base_url,
                        "preflight probe ready"
                    );
                    return Ok(());
                }
                Err(StartupAccessError::Fatal(message)) => {
                    tracing::error!(
                        attempt,
                        elapsed_ms = started.elapsed().as_millis() as u64,
                        url = %self.base_url,
                        message = %message,
                        "preflight probe failed (fatal)"
                    );
                    return Err(message);
                }
                Err(StartupAccessError::Retryable(message)) => {
                    let elapsed_ms = started.elapsed().as_millis() as u64;
                    if Instant::now() >= deadline {
                        tracing::error!(
                            attempt,
                            elapsed_ms,
                            url = %self.base_url,
                            message = %message,
                            "preflight probe deadline exceeded"
                        );
                        return Err(message);
                    }
                    tracing::warn!(
                        attempt,
                        elapsed_ms,
                        url = %self.base_url,
                        message = %message,
                        "preflight probe retrying"
                    );
                }
            }
            tokio::time::sleep(self.startup_retry_interval).await;
        }
    }

    async fn preflight_local_startup_access(&self) -> Result<(), String> {
        let deadline = Instant::now() + self.startup_wait_timeout;
        self.wait_for_local_startup_probe(deadline, || {
            self.preflight_session_refresh_access_with_client(&self.startup_http)
        })
        .await?;
        self.wait_for_local_startup_probe(deadline, || {
            self.preflight_selection_sync_access_with_client(&self.startup_http)
        })
        .await
    }

    pub(crate) async fn preflight_startup_access(&self) -> Result<(), String> {
        let local = self.targets_local_backend();
        tracing::info!(
            url = %self.base_url,
            local,
            wait_timeout_ms = self.startup_wait_timeout.as_millis() as u64,
            "preflight startup access begin"
        );
        if local {
            return self.preflight_local_startup_access().await;
        }
        self.preflight_session_refresh_access().await?;
        self.preflight_selection_sync_access().await?;
        Ok(())
    }

    async fn local_test_thought_config(
        &self,
        config: ThoughtConfig,
    ) -> Result<ThoughtConfigTestResponse, String> {
        let config = config
            .normalize_and_validate()
            .map_err(|err| err.to_string())?;
        Ok(run_thought_config_probe(&config).await)
    }

    async fn refresh_openrouter_candidates_inner(&self) -> Result<Vec<String>, String> {
        refresh_openrouter_model_cache(&self.http)
            .await
            .map(|cache| cache.models)
    }
}

pub(crate) fn root_error_message(err: &(dyn StdError + 'static)) -> String {
    let mut current = Some(err);
    let mut last = err.to_string();

    while let Some(next) = current.and_then(StdError::source) {
        let next_text = next.to_string();
        if !next_text.is_empty() {
            last = next_text;
        }
        current = Some(next);
    }

    last
}

fn friendly_transport_error_with_detail(
    base_url: &str,
    action: &str,
    err: &reqwest::Error,
    detail: &str,
) -> String {
    let summary = if err.is_timeout() {
        format!("timed out while trying to {action}")
    } else {
        format!("could not {action}")
    };
    let mut msg = format!(
        "swimmers API unavailable at {base_url}: {summary} ({detail}). Start `swimmers` or set SWIMMERS_TUI_URL."
    );
    if let Some(path) = client_log_path() {
        msg.push_str(&format!(" Tail logs: {}", path.display()));
    }
    msg
}

pub(crate) trait TuiApi: Send + Sync + 'static {
    fn fetch_sessions(&self) -> BoxFuture<'_, Result<Vec<SessionSummary>, String>>;
    fn fetch_thought_config(&self) -> BoxFuture<'_, Result<ThoughtConfigResponse, String>>;
    fn update_thought_config(
        &self,
        config: ThoughtConfig,
    ) -> BoxFuture<'_, Result<ThoughtConfig, String>>;
    fn test_thought_config(
        &self,
        config: ThoughtConfig,
    ) -> BoxFuture<'_, Result<ThoughtConfigTestResponse, String>>;
    fn refresh_openrouter_candidates(&self) -> BoxFuture<'_, Result<Vec<String>, String>>;
    fn fetch_mermaid_artifact(
        &self,
        session_id: &str,
    ) -> BoxFuture<'_, Result<MermaidArtifactResponse, String>>;
    fn fetch_plan_file(
        &self,
        session_id: &str,
        name: &str,
    ) -> BoxFuture<'_, Result<PlanFileResponse, String>>;
    fn fetch_native_status(&self) -> BoxFuture<'_, Result<NativeDesktopStatusResponse, String>>;
    fn set_native_app(
        &self,
        app: NativeDesktopApp,
    ) -> BoxFuture<'_, Result<NativeDesktopStatusResponse, String>>;
    fn set_native_mode(
        &self,
        mode: GhosttyOpenMode,
    ) -> BoxFuture<'_, Result<NativeDesktopStatusResponse, String>>;
    fn publish_selection(&self, session_id: Option<&str>) -> BoxFuture<'_, Result<(), String>>;
    fn open_session(
        &self,
        session_id: &str,
    ) -> BoxFuture<'_, Result<NativeDesktopOpenResponse, String>>;
    fn list_dirs(
        &self,
        path: Option<&str>,
        managed_only: bool,
        group: Option<&str>,
    ) -> BoxFuture<'_, Result<DirListResponse, String>>;
    fn start_repo_action(
        &self,
        path: &str,
        kind: RepoActionKind,
    ) -> BoxFuture<'_, Result<DirRepoActionResponse, String>>;
    fn create_session(
        &self,
        cwd: &str,
        spawn_tool: SpawnTool,
        initial_request: Option<String>,
    ) -> BoxFuture<'_, Result<CreateSessionResponse, String>>;
}

impl TuiApi for ApiClient {
    fn fetch_sessions(&self) -> BoxFuture<'_, Result<Vec<SessionSummary>, String>> {
        Box::pin(async move {
            let url = format!("{}/v1/sessions", self.base_url);
            let started = Instant::now();
            let response = self
                .with_auth(self.http.get(url).timeout(API_SESSION_LIST_TIMEOUT))
                .send()
                .await
                .map_err(|err| self.transport_error("refresh sessions", err))?;

            let status = response.status();
            tracing::debug!(
                elapsed_ms = started.elapsed().as_millis() as u64,
                status = %status,
                "fetch_sessions response"
            );
            if status.is_success() {
                let payload = response
                    .json::<SessionListResponse>()
                    .await
                    .map_err(|err| format!("failed to parse sessions response: {err}"))?;
                return Ok(payload.sessions);
            }

            let body = read_error(response).await;
            tracing::warn!(status = %status, body = %body, "fetch_sessions non-success status");
            Err(body)
        })
    }

    fn fetch_thought_config(&self) -> BoxFuture<'_, Result<ThoughtConfigResponse, String>> {
        Box::pin(async move {
            let url = format!("{}/v1/thought-config", self.base_url);
            let response = self
                .with_auth(self.http.get(url))
                .send()
                .await
                .map_err(|err| self.transport_error("fetch thought config", err))?;

            if response.status().is_success() {
                return response
                    .json::<ThoughtConfigResponse>()
                    .await
                    .map_err(|err| format!("failed to parse thought config: {err}"));
            }

            Err(read_error(response).await)
        })
    }

    fn update_thought_config(
        &self,
        config: ThoughtConfig,
    ) -> BoxFuture<'_, Result<ThoughtConfig, String>> {
        Box::pin(async move {
            let url = format!("{}/v1/thought-config", self.base_url);
            let response = self
                .with_auth(self.http.put(url))
                .json(&config)
                .send()
                .await
                .map_err(|err| self.transport_error("update thought config", err))?;

            if response.status().is_success() {
                return response
                    .json::<ThoughtConfig>()
                    .await
                    .map_err(|err| format!("failed to parse updated thought config: {err}"));
            }

            Err(read_error(response).await)
        })
    }

    fn test_thought_config(
        &self,
        config: ThoughtConfig,
    ) -> BoxFuture<'_, Result<ThoughtConfigTestResponse, String>> {
        Box::pin(async move {
            let url = format!("{}/v1/thought-config/test", self.base_url);
            let response = self
                .with_auth(self.http.post(url))
                .json(&config)
                .send()
                .await;

            let response = match response {
                Ok(response) => response,
                Err(err) if self.targets_local_backend() => {
                    return self.local_test_thought_config(config).await;
                }
                Err(err) => return Err(self.transport_error("test thought config", err)),
            };

            if response.status().is_success() {
                return response
                    .json::<ThoughtConfigTestResponse>()
                    .await
                    .map_err(|err| format!("failed to parse thought config test: {err}"));
            }

            if response.status() == reqwest::StatusCode::NOT_FOUND && self.targets_local_backend() {
                return self.local_test_thought_config(config).await;
            }

            Err(read_error(response).await)
        })
    }

    fn refresh_openrouter_candidates(&self) -> BoxFuture<'_, Result<Vec<String>, String>> {
        Box::pin(async move {
            match self.refresh_openrouter_candidates_inner().await {
                Ok(models) if !models.is_empty() => Ok(models),
                Ok(_) => Ok(cached_or_default_openrouter_candidates()),
                Err(err) => Err(err),
            }
        })
    }

    fn fetch_mermaid_artifact(
        &self,
        session_id: &str,
    ) -> BoxFuture<'_, Result<MermaidArtifactResponse, String>> {
        let session_id = session_id.to_string();
        Box::pin(async move {
            let url = format!(
                "{}/v1/sessions/{}/mermaid-artifact",
                self.base_url, session_id
            );
            let response = self
                .with_auth(self.http.get(url).timeout(API_MERMAID_ARTIFACT_TIMEOUT))
                .send()
                .await
                .map_err(|err| self.transport_error("fetch mermaid artifact", err))?;

            if response.status().is_success() {
                return response
                    .json::<MermaidArtifactResponse>()
                    .await
                    .map_err(|err| format!("failed to parse mermaid artifact: {err}"));
            }

            Err(read_error(response).await)
        })
    }

    fn fetch_plan_file(
        &self,
        session_id: &str,
        name: &str,
    ) -> BoxFuture<'_, Result<PlanFileResponse, String>> {
        let session_id = session_id.to_string();
        let name = name.to_string();
        Box::pin(async move {
            let url = format!("{}/v1/sessions/{}/plan-file", self.base_url, session_id);
            let response = self
                .with_auth(self.http.get(url))
                .query(&[("name", &name)])
                .send()
                .await
                .map_err(|err| self.transport_error("fetch plan file", err))?;

            if response.status().is_success() {
                return response
                    .json::<PlanFileResponse>()
                    .await
                    .map_err(|err| format!("failed to parse plan file: {err}"));
            }

            Err(read_error(response).await)
        })
    }

    fn fetch_native_status(&self) -> BoxFuture<'_, Result<NativeDesktopStatusResponse, String>> {
        Box::pin(async move {
            let url = format!("{}/v1/native/status", self.base_url);
            let response = self
                .with_auth(self.http.get(url))
                .send()
                .await
                .map_err(|err| self.transport_error("check native desktop status", err))?;

            if response.status().is_success() {
                return response
                    .json::<NativeDesktopStatusResponse>()
                    .await
                    .map_err(|err| format!("failed to parse native status: {err}"));
            }

            Err(read_error(response).await)
        })
    }

    fn set_native_app(
        &self,
        app: NativeDesktopApp,
    ) -> BoxFuture<'_, Result<NativeDesktopStatusResponse, String>> {
        Box::pin(async move {
            let url = format!("{}/v1/native/app", self.base_url);
            let response = self
                .with_auth(self.http.put(url))
                .json(&NativeDesktopConfigRequest { app })
                .send()
                .await
                .map_err(|err| self.transport_error("switch the native desktop target", err))?;

            if response.status().is_success() {
                return response
                    .json::<NativeDesktopStatusResponse>()
                    .await
                    .map_err(|err| format!("failed to parse native status: {err}"));
            }

            if response.status() == reqwest::StatusCode::NOT_FOUND {
                return Err(format!(
                    "backend at {} does not support runtime native target switching yet. If this is your local server, restart `swimmers` or relaunch via `make tui`.",
                    self.base_url
                ));
            }

            Err(read_error(response).await)
        })
    }

    fn set_native_mode(
        &self,
        mode: GhosttyOpenMode,
    ) -> BoxFuture<'_, Result<NativeDesktopStatusResponse, String>> {
        Box::pin(async move {
            let url = format!("{}/v1/native/mode", self.base_url);
            let response = self
                .with_auth(self.http.put(url))
                .json(&NativeDesktopModeRequest { mode })
                .send()
                .await
                .map_err(|err| self.transport_error("switch the Ghostty preview mode", err))?;

            if response.status().is_success() {
                return response
                    .json::<NativeDesktopStatusResponse>()
                    .await
                    .map_err(|err| format!("failed to parse native status: {err}"));
            }

            if response.status() == reqwest::StatusCode::NOT_FOUND {
                return Err(format!(
                    "backend at {} does not support runtime Ghostty preview mode switching yet. If this is your local server, restart `swimmers` or relaunch via `make tui`.",
                    self.base_url
                ));
            }

            Err(read_error(response).await)
        })
    }

    fn publish_selection(&self, session_id: Option<&str>) -> BoxFuture<'_, Result<(), String>> {
        let session_id = session_id.map(|value| value.to_string());
        Box::pin(async move {
            let url = format!("{}/v1/selection", self.base_url);
            let response = self
                .with_auth(self.http.put(url))
                .json(&PublishSelectionRequest { session_id })
                .send()
                .await
                .map_err(|err| self.transport_error("publish the selected session", err))?;

            if response.status().is_success() {
                return Ok(());
            }

            Err(read_error(response).await)
        })
    }

    fn open_session(
        &self,
        session_id: &str,
    ) -> BoxFuture<'_, Result<NativeDesktopOpenResponse, String>> {
        let session_id = session_id.to_string();
        Box::pin(async move {
            let url = format!("{}/v1/native/open", self.base_url);
            let response = self
                .with_auth(self.http.post(url))
                .timeout(API_NATIVE_OPEN_TIMEOUT)
                .json(&NativeDesktopOpenRequest { session_id })
                .send()
                .await
                .map_err(|err| self.transport_error("open the selected session", err))?;

            if response.status().is_success() {
                return response
                    .json::<NativeDesktopOpenResponse>()
                    .await
                    .map_err(|err| format!("failed to parse native open response: {err}"));
            }

            Err(read_error(response).await)
        })
    }

    fn list_dirs(
        &self,
        path: Option<&str>,
        managed_only: bool,
        group: Option<&str>,
    ) -> BoxFuture<'_, Result<DirListResponse, String>> {
        let path = path.map(|value| value.to_string());
        let group = group.map(|value| value.to_string());
        Box::pin(async move {
            let url = format!("{}/v1/dirs", self.base_url);
            let mut request = self.http.get(url);
            if let Some(path) = path {
                request = request.query(&[("path", path)]);
            }
            if managed_only {
                request = request.query(&[("managed_only", true)]);
            }
            if let Some(group) = group {
                request = request.query(&[("group", group)]);
            }

            let response = self
                .with_auth(request.timeout(API_DIRECTORY_LIST_TIMEOUT))
                .send()
                .await
                .map_err(|err| self.transport_error("list directories", err))?;

            if response.status().is_success() {
                return response
                    .json::<DirListResponse>()
                    .await
                    .map_err(|err| format!("failed to parse dirs response: {err}"));
            }

            if response.status() == reqwest::StatusCode::NOT_FOUND {
                return Err(format!(
                    "backend at {} does not expose /v1/dirs. Click-to-spawn directory browsing requires a `swimmers` build with `--features personal-workflows`; if this is your local server, relaunch via `make tui`.",
                    self.base_url
                ));
            }

            Err(read_error(response).await)
        })
    }

    fn start_repo_action(
        &self,
        path: &str,
        kind: RepoActionKind,
    ) -> BoxFuture<'_, Result<DirRepoActionResponse, String>> {
        let path = path.to_string();
        Box::pin(async move {
            let url = format!("{}/v1/dirs/actions", self.base_url);
            let response = self
                .with_auth(self.http.post(url))
                .timeout(API_DIRECTORY_ACTION_TIMEOUT)
                .json(&DirRepoActionRequest { path, kind })
                .send()
                .await
                .map_err(|err| self.transport_error("start the repo action", err))?;

            if response.status().is_success() {
                return response
                    .json::<DirRepoActionResponse>()
                    .await
                    .map_err(|err| format!("failed to parse repo action response: {err}"));
            }

            if response.status() == reqwest::StatusCode::NOT_FOUND {
                return Err(format!(
                    "backend at {} does not expose /v1/dirs/actions. Repo actions require a `swimmers` build with `--features personal-workflows`; if this is your local server, relaunch via `make tui`.",
                    self.base_url
                ));
            }

            Err(read_error(response).await)
        })
    }

    fn create_session(
        &self,
        cwd: &str,
        spawn_tool: SpawnTool,
        initial_request: Option<String>,
    ) -> BoxFuture<'_, Result<CreateSessionResponse, String>> {
        let cwd = cwd.to_string();
        Box::pin(async move {
            let url = format!("{}/v1/sessions", self.base_url);
            let response = self
                .with_auth(self.http.post(url))
                .timeout(API_CREATE_SESSION_TIMEOUT)
                .json(&CreateSessionRequest {
                    name: None,
                    cwd: Some(cwd),
                    spawn_tool: Some(spawn_tool),
                    initial_request,
                })
                .send()
                .await
                .map_err(|err| self.transport_error("create a session", err))?;

            if response.status().is_success() {
                return response
                    .json::<CreateSessionResponse>()
                    .await
                    .map_err(|err| format!("failed to parse create session response: {err}"));
            }

            Err(read_error(response).await)
        })
    }
}

pub(crate) async fn read_error(response: reqwest::Response) -> String {
    let status = response.status();
    match response.json::<ErrorResponse>().await {
        Ok(body) => body
            .message
            .unwrap_or_else(|| format!("request failed: {}", status)),
        Err(_) => format!("request failed: {}", status),
    }
}