codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
//! Ghost-text follow-up prompt suggestion.
//!
//! After each completed turn, a lightweight API call generates ONE short
//! follow-up question the user might want to ask next. The suggestion is
//! rendered as dimmed ghost text in the composer when the input is empty.

use std::fmt;
use std::sync::OnceLock;

use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
use serde_json::Value;
use tracing::debug;

use crate::config::{ApiProvider, Config};
use crate::core::events::TurnRoute;
use crate::route_receipt::{TurnRouteReceipt, endpoint_identity};

/// The exact route authority a turn was launched against.
///
/// This is a thin, gated wrapper around the [`TurnRouteReceipt`] the **engine**
/// minted from the installed, preflighted client. It is never derived from
/// live config: the whole point is that by the time the TUI processes
/// `TurnStarted`, config may already describe a different endpoint or
/// credential (web config events are drained ahead of engine events), and
/// authority resolved from that mutable state would authorize sending a
/// completed turn's context to a route the turn never ran on.
///
/// `TurnComplete` re-resolves the same identity and must reproduce every field
/// of this record; anything else — including a same-identity endpoint or key
/// rotation performed mid-turn — fails closed.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SuggestionRouteAuthority {
    receipt: TurnRouteReceipt,
}

impl SuggestionRouteAuthority {
    #[must_use]
    pub fn provider(&self) -> ApiProvider {
        self.receipt.provider()
    }

    /// Exact configured route key (`TurnRoute::provider_identity`).
    #[must_use]
    pub fn provider_identity(&self) -> &str {
        self.receipt.provider_identity()
    }

    /// Exact wire model the turn's client was bound to.
    #[must_use]
    pub fn model(&self) -> &str {
        self.receipt.wire_model()
    }

    /// Normalized, redacted identity of the endpoint the turn's client used.
    #[must_use]
    pub fn endpoint_identity(&self) -> &str {
        self.receipt.endpoint_identity()
    }

    /// Whether a live re-resolution still lands on the same endpoint and the
    /// same credential generation.
    fn authorizes(&self, base_url: &str, api_key: &str) -> bool {
        self.receipt.matches_live_route(base_url, api_key)
    }

    #[cfg(test)]
    pub(crate) fn from_receipt_for_test(receipt: TurnRouteReceipt) -> Self {
        Self { receipt }
    }
}

/// Non-secret route provenance for the turn that just completed.
///
/// This is a snapshot of `TurnRoute` plus the authority minted when that turn's
/// client was installed, not live UI selection state. Every suggestion decision
/// is anchored to it, so a route switch made after the turn completed cannot
/// redirect the background request.
#[derive(Clone, Copy)]
pub struct SuggestionRouteSnapshot<'a> {
    pub provider: ApiProvider,
    /// Exact configured route key (`TurnRoute::provider_identity`).
    pub provider_identity: &'a str,
    /// Exact wire model the completed turn actually used.
    pub model: &'a str,
    /// Authority carried on the completed turn's route receipt.
    pub authority: &'a SuggestionRouteAuthority,
    /// Actual base URL this turn's client used, from `Event::TurnComplete`.
    pub actual_base_url: Option<&'a str>,
}

/// Redacted: `actual_base_url` is a raw endpoint that may carry URL userinfo or
/// sensitive query values, so it renders as its normalized redacted identity.
impl fmt::Debug for SuggestionRouteSnapshot<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SuggestionRouteSnapshot")
            .field("provider", &self.provider)
            .field("provider_identity", &self.provider_identity)
            .field("model", &self.model)
            .field("authority", &self.authority)
            .field(
                "actual_endpoint_identity",
                &self.actual_base_url.map(endpoint_identity),
            )
            .finish()
    }
}

/// Credential material resolved for exactly one route identity.
///
/// The resolver that produces this must scope itself to the snapshot identity;
/// it must never fall back to the ambient/active provider.
#[derive(Clone, PartialEq, Eq)]
pub struct SuggestionRouteCredentials {
    pub api_key: String,
    pub base_url: String,
    /// Wire model the resolver arrived at. Must equal the snapshot model.
    pub model: String,
}

/// Redacted: an API key must never reach a log line, panic message, or test
/// failure output through `{:?}`, and a raw `base_url` can itself carry
/// credentials in URL userinfo or a query token.
impl fmt::Debug for SuggestionRouteCredentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SuggestionRouteCredentials")
            .field("api_key", &"<redacted>")
            .field("endpoint_identity", &endpoint_identity(&self.base_url))
            .field("model", &self.model)
            .finish()
    }
}

/// A fully validated background suggestion request.
#[derive(Clone, PartialEq, Eq)]
pub struct SuggestionLaunch {
    pub api_key: String,
    pub base_url: String,
    pub model: String,
}

/// Redacted: see [`SuggestionRouteCredentials`].
impl fmt::Debug for SuggestionLaunch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SuggestionLaunch")
            .field("api_key", &"<redacted>")
            .field("endpoint_identity", &endpoint_identity(&self.base_url))
            .field("model", &self.model)
            .finish()
    }
}

/// Whether a provider speaks the exact DeepSeek OpenAI-compatible
/// `/chat/completions` shape [`generate_suggestion`] hardcodes.
///
/// This is deliberately narrow: `DeepseekAnthropic` is a different wire
/// protocol, and every other provider is out of scope. Widening this set is a
/// feature change, not a bug fix.
#[must_use]
pub fn route_is_supported_suggestion_provider(provider: ApiProvider) -> bool {
    matches!(provider, ApiProvider::Deepseek | ApiProvider::DeepseekCN)
}

/// Resolve credentials for exactly one configured route identity.
///
/// The identity is revalidated against live config and then scoped with
/// `resolve_runtime_route_for_identity`, so the key and endpoint come from that
/// route's own configuration rather than from whichever provider happens to be
/// selected now. An identity that no longer resolves, or that now resolves to a
/// different provider kind, yields `None`.
///
/// The returned `base_url` is the **resolved route candidate's** endpoint, not
/// `Config::deepseek_base_url()`. Those two are not the same string: the config
/// accessor is one input to candidate resolution, and the candidate endpoint is
/// what `DeepSeekClient::from_candidate` binds the transport to and therefore
/// what `Event::TurnComplete` reports back. Comparing anything else here would
/// compare a turn's actual endpoint against a differently-canonicalized value
/// and fail closed on routes that never changed.
fn resolve_credentials_for_identity(
    config: &Config,
    provider: ApiProvider,
    provider_identity: &str,
    model: &str,
) -> Option<SuggestionRouteCredentials> {
    // Belt and braces: callers already gated, but this function must never be
    // the thing that reads a non-DeepSeek route's credentials.
    if !route_is_supported_suggestion_provider(provider) {
        return None;
    }
    let identity = config.resolve_provider_identity(provider_identity).ok()?;
    if identity.provider != provider {
        return None;
    }
    let resolved =
        crate::route_runtime::resolve_runtime_route_for_identity(config, &identity, Some(model))
            .ok()?;
    if resolved.identity.provider != provider {
        return None;
    }
    // This helper intentionally sends the ordinary Chat Completions shape.
    // A configured path override may describe a provider-specific transport
    // contract that this bounded feature does not implement, so fail closed
    // instead of silently bypassing it with the canonical path.
    if resolved
        .config
        .provider_config_for(provider)
        .and_then(|route| route.path_suffix.as_ref())
        .is_some()
    {
        return None;
    }
    let api_key = resolved.config.deepseek_api_key().ok()?;
    Some(SuggestionRouteCredentials {
        api_key,
        base_url: resolved.candidate.endpoint().base_url.clone(),
        model: resolved.model.clone(),
    })
}

/// Adopt the engine's route receipt as this turn's suggestion authority.
///
/// Takes **no `Config`**, by design. This runs while the TUI handles
/// `TurnStarted`, which is strictly after the engine resolved, preflighted, and
/// installed the turn's client — and strictly after any web config event queued
/// in the meantime has been drained. Reading credentials here would capture
/// whatever route config describes *now*, not the route the turn is running on.
/// The receipt was minted from the installed client itself, so it cannot drift.
///
/// Unsupported providers — every non-DeepSeek route, including
/// `DeepseekAnthropic` — return `None`, and no credential material of any
/// provider is inspected on this path at all.
#[must_use]
pub fn capture_route_authority(route: &TurnRoute) -> Option<SuggestionRouteAuthority> {
    if !route_is_supported_suggestion_provider(route.provider) {
        return None;
    }
    let provider_identity = route.provider_identity.trim();
    let model = route.model.trim();
    if provider_identity.is_empty() || model.is_empty() {
        return None;
    }

    // A receipt that describes a different route than the event's own
    // `TurnRoute` is broken provenance, not a usable authority.
    let receipt = route.receipt.as_ref()?;
    if receipt.provider() != route.provider
        || receipt.provider_identity() != provider_identity
        || receipt.wire_model() != model
        || receipt.endpoint_identity().is_empty()
        || receipt.credential_generation().is_empty()
    {
        return None;
    }

    Some(SuggestionRouteAuthority {
        receipt: receipt.clone(),
    })
}

/// Decide whether a completed turn may launch a background prompt suggestion,
/// and with exactly what credentials, endpoint, and model.
///
/// Fail-closed by construction:
/// - `resolve_route_credentials` is only invoked once every non-credential gate
///   has passed for a supported DeepSeek route, so a non-DeepSeek completion
///   never reaches DeepSeek credential material at all.
/// - The decision reads only `completed_route`, never live selection state, so
///   a later route switch cannot redirect it.
/// - The route must still resolve to the *same* provider, identity, wire model,
///   endpoint identity, and credential generation the engine recorded on this
///   turn's route receipt, and to the endpoint the turn's client actually used.
///   A same-identity endpoint or key rotation is therefore a mismatch, not an
///   accepted match, and no conversation context is sent anywhere.
pub fn plan_suggestion_launch<F>(
    turn_completed: bool,
    suggestion_enabled: bool,
    api_message_count: usize,
    completed_route: Option<SuggestionRouteSnapshot<'_>>,
    resolve_route_credentials: F,
) -> Option<SuggestionLaunch>
where
    F: FnOnce(&SuggestionRouteSnapshot<'_>) -> Option<SuggestionRouteCredentials>,
{
    if !turn_completed || !suggestion_enabled || api_message_count < 2 {
        return None;
    }
    // No route snapshot means no provenance. Non-model turns (composer `!`
    // shell commands) land here too.
    let route = completed_route?;
    if !route_is_supported_suggestion_provider(route.provider) {
        return None;
    }
    let identity = route.provider_identity.trim();
    if identity.is_empty() {
        return None;
    }
    let model = route.model.trim();
    if model.is_empty() {
        return None;
    }

    // The authority came off this turn's own route receipt. If it describes
    // anything else, the provenance chain is broken.
    let authority = route.authority;
    if authority.provider() != route.provider
        || authority.provider_identity() != identity
        || authority.model() != model
        || authority.endpoint_identity().is_empty()
    {
        return None;
    }

    // The engine reports the endpoint this turn's client actually used. It is
    // required, and it must be the endpoint the receipt was minted from.
    let actual_endpoint = endpoint_identity(route.actual_base_url?);
    if actual_endpoint.is_empty() || actual_endpoint != authority.endpoint_identity() {
        return None;
    }

    let credentials = resolve_route_credentials(&route)?;
    if credentials.api_key.trim().is_empty() {
        return None;
    }
    // Never silently swap in a cheaper/different model than the one the
    // completed turn was actually routed to.
    if credentials.model.trim() != model {
        return None;
    }
    // A same-identity endpoint mutation *or* credential rotation lands here.
    // Both are checked against the receipt in one step, over the raw endpoint
    // and raw credential, so a mutation hidden behind identical redaction (URL
    // userinfo, a query token) is still a mismatch.
    if !authority.authorizes(&credentials.base_url, &credentials.api_key) {
        return None;
    }

    // Dispatch from the exact base endpoint and credential the receipt
    // authorized — the raw pair the digest was taken over, not a
    // re-canonicalized variant. `generate_suggestion` applies the same
    // canonical ordinary Chat Completions path mapping as the installed
    // client; custom path overrides failed closed above.
    Some(SuggestionLaunch {
        api_key: credentials.api_key,
        base_url: credentials.base_url,
        model: model.to_string(),
    })
}

/// [`plan_suggestion_launch`] wired to the real, identity-scoped config
/// resolver. This is the only production entry point.
#[must_use]
pub fn plan_suggestion_launch_with_config(
    config: &Config,
    turn_completed: bool,
    suggestion_enabled: bool,
    api_message_count: usize,
    completed_route: Option<SuggestionRouteSnapshot<'_>>,
) -> Option<SuggestionLaunch> {
    plan_suggestion_launch(
        turn_completed,
        suggestion_enabled,
        api_message_count,
        completed_route,
        |route| {
            resolve_credentials_for_identity(
                config,
                route.provider,
                route.provider_identity.trim(),
                route.model.trim(),
            )
        },
    )
}

/// Reusable static client — avoids creating a new connection pool per request.
fn suggestion_client() -> &'static reqwest::Client {
    static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
    CLIENT.get_or_init(crate::tls::reqwest_client)
}

/// Generate a follow-up prompt suggestion based on recent messages.
///
/// Sends the conversation summary to the API with a system prompt that
/// asks for a single short follow-up question. Returns `None` on failure
/// or empty result — callers treat this as best-effort.
pub async fn generate_suggestion(
    api_key: &str,
    base_url: &str,
    model: &str,
    recent_messages: &str,
) -> Option<String> {
    let client = suggestion_client();
    let body = serde_json::json!({
        "model": model,
        "messages": [
            {
                "role": "system",
                "content": "\
    You are a helpful assistant. Based on the recent conversation context, generate \
    ONE short follow-up question (under 60 characters) the user might want to ask \
    next. Reply with ONLY the question text, nothing else — no quotes, no explanations, \
    no prefixes."
            },
            {
                "role": "user",
                "content": format!(
                    "Recent conversation:\n{recent_messages}\n\n\
                     Generate ONE short follow-up question the user might ask next:"
                )
            }
        ],
        "max_tokens": 64,
        "temperature": 0.3,
        "stream": false
    });

    let url = crate::client::api_url(base_url, "chat/completions");
    // Never log the raw request URL: a base URL can carry credentials in its
    // userinfo or in a query token. The redacted endpoint identity keeps the
    // line diagnosable without carrying either.
    debug!(
        endpoint = %endpoint_identity(&url),
        %model,
        "generating prompt suggestion"
    );
    let response = match client
        .post(&url)
        .header(AUTHORIZATION, format!("Bearer {api_key}"))
        .header(CONTENT_TYPE, "application/json")
        .timeout(std::time::Duration::from_secs(10))
        .json(&body)
        .send()
        .await
    {
        Ok(r) => r,
        Err(_) => return None,
    };

    let value: Value = match response.json().await {
        Ok(v) => v,
        Err(_) => return None,
    };

    let suggestion = value["choices"][0]["message"]["content"]
        .as_str()
        .map(|s| s.trim().trim_matches('"').to_string())
        .filter(|s| !s.is_empty() && s.len() <= 200)?;

    // The suggestion is model output derived from conversation context, so its
    // text stays out of logs; only its shape is recorded.
    debug!(
        chars = suggestion.chars().count(),
        "prompt suggestion generated"
    );
    Some(suggestion)
}

/// Extract the first text line from a single message.
fn message_summary(m: &crate::models::Message) -> Option<String> {
    let role = match m.role.as_str() {
        "user" => "User",
        "assistant" => "Assistant",
        _ => return None,
    };
    let text = m
        .content
        .iter()
        .filter_map(|block| match block {
            crate::models::ContentBlock::Text { text, .. } => Some(text.as_str()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join(" ");
    let first_line = text.lines().next().unwrap_or("").trim();
    if first_line.is_empty() {
        return None;
    }
    let truncated: String = first_line
        .chars()
        .take(120)
        .chain(if first_line.chars().count() > 120 {
            Some('…')
        } else {
            None
        })
        .collect();
    Some(format!("{role}: {truncated}"))
}

/// Build a one-line-per-message summary of recent conversation context.
/// Takes the last N messages, skipping tool-only messages.
pub fn summarize_recent_messages(messages: &[crate::models::Message], limit: usize) -> String {
    let start = messages.len().saturating_sub(limit);
    messages[start..]
        .iter()
        .filter_map(message_summary)
        .collect::<Vec<_>>()
        .join("\n")
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;

    use super::{
        ApiProvider, Config, SuggestionRouteAuthority, SuggestionRouteCredentials,
        SuggestionRouteSnapshot, TurnRoute, TurnRouteReceipt, capture_route_authority,
        endpoint_identity, plan_suggestion_launch, plan_suggestion_launch_with_config,
        resolve_credentials_for_identity,
    };
    use crate::config::ProvidersConfig;
    use crate::test_support::{EnvVarGuard, TestEnvLock, lock_test_env};

    const DEEPSEEK_BASE: &str = "https://api.deepseek.com/v1";
    const DEEPSEEK_KEY: &str = "sk-deepseek-secret";

    /// Stand-in for the real credential resolver. Records every identity it was
    /// asked about so a test can prove it was never consulted at all.
    struct RecordingResolver {
        /// Credentials keyed by exact `(provider, provider_identity)`.
        available: Vec<(ApiProvider, &'static str, SuggestionRouteCredentials)>,
        asked: RefCell<Vec<(ApiProvider, String)>>,
    }

    impl RecordingResolver {
        fn new(available: Vec<(ApiProvider, &'static str, SuggestionRouteCredentials)>) -> Self {
            Self {
                available,
                asked: RefCell::new(Vec::new()),
            }
        }

        fn resolve(
            &self,
            route: &SuggestionRouteSnapshot<'_>,
        ) -> Option<SuggestionRouteCredentials> {
            self.asked
                .borrow_mut()
                .push((route.provider, route.provider_identity.to_string()));
            self.available
                .iter()
                .find(|(provider, identity, _)| {
                    *provider == route.provider && *identity == route.provider_identity
                })
                .map(|(_, _, credentials)| credentials.clone())
        }

        fn asked(&self) -> Vec<(ApiProvider, String)> {
            self.asked.borrow().clone()
        }
    }

    fn credentials(api_key: &str, base_url: &str, model: &str) -> SuggestionRouteCredentials {
        SuggestionRouteCredentials {
            api_key: api_key.to_string(),
            base_url: base_url.to_string(),
            model: model.to_string(),
        }
    }

    fn deepseek_credentials(model: &str) -> SuggestionRouteCredentials {
        credentials(DEEPSEEK_KEY, DEEPSEEK_BASE, model)
    }

    /// A receipt as the engine would have minted it from the installed client.
    fn receipt(
        provider: ApiProvider,
        identity: &str,
        model: &str,
        base_url: &str,
        api_key: &str,
    ) -> TurnRouteReceipt {
        TurnRouteReceipt::new(provider, identity, model, base_url, api_key)
    }

    /// Authority as the TUI would have adopted it at `TurnStarted`.
    ///
    /// Bypasses the provider gate so the unsupported-provider tests below can
    /// prove the *later* gates also hold, not just the first one.
    fn route_authority(
        provider: ApiProvider,
        identity: &str,
        model: &str,
        base_url: &str,
        api_key: &str,
    ) -> SuggestionRouteAuthority {
        SuggestionRouteAuthority::from_receipt_for_test(receipt(
            provider, identity, model, base_url, api_key,
        ))
    }

    fn deepseek_authority(model: &str) -> SuggestionRouteAuthority {
        route_authority(
            ApiProvider::Deepseek,
            "deepseek",
            model,
            DEEPSEEK_BASE,
            DEEPSEEK_KEY,
        )
    }

    fn snapshot<'a>(
        provider: ApiProvider,
        identity: &'a str,
        model: &'a str,
        authority: &'a SuggestionRouteAuthority,
    ) -> SuggestionRouteSnapshot<'a> {
        SuggestionRouteSnapshot {
            provider,
            provider_identity: identity,
            model,
            authority,
            actual_base_url: Some(DEEPSEEK_BASE),
        }
    }

    #[test]
    fn deepseek_route_uses_its_exact_wire_model_and_base_url() {
        let resolver = RecordingResolver::new(vec![(
            ApiProvider::Deepseek,
            "deepseek",
            deepseek_credentials("deepseek-reasoner"),
        )]);
        let authority = deepseek_authority("deepseek-reasoner");
        let launch = plan_suggestion_launch(
            true,
            true,
            2,
            Some(snapshot(
                ApiProvider::Deepseek,
                "deepseek",
                "deepseek-reasoner",
                &authority,
            )),
            |route| resolver.resolve(route),
        )
        .expect("supported deepseek route with unchanged credentials must launch");

        assert_eq!(launch.model, "deepseek-reasoner");
        assert_eq!(launch.base_url, DEEPSEEK_BASE);
        assert_eq!(launch.api_key, DEEPSEEK_KEY);
    }

    #[test]
    fn non_deepseek_completion_never_touches_deepseek_credentials() {
        // A DeepSeek key exists and would resolve fine — the gate must run
        // before the resolver is ever consulted.
        let resolver = RecordingResolver::new(vec![(
            ApiProvider::Deepseek,
            "deepseek",
            deepseek_credentials("deepseek-chat"),
        )]);
        for (provider, identity, model) in [
            (ApiProvider::Anthropic, "anthropic", "claude-sonnet-4"),
            (ApiProvider::Openai, "openai", "gpt-4.1"),
            (ApiProvider::Openrouter, "openrouter", "some/model"),
            (ApiProvider::Custom, "lm-studio", "local-model"),
            (
                ApiProvider::DeepseekAnthropic,
                "deepseek-anthropic",
                "deepseek-chat",
            ),
        ] {
            let authority = route_authority(provider, identity, model, DEEPSEEK_BASE, DEEPSEEK_KEY);
            let launch = plan_suggestion_launch(
                true,
                true,
                8,
                Some(snapshot(provider, identity, model, &authority)),
                |route| resolver.resolve(route),
            );
            assert!(
                launch.is_none(),
                "{provider:?} completion must not launch a prompt suggestion"
            );
        }
        assert!(
            resolver.asked().is_empty(),
            "credential resolution must never be attempted for unsupported routes, got {:?}",
            resolver.asked()
        );
    }

    #[test]
    fn missing_credentials_fail_closed() {
        let authority = deepseek_authority("deepseek-chat");
        // No entry for the deepseek identity: resolver returns None.
        let empty = RecordingResolver::new(Vec::new());
        assert!(
            plan_suggestion_launch(
                true,
                true,
                2,
                Some(snapshot(
                    ApiProvider::Deepseek,
                    "deepseek",
                    "deepseek-chat",
                    &authority
                )),
                |route| empty.resolve(route),
            )
            .is_none(),
            "unresolvable route credentials must fail closed"
        );

        for incomplete in [
            credentials("   ", DEEPSEEK_BASE, "deepseek-chat"),
            credentials(DEEPSEEK_KEY, "", "deepseek-chat"),
        ] {
            assert!(
                plan_suggestion_launch(
                    true,
                    true,
                    2,
                    Some(snapshot(
                        ApiProvider::Deepseek,
                        "deepseek",
                        "deepseek-chat",
                        &authority
                    )),
                    |_| Some(incomplete.clone()),
                )
                .is_none(),
                "incomplete credentials must fail closed: {incomplete:?}"
            );
        }
    }

    #[test]
    fn resolver_is_asked_only_about_the_completed_route_identity() {
        // Live selection has moved on to another provider; the plan is built
        // from the completed-turn snapshot, so the resolver only ever sees the
        // completed identity.
        const CN_BASE: &str = "https://api.deepseek.cn/v1";
        let resolver = RecordingResolver::new(vec![
            (
                ApiProvider::Deepseek,
                "deepseek",
                deepseek_credentials("deepseek-chat"),
            ),
            (
                ApiProvider::DeepseekCN,
                "deepseek-cn",
                credentials("sk-cn", CN_BASE, "deepseek-chat"),
            ),
        ]);
        let authority = route_authority(
            ApiProvider::DeepseekCN,
            "deepseek-cn",
            "deepseek-chat",
            CN_BASE,
            "sk-cn",
        );
        let launch = plan_suggestion_launch(
            true,
            true,
            4,
            Some(SuggestionRouteSnapshot {
                provider: ApiProvider::DeepseekCN,
                provider_identity: "deepseek-cn",
                model: "deepseek-chat",
                authority: &authority,
                actual_base_url: Some(CN_BASE),
            }),
            |route| resolver.resolve(route),
        )
        .expect("completed deepseek-cn route must launch on its own endpoint");

        assert_eq!(launch.base_url, CN_BASE);
        assert_eq!(launch.api_key, "sk-cn");
        assert_eq!(
            resolver.asked(),
            vec![(ApiProvider::DeepseekCN, "deepseek-cn".to_string())],
            "only the completed route identity may be inspected"
        );
    }

    #[test]
    fn model_substitution_by_the_resolver_fails_closed() {
        let authority = deepseek_authority("deepseek-reasoner");
        assert!(
            plan_suggestion_launch(
                true,
                true,
                2,
                Some(snapshot(
                    ApiProvider::Deepseek,
                    "deepseek",
                    "deepseek-reasoner",
                    &authority
                )),
                // Silent downgrade to a cheaper model.
                |_| Some(deepseek_credentials("deepseek-chat")),
            )
            .is_none(),
            "a resolver-substituted model must not be dispatched"
        );
    }

    #[test]
    fn same_identity_endpoint_or_key_rotation_fails_closed() {
        let authority = deepseek_authority("deepseek-chat");
        // Same provider, same identity, same model — but the endpoint moved
        // while the turn was in flight.
        assert!(
            plan_suggestion_launch(
                true,
                true,
                2,
                Some(snapshot(
                    ApiProvider::Deepseek,
                    "deepseek",
                    "deepseek-chat",
                    &authority
                )),
                |_| Some(credentials(
                    DEEPSEEK_KEY,
                    "https://exfil.example.com/v1",
                    "deepseek-chat"
                )),
            )
            .is_none(),
            "a same-identity endpoint mutation must fail closed"
        );
        // …and the same for a credential rotation onto the same endpoint.
        assert!(
            plan_suggestion_launch(
                true,
                true,
                2,
                Some(snapshot(
                    ApiProvider::Deepseek,
                    "deepseek",
                    "deepseek-chat",
                    &authority
                )),
                |_| Some(credentials(
                    "sk-rotated-elsewhere",
                    DEEPSEEK_BASE,
                    "deepseek-chat"
                )),
            )
            .is_none(),
            "a same-identity credential mutation must fail closed"
        );
    }

    #[test]
    fn userinfo_rotation_behind_identical_redaction_fails_closed() {
        // Both endpoints redact to the same identity string. Only the
        // credential-generation digest, which covers the raw endpoint, can
        // tell them apart — so redaction must not be the whole comparison.
        const ORIGINAL: &str = "https://svc:original@api.deepseek.com/v1";
        const ROTATED: &str = "https://svc:rotated@api.deepseek.com/v1";
        assert_eq!(endpoint_identity(ORIGINAL), endpoint_identity(ROTATED));

        let authority = route_authority(
            ApiProvider::Deepseek,
            "deepseek",
            "deepseek-chat",
            ORIGINAL,
            DEEPSEEK_KEY,
        );
        let route = SuggestionRouteSnapshot {
            provider: ApiProvider::Deepseek,
            provider_identity: "deepseek",
            model: "deepseek-chat",
            authority: &authority,
            actual_base_url: Some(ORIGINAL),
        };
        assert!(
            plan_suggestion_launch(true, true, 2, Some(route), |_| Some(credentials(
                DEEPSEEK_KEY,
                ROTATED,
                "deepseek-chat"
            )))
            .is_none(),
            "a URL-userinfo rotation hidden by redaction must fail closed"
        );
        assert!(
            plan_suggestion_launch(true, true, 2, Some(route), |_| Some(credentials(
                DEEPSEEK_KEY,
                ORIGINAL,
                "deepseek-chat"
            )))
            .is_some(),
            "control: the unrotated endpoint still launches"
        );
    }

    #[test]
    fn actual_turn_endpoint_must_be_present_and_match_the_authority() {
        let authority = deepseek_authority("deepseek-chat");
        for actual_base_url in [None, Some("https://exfil.example.com/v1"), Some("  ")] {
            let route = SuggestionRouteSnapshot {
                provider: ApiProvider::Deepseek,
                provider_identity: "deepseek",
                model: "deepseek-chat",
                authority: &authority,
                actual_base_url,
            };
            assert!(
                plan_suggestion_launch(true, true, 2, Some(route), |_| Some(deepseek_credentials(
                    "deepseek-chat"
                )))
                .is_none(),
                "actual turn endpoint {actual_base_url:?} must fail closed"
            );
        }

        // A trailing-slash-only difference is the same endpoint.
        let route = SuggestionRouteSnapshot {
            provider: ApiProvider::Deepseek,
            provider_identity: "deepseek",
            model: "deepseek-chat",
            authority: &authority,
            actual_base_url: Some("https://api.deepseek.com/v1/"),
        };
        assert!(
            plan_suggestion_launch(true, true, 2, Some(route), |_| Some(deepseek_credentials(
                "deepseek-chat"
            )))
            .is_some(),
            "trailing-slash normalization must not break the exact-route match"
        );
    }

    #[test]
    fn authority_from_a_different_route_fails_closed() {
        // Authority belongs to deepseek-cn; the completed snapshot claims
        // deepseek. Broken provenance must never dispatch.
        let cn = route_authority(
            ApiProvider::DeepseekCN,
            "deepseek-cn",
            "deepseek-chat",
            "https://api.deepseek.cn/v1",
            "sk-cn",
        );
        let route = SuggestionRouteSnapshot {
            provider: ApiProvider::Deepseek,
            provider_identity: "deepseek",
            model: "deepseek-chat",
            authority: &cn,
            actual_base_url: Some(DEEPSEEK_BASE),
        };
        assert!(
            plan_suggestion_launch(true, true, 2, Some(route), |_| Some(deepseek_credentials(
                "deepseek-chat"
            )))
            .is_none(),
            "an authority captured for another route must fail closed"
        );
    }

    #[test]
    fn missing_route_snapshot_or_disabled_gates_produce_no_request() {
        let resolver = RecordingResolver::new(vec![(
            ApiProvider::Deepseek,
            "deepseek",
            deepseek_credentials("deepseek-chat"),
        )]);
        let authority = deepseek_authority("deepseek-chat");
        let route = snapshot(
            ApiProvider::Deepseek,
            "deepseek",
            "deepseek-chat",
            &authority,
        );

        // No route provenance (non-model turn).
        assert!(plan_suggestion_launch(true, true, 4, None, |r| resolver.resolve(r)).is_none());
        // Turn did not complete.
        assert!(
            plan_suggestion_launch(false, true, 4, Some(route), |r| resolver.resolve(r)).is_none()
        );
        // Feature disabled.
        assert!(
            plan_suggestion_launch(true, false, 4, Some(route), |r| resolver.resolve(r)).is_none()
        );
        // Not enough conversation context.
        assert!(
            plan_suggestion_launch(true, true, 1, Some(route), |r| resolver.resolve(r)).is_none()
        );
        // Empty identity is malformed provenance, not a legacy root route.
        let empty_identity = route_authority(
            ApiProvider::Deepseek,
            "  ",
            "deepseek-chat",
            DEEPSEEK_BASE,
            DEEPSEEK_KEY,
        );
        assert!(
            plan_suggestion_launch(
                true,
                true,
                4,
                Some(snapshot(
                    ApiProvider::Deepseek,
                    "  ",
                    "deepseek-chat",
                    &empty_identity
                )),
                |r| resolver.resolve(r),
            )
            .is_none()
        );
        // Empty model.
        let empty_model = route_authority(
            ApiProvider::Deepseek,
            "deepseek",
            "",
            DEEPSEEK_BASE,
            DEEPSEEK_KEY,
        );
        assert!(
            plan_suggestion_launch(
                true,
                true,
                4,
                Some(snapshot(
                    ApiProvider::Deepseek,
                    "deepseek",
                    "",
                    &empty_model
                )),
                |r| resolver.resolve(r),
            )
            .is_none()
        );

        assert!(
            resolver.asked().is_empty(),
            "gates must reject before credential resolution, got {:?}",
            resolver.asked()
        );
    }

    /// Every URL-bearing rendered surface in this feature, exercised against a
    /// base URL that carries credentials in both userinfo and query values.
    #[test]
    fn debug_never_renders_credential_material_or_raw_urls() {
        let secret_base = format!(
            "https://{}:{}@api.deepseek.com/v1?api_key={}{}&token={}{}&region=us-east",
            "svc-user", "hunter2", "sk", "-live-abc123", "tok", "-secret-xyz"
        );
        let secrets = [
            DEEPSEEK_KEY.to_string(),
            "svc-user".to_string(),
            "hunter2".to_string(),
            ["sk", "-live-abc123"].concat(),
            ["tok", "-secret-xyz"].concat(),
        ];

        let credentials = credentials(DEEPSEEK_KEY, &secret_base, "deepseek-chat");
        let authority = route_authority(
            ApiProvider::Deepseek,
            "deepseek",
            "deepseek-chat",
            &secret_base,
            DEEPSEEK_KEY,
        );
        let route = SuggestionRouteSnapshot {
            provider: ApiProvider::Deepseek,
            provider_identity: "deepseek",
            model: "deepseek-chat",
            authority: &authority,
            actual_base_url: Some(&secret_base),
        };
        let launch =
            plan_suggestion_launch(true, true, 2, Some(route), |_| Some(credentials.clone()))
                .expect("unchanged route must launch");

        for rendered in [
            format!("{credentials:?}"),
            format!("{credentials:#?}"),
            format!("{launch:?}"),
            format!("{launch:#?}"),
            format!("{authority:?}"),
            format!("{authority:#?}"),
            format!("{route:?}"),
            format!("{route:#?}"),
        ] {
            for secret in &secrets {
                assert!(
                    !rendered.contains(secret),
                    "a rendered surface leaked {secret}: {rendered}"
                );
            }
            // The endpoint identity is still useful for diagnostics.
            assert!(
                rendered.contains("api.deepseek.com"),
                "endpoint identity must survive redaction: {rendered}"
            );
            assert!(
                rendered.contains("region=us-east"),
                "non-sensitive query values must survive redaction: {rendered}"
            );
        }
        for rendered in [format!("{credentials:?}"), format!("{launch:?}")] {
            assert!(
                rendered.contains("<redacted>"),
                "Debug must mark the redacted field: {rendered}"
            );
        }
        // …while the launch still dispatches to the real, unredacted endpoint.
        assert_eq!(launch.base_url, secret_base);
        assert_eq!(launch.api_key, DEEPSEEK_KEY);
    }

    // === Config-backed tests ===
    //
    // These drive the real, identity-scoped config resolver and the real
    // client-minted route receipt rather than recording stand-ins, so they
    // cover the actual production path.

    /// Hold the env lock and remove every ambient variable that could displace
    /// the fixture's configured DeepSeek route.
    ///
    /// Without this, a developer shell that exports `DEEPSEEK_API_KEY` (or a
    /// dispatcher-marked `--api-key` forward) can make these tests pass or fail
    /// for reasons that have nothing to do with the privacy contract.
    ///
    /// Field order is load-bearing: the guards must restore the environment
    /// before the lock is released.
    struct SealedDeepseekEnv {
        _guards: Vec<EnvVarGuard>,
        _lock: TestEnvLock,
    }

    fn seal_deepseek_env() -> SealedDeepseekEnv {
        let lock = lock_test_env();
        let guards = [
            "DEEPSEEK_API_KEY",
            "DEEPSEEK_API_KEY_SOURCE",
            "CODEWHALE_CLI_API_KEY",
            "DEEPSEEK_BASE_URL",
            "CODEWHALE_BASE_URL",
        ]
        .into_iter()
        .map(EnvVarGuard::remove)
        .collect();
        SealedDeepseekEnv {
            _guards: guards,
            _lock: lock,
        }
    }

    fn deepseek_config(api_key: &str, base_url: &str) -> Config {
        let mut config = Config {
            provider: Some("deepseek".to_string()),
            ..Config::default()
        };
        let providers = config
            .providers
            .get_or_insert_with(ProvidersConfig::default);
        providers.deepseek.api_key = Some(api_key.to_string());
        providers.deepseek.base_url = Some(base_url.to_string());
        config
    }

    /// Build the completed-turn route the engine would have reported, using the
    /// same resolution the engine performs. This keeps the tests correct even
    /// if a model selector normalizes to a different wire id.
    ///
    /// The receipt is minted from the **preflighted client**, exactly as
    /// `Engine::send_message` does — not from config — so these tests exercise
    /// the real provenance chain rather than a re-derivation of it.
    fn deepseek_turn_route(config: &Config) -> TurnRoute {
        let identity = config
            .resolve_provider_identity("deepseek")
            .expect("test config must expose the deepseek identity");
        let resolved = crate::route_runtime::resolve_runtime_route_for_identity(
            config,
            &identity,
            Some(crate::config::DEFAULT_TEXT_MODEL),
        )
        .expect("test config must resolve the deepseek route");
        let model = resolved.model.clone();
        let validated = resolved
            .validate()
            .expect("test config must preflight a deepseek client");
        TurnRoute {
            provider: ApiProvider::Deepseek,
            provider_identity: "deepseek".to_string(),
            model,
            auto_model: false,
            receipt: Some(validated.client.turn_route_receipt("deepseek")),
            billing: Some(crate::core::events::RouteBillingEnvelope {
                billing_surface: None,
                endpoint_fingerprint: None,
                billing_mode: crate::cost_status::RouteBillingMode::Unknown,
                dispatched_at: chrono::Utc::now(),
            }),
            base_url: crate::config::DEFAULT_DEEPSEEK_BASE_URL.to_string(),
            billing_product: crate::route_billing::RouteProduct::Unproven,
        }
    }

    /// The endpoint `Event::TurnComplete` would report for this config.
    ///
    /// Deliberately derived from the production resolver rather than written
    /// as a literal: `Config::deepseek_base_url()` canonicalizes DeepSeek hosts
    /// (it strips a trailing `/v1`), and the transport is bound to the resolved
    /// candidate's endpoint, so a hand-written literal is a different string
    /// than the one the client actually uses.
    fn deepseek_actual_base_url(config: &Config, route: &TurnRoute) -> String {
        resolve_credentials_for_identity(
            config,
            route.provider,
            &route.provider_identity,
            &route.model,
        )
        .expect("test config must resolve the deepseek route")
        .base_url
    }

    /// Redacted mismatch report for a route that unexpectedly failed closed.
    ///
    /// Names the non-secret field that diverged so a future regression is
    /// diagnosable without ever printing a key, a raw URL, or a credential
    /// generation digest.
    fn route_mismatch_report(config: &Config, snapshot: &SuggestionRouteSnapshot<'_>) -> String {
        let resolved = resolve_credentials_for_identity(
            config,
            snapshot.provider,
            snapshot.provider_identity.trim(),
            snapshot.model.trim(),
        );
        let credential_matches = resolved.as_ref().map(|credentials| {
            snapshot
                .authority
                .authorizes(&credentials.base_url, &credentials.api_key)
        });
        format!(
            "snapshot={snapshot:?}, resolved={resolved:?}, \
             resolved_authorized_by_receipt={credential_matches:?}"
        )
    }

    fn config_snapshot<'a>(
        route: &'a TurnRoute,
        authority: &'a SuggestionRouteAuthority,
        actual_base_url: &'a str,
    ) -> SuggestionRouteSnapshot<'a> {
        SuggestionRouteSnapshot {
            provider: route.provider,
            provider_identity: route.provider_identity.as_str(),
            model: route.model.as_str(),
            authority,
            actual_base_url: Some(actual_base_url),
        }
    }

    #[test]
    fn config_exact_unchanged_completed_route_launches() {
        let _env = seal_deepseek_env();
        let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
        let route = deepseek_turn_route(&config);
        let actual_base_url = deepseek_actual_base_url(&config, &route);
        let authority =
            capture_route_authority(&route).expect("deepseek turn must capture authority");

        let snapshot = config_snapshot(&route, &authority, &actual_base_url);
        let launch = plan_suggestion_launch_with_config(&config, true, true, 4, Some(snapshot))
            .unwrap_or_else(|| {
                panic!(
                    "an unchanged deepseek route must launch: {}",
                    route_mismatch_report(&config, &snapshot)
                )
            });

        assert_eq!(launch.base_url, actual_base_url);
        assert_eq!(launch.api_key, DEEPSEEK_KEY);
        assert_eq!(launch.model, route.model);
        // The turn's endpoint is the configured DeepSeek host, canonicalized
        // by the route resolver — not some other provider's endpoint.
        assert!(
            launch.base_url.contains("api.deepseek.com"),
            "unexpected endpoint host: {}",
            endpoint_identity(&launch.base_url)
        );
    }

    #[test]
    fn configured_chat_path_override_fails_closed() {
        let _env = seal_deepseek_env();
        let mut config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
        config
            .providers
            .as_mut()
            .expect("providers")
            .deepseek
            .path_suffix = Some("/private/chat".to_string());
        let route = deepseek_turn_route(&config);
        let authority =
            capture_route_authority(&route).expect("deepseek turn must capture authority");
        let identity = config
            .resolve_provider_identity("deepseek")
            .expect("deepseek identity");
        let actual_base_url = crate::route_runtime::resolve_runtime_route_for_identity(
            &config,
            &identity,
            Some(&route.model),
        )
        .expect("resolved route")
        .candidate
        .endpoint()
        .base_url
        .clone();
        let snapshot = config_snapshot(&route, &authority, &actual_base_url);

        assert!(
            plan_suggestion_launch_with_config(&config, true, true, 4, Some(snapshot)).is_none(),
            "the suggestion helper must not bypass a provider-specific path contract"
        );

        config
            .providers
            .as_mut()
            .expect("providers")
            .deepseek
            .path_suffix = Some("   ".to_string());
        assert!(
            resolve_credentials_for_identity(
                &config,
                route.provider,
                &route.provider_identity,
                &route.model,
            )
            .is_none(),
            "even a blank configured suffix is an installed transport override"
        );
    }

    /// The #4404/#4411 race, end to end.
    ///
    /// Route A is resolved, preflighted, and installed; the engine mints its
    /// receipt from that client. Config is then mutated to route B *before* the
    /// TUI ever handles `TurnStarted` — which is reachable because web config
    /// events are drained ahead of engine events. Authority must still be A,
    /// and the completed turn's context must not be dispatchable with B.
    #[test]
    fn config_mutated_before_turn_started_cannot_move_authority_off_route_a() {
        let _env = seal_deepseek_env();

        // --- Route A: resolved, preflighted, installed, receipt minted. ---
        const KEY_A: &str = "sk-route-a-secret";
        const BASE_A: &str = "https://api.deepseek.com/v1";
        let config_a = deepseek_config(KEY_A, BASE_A);
        let route = deepseek_turn_route(&config_a);
        let actual_base_url = deepseek_actual_base_url(&config_a, &route);

        // --- Config mutates to route B, still before TurnStarted handling. ---
        const KEY_B: &str = "sk-route-b-attacker";
        const BASE_B: &str = "https://exfil.example.com/v1";
        let config_b = deepseek_config(KEY_B, BASE_B);

        // --- TurnStarted handling. It takes no config, by construction. ---
        let authority =
            capture_route_authority(&route).expect("deepseek turn must capture authority");
        assert_eq!(
            authority.endpoint_identity(),
            endpoint_identity(&actual_base_url),
            "authority must describe route A, not whatever config says now"
        );
        assert!(
            !authority.endpoint_identity().contains("exfil.example.com"),
            "authority leaked onto route B: {}",
            authority.endpoint_identity()
        );
        assert!(
            !authority.authorizes(BASE_B, KEY_B),
            "route B must not be authorized by route A's receipt"
        );
        assert!(
            authority.authorizes(&actual_base_url, KEY_A),
            "route A must still authorize itself"
        );

        // --- TurnComplete: the later suggestion launch is refused. ---
        let snapshot = config_snapshot(&route, &authority, &actual_base_url);
        assert!(
            plan_suggestion_launch_with_config(&config_b, true, true, 4, Some(snapshot)).is_none(),
            "completed-turn context must not be dispatchable under the mutated config"
        );
        // A mutation of only the key, with route A's endpoint intact, is the
        // narrower form of the same race and must also fail closed.
        let key_only_mutation = deepseek_config(KEY_B, BASE_A);
        assert!(
            plan_suggestion_launch_with_config(&key_only_mutation, true, true, 4, Some(snapshot))
                .is_none(),
            "a credential-only mutation must fail closed too"
        );

        // --- Control: under the unmutated config A, the launch happens on A. ---
        let launch = plan_suggestion_launch_with_config(&config_a, true, true, 4, Some(snapshot))
            .unwrap_or_else(|| {
                panic!(
                    "route A must still launch on itself: {}",
                    route_mismatch_report(&config_a, &snapshot)
                )
            });
        assert_eq!(launch.api_key, KEY_A);
        assert_eq!(launch.base_url, actual_base_url);
        assert_ne!(launch.api_key, KEY_B);
        assert!(!launch.base_url.contains("exfil.example.com"));
    }

    #[test]
    fn config_same_identity_base_url_mutation_fails_closed() {
        let _env = seal_deepseek_env();
        let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
        let route = deepseek_turn_route(&config);
        // The endpoint the completed turn really used, so this test fails
        // closed on the mutation itself rather than on a stale literal.
        let actual_base_url = deepseek_actual_base_url(&config, &route);
        let authority =
            capture_route_authority(&route).expect("deepseek turn must capture authority");

        // The web config surface repoints the SAME provider identity at a
        // different endpoint while the turn is still running.
        let mutated = deepseek_config(DEEPSEEK_KEY, "https://exfil.example.com/v1");

        assert!(
            plan_suggestion_launch_with_config(
                &mutated,
                true,
                true,
                4,
                Some(config_snapshot(&route, &authority, &actual_base_url)),
            )
            .is_none(),
            "a same-identity endpoint mutation must send no context anywhere"
        );
    }

    #[test]
    fn config_same_identity_api_key_mutation_fails_closed() {
        let _env = seal_deepseek_env();
        let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
        let route = deepseek_turn_route(&config);
        let actual_base_url = deepseek_actual_base_url(&config, &route);
        let authority =
            capture_route_authority(&route).expect("deepseek turn must capture authority");

        // Same identity, same endpoint, different credential. Everything except
        // the key matches, so only the credential-generation gate can reject.
        let mutated = deepseek_config("sk-attacker-rotated", DEEPSEEK_BASE);
        assert_eq!(
            deepseek_actual_base_url(&mutated, &route),
            actual_base_url,
            "this test must isolate the credential rotation, not an endpoint change"
        );

        assert!(
            plan_suggestion_launch_with_config(
                &mutated,
                true,
                true,
                4,
                Some(config_snapshot(&route, &authority, &actual_base_url)),
            )
            .is_none(),
            "a same-identity credential mutation must send no context anywhere"
        );
    }

    #[test]
    fn config_selection_switch_cannot_redirect_the_completed_route() {
        let _env = seal_deepseek_env();
        let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
        let route = deepseek_turn_route(&config);
        let actual_base_url = deepseek_actual_base_url(&config, &route);
        let authority =
            capture_route_authority(&route).expect("deepseek turn must capture authority");

        // Ordinary UI selection switch: the live provider is now OpenAI, with
        // its own key and endpoint. The completed DeepSeek turn must still
        // resolve DeepSeek — and must never reach the OpenAI route.
        let mut switched = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
        switched.provider = Some("openai".to_string());
        {
            let providers = switched
                .providers
                .get_or_insert_with(ProvidersConfig::default);
            providers.openai.api_key = Some("sk-openai-secret".to_string());
            providers.openai.base_url = Some("https://api.openai.com/v1".to_string());
        }

        let snapshot = config_snapshot(&route, &authority, &actual_base_url);
        let launch = plan_suggestion_launch_with_config(&switched, true, true, 4, Some(snapshot))
            .unwrap_or_else(|| {
                panic!(
                    "the completed deepseek route stays valid across a selection switch: {}",
                    route_mismatch_report(&switched, &snapshot)
                )
            });

        assert_eq!(launch.base_url, actual_base_url);
        assert_eq!(launch.api_key, DEEPSEEK_KEY);
        assert_ne!(launch.api_key, "sk-openai-secret");
        assert!(!launch.base_url.contains("openai"));
    }

    #[test]
    fn config_unsupported_providers_capture_no_authority() {
        let _env = seal_deepseek_env();
        // A usable DeepSeek credential exists in this config, and each route
        // below is even handed a DeepSeek-shaped receipt. An unsupported
        // completed route must still capture nothing.
        let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);

        for (provider, identity, model) in [
            (ApiProvider::Anthropic, "anthropic", "claude-sonnet-4"),
            (ApiProvider::Openai, "openai", "gpt-4.1"),
            (ApiProvider::Openrouter, "openrouter", "some/model"),
            (ApiProvider::Custom, "lm-studio", "local-model"),
            (
                ApiProvider::DeepseekAnthropic,
                "deepseek-anthropic",
                "deepseek-chat",
            ),
        ] {
            let route = TurnRoute {
                provider,
                provider_identity: identity.to_string(),
                model: model.to_string(),
                auto_model: false,
                receipt: Some(receipt(
                    provider,
                    identity,
                    model,
                    DEEPSEEK_BASE,
                    DEEPSEEK_KEY,
                )),
                billing: Some(crate::core::events::RouteBillingEnvelope {
                    billing_surface: None,
                    endpoint_fingerprint: None,
                    billing_mode: crate::cost_status::RouteBillingMode::Unknown,
                    dispatched_at: chrono::Utc::now(),
                }),
                base_url: DEEPSEEK_BASE.to_string(),
                billing_product: crate::route_billing::RouteProduct::Unproven,
            };
            assert!(
                capture_route_authority(&route).is_none(),
                "{provider:?} must not capture a suggestion authority"
            );
        }

        // The direct credential resolver refuses unsupported providers too, so
        // no later caller can reach a key through it.
        assert!(
            resolve_credentials_for_identity(
                &config,
                ApiProvider::DeepseekAnthropic,
                "deepseek-anthropic",
                "deepseek-chat",
            )
            .is_none(),
            "DeepseekAnthropic must never reach a credential lookup"
        );
    }

    #[test]
    fn route_without_a_receipt_captures_no_authority() {
        let _env = seal_deepseek_env();
        let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
        let mut route = deepseek_turn_route(&config);
        route.receipt = None;
        assert!(
            capture_route_authority(&route).is_none(),
            "a turn with no installed-client receipt has no provenance to trust"
        );
    }

    #[test]
    fn receipt_describing_another_route_captures_no_authority() {
        let _env = seal_deepseek_env();
        let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
        let mut route = deepseek_turn_route(&config);
        // Same provider and identity, different wire model than the event's
        // own route: the chain is broken, not merely stale.
        route.receipt = Some(receipt(
            ApiProvider::Deepseek,
            "deepseek",
            "some-other-model",
            DEEPSEEK_BASE,
            DEEPSEEK_KEY,
        ));
        assert!(capture_route_authority(&route).is_none());

        route.receipt = Some(receipt(
            ApiProvider::DeepseekCN,
            "deepseek-cn",
            &route.model,
            DEEPSEEK_BASE,
            DEEPSEEK_KEY,
        ));
        assert!(capture_route_authority(&route).is_none());
    }

    #[test]
    fn config_requires_the_endpoint_the_turn_actually_used() {
        let _env = seal_deepseek_env();
        let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
        let route = deepseek_turn_route(&config);
        let actual_base_url = deepseek_actual_base_url(&config, &route);
        let authority =
            capture_route_authority(&route).expect("deepseek turn must capture authority");

        // Control: with the endpoint the turn really used, this route launches.
        // Without it, the two negatives below would prove nothing.
        let baseline = config_snapshot(&route, &authority, &actual_base_url);
        assert!(
            plan_suggestion_launch_with_config(&config, true, true, 4, Some(baseline)).is_some(),
            "baseline route must launch: {}",
            route_mismatch_report(&config, &baseline)
        );

        // `Event::TurnComplete` reported a different endpoint than the one the
        // receipt was minted from: the turn was not on this route.
        let mut snapshot = config_snapshot(&route, &authority, &actual_base_url);
        snapshot.actual_base_url = Some("https://exfil.example.com/v1");
        assert!(
            plan_suggestion_launch_with_config(&config, true, true, 4, Some(snapshot)).is_none(),
            "a completed turn on a different endpoint must fail closed"
        );

        // A missing endpoint is missing provenance, not an implicit match.
        let mut snapshot = config_snapshot(&route, &authority, &actual_base_url);
        snapshot.actual_base_url = None;
        assert!(
            plan_suggestion_launch_with_config(&config, true, true, 4, Some(snapshot)).is_none(),
            "an absent turn endpoint must fail closed"
        );
    }
}