suno-core 0.2.0

Engine for a download-only Suno.ai library tool: feed selection, sync reconciliation, and audio tagging.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
//! The Suno API client: lists the library behind the [`Http`](crate::Http) port.

use serde_json::Value;

use crate::auth::ClerkAuth;
use crate::consts::{
    CLIP_PARENT_PATH, FEED_V2_PATH, IDS_PER_REQUEST, MAX_PAGES, PLAYLIST_ME_PATH, PLAYLIST_PATH,
    SUNO_API_BASE_URL,
};
use crate::error::{Error, Result};
use crate::http::{Http, HttpRequest, Method};
use crate::model::Clip;

const EXCLUDED_TASKS: [&str; 2] = ["infill", "fixed_infill"];
const EXCLUDED_TYPES: [&str; 1] = ["rendered_context_window"];

/// One of the account's own playlists, as listed by `/api/playlist/me`.
///
/// Carries only what playlist reconciliation needs: the stable id (the state
/// key), the display name (drives the `.m3u8` file name and `#PLAYLIST` line),
/// and the member count for reporting. The ordered members are fetched
/// separately with [`SunoClient::get_playlist_clips`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Playlist {
    /// The playlist's stable Suno id.
    pub id: String,
    /// The playlist's display name.
    pub name: String,
    /// The number of clips Suno reports in the playlist.
    pub num_clips: u64,
}

/// A client for the Suno library API, owning the account's [`ClerkAuth`].
pub struct SunoClient {
    auth: ClerkAuth,
}

impl SunoClient {
    /// Create a client from a fresh or already-authenticated [`ClerkAuth`].
    pub fn new(auth: ClerkAuth) -> Self {
        Self { auth }
    }

    /// Borrow the underlying authenticator.
    pub fn auth(&self) -> &ClerkAuth {
        &self.auth
    }

    /// List clips across the whole library, or only liked clips.
    ///
    /// Stops early once `limit` clips are collected. Paging is hard-capped at
    /// [`MAX_PAGES`] so a runaway `has_more` can never loop forever.
    ///
    /// Returns the clips paired with a `complete` flag that is `true` only when
    /// paging ended because the server reported `has_more == false` (the feed
    /// fully drained). A `limit` stop, or exhausting [`MAX_PAGES`] while
    /// `has_more` is still set, yields `false` so the caller can refuse to treat
    /// a truncated listing as authoritative for deletion.
    pub async fn list_clips(
        &mut self,
        http: &impl Http,
        liked: bool,
        limit: Option<usize>,
    ) -> Result<(Vec<Clip>, bool)> {
        let mut clips = Vec::new();
        let suffix = if liked { "&is_liked=true" } else { "" };
        let mut complete = false;
        for page in 0..MAX_PAGES {
            let path = format!("/api/feed/v2/?page={page}{suffix}");
            let body = self.api_get(http, &path).await?;
            let (page_clips, has_more) = parse_feed(&body)?;
            clips.extend(page_clips);
            if !has_more {
                complete = true;
                break;
            }
            if limit.is_some_and(|n| clips.len() >= n) {
                break;
            }
        }
        if let Some(n) = limit {
            clips.truncate(n);
        }
        Ok((clips, complete))
    }

    /// Fetch one clip by ID.
    ///
    /// Tries the dedicated `/api/clip/{id}` endpoint first, then falls back to
    /// scanning the library feed, since that endpoint's exact shape is not yet
    /// confirmed against the live API.
    pub async fn get_clip(&mut self, http: &impl Http, id: &str) -> Result<Clip> {
        if let Some(clip) = self.try_get_clip(http, id).await? {
            return Ok(clip);
        }
        self.find_in_feed(http, id).await
    }

    /// Ask Suno to render a clip to lossless WAV (server-side, asynchronous).
    pub async fn request_wav(&mut self, http: &impl Http, id: &str) -> Result<()> {
        let path = format!("/api/gen/{id}/convert_wav/");
        self.api_request(http, Method::Post, &path).await?;
        Ok(())
    }

    /// Read the rendered WAV URL for a clip, or `None` while it is not ready.
    pub async fn wav_url(&mut self, http: &impl Http, id: &str) -> Result<Option<String>> {
        let path = format!("/api/gen/{id}/wav_file/");
        let body = self.api_get(http, &path).await?;
        let data: Value = serde_json::from_slice(&body)
            .map_err(|err| Error::Api(format!("invalid wav_file JSON: {err}")))?;
        Ok(data
            .get("wav_file_url")
            .and_then(Value::as_str)
            .filter(|url| !url.is_empty())
            .map(str::to_string))
    }

    /// Fetch specific clips by id through the feed's `?ids=` filter.
    ///
    /// Used by lineage resolution to gap-fill ancestors that are absent from a
    /// normal listing, including trashed ones. Unlike
    /// [`list_clips`](Self::list_clips), no `keep_clip` filtering is applied: an
    /// ancestor may itself be an infill or context-window artefact that the
    /// lineage walk must still traverse. Clips returned here are ancestors for
    /// resolution only and must never be treated as download candidates. Ids are
    /// chunked so a long list cannot build an over-long URL.
    pub async fn get_clips_by_ids(&mut self, http: &impl Http, ids: &[&str]) -> Result<Vec<Clip>> {
        let mut clips = Vec::new();
        for chunk in ids.chunks(IDS_PER_REQUEST) {
            if chunk.is_empty() {
                continue;
            }
            let joined = chunk.join(",");
            let path = format!("{FEED_V2_PATH}?ids={joined}");
            let body = self.api_get(http, &path).await?;
            clips.extend(map_all_clips(&body)?);
        }
        Ok(clips)
    }

    /// Fetch a clip's immediate parent via the dedicated parent endpoint.
    ///
    /// Returns the parent clip, or `None` when the clip is a root (no parent) or
    /// the endpoint yields no clip. Lineage resolution uses this as a fallback
    /// when a missing ancestor cannot be retrieved by id. Only a `404` (the clip
    /// has no parent) maps to `None`; any other failure, including a transient
    /// `5xx`, propagates as an error rather than being mistaken for a root.
    pub async fn get_clip_parent(&mut self, http: &impl Http, id: &str) -> Result<Option<Clip>> {
        let path = format!("{CLIP_PARENT_PATH}?clip_id={id}");
        match self.api_get(http, &path).await {
            Ok(body) => Ok(parse_clip(&body)),
            Err(Error::NotFound(_)) => Ok(None),
            Err(err) => Err(err),
        }
    }

    /// List the account's own playlists, paging `/api/playlist/me`.
    ///
    /// Trashed and share-list playlists are excluded by query, so the result is
    /// the account's authoritative own set. Paging stops on the first empty page
    /// and is hard-capped at [`MAX_PAGES`] so a server that ignores the page
    /// parameter cannot loop forever. Only entries with a non-empty id are kept.
    ///
    /// A hard failure propagates as an error; the caller treats that as "the
    /// playlist listing did not fully enumerate" and refuses every playlist
    /// deletion this run, so a dropped fetch can never remove a `.m3u8`.
    pub async fn get_playlists(&mut self, http: &impl Http) -> Result<Vec<Playlist>> {
        let mut playlists = Vec::new();
        for page in 1..=MAX_PAGES {
            let path =
                format!("{PLAYLIST_ME_PATH}?page={page}&show_trashed=false&show_sharelist=false");
            let body = self.api_get(http, &path).await?;
            let page_playlists = parse_playlists(&body)?;
            if page_playlists.is_empty() {
                break;
            }
            playlists.extend(page_playlists);
        }
        Ok(playlists)
    }

    /// Fetch one playlist's clips in Suno order via `/api/playlist/{id}/`.
    ///
    /// The response's `playlist_clips[]` is already ordered and trashed members
    /// are excluded by Suno, so the order is preserved exactly and no `keep_clip`
    /// filtering is applied — a playlist may legitimately contain any clip. Each
    /// entry's `clip` object is mapped (falling back to the entry itself), and
    /// only clips with a non-empty id are kept.
    pub async fn get_playlist_clips(&mut self, http: &impl Http, id: &str) -> Result<Vec<Clip>> {
        let path = format!("{PLAYLIST_PATH}{id}/");
        let body = self.api_get(http, &path).await?;
        parse_playlist_clips(&body)
    }

    /// Try the dedicated clip endpoint, returning `None` when it is missing or
    /// returns a body that does not yield the requested clip.
    async fn try_get_clip(&mut self, http: &impl Http, id: &str) -> Result<Option<Clip>> {
        let path = format!("/api/clip/{id}");
        match self.api_get(http, &path).await {
            Ok(body) => Ok(parse_clip(&body).filter(|clip| clip.id == id)),
            Err(Error::NotFound(_)) => Ok(None),
            Err(err) => Err(err),
        }
    }

    /// Locate a clip by scanning the library feed.
    async fn find_in_feed(&mut self, http: &impl Http, id: &str) -> Result<Clip> {
        let (clips, _complete) = self.list_clips(http, false, None).await?;
        clips
            .into_iter()
            .find(|clip| clip.id == id)
            .ok_or_else(|| Error::Api(format!("clip {id} not found in the library")))
    }

    /// Perform an authenticated GET, refreshing the JWT once on a 401/403.
    async fn api_get(&mut self, http: &impl Http, path: &str) -> Result<Vec<u8>> {
        self.api_request(http, Method::Get, path).await
    }

    /// Perform an authenticated request, refreshing the JWT once on a 401/403.
    async fn api_request(
        &mut self,
        http: &impl Http,
        method: Method,
        path: &str,
    ) -> Result<Vec<u8>> {
        let url = format!("{SUNO_API_BASE_URL}{path}");
        for attempt in 0..2 {
            let jwt = self.auth.ensure_jwt(http).await?;
            let request = HttpRequest {
                method,
                url: url.clone(),
                headers: vec![("Authorization".to_string(), format!("Bearer {jwt}"))],
            };
            let response = http
                .send(request)
                .await
                .map_err(|err| Error::Connection(err.to_string()))?;
            match response.status {
                200..=299 => return Ok(response.body),
                401 | 403 if attempt == 0 => self.auth.invalidate_jwt(),
                401 | 403 => {
                    return Err(Error::Auth(format!(
                        "Suno API auth failed with status {}",
                        response.status
                    )));
                }
                429 => return Err(Error::RateLimited),
                404 => {
                    return Err(Error::NotFound(format!("Suno API returned 404: {path}")));
                }
                status => {
                    let preview: String = String::from_utf8_lossy(&response.body)
                        .chars()
                        .take(200)
                        .collect();
                    return Err(Error::Api(format!("Suno API returned {status}: {preview}")));
                }
            }
        }
        Err(Error::Api("Suno API request failed after retries".into()))
    }
}

/// Parse a single-clip response body, accepting either a bare clip object or a
/// `{"clip": {...}}` wrapper. Returns `None` when no clip id is present.
fn parse_clip(body: &[u8]) -> Option<Clip> {
    let data: Value = serde_json::from_slice(body).ok()?;
    let raw = data
        .get("clip")
        .filter(|value| value.is_object())
        .unwrap_or(&data);
    let has_id = raw
        .get("id")
        .and_then(Value::as_str)
        .is_some_and(|id| !id.is_empty());
    has_id.then(|| Clip::from_json(raw))
}

/// Parse a feed page body into the kept clips and the `has_more` flag.
fn parse_feed(body: &[u8]) -> Result<(Vec<Clip>, bool)> {
    let data: Value = serde_json::from_slice(body)
        .map_err(|err| Error::Api(format!("invalid feed JSON: {err}")))?;
    let Some(object) = data.as_object() else {
        return Ok((Vec::new(), false));
    };
    let clips = object
        .get("clips")
        .and_then(Value::as_array)
        .map(|raw| {
            raw.iter()
                .filter(|clip| keep_clip(clip))
                .map(Clip::from_json)
                .collect()
        })
        .unwrap_or_default();
    let has_more = object
        .get("has_more")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    Ok((clips, has_more))
}

/// Map every clip in a feed-shaped body, skipping the `keep_clip` filter.
///
/// Accepts either a `{"clips": [...]}` wrapper or a bare array, dropping only
/// elements that carry no id. Used for id-filtered gap-fill fetches, which must
/// preserve trashed and artefact clips so the lineage walk can traverse them.
fn map_all_clips(body: &[u8]) -> Result<Vec<Clip>> {
    let data: Value = serde_json::from_slice(body)
        .map_err(|err| Error::Api(format!("invalid feed JSON: {err}")))?;
    let items: &[Value] = match &data {
        Value::Array(items) => items.as_slice(),
        Value::Object(_) => data
            .get("clips")
            .and_then(Value::as_array)
            .map_or(&[][..], |arr| arr.as_slice()),
        _ => &[],
    };
    Ok(items
        .iter()
        .map(Clip::from_json)
        .filter(|clip| !clip.id.is_empty())
        .collect())
}

/// Parse a `/api/playlist/me` page into playlists, dropping entries with no id.
fn parse_playlists(body: &[u8]) -> Result<Vec<Playlist>> {
    let data: Value = serde_json::from_slice(body)
        .map_err(|err| Error::Api(format!("invalid playlist JSON: {err}")))?;
    Ok(data
        .get("playlists")
        .and_then(Value::as_array)
        .map(|raw| raw.iter().filter_map(parse_playlist_item).collect())
        .unwrap_or_default())
}

/// Map one raw `/api/playlist/me` entry, or `None` when it carries no id.
///
/// `num_total_results` is the playlist's member count; a missing name defaults
/// to `Untitled` (matching the clip mapping) so the file name is never empty.
fn parse_playlist_item(raw: &Value) -> Option<Playlist> {
    let id = raw
        .get("id")
        .and_then(Value::as_str)
        .filter(|id| !id.is_empty())?
        .to_string();
    let name = match raw.get("name") {
        Some(Value::String(name)) if !name.is_empty() => name.clone(),
        _ => "Untitled".to_string(),
    };
    let num_clips = raw
        .get("num_total_results")
        .and_then(Value::as_u64)
        .unwrap_or(0);
    Some(Playlist {
        id,
        name,
        num_clips,
    })
}

/// Parse a `/api/playlist/{id}/` body into its ordered member clips.
///
/// Each `playlist_clips[]` entry wraps the clip under `clip`; the wrapper is
/// unwrapped (falling back to the entry itself), order is preserved exactly, and
/// only clips with a non-empty id survive. No `keep_clip` filter is applied: a
/// playlist may hold any clip, and members absent from the local library are
/// reconciled as comment lines by the caller, not dropped here.
fn parse_playlist_clips(body: &[u8]) -> Result<Vec<Clip>> {
    let data: Value = serde_json::from_slice(body)
        .map_err(|err| Error::Api(format!("invalid playlist JSON: {err}")))?;
    Ok(data
        .get("playlist_clips")
        .and_then(Value::as_array)
        .map(|raw| {
            raw.iter()
                .map(|entry| {
                    let clip = entry
                        .get("clip")
                        .filter(|value| value.is_object())
                        .unwrap_or(entry);
                    Clip::from_json(clip)
                })
                .filter(|clip| !clip.id.is_empty())
                .collect()
        })
        .unwrap_or_default())
}

/// Keep only finished clips that are not infills or context-window artefacts.
fn keep_clip(raw: &Value) -> bool {
    if raw.get("status").and_then(Value::as_str) != Some("complete") {
        return false;
    }
    let metadata = raw.get("metadata");
    let clip_type = metadata.and_then(|m| m.get("type")).and_then(Value::as_str);
    if clip_type.is_some_and(|t| EXCLUDED_TYPES.contains(&t)) {
        return false;
    }
    let task = metadata.and_then(|m| m.get("task")).and_then(Value::as_str);
    !task.is_some_and(|t| EXCLUDED_TASKS.contains(&t))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testutil::{MockHttp, Rule};

    fn feed_body() -> String {
        serde_json::json!({
            "has_more": false,
            "clips": [
                {
                    "id": "a", "title": "Song A", "status": "complete",
                    "audio_url": "https://cdn1.suno.ai/a.mp3",
                    "metadata": {"tags": "rock", "duration": 120.5, "type": "gen"}
                },
                {"id": "b", "title": "Infill", "status": "complete", "metadata": {"task": "infill"}},
                {"id": "c", "title": "Streaming", "status": "streaming", "metadata": {}},
                {
                    "id": "d", "title": "Context", "status": "complete",
                    "metadata": {"type": "rendered_context_window"}
                }
            ]
        })
        .to_string()
    }

    #[test]
    fn parse_feed_filters_and_maps() {
        let (clips, has_more) = parse_feed(feed_body().as_bytes()).unwrap();
        assert!(!has_more);
        assert_eq!(clips.len(), 1);
        assert_eq!(clips[0].id, "a");
        assert_eq!(clips[0].tags, "rock");
        assert!((clips[0].duration - 120.5).abs() < f64::EPSILON);
    }

    #[test]
    fn audiopipe_url_is_rewritten_to_cdn() {
        let raw =
            serde_json::json!({"id": "x", "audio_url": "https://audiopipe.suno.ai/?item_id=x"});
        assert_eq!(
            Clip::from_json(&raw).audio_url,
            "https://cdn1.suno.ai/x.mp3"
        );
    }

    #[test]
    fn list_clips_authenticates_then_reads_the_feed() {
        let client_body = serde_json::json!({
            "response": {
                "last_active_session_id": "s",
                "sessions": [{"id": "s", "user": {"id": "u", "username": "h"}}]
            }
        })
        .to_string();
        let http = MockHttp::new(vec![
            Rule::new(
                "/v1/client/sessions/",
                200,
                r#"{"jwt": "a.b.c"}"#.to_string(),
            ),
            Rule::new("/v1/client", 200, client_body),
            Rule::new("/api/feed/v2", 200, feed_body()),
        ]);

        let mut auth = ClerkAuth::new("eyJtoken");
        pollster::block_on(auth.authenticate(&http)).unwrap();
        let mut client = SunoClient::new(auth);
        let (clips, complete) = pollster::block_on(client.list_clips(&http, false, None)).unwrap();
        assert_eq!(clips.len(), 1);
        assert_eq!(clips[0].id, "a");
        assert!(complete);
    }

    #[test]
    fn list_clips_reports_incomplete_when_paging_is_capped() {
        let mut rules = auth_rules();
        rules.push(Rule::new(
            "/api/feed/v2",
            200,
            serde_json::json!({
                "has_more": true,
                "clips": [{
                    "id": "a", "title": "Song A", "status": "complete",
                    "audio_url": "https://cdn1.suno.ai/a.mp3",
                    "metadata": {"type": "gen"}
                }]
            })
            .to_string(),
        ));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let (_clips, complete) = pollster::block_on(client.list_clips(&http, false, None)).unwrap();
        assert!(!complete);
    }

    fn auth_rules() -> Vec<Rule> {
        let client_body = serde_json::json!({
            "response": {
                "last_active_session_id": "s",
                "sessions": [{"id": "s", "user": {"id": "u", "username": "h"}}]
            }
        })
        .to_string();
        vec![
            Rule::new(
                "/v1/client/sessions/",
                200,
                r#"{"jwt": "a.b.c"}"#.to_string(),
            ),
            Rule::new("/v1/client", 200, client_body),
        ]
    }

    fn authed_client(http: &MockHttp) -> SunoClient {
        let mut auth = ClerkAuth::new("eyJtoken");
        pollster::block_on(auth.authenticate(http)).unwrap();
        SunoClient::new(auth)
    }

    #[test]
    fn parse_clip_accepts_bare_and_wrapped_shapes() {
        let bare = serde_json::json!({"id": "z", "title": "Zed"}).to_string();
        assert_eq!(parse_clip(bare.as_bytes()).unwrap().id, "z");

        let wrapped = serde_json::json!({"clip": {"id": "w", "title": "Wai"}}).to_string();
        assert_eq!(parse_clip(wrapped.as_bytes()).unwrap().id, "w");

        let missing = serde_json::json!({"detail": "not found"}).to_string();
        assert!(parse_clip(missing.as_bytes()).is_none());
    }

    #[test]
    fn get_clip_uses_the_dedicated_endpoint() {
        let clip_body = serde_json::json!({
            "id": "z", "title": "Zed", "status": "complete",
            "audio_url": "https://cdn1.suno.ai/z.mp3",
            "metadata": {"tags": "jazz", "duration": 99.0, "type": "gen"}
        })
        .to_string();
        let mut rules = auth_rules();
        rules.push(Rule::new("/api/clip/", 200, clip_body));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let clip = pollster::block_on(client.get_clip(&http, "z")).unwrap();
        assert_eq!(clip.id, "z");
        assert_eq!(clip.title, "Zed");
        assert_eq!(clip.tags, "jazz");
    }

    #[test]
    fn get_clip_falls_back_to_the_feed_when_endpoint_missing() {
        let mut rules = auth_rules();
        rules.push(Rule::new(
            "/api/clip/",
            404,
            r#"{"detail": "not found"}"#.to_string(),
        ));
        rules.push(Rule::new("/api/feed/v2", 200, feed_body()));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let clip = pollster::block_on(client.get_clip(&http, "a")).unwrap();
        assert_eq!(clip.id, "a");
        assert_eq!(clip.tags, "rock");
    }

    #[test]
    fn request_wav_accepts_a_2xx_status() {
        let mut rules = auth_rules();
        rules.push(Rule::new("/convert_wav/", 201, "{}".to_string()));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        assert!(pollster::block_on(client.request_wav(&http, "z")).is_ok());
    }

    #[test]
    fn wav_url_reads_the_ready_url() {
        let mut rules = auth_rules();
        rules.push(Rule::new(
            "/wav_file/",
            200,
            r#"{"wav_file_url": "https://cdn1.suno.ai/z.wav"}"#.to_string(),
        ));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let url = pollster::block_on(client.wav_url(&http, "z")).unwrap();
        assert_eq!(url.as_deref(), Some("https://cdn1.suno.ai/z.wav"));
    }

    #[test]
    fn wav_url_is_none_until_the_render_is_ready() {
        let mut rules = auth_rules();
        rules.push(Rule::new("/wav_file/", 200, "{}".to_string()));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let url = pollster::block_on(client.wav_url(&http, "z")).unwrap();
        assert_eq!(url, None);
    }

    #[test]
    fn get_clips_by_ids_uses_the_ids_filter_and_keeps_all_clips() {
        // The `?ids=` gap-fill path must not apply the listing's `keep_clip`
        // filter: an infill ancestor and an upload root both survive.
        let feed = serde_json::json!({
            "clips": [
                {
                    "id": "p1", "title": "Infill Ancestor", "status": "complete",
                    "metadata": {"type": "gen", "task": "infill"}
                },
                {
                    "id": "p2", "title": "Uploaded Root", "status": "complete",
                    "metadata": {"type": "upload"}
                }
            ]
        })
        .to_string();
        let mut rules = auth_rules();
        // The exact substring also asserts the ids are comma-joined into the URL.
        rules.push(Rule::new("/api/feed/v2/?ids=p1,p2", 200, feed));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let clips = pollster::block_on(client.get_clips_by_ids(&http, &["p1", "p2"])).unwrap();
        assert_eq!(
            clips.len(),
            2,
            "infill and upload ancestors must not be filtered"
        );
        assert_eq!(clips[0].id, "p1");
        assert_eq!(clips[1].id, "p2");
    }

    #[test]
    fn get_clips_by_ids_accepts_a_bare_array_body() {
        let body = serde_json::json!([
            {"id": "only", "title": "Bare", "status": "complete", "metadata": {"type": "gen"}}
        ])
        .to_string();
        let mut rules = auth_rules();
        rules.push(Rule::new("/api/feed/v2/?ids=only", 200, body));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let clips = pollster::block_on(client.get_clips_by_ids(&http, &["only"])).unwrap();
        assert_eq!(clips.len(), 1);
        assert_eq!(clips[0].id, "only");
    }

    #[test]
    fn get_clip_parent_reads_the_parent_clip() {
        let parent = serde_json::json!({
            "id": "par", "title": "Ancestor", "status": "complete",
            "metadata": {"type": "gen"}
        })
        .to_string();
        let mut rules = auth_rules();
        rules.push(Rule::new("/api/clips/parent?clip_id=child", 200, parent));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let clip = pollster::block_on(client.get_clip_parent(&http, "child")).unwrap();
        assert_eq!(clip.unwrap().id, "par");
    }

    #[test]
    fn get_clip_parent_is_none_for_a_root() {
        let mut rules = auth_rules();
        rules.push(Rule::new(
            "/api/clips/parent",
            404,
            r#"{"detail": "no parent"}"#.to_string(),
        ));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let clip = pollster::block_on(client.get_clip_parent(&http, "root")).unwrap();
        assert!(clip.is_none());
    }

    #[test]
    fn get_clip_parent_propagates_server_errors_instead_of_reporting_no_parent() {
        // A transient 5xx must never be mistaken for "this clip is a root":
        // folding it into Ok(None) would fabricate a wrong external root and let
        // a blip rewrite lineage (HARDENING H3). Only a real 404 means no parent.
        for status in [500u16, 503] {
            let mut rules = auth_rules();
            rules.push(Rule::new(
                "/api/clips/parent",
                status,
                r#"{"detail": "server error"}"#.to_string(),
            ));
            let http = MockHttp::new(rules);
            let mut client = authed_client(&http);

            let result = pollster::block_on(client.get_clip_parent(&http, "child"));
            assert!(
                matches!(result, Err(Error::Api(_))),
                "status {status} must propagate as an error, not Ok(None)"
            );
        }
    }

    #[test]
    fn get_playlists_maps_entries_and_skips_missing_ids() {
        let page1 = serde_json::json!({
            "playlists": [
                {"id": "pl1", "name": "Road Trip", "num_total_results": 12},
                {"id": "", "name": "No Id", "num_total_results": 3},
                {"name": "Also No Id"}
            ]
        })
        .to_string();
        let mut rules = auth_rules();
        // Page 1 returns entries; page 2 is empty, ending pagination.
        rules.push(Rule::new("/api/playlist/me?page=1", 200, page1));
        rules.push(Rule::new(
            "/api/playlist/me?page=2",
            200,
            r#"{"playlists": []}"#.to_string(),
        ));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let playlists = pollster::block_on(client.get_playlists(&http)).unwrap();
        assert_eq!(playlists.len(), 1, "entries without an id are dropped");
        assert_eq!(
            playlists[0],
            Playlist {
                id: "pl1".to_owned(),
                name: "Road Trip".to_owned(),
                num_clips: 12,
            }
        );
    }

    #[test]
    fn get_playlists_defaults_a_missing_name_to_untitled() {
        let page1 = serde_json::json!({
            "playlists": [{"id": "pl9", "num_total_results": 1}]
        })
        .to_string();
        let mut rules = auth_rules();
        rules.push(Rule::new("/api/playlist/me?page=1", 200, page1));
        rules.push(Rule::new(
            "/api/playlist/me?page=2",
            200,
            r#"{"playlists": []}"#.to_string(),
        ));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let playlists = pollster::block_on(client.get_playlists(&http)).unwrap();
        assert_eq!(playlists[0].name, "Untitled");
    }

    #[test]
    fn get_playlist_clips_preserves_order_and_unwraps_clip() {
        // Members arrive wrapped under `clip`, in playlist order, already
        // non-trashed. Order is preserved and no keep_clip filter is applied.
        let body = serde_json::json!({
            "playlist_clips": [
                {"clip": {
                    "id": "second", "title": "Second", "status": "complete",
                    "metadata": {"duration": 60.0, "type": "gen"}
                }},
                {"clip": {
                    "id": "first", "title": "First", "status": "complete",
                    "metadata": {"duration": 30.0, "task": "infill", "type": "gen"}
                }}
            ]
        })
        .to_string();
        let mut rules = auth_rules();
        rules.push(Rule::new("/api/playlist/pl1/", 200, body));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let clips = pollster::block_on(client.get_playlist_clips(&http, "pl1")).unwrap();
        assert_eq!(clips.len(), 2, "an infill member is not filtered out");
        assert_eq!(clips[0].id, "second");
        assert_eq!(clips[1].id, "first");
    }

    #[test]
    fn get_playlist_clips_is_empty_for_a_playlist_with_no_members() {
        let mut rules = auth_rules();
        rules.push(Rule::new(
            "/api/playlist/empty/",
            200,
            r#"{"playlist_clips": []}"#.to_string(),
        ));
        let http = MockHttp::new(rules);
        let mut client = authed_client(&http);

        let clips = pollster::block_on(client.get_playlist_clips(&http, "empty")).unwrap();
        assert!(clips.is_empty());
    }
}