返回 CodeWhale
prompt_suggestion.rs
根目录 / crates / tui / src / tui / prompt_suggestion.rs
1 //! Ghost-text follow-up prompt suggestion.
2 //!
3 //! After each completed turn, a lightweight API call generates ONE short
4 //! follow-up question the user might want to ask next. The suggestion is
5 //! rendered as dimmed ghost text in the composer when the input is empty.
6
7 use std::fmt;
8 use std::sync::OnceLock;
9
10 use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
11 use serde_json::Value;
12 use tracing::debug;
13
14 const MAX_SUGGESTION_RESPONSE_BYTES: usize = 64 * 1024;
15
16 use codewhale_config::ProviderKind;
17 use codewhale_engine::core::events::TurnRoute;
18 use codewhale_engine::route_receipt::{TurnRouteReceipt, endpoint_identity};
19 use codewhale_runtime::config::Config;
20
21 /// The exact route authority a turn was launched against.
22 ///
23 /// This is a thin, gated wrapper around the [`TurnRouteReceipt`] the **engine**
24 /// minted from the installed, preflighted client. It is never derived from
25 /// live config: the whole point is that by the time the TUI processes
26 /// `TurnStarted`, config may already describe a different endpoint or
27 /// credential (web config events are drained ahead of engine events), and
28 /// authority resolved from that mutable state would authorize sending a
29 /// completed turn's context to a route the turn never ran on.
30 ///
31 /// `TurnComplete` re-resolves the same identity and must reproduce every field
32 /// of this record; anything else — including a same-identity endpoint or key
33 /// rotation performed mid-turn — fails closed.
34 #[derive(Clone, PartialEq, Eq, Debug)]
35 pub struct SuggestionRouteAuthority {
36 receipt: TurnRouteReceipt,
37 }
38
39 impl SuggestionRouteAuthority {
40 #[must_use]
41 pub fn provider(&self) -> ProviderKind {
42 self.receipt.provider()
43 }
44
45 /// Exact configured route key (`TurnRoute::provider_identity`).
46 #[must_use]
47 pub fn provider_identity(&self) -> &str {
48 self.receipt.provider_identity()
49 }
50
51 /// Exact wire model the turn's client was bound to.
52 #[must_use]
53 pub fn model(&self) -> &str {
54 self.receipt.wire_model()
55 }
56
57 /// Normalized, redacted identity of the endpoint the turn's client used.
58 #[must_use]
59 pub fn endpoint_identity(&self) -> &str {
60 self.receipt.endpoint_identity()
61 }
62
63 /// Whether a live re-resolution still lands on the same endpoint and the
64 /// same credential generation.
65 fn authorizes(&self, base_url: &str, api_key: &str, openrouter_vendor: Option<&str>) -> bool {
66 self.receipt.matches_live_route(base_url, api_key)
67 && self.receipt.openrouter_vendor() == openrouter_vendor
68 }
69
70 #[cfg(test)]
71 pub(crate) fn from_receipt_for_test(receipt: TurnRouteReceipt) -> Self {
72 Self { receipt }
73 }
74 }
75
76 /// Non-secret route provenance for the turn that just completed.
77 ///
78 /// This is a snapshot of `TurnRoute` plus the authority minted when that turn's
79 /// client was installed, not live UI selection state. Every suggestion decision
80 /// is anchored to it, so a route switch made after the turn completed cannot
81 /// redirect the background request.
82 #[derive(Clone, Copy)]
83 pub struct SuggestionRouteSnapshot<'a> {
84 pub provider: ProviderKind,
85 /// Exact configured route key (`TurnRoute::provider_identity`).
86 pub provider_identity: &'a str,
87 /// Exact wire model the completed turn actually used.
88 pub model: &'a str,
89 /// Authority carried on the completed turn's route receipt.
90 pub authority: &'a SuggestionRouteAuthority,
91 /// Actual base URL this turn's client used, from `Event::TurnComplete`.
92 pub actual_base_url: Option<&'a str>,
93 }
94
95 /// Redacted: `actual_base_url` is a raw endpoint that may carry URL userinfo or
96 /// sensitive query values, so it renders as its normalized redacted identity.
97 impl fmt::Debug for SuggestionRouteSnapshot<'_> {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 f.debug_struct("SuggestionRouteSnapshot")
100 .field("provider", &self.provider)
101 .field("provider_identity", &self.provider_identity)
102 .field("model", &self.model)
103 .field("authority", &self.authority)
104 .field(
105 "actual_endpoint_identity",
106 &self.actual_base_url.map(endpoint_identity),
107 )
108 .finish()
109 }
110 }
111
112 /// Credential material resolved for exactly one route identity.
113 ///
114 /// The resolver that produces this must scope itself to the snapshot identity;
115 /// it must never fall back to the ambient/active provider.
116 #[derive(Clone, PartialEq, Eq)]
117 pub struct SuggestionRouteCredentials {
118 pub api_key: String,
119 pub base_url: String,
120 /// Wire model the resolver arrived at. Must equal the snapshot model.
121 pub model: String,
122 pub openrouter_vendor: Option<String>,
123 }
124
125 /// Redacted: an API key must never reach a log line, panic message, or test
126 /// failure output through `{:?}`, and a raw `base_url` can itself carry
127 /// credentials in URL userinfo or a query token.
128 impl fmt::Debug for SuggestionRouteCredentials {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 f.debug_struct("SuggestionRouteCredentials")
131 .field("api_key", &"<redacted>")
132 .field("endpoint_identity", &endpoint_identity(&self.base_url))
133 .field("model", &self.model)
134 .finish()
135 }
136 }
137
138 /// A fully validated background suggestion request.
139 #[derive(Clone, PartialEq, Eq)]
140 pub struct SuggestionLaunch {
141 pub api_key: String,
142 pub base_url: String,
143 pub model: String,
144 pub openrouter_vendor: Option<String>,
145 }
146
147 /// Redacted: see [`SuggestionRouteCredentials`].
148 impl fmt::Debug for SuggestionLaunch {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 f.debug_struct("SuggestionLaunch")
151 .field("api_key", &"<redacted>")
152 .field("endpoint_identity", &endpoint_identity(&self.base_url))
153 .field("model", &self.model)
154 .finish()
155 }
156 }
157
158 /// Whether a provider speaks the ordinary OpenAI-compatible
159 /// `/chat/completions` shape [`generate_suggestion`] hardcodes.
160 ///
161 /// Gate on wire protocol, not a vendor enum: Anthropic Messages and the
162 /// OpenAI Responses API are different request shapes and stay out.
163 #[must_use]
164 pub fn route_is_supported_suggestion_provider(provider: ProviderKind) -> bool {
165 codewhale_engine::client::provider_speaks_chat_completions(provider)
166 }
167
168 /// Resolve credentials for exactly one configured route identity.
169 ///
170 /// The identity is revalidated against live config and then scoped with
171 /// `resolve_runtime_route_for_identity`, so the key and endpoint come from that
172 /// route's own configuration rather than from whichever provider happens to be
173 /// selected now. An identity that no longer resolves, or that now resolves to a
174 /// different provider kind, yields `None`.
175 ///
176 /// The returned `base_url` is the **resolved route candidate's** endpoint, not
177 /// `Config::active_route_base_url()`. Those two are not the same string: the config
178 /// accessor is one input to candidate resolution, and the candidate endpoint is
179 /// what `CodewhaleClient::from_candidate` binds the transport to and therefore
180 /// what `Event::TurnComplete` reports back. Comparing anything else here would
181 /// compare a turn's actual endpoint against a differently-canonicalized value
182 /// and fail closed on routes that never changed.
183 fn resolve_credentials_for_identity(
184 config: &Config,
185 identity: &codewhale_runtime::config::ProviderIdentity,
186 model: &str,
187 ) -> Option<SuggestionRouteCredentials> {
188 // Belt and braces: callers already gated, but this function must never
189 // read credentials for a wire this helper does not speak.
190 let provider = identity.provider;
191 if !route_is_supported_suggestion_provider(provider) {
192 return None;
193 }
194 config.verify_provider_identity(identity).ok()?;
195 let resolved = codewhale_engine::route_runtime::resolve_runtime_route_for_identity(
196 config,
197 identity,
198 Some(model),
199 )
200 .ok()?;
201 if resolved.identity.provider != provider {
202 return None;
203 }
204 // This helper intentionally sends the ordinary Chat Completions shape.
205 // A configured path override may describe a provider-specific transport
206 // contract that this bounded feature does not implement, so fail closed
207 // instead of silently bypassing it with the canonical path.
208 if resolved
209 .config
210 .provider_config_for(&resolved.identity)
211 .and_then(|route| route.path_suffix.as_ref())
212 .is_some()
213 {
214 return None;
215 }
216 let api_key = resolved.config.active_route_api_key().ok()?;
217 Some(SuggestionRouteCredentials {
218 api_key,
219 base_url: resolved.candidate.endpoint().base_url.clone(),
220 model: resolved.model.clone(),
221 openrouter_vendor: resolved.config.openrouter_vendor().ok()?,
222 })
223 }
224
225 /// Adopt the engine's route receipt as this turn's suggestion authority.
226 ///
227 /// Takes **no `Config`**, by design. This runs while the TUI handles
228 /// `TurnStarted`, which is strictly after the engine resolved, preflighted, and
229 /// installed the turn's client — and strictly after any web config event queued
230 /// in the meantime has been drained. Reading credentials here would capture
231 /// whatever route config describes *now*, not the route the turn is running on.
232 /// The receipt was minted from the installed client itself, so it cannot drift.
233 ///
234 /// Unsupported providers — Anthropic Messages, Responses, and any other
235 /// non-Chat-Completions wire — return `None`, and no credential material
236 /// of any provider is inspected on this path at all.
237 #[must_use]
238 pub fn capture_route_authority(route: &TurnRoute) -> Option<SuggestionRouteAuthority> {
239 if !route_is_supported_suggestion_provider(route.provider) {
240 return None;
241 }
242 let provider_identity = route.provider_identity.trim();
243 let model = route.model.trim();
244 if provider_identity.is_empty() || model.is_empty() {
245 return None;
246 }
247
248 // A receipt that describes a different route than the event's own
249 // `TurnRoute` is broken provenance, not a usable authority.
250 let receipt = route.receipt.as_ref()?;
251 if receipt.provider() != route.provider
252 || receipt.provider_identity() != provider_identity
253 || receipt.wire_model() != model
254 || receipt.endpoint_identity().is_empty()
255 || receipt.credential_generation().is_empty()
256 {
257 return None;
258 }
259
260 Some(SuggestionRouteAuthority {
261 receipt: receipt.clone(),
262 })
263 }
264
265 /// Decide whether a completed turn may launch a background prompt suggestion,
266 /// and with exactly what credentials, endpoint, and model.
267 ///
268 /// Fail-closed by construction:
269 /// - `resolve_route_credentials` is only invoked once every non-credential gate
270 /// has passed for a Chat Completions route, so a Messages/Responses
271 /// completion never reaches another provider's credentials at all.
272 /// - The decision reads only `completed_route`, never live selection state, so
273 /// a later route switch cannot redirect it.
274 /// - The route must still resolve to the *same* provider, identity, wire model,
275 /// endpoint identity, and credential generation the engine recorded on this
276 /// turn's route receipt, and to the endpoint the turn's client actually used.
277 /// A same-identity endpoint or key rotation is therefore a mismatch, not an
278 /// accepted match, and no conversation context is sent anywhere.
279 pub fn plan_suggestion_launch<F>(
280 turn_completed: bool,
281 suggestion_enabled: bool,
282 api_message_count: usize,
283 completed_route: Option<SuggestionRouteSnapshot<'_>>,
284 resolve_route_credentials: F,
285 ) -> Option<SuggestionLaunch>
286 where
287 F: FnOnce(&SuggestionRouteSnapshot<'_>) -> Option<SuggestionRouteCredentials>,
288 {
289 if !turn_completed || !suggestion_enabled || api_message_count < 2 {
290 return None;
291 }
292 // No route snapshot means no provenance. Non-model turns (composer `!`
293 // shell commands) land here too.
294 let route = completed_route?;
295 if !route_is_supported_suggestion_provider(route.provider) {
296 return None;
297 }
298 let identity = route.provider_identity.trim();
299 if identity.is_empty() {
300 return None;
301 }
302 let model = route.model.trim();
303 if model.is_empty() {
304 return None;
305 }
306
307 // The authority came off this turn's own route receipt. If it describes
308 // anything else, the provenance chain is broken.
309 let authority = route.authority;
310 if authority.provider() != route.provider
311 || authority.provider_identity() != identity
312 || authority.model() != model
313 || authority.endpoint_identity().is_empty()
314 {
315 return None;
316 }
317
318 // The engine reports the endpoint this turn's client actually used. It is
319 // required, and it must be the endpoint the receipt was minted from.
320 let actual_endpoint = endpoint_identity(route.actual_base_url?);
321 if actual_endpoint.is_empty() || actual_endpoint != authority.endpoint_identity() {
322 return None;
323 }
324
325 let credentials = resolve_route_credentials(&route)?;
326 if credentials.api_key.trim().is_empty() {
327 return None;
328 }
329 // Never silently swap in a cheaper/different model than the one the
330 // completed turn was actually routed to.
331 if credentials.model.trim() != model {
332 return None;
333 }
334 // A same-identity endpoint mutation *or* credential rotation lands here.
335 // Both are checked against the receipt in one step, over the raw endpoint
336 // and raw credential, so a mutation hidden behind identical redaction (URL
337 // userinfo, a query token) is still a mismatch.
338 if !authority.authorizes(
339 &credentials.base_url,
340 &credentials.api_key,
341 credentials.openrouter_vendor.as_deref(),
342 ) {
343 return None;
344 }
345
346 // Dispatch from the exact base endpoint and credential the receipt
347 // authorized — the raw pair the digest was taken over, not a
348 // re-canonicalized variant. `generate_suggestion` applies the same
349 // canonical ordinary Chat Completions path mapping as the installed
350 // client; custom path overrides failed closed above.
351 Some(SuggestionLaunch {
352 api_key: credentials.api_key,
353 base_url: credentials.base_url,
354 model: model.to_string(),
355 openrouter_vendor: credentials.openrouter_vendor,
356 })
357 }
358
359 /// [`plan_suggestion_launch`] wired to the real, identity-scoped config
360 /// resolver. This is the only production entry point.
361 #[must_use]
362 pub fn plan_suggestion_launch_with_config(
363 config: &Config,
364 turn_completed: bool,
365 suggestion_enabled: bool,
366 api_message_count: usize,
367 completed_route: Option<SuggestionRouteSnapshot<'_>>,
368 ) -> Option<SuggestionLaunch> {
369 plan_suggestion_launch(
370 turn_completed,
371 suggestion_enabled,
372 api_message_count,
373 completed_route,
374 |route| {
375 resolve_credentials_for_identity(
376 config,
377 route.authority.receipt.admitted_identity(),
378 route.model.trim(),
379 )
380 },
381 )
382 }
383
384 /// Reusable static client — avoids creating a new connection pool per request.
385 fn suggestion_client() -> &'static reqwest::Client {
386 static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
387 CLIENT.get_or_init(codewhale_release::tls::reqwest_client)
388 }
389
390 /// Generate a follow-up prompt suggestion based on recent messages.
391 ///
392 /// Sends the conversation summary to the API with a system prompt that
393 /// asks for a single short follow-up question. Returns `None` on failure
394 /// or empty result — callers treat this as best-effort.
395 pub async fn generate_suggestion(
396 api_key: &str,
397 base_url: &str,
398 model: &str,
399 recent_messages: &str,
400 openrouter_vendor: Option<&str>,
401 ) -> Option<String> {
402 // Suggestions are model output derived from the just-completed
403 // interactive transcript. They therefore participate in the same
404 // attached CWC run even though this narrow adapter owns a raw reqwest
405 // client instead of a `CodewhaleClient`. Retain the permit through decode
406 // so Runtime Chat cannot overlap or project a second inference lifecycle.
407 let _inference = codewhale_engine::client::acquire_remote_control_inference_participant().await;
408 let client = suggestion_client();
409 let mut body = serde_json::json!({
410 "model": model,
411 "messages": [
412 {
413 "role": "system",
414 "content": "\
415 You are a helpful assistant. Based on the recent conversation context, generate \
416 ONE short follow-up question (under 60 characters) the user might want to ask \
417 next. Reply with ONLY the question text, nothing else — no quotes, no explanations, \
418 no prefixes."
419 },
420 {
421 "role": "user",
422 "content": format!(
423 "Recent conversation:\n{recent_messages}\n\n\
424 Generate ONE short follow-up question the user might ask next:"
425 )
426 }
427 ],
428 "max_tokens": 64,
429 "temperature": 0.3,
430 "stream": false
431 });
432 codewhale_engine::client::apply_openrouter_vendor(&mut body, openrouter_vendor);
433
434 let url = codewhale_engine::client::api_url(base_url, "chat/completions");
435 // Never log the raw request URL: a base URL can carry credentials in its
436 // userinfo or in a query token. The redacted endpoint identity keeps the
437 // line diagnosable without carrying either.
438 debug!(
439 endpoint = %endpoint_identity(&url),
440 %model,
441 "generating prompt suggestion"
442 );
443 let mut request = client
444 .post(&url)
445 .header(AUTHORIZATION, format!("Bearer {api_key}"))
446 .header(CONTENT_TYPE, "application/json")
447 .timeout(std::time::Duration::from_secs(10))
448 .json(&body);
449 // OpenRouter app attribution: same headers the Chat Completions client
450 // already sends. Infer from the turn's actual endpoint so this helper
451 // does not grow a provider enum of its own.
452 if endpoint_identity(&url).contains("openrouter.ai") {
453 request = request
454 .header("HTTP-Referer", "https://codewhale.net")
455 .header("X-Title", "Codewhale");
456 }
457 let response = match request.send().await {
458 Ok(r) => r,
459 Err(error) => {
460 debug!(error = %error.without_url(), "prompt suggestion request failed");
461 return None;
462 }
463 };
464 if response
465 .content_length()
466 .is_some_and(|len| len > MAX_SUGGESTION_RESPONSE_BYTES as u64)
467 {
468 debug!("prompt suggestion response exceeds the size limit");
469 return None;
470 }
471 let mut body = Vec::new();
472 let mut stream = response.bytes_stream();
473 while let Some(chunk) = futures_util::StreamExt::next(&mut stream).await {
474 match chunk {
475 Ok(chunk)
476 if body.len().saturating_add(chunk.len()) <= MAX_SUGGESTION_RESPONSE_BYTES =>
477 {
478 body.extend_from_slice(&chunk);
479 }
480 Ok(_) => {
481 debug!("prompt suggestion response exceeds the size limit");
482 return None;
483 }
484 Err(error) => {
485 debug!(
486 error = %error.without_url(),
487 "prompt suggestion response read failed"
488 );
489 return None;
490 }
491 }
492 }
493 let value: Value = match serde_json::from_slice(&body) {
494 Ok(v) => v,
495 Err(error) => {
496 debug!(%error, "prompt suggestion response is not valid JSON");
497 return None;
498 }
499 };
500
501 let suggestion = value["choices"][0]["message"]["content"]
502 .as_str()
503 .map(|s| s.trim().trim_matches('"').to_string())
504 .filter(|s| !s.is_empty() && s.len() <= 200)?;
505
506 // The suggestion is model output derived from conversation context, so its
507 // text stays out of logs; only its shape is recorded.
508 debug!(
509 chars = suggestion.chars().count(),
510 "prompt suggestion generated"
511 );
512 Some(suggestion)
513 }
514
515 /// Extract the first text line from a single message.
516 fn message_summary(m: &codewhale_models::Message) -> Option<String> {
517 let role = match m.role.as_str() {
518 "user" => "User",
519 "assistant" => "Assistant",
520 _ => return None,
521 };
522 let text = m
523 .content
524 .iter()
525 .filter_map(|block| match block {
526 codewhale_models::ContentBlock::Text { text, .. } => Some(text.as_str()),
527 _ => None,
528 })
529 .collect::<Vec<_>>()
530 .join(" ");
531 let first_line = text.lines().next().unwrap_or("").trim();
532 if first_line.is_empty() {
533 return None;
534 }
535 let truncated: String = first_line
536 .chars()
537 .take(120)
538 .chain(if first_line.chars().count() > 120 {
539 Some('…')
540 } else {
541 None
542 })
543 .collect();
544 Some(format!("{role}: {truncated}"))
545 }
546
547 /// Build a one-line-per-message summary of recent conversation context.
548 /// Takes the last N messages, skipping tool-only messages.
549 pub fn summarize_recent_messages(messages: &[codewhale_models::Message], limit: usize) -> String {
550 let start = messages.len().saturating_sub(limit);
551 messages[start..]
552 .iter()
553 .filter_map(message_summary)
554 .collect::<Vec<_>>()
555 .join("\n")
556 }
557
558 #[cfg(test)]
559 mod tests {
560 use std::cell::RefCell;
561
562 use super::{
563 Config, ProviderKind, SuggestionRouteAuthority, SuggestionRouteCredentials,
564 SuggestionRouteSnapshot, TurnRoute, TurnRouteReceipt, capture_route_authority,
565 endpoint_identity, generate_suggestion, plan_suggestion_launch,
566 plan_suggestion_launch_with_config, resolve_credentials_for_identity,
567 };
568 use crate::test_support::{EnvVarGuard, TestEnvLock, lock_test_env};
569 use codewhale_runtime::config::ProvidersConfig;
570 use wiremock::matchers::{method, path};
571 use wiremock::{Mock, MockServer, ResponseTemplate};
572
573 const DEEPSEEK_BASE: &str = "https://api.deepseek.com/v1";
574 const DEEPSEEK_KEY: &str = "sk-deepseek-secret";
575
576 #[tokio::test]
577 async fn suggestion_request_preserves_openrouter_vendor_pin() {
578 let server = MockServer::start().await;
579 Mock::given(method("POST"))
580 .and(path("/v1/chat/completions"))
581 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
582 "choices": [{ "message": { "content": "What should we do next?" } }]
583 })))
584 .expect(2)
585 .mount(&server)
586 .await;
587
588 for vendor in [Some("chutes/region-fixture"), None] {
589 assert!(
590 generate_suggestion(
591 "fixture-key",
592 &format!("{}/v1", server.uri()),
593 "fixture/model",
594 "User: hello",
595 vendor,
596 )
597 .await
598 .is_some()
599 );
600 }
601 let requests = server.received_requests().await.unwrap();
602 assert_eq!(requests.len(), 2);
603 let pinned: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap();
604 assert_eq!(
605 pinned["provider"],
606 serde_json::json!({"order": ["chutes/region-fixture"], "allow_fallbacks": false})
607 );
608 let unpinned: serde_json::Value = serde_json::from_slice(&requests[1].body).unwrap();
609 assert!(unpinned.get("provider").is_none());
610 }
611
612 #[tokio::test]
613 async fn suggestion_inference_waits_for_runtime_chat_ownership() {
614 let server = MockServer::start().await;
615 Mock::given(method("POST"))
616 .and(path("/v1/chat/completions"))
617 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
618 "choices": [{ "message": { "content": "What should we do next?" } }]
619 })))
620 .expect(1)
621 .mount(&server)
622 .await;
623
624 let ownership = codewhale_engine::client::acquire_runtime_chat_inference_ownership().await;
625 let base_url = format!("{}/v1", server.uri());
626 let mut suggestion = tokio::spawn(async move {
627 generate_suggestion(
628 "fixture-key",
629 &base_url,
630 "deepseek-v4-flash",
631 "User: hello\nAssistant: hi",
632 None,
633 )
634 .await
635 });
636 assert!(
637 tokio::time::timeout(std::time::Duration::from_millis(40), &mut suggestion)
638 .await
639 .is_err(),
640 "background suggestion provider output must wait behind Runtime Chat"
641 );
642 drop(ownership);
643 assert_eq!(
644 tokio::time::timeout(std::time::Duration::from_secs(1), suggestion)
645 .await
646 .expect("suggestion resumes after relay settlement")
647 .expect("suggestion task")
648 .as_deref(),
649 Some("What should we do next?")
650 );
651 }
652
653 /// Stand-in for the real credential resolver. Records every identity it was
654 /// asked about so a test can prove it was never consulted at all.
655 struct RecordingResolver {
656 /// Credentials keyed by exact `(provider, provider_identity)`.
657 available: Vec<(ProviderKind, &'static str, SuggestionRouteCredentials)>,
658 asked: RefCell<Vec<(ProviderKind, String)>>,
659 }
660
661 impl RecordingResolver {
662 fn new(available: Vec<(ProviderKind, &'static str, SuggestionRouteCredentials)>) -> Self {
663 Self {
664 available,
665 asked: RefCell::new(Vec::new()),
666 }
667 }
668
669 fn resolve(
670 &self,
671 route: &SuggestionRouteSnapshot<'_>,
672 ) -> Option<SuggestionRouteCredentials> {
673 self.asked
674 .borrow_mut()
675 .push((route.provider, route.provider_identity.to_string()));
676 self.available
677 .iter()
678 .find(|(provider, identity, _)| {
679 *provider == route.provider && *identity == route.provider_identity
680 })
681 .map(|(_, _, credentials)| credentials.clone())
682 }
683
684 fn asked(&self) -> Vec<(ProviderKind, String)> {
685 self.asked.borrow().clone()
686 }
687 }
688
689 fn credentials(api_key: &str, base_url: &str, model: &str) -> SuggestionRouteCredentials {
690 SuggestionRouteCredentials {
691 api_key: api_key.to_string(),
692 base_url: base_url.to_string(),
693 model: model.to_string(),
694 openrouter_vendor: None,
695 }
696 }
697
698 fn deepseek_credentials(model: &str) -> SuggestionRouteCredentials {
699 credentials(DEEPSEEK_KEY, DEEPSEEK_BASE, model)
700 }
701
702 /// A receipt as the engine would have minted it from the installed client.
703 fn receipt(
704 provider: ProviderKind,
705 identity: &str,
706 model: &str,
707 base_url: &str,
708 api_key: &str,
709 ) -> TurnRouteReceipt {
710 TurnRouteReceipt::new(provider, identity, model, base_url, api_key)
711 }
712
713 /// Authority as the TUI would have adopted it at `TurnStarted`.
714 ///
715 /// Bypasses the provider gate so the unsupported-provider tests below can
716 /// prove the *later* gates also hold, not just the first one.
717 fn route_authority(
718 provider: ProviderKind,
719 identity: &str,
720 model: &str,
721 base_url: &str,
722 api_key: &str,
723 ) -> SuggestionRouteAuthority {
724 SuggestionRouteAuthority::from_receipt_for_test(receipt(
725 provider, identity, model, base_url, api_key,
726 ))
727 }
728
729 fn deepseek_authority(model: &str) -> SuggestionRouteAuthority {
730 route_authority(
731 ProviderKind::Deepseek,
732 "deepseek",
733 model,
734 DEEPSEEK_BASE,
735 DEEPSEEK_KEY,
736 )
737 }
738
739 fn snapshot<'a>(
740 provider: ProviderKind,
741 identity: &'a str,
742 model: &'a str,
743 authority: &'a SuggestionRouteAuthority,
744 ) -> SuggestionRouteSnapshot<'a> {
745 SuggestionRouteSnapshot {
746 provider,
747 provider_identity: identity,
748 model,
749 authority,
750 actual_base_url: Some(DEEPSEEK_BASE),
751 }
752 }
753
754 #[test]
755 fn deepseek_route_uses_its_exact_wire_model_and_base_url() {
756 let resolver = RecordingResolver::new(vec![(
757 ProviderKind::Deepseek,
758 "deepseek",
759 deepseek_credentials("deepseek-reasoner"),
760 )]);
761 let authority = deepseek_authority("deepseek-reasoner");
762 let launch = plan_suggestion_launch(
763 true,
764 true,
765 2,
766 Some(snapshot(
767 ProviderKind::Deepseek,
768 "deepseek",
769 "deepseek-reasoner",
770 &authority,
771 )),
772 |route| resolver.resolve(route),
773 )
774 .expect("supported deepseek route with unchanged credentials must launch");
775
776 assert_eq!(launch.model, "deepseek-reasoner");
777 assert_eq!(launch.base_url, DEEPSEEK_BASE);
778 assert_eq!(launch.api_key, DEEPSEEK_KEY);
779 }
780
781 #[test]
782 fn non_chat_completions_completion_never_touches_foreign_credentials() {
783 // A Chat Completions key exists and would resolve fine — the gate must
784 // run before the resolver is ever consulted.
785 let resolver = RecordingResolver::new(vec![(
786 ProviderKind::Deepseek,
787 "deepseek",
788 deepseek_credentials("deepseek-chat"),
789 )]);
790 for (provider, identity, model) in [
791 (ProviderKind::Anthropic, "anthropic", "claude-sonnet-4"),
792 (ProviderKind::OpenaiCodex, "openai-codex", "gpt-5.4"),
793 (
794 ProviderKind::DeepseekAnthropic,
795 "deepseek-anthropic",
796 "deepseek-chat",
797 ),
798 ] {
799 let authority = route_authority(provider, identity, model, DEEPSEEK_BASE, DEEPSEEK_KEY);
800 let launch = plan_suggestion_launch(
801 true,
802 true,
803 8,
804 Some(snapshot(provider, identity, model, &authority)),
805 |route| resolver.resolve(route),
806 );
807 assert!(
808 launch.is_none(),
809 "{provider:?} completion must not launch a prompt suggestion"
810 );
811 }
812 assert!(
813 resolver.asked().is_empty(),
814 "credential resolution must never be attempted for unsupported routes, got {:?}",
815 resolver.asked()
816 );
817 }
818
819 #[test]
820 fn chat_completions_routes_launch_with_their_own_credentials() {
821 for (provider, identity, model, base, key) in [
822 (
823 ProviderKind::Deepseek,
824 "deepseek",
825 "deepseek-chat",
826 DEEPSEEK_BASE,
827 DEEPSEEK_KEY,
828 ),
829 (
830 ProviderKind::Openai,
831 "openai",
832 "gpt-5.6",
833 "https://api.openai.com/v1",
834 "sk-openai",
835 ),
836 (
837 ProviderKind::Openrouter,
838 "openrouter",
839 "some/model",
840 "https://openrouter.ai/api/v1",
841 "sk-or",
842 ),
843 (
844 ProviderKind::Custom,
845 "lm-studio",
846 "local-model",
847 "http://127.0.0.1:1234/v1",
848 "lm-key",
849 ),
850 (
851 ProviderKind::Zai,
852 "zai",
853 "GLM-5.3",
854 "https://api.z.ai/api/paas/v4",
855 "zai-key",
856 ),
857 ] {
858 let resolver =
859 RecordingResolver::new(vec![(provider, identity, credentials(key, base, model))]);
860 let authority = route_authority(provider, identity, model, base, key);
861 let route = SuggestionRouteSnapshot {
862 provider,
863 provider_identity: identity,
864 model,
865 authority: &authority,
866 actual_base_url: Some(base),
867 };
868 let launch =
869 plan_suggestion_launch(true, true, 2, Some(route), |route| resolver.resolve(route))
870 .unwrap_or_else(|| panic!("{provider:?} Chat Completions route must launch"));
871 assert_eq!(launch.api_key, key, "{provider:?}");
872 assert_eq!(launch.base_url, base, "{provider:?}");
873 assert_eq!(launch.model, model, "{provider:?}");
874 assert_eq!(resolver.asked(), vec![(provider, identity.to_string())]);
875 }
876 }
877
878 #[test]
879 fn missing_credentials_fail_closed() {
880 let authority = deepseek_authority("deepseek-chat");
881 // No entry for the deepseek identity: resolver returns None.
882 let empty = RecordingResolver::new(Vec::new());
883 assert!(
884 plan_suggestion_launch(
885 true,
886 true,
887 2,
888 Some(snapshot(
889 ProviderKind::Deepseek,
890 "deepseek",
891 "deepseek-chat",
892 &authority
893 )),
894 |route| empty.resolve(route),
895 )
896 .is_none(),
897 "unresolvable route credentials must fail closed"
898 );
899
900 for incomplete in [
901 credentials(" ", DEEPSEEK_BASE, "deepseek-chat"),
902 credentials(DEEPSEEK_KEY, "", "deepseek-chat"),
903 ] {
904 assert!(
905 plan_suggestion_launch(
906 true,
907 true,
908 2,
909 Some(snapshot(
910 ProviderKind::Deepseek,
911 "deepseek",
912 "deepseek-chat",
913 &authority
914 )),
915 |_| Some(incomplete.clone()),
916 )
917 .is_none(),
918 "incomplete credentials must fail closed: {incomplete:?}"
919 );
920 }
921 }
922
923 #[test]
924 fn resolver_is_asked_only_about_the_completed_route_identity() {
925 // Live selection has moved on to another provider; the plan is built
926 // from the completed-turn snapshot, so the resolver only ever sees the
927 // completed identity.
928 const CN_BASE: &str = "https://api.deepseek.cn/v1";
929 let resolver = RecordingResolver::new(vec![
930 (
931 ProviderKind::Deepseek,
932 "deepseek",
933 deepseek_credentials("deepseek-chat"),
934 ),
935 (
936 ProviderKind::Deepseek,
937 "deepseek-cn",
938 credentials("sk-cn", CN_BASE, "deepseek-chat"),
939 ),
940 ]);
941 let authority = route_authority(
942 ProviderKind::Deepseek,
943 "deepseek-cn",
944 "deepseek-chat",
945 CN_BASE,
946 "sk-cn",
947 );
948 let launch = plan_suggestion_launch(
949 true,
950 true,
951 4,
952 Some(SuggestionRouteSnapshot {
953 provider: ProviderKind::Deepseek,
954 provider_identity: "deepseek-cn",
955 model: "deepseek-chat",
956 authority: &authority,
957 actual_base_url: Some(CN_BASE),
958 }),
959 |route| resolver.resolve(route),
960 )
961 .expect("completed deepseek-cn route must launch on its own endpoint");
962
963 assert_eq!(launch.base_url, CN_BASE);
964 assert_eq!(launch.api_key, "sk-cn");
965 assert_eq!(
966 resolver.asked(),
967 vec![(ProviderKind::Deepseek, "deepseek-cn".to_string())],
968 "only the completed route identity may be inspected"
969 );
970 }
971
972 #[test]
973 fn model_substitution_by_the_resolver_fails_closed() {
974 let authority = deepseek_authority("deepseek-reasoner");
975 assert!(
976 plan_suggestion_launch(
977 true,
978 true,
979 2,
980 Some(snapshot(
981 ProviderKind::Deepseek,
982 "deepseek",
983 "deepseek-reasoner",
984 &authority
985 )),
986 // Silent downgrade to a cheaper model.
987 |_| Some(deepseek_credentials("deepseek-chat")),
988 )
989 .is_none(),
990 "a resolver-substituted model must not be dispatched"
991 );
992 }
993
994 #[test]
995 fn same_identity_endpoint_or_key_rotation_fails_closed() {
996 let authority = deepseek_authority("deepseek-chat");
997 // Same provider, same identity, same model — but the endpoint moved
998 // while the turn was in flight.
999 assert!(
1000 plan_suggestion_launch(
1001 true,
1002 true,
1003 2,
1004 Some(snapshot(
1005 ProviderKind::Deepseek,
1006 "deepseek",
1007 "deepseek-chat",
1008 &authority
1009 )),
1010 |_| Some(credentials(
1011 DEEPSEEK_KEY,
1012 "https://exfil.example.com/v1",
1013 "deepseek-chat"
1014 )),
1015 )
1016 .is_none(),
1017 "a same-identity endpoint mutation must fail closed"
1018 );
1019 // …and the same for a credential rotation onto the same endpoint.
1020 assert!(
1021 plan_suggestion_launch(
1022 true,
1023 true,
1024 2,
1025 Some(snapshot(
1026 ProviderKind::Deepseek,
1027 "deepseek",
1028 "deepseek-chat",
1029 &authority
1030 )),
1031 |_| Some(credentials(
1032 "sk-rotated-elsewhere",
1033 DEEPSEEK_BASE,
1034 "deepseek-chat"
1035 )),
1036 )
1037 .is_none(),
1038 "a same-identity credential mutation must fail closed"
1039 );
1040 }
1041
1042 #[test]
1043 fn userinfo_rotation_behind_identical_redaction_fails_closed() {
1044 // Both endpoints redact to the same identity string. Only the
1045 // credential-generation digest, which covers the raw endpoint, can
1046 // tell them apart — so redaction must not be the whole comparison.
1047 const ORIGINAL: &str = "https://svc:original@api.deepseek.com/v1";
1048 const ROTATED: &str = "https://svc:rotated@api.deepseek.com/v1";
1049 assert_eq!(endpoint_identity(ORIGINAL), endpoint_identity(ROTATED));
1050
1051 let authority = route_authority(
1052 ProviderKind::Deepseek,
1053 "deepseek",
1054 "deepseek-chat",
1055 ORIGINAL,
1056 DEEPSEEK_KEY,
1057 );
1058 let route = SuggestionRouteSnapshot {
1059 provider: ProviderKind::Deepseek,
1060 provider_identity: "deepseek",
1061 model: "deepseek-chat",
1062 authority: &authority,
1063 actual_base_url: Some(ORIGINAL),
1064 };
1065 assert!(
1066 plan_suggestion_launch(true, true, 2, Some(route), |_| Some(credentials(
1067 DEEPSEEK_KEY,
1068 ROTATED,
1069 "deepseek-chat"
1070 )))
1071 .is_none(),
1072 "a URL-userinfo rotation hidden by redaction must fail closed"
1073 );
1074 assert!(
1075 plan_suggestion_launch(true, true, 2, Some(route), |_| Some(credentials(
1076 DEEPSEEK_KEY,
1077 ORIGINAL,
1078 "deepseek-chat"
1079 )))
1080 .is_some(),
1081 "control: the unrotated endpoint still launches"
1082 );
1083 }
1084
1085 #[test]
1086 fn actual_turn_endpoint_must_be_present_and_match_the_authority() {
1087 let authority = deepseek_authority("deepseek-chat");
1088 for actual_base_url in [None, Some("https://exfil.example.com/v1"), Some(" ")] {
1089 let route = SuggestionRouteSnapshot {
1090 provider: ProviderKind::Deepseek,
1091 provider_identity: "deepseek",
1092 model: "deepseek-chat",
1093 authority: &authority,
1094 actual_base_url,
1095 };
1096 assert!(
1097 plan_suggestion_launch(true, true, 2, Some(route), |_| Some(deepseek_credentials(
1098 "deepseek-chat"
1099 )))
1100 .is_none(),
1101 "actual turn endpoint {actual_base_url:?} must fail closed"
1102 );
1103 }
1104
1105 // A trailing-slash-only difference is the same endpoint.
1106 let route = SuggestionRouteSnapshot {
1107 provider: ProviderKind::Deepseek,
1108 provider_identity: "deepseek",
1109 model: "deepseek-chat",
1110 authority: &authority,
1111 actual_base_url: Some("https://api.deepseek.com/v1/"),
1112 };
1113 assert!(
1114 plan_suggestion_launch(true, true, 2, Some(route), |_| Some(deepseek_credentials(
1115 "deepseek-chat"
1116 )))
1117 .is_some(),
1118 "trailing-slash normalization must not break the exact-route match"
1119 );
1120 }
1121
1122 #[test]
1123 fn authority_from_a_different_route_fails_closed() {
1124 // Authority belongs to deepseek-cn; the completed snapshot claims
1125 // deepseek. Broken provenance must never dispatch.
1126 let cn = route_authority(
1127 ProviderKind::Deepseek,
1128 "deepseek-cn",
1129 "deepseek-chat",
1130 "https://api.deepseek.cn/v1",
1131 "sk-cn",
1132 );
1133 let route = SuggestionRouteSnapshot {
1134 provider: ProviderKind::Deepseek,
1135 provider_identity: "deepseek",
1136 model: "deepseek-chat",
1137 authority: &cn,
1138 actual_base_url: Some(DEEPSEEK_BASE),
1139 };
1140 assert!(
1141 plan_suggestion_launch(true, true, 2, Some(route), |_| Some(deepseek_credentials(
1142 "deepseek-chat"
1143 )))
1144 .is_none(),
1145 "an authority captured for another route must fail closed"
1146 );
1147 }
1148
1149 #[test]
1150 fn missing_route_snapshot_or_disabled_gates_produce_no_request() {
1151 let resolver = RecordingResolver::new(vec![(
1152 ProviderKind::Deepseek,
1153 "deepseek",
1154 deepseek_credentials("deepseek-chat"),
1155 )]);
1156 let authority = deepseek_authority("deepseek-chat");
1157 let route = snapshot(
1158 ProviderKind::Deepseek,
1159 "deepseek",
1160 "deepseek-chat",
1161 &authority,
1162 );
1163
1164 // No route provenance (non-model turn).
1165 assert!(plan_suggestion_launch(true, true, 4, None, |r| resolver.resolve(r)).is_none());
1166 // Turn did not complete.
1167 assert!(
1168 plan_suggestion_launch(false, true, 4, Some(route), |r| resolver.resolve(r)).is_none()
1169 );
1170 // Feature disabled.
1171 assert!(
1172 plan_suggestion_launch(true, false, 4, Some(route), |r| resolver.resolve(r)).is_none()
1173 );
1174 // Not enough conversation context.
1175 assert!(
1176 plan_suggestion_launch(true, true, 1, Some(route), |r| resolver.resolve(r)).is_none()
1177 );
1178 // Empty identity is malformed provenance, not a legacy root route.
1179 let empty_identity = route_authority(
1180 ProviderKind::Deepseek,
1181 " ",
1182 "deepseek-chat",
1183 DEEPSEEK_BASE,
1184 DEEPSEEK_KEY,
1185 );
1186 assert!(
1187 plan_suggestion_launch(
1188 true,
1189 true,
1190 4,
1191 Some(snapshot(
1192 ProviderKind::Deepseek,
1193 " ",
1194 "deepseek-chat",
1195 &empty_identity
1196 )),
1197 |r| resolver.resolve(r),
1198 )
1199 .is_none()
1200 );
1201 // Empty model.
1202 let empty_model = route_authority(
1203 ProviderKind::Deepseek,
1204 "deepseek",
1205 "",
1206 DEEPSEEK_BASE,
1207 DEEPSEEK_KEY,
1208 );
1209 assert!(
1210 plan_suggestion_launch(
1211 true,
1212 true,
1213 4,
1214 Some(snapshot(
1215 ProviderKind::Deepseek,
1216 "deepseek",
1217 "",
1218 &empty_model
1219 )),
1220 |r| resolver.resolve(r),
1221 )
1222 .is_none()
1223 );
1224
1225 assert!(
1226 resolver.asked().is_empty(),
1227 "gates must reject before credential resolution, got {:?}",
1228 resolver.asked()
1229 );
1230 }
1231
1232 /// Every URL-bearing rendered surface in this feature, exercised against a
1233 /// base URL that carries credentials in both userinfo and query values.
1234 #[test]
1235 fn debug_never_renders_credential_material_or_raw_urls() {
1236 let secret_base = format!(
1237 "https://{}:{}@api.deepseek.com/v1?api_key={}{}&token={}{}&region=us-east",
1238 "svc-user", "hunter2", "sk", "-live-abc123", "tok", "-secret-xyz"
1239 );
1240 let secrets = [
1241 DEEPSEEK_KEY.to_string(),
1242 "svc-user".to_string(),
1243 "hunter2".to_string(),
1244 ["sk", "-live-abc123"].concat(),
1245 ["tok", "-secret-xyz"].concat(),
1246 ];
1247
1248 let credentials = credentials(DEEPSEEK_KEY, &secret_base, "deepseek-chat");
1249 let authority = route_authority(
1250 ProviderKind::Deepseek,
1251 "deepseek",
1252 "deepseek-chat",
1253 &secret_base,
1254 DEEPSEEK_KEY,
1255 );
1256 let route = SuggestionRouteSnapshot {
1257 provider: ProviderKind::Deepseek,
1258 provider_identity: "deepseek",
1259 model: "deepseek-chat",
1260 authority: &authority,
1261 actual_base_url: Some(&secret_base),
1262 };
1263 let launch =
1264 plan_suggestion_launch(true, true, 2, Some(route), |_| Some(credentials.clone()))
1265 .expect("unchanged route must launch");
1266
1267 for rendered in [
1268 format!("{credentials:?}"),
1269 format!("{credentials:#?}"),
1270 format!("{launch:?}"),
1271 format!("{launch:#?}"),
1272 format!("{authority:?}"),
1273 format!("{authority:#?}"),
1274 format!("{route:?}"),
1275 format!("{route:#?}"),
1276 ] {
1277 for secret in &secrets {
1278 assert!(
1279 !rendered.contains(secret),
1280 "a rendered surface leaked {secret}: {rendered}"
1281 );
1282 }
1283 // The endpoint identity is still useful for diagnostics.
1284 assert!(
1285 rendered.contains("api.deepseek.com"),
1286 "endpoint identity must survive redaction: {rendered}"
1287 );
1288 assert!(
1289 rendered.contains("region=us-east"),
1290 "non-sensitive query values must survive redaction: {rendered}"
1291 );
1292 }
1293 for rendered in [format!("{credentials:?}"), format!("{launch:?}")] {
1294 assert!(
1295 rendered.contains("<redacted>"),
1296 "Debug must mark the redacted field: {rendered}"
1297 );
1298 }
1299 // …while the launch still dispatches to the real, unredacted endpoint.
1300 assert_eq!(launch.base_url, secret_base);
1301 assert_eq!(launch.api_key, DEEPSEEK_KEY);
1302 }
1303
1304 // === Config-backed tests ===
1305 //
1306 // These drive the real, identity-scoped config resolver and the real
1307 // client-minted route receipt rather than recording stand-ins, so they
1308 // cover the actual production path.
1309
1310 /// Hold the env lock and remove every ambient variable that could displace
1311 /// the fixture's configured DeepSeek route.
1312 ///
1313 /// Without this, a developer shell that exports `DEEPSEEK_API_KEY` (or a
1314 /// dispatcher-marked `--api-key` forward) can make these tests pass or fail
1315 /// for reasons that have nothing to do with the privacy contract.
1316 ///
1317 /// Field order is load-bearing: the guards must restore the environment
1318 /// before the lock is released.
1319 struct SealedDeepseekEnv {
1320 _guards: Vec<EnvVarGuard>,
1321 _lock: TestEnvLock,
1322 }
1323
1324 fn seal_deepseek_env() -> SealedDeepseekEnv {
1325 let lock = lock_test_env();
1326 let guards = [
1327 "DEEPSEEK_API_KEY",
1328 "DEEPSEEK_API_KEY_SOURCE",
1329 "CODEWHALE_CLI_API_KEY",
1330 "DEEPSEEK_BASE_URL",
1331 "CODEWHALE_BASE_URL",
1332 ]
1333 .into_iter()
1334 .map(EnvVarGuard::remove)
1335 .collect();
1336 SealedDeepseekEnv {
1337 _guards: guards,
1338 _lock: lock,
1339 }
1340 }
1341
1342 fn deepseek_config(api_key: &str, base_url: &str) -> Config {
1343 let mut config = {
1344 let __cw_config_init_0_0 = Some("deepseek".to_string());
1345 let mut __cw_config_init_0_value: Config = Config::default();
1346 __cw_config_init_0_value.provider = __cw_config_init_0_0;
1347 __cw_config_init_0_value
1348 };
1349 let providers = config
1350 .providers
1351 .get_or_insert_with(ProvidersConfig::default);
1352 providers.deepseek.api_key = Some(api_key.to_string());
1353 providers.deepseek.base_url = Some(base_url.to_string());
1354 config
1355 }
1356
1357 #[test]
1358 fn suggestion_vendor_pin_rotation_or_invalid_config_fails_closed() {
1359 let _env = seal_deepseek_env();
1360 let mut config = {
1361 let __cw_config_init_1_0 = Some("openrouter".to_string());
1362 let __cw_config_init_1_1 = Some(ProvidersConfig {
1363 openrouter: codewhale_runtime::config::ProviderConfig {
1364 api_key: Some("fixture-openrouter-key".to_string()),
1365 base_url: Some("http://127.0.0.1:18080/v1".to_string()),
1366 model: Some("fixture/model".to_string()),
1367 vendor: Some("chutes/region-fixture".to_string()),
1368 ..Default::default()
1369 },
1370 ..Default::default()
1371 });
1372 let mut __cw_config_init_1_value: Config = Default::default();
1373 __cw_config_init_1_value.provider = __cw_config_init_1_0;
1374 __cw_config_init_1_value.providers = __cw_config_init_1_1;
1375 __cw_config_init_1_value
1376 };
1377 let client = codewhale_engine::client::CodewhaleClient::new(&config).unwrap();
1378 let authority =
1379 SuggestionRouteAuthority::from_receipt_for_test(client.turn_route_receipt());
1380 let route = SuggestionRouteSnapshot {
1381 provider: ProviderKind::Openrouter,
1382 provider_identity: "openrouter",
1383 model: authority.model(),
1384 authority: &authority,
1385 actual_base_url: Some(client.base_url()),
1386 };
1387 let launch = plan_suggestion_launch_with_config(&config, true, true, 2, Some(route))
1388 .expect("unchanged OpenRouter pin remains authorized");
1389 assert_eq!(
1390 launch.openrouter_vendor.as_deref(),
1391 Some("chutes/region-fixture")
1392 );
1393
1394 for changed_vendor in [Some("another-vendor"), None, Some("bad vendor")] {
1395 config.providers.as_mut().unwrap().openrouter.vendor =
1396 changed_vendor.map(str::to_string);
1397 assert!(
1398 plan_suggestion_launch_with_config(&config, true, true, 2, Some(route)).is_none(),
1399 "changed, removed, or invalid vendor must not broaden the completed turn's route"
1400 );
1401 }
1402 }
1403
1404 /// Build the completed-turn route the engine would have reported, using the
1405 /// same resolution the engine performs. This keeps the tests correct even
1406 /// if a model selector normalizes to a different wire id.
1407 ///
1408 /// The receipt is minted from the **preflighted client**, exactly as
1409 /// `Engine::send_message` does — not from config — so these tests exercise
1410 /// the real provenance chain rather than a re-derivation of it.
1411 fn deepseek_turn_route(config: &Config) -> TurnRoute {
1412 let identity = config
1413 .resolve_provider_identity("deepseek")
1414 .expect("test config must expose the deepseek identity");
1415 let resolved = codewhale_engine::route_runtime::resolve_runtime_route_for_identity(
1416 config,
1417 &identity,
1418 Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL),
1419 )
1420 .expect("test config must resolve the deepseek route");
1421 let model = resolved.model.clone();
1422 let validated = resolved
1423 .validate()
1424 .expect("test config must preflight a deepseek client");
1425 TurnRoute {
1426 provider: ProviderKind::Deepseek,
1427 provider_identity: "deepseek".to_string(),
1428 model,
1429 auto_model: false,
1430 receipt: Some(validated.client.turn_route_receipt()),
1431 billing: Some(codewhale_engine::core::events::RouteBillingEnvelope {
1432 billing_surface: None,
1433 endpoint_fingerprint: None,
1434 openrouter_vendor: None,
1435 provider_live_pricing: None,
1436 billing_mode: codewhale_engine::cost_status::RouteBillingMode::Unknown,
1437 dispatched_at: chrono::Utc::now(),
1438 }),
1439 base_url: codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL
1440 .to_string(),
1441 billing_product: codewhale_engine::route_billing::RouteProduct::Unproven,
1442 }
1443 }
1444
1445 /// The endpoint `Event::TurnComplete` would report for this config.
1446 ///
1447 /// Deliberately derived from the production resolver rather than written
1448 /// as a literal: `Config::active_route_base_url()` canonicalizes DeepSeek hosts
1449 /// (it strips a trailing `/v1`), and the transport is bound to the resolved
1450 /// candidate's endpoint, so a hand-written literal is a different string
1451 /// than the one the client actually uses.
1452 fn deepseek_actual_base_url(config: &Config, route: &TurnRoute) -> String {
1453 resolve_credentials_for_identity(
1454 config,
1455 route
1456 .receipt
1457 .as_ref()
1458 .expect("test receipt")
1459 .admitted_identity(),
1460 &route.model,
1461 )
1462 .expect("test config must resolve the deepseek route")
1463 .base_url
1464 }
1465
1466 /// Redacted mismatch report for a route that unexpectedly failed closed.
1467 ///
1468 /// Names the non-secret field that diverged so a future regression is
1469 /// diagnosable without ever printing a key, a raw URL, or a credential
1470 /// generation digest.
1471 fn route_mismatch_report(config: &Config, snapshot: &SuggestionRouteSnapshot<'_>) -> String {
1472 let resolved = resolve_credentials_for_identity(
1473 config,
1474 snapshot.authority.receipt.admitted_identity(),
1475 snapshot.model.trim(),
1476 );
1477 let credential_matches = resolved.as_ref().map(|credentials| {
1478 snapshot
1479 .authority
1480 .authorizes(&credentials.base_url, &credentials.api_key, None)
1481 });
1482 format!(
1483 "snapshot={snapshot:?}, resolved={resolved:?}, \
1484 resolved_authorized_by_receipt={credential_matches:?}"
1485 )
1486 }
1487
1488 fn config_snapshot<'a>(
1489 route: &'a TurnRoute,
1490 authority: &'a SuggestionRouteAuthority,
1491 actual_base_url: &'a str,
1492 ) -> SuggestionRouteSnapshot<'a> {
1493 SuggestionRouteSnapshot {
1494 provider: route.provider,
1495 provider_identity: route.provider_identity.as_str(),
1496 model: route.model.as_str(),
1497 authority,
1498 actual_base_url: Some(actual_base_url),
1499 }
1500 }
1501
1502 #[test]
1503 fn config_exact_unchanged_completed_route_launches() {
1504 let _env = seal_deepseek_env();
1505 let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
1506 let route = deepseek_turn_route(&config);
1507 let actual_base_url = deepseek_actual_base_url(&config, &route);
1508 let authority =
1509 capture_route_authority(&route).expect("deepseek turn must capture authority");
1510
1511 let snapshot = config_snapshot(&route, &authority, &actual_base_url);
1512 let launch = plan_suggestion_launch_with_config(&config, true, true, 4, Some(snapshot))
1513 .unwrap_or_else(|| {
1514 panic!(
1515 "an unchanged deepseek route must launch: {}",
1516 route_mismatch_report(&config, &snapshot)
1517 )
1518 });
1519
1520 assert_eq!(launch.base_url, actual_base_url);
1521 assert_eq!(launch.api_key, DEEPSEEK_KEY);
1522 assert_eq!(launch.model, route.model);
1523 // The turn's endpoint is the configured DeepSeek host, canonicalized
1524 // by the route resolver — not some other provider's endpoint.
1525 assert!(
1526 launch.base_url.contains("api.deepseek.com"),
1527 "unexpected endpoint host: {}",
1528 endpoint_identity(&launch.base_url)
1529 );
1530 }
1531
1532 #[test]
1533 fn configured_chat_path_override_fails_closed() {
1534 let _env = seal_deepseek_env();
1535 let mut config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
1536 config
1537 .providers
1538 .as_mut()
1539 .expect("providers")
1540 .deepseek
1541 .path_suffix = Some("/private/chat".to_string());
1542 let route = deepseek_turn_route(&config);
1543 let authority =
1544 capture_route_authority(&route).expect("deepseek turn must capture authority");
1545 let identity = config
1546 .resolve_provider_identity("deepseek")
1547 .expect("deepseek identity");
1548 let actual_base_url = codewhale_engine::route_runtime::resolve_runtime_route_for_identity(
1549 &config,
1550 &identity,
1551 Some(&route.model),
1552 )
1553 .expect("resolved route")
1554 .candidate
1555 .endpoint()
1556 .base_url
1557 .clone();
1558 let snapshot = config_snapshot(&route, &authority, &actual_base_url);
1559
1560 assert!(
1561 plan_suggestion_launch_with_config(&config, true, true, 4, Some(snapshot)).is_none(),
1562 "the suggestion helper must not bypass a provider-specific path contract"
1563 );
1564
1565 config
1566 .providers
1567 .as_mut()
1568 .expect("providers")
1569 .deepseek
1570 .path_suffix = Some(" ".to_string());
1571 assert!(
1572 resolve_credentials_for_identity(
1573 &config,
1574 route
1575 .receipt
1576 .as_ref()
1577 .expect("test receipt")
1578 .admitted_identity(),
1579 &route.model,
1580 )
1581 .is_none(),
1582 "even a blank configured suffix is an installed transport override"
1583 );
1584 }
1585
1586 /// The #4404/#4411 race, end to end.
1587 ///
1588 /// Route A is resolved, preflighted, and installed; the engine mints its
1589 /// receipt from that client. Config is then mutated to route B *before* the
1590 /// TUI ever handles `TurnStarted` — which is reachable because web config
1591 /// events are drained ahead of engine events. Authority must still be A,
1592 /// and the completed turn's context must not be dispatchable with B.
1593 #[test]
1594 fn config_mutated_before_turn_started_cannot_move_authority_off_route_a() {
1595 let _env = seal_deepseek_env();
1596
1597 // --- Route A: resolved, preflighted, installed, receipt minted. ---
1598 const KEY_A: &str = "sk-route-a-secret";
1599 const BASE_A: &str = "https://api.deepseek.com/v1";
1600 let config_a = deepseek_config(KEY_A, BASE_A);
1601 let route = deepseek_turn_route(&config_a);
1602 let actual_base_url = deepseek_actual_base_url(&config_a, &route);
1603
1604 // --- Config mutates to route B, still before TurnStarted handling. ---
1605 const KEY_B: &str = "sk-route-b-attacker";
1606 const BASE_B: &str = "https://exfil.example.com/v1";
1607 let config_b = deepseek_config(KEY_B, BASE_B);
1608
1609 // --- TurnStarted handling. It takes no config, by construction. ---
1610 let authority =
1611 capture_route_authority(&route).expect("deepseek turn must capture authority");
1612 assert_eq!(
1613 authority.endpoint_identity(),
1614 endpoint_identity(&actual_base_url),
1615 "authority must describe route A, not whatever config says now"
1616 );
1617 assert!(
1618 !authority.endpoint_identity().contains("exfil.example.com"),
1619 "authority leaked onto route B: {}",
1620 authority.endpoint_identity()
1621 );
1622 assert!(
1623 !authority.authorizes(BASE_B, KEY_B, None),
1624 "route B must not be authorized by route A's receipt"
1625 );
1626 assert!(
1627 authority.authorizes(&actual_base_url, KEY_A, None),
1628 "route A must still authorize itself"
1629 );
1630
1631 // --- TurnComplete: the later suggestion launch is refused. ---
1632 let snapshot = config_snapshot(&route, &authority, &actual_base_url);
1633 assert!(
1634 plan_suggestion_launch_with_config(&config_b, true, true, 4, Some(snapshot)).is_none(),
1635 "completed-turn context must not be dispatchable under the mutated config"
1636 );
1637 // A mutation of only the key, with route A's endpoint intact, is the
1638 // narrower form of the same race and must also fail closed.
1639 let key_only_mutation = deepseek_config(KEY_B, BASE_A);
1640 assert!(
1641 plan_suggestion_launch_with_config(&key_only_mutation, true, true, 4, Some(snapshot))
1642 .is_none(),
1643 "a credential-only mutation must fail closed too"
1644 );
1645
1646 // --- Control: under the unmutated config A, the launch happens on A. ---
1647 let launch = plan_suggestion_launch_with_config(&config_a, true, true, 4, Some(snapshot))
1648 .unwrap_or_else(|| {
1649 panic!(
1650 "route A must still launch on itself: {}",
1651 route_mismatch_report(&config_a, &snapshot)
1652 )
1653 });
1654 assert_eq!(launch.api_key, KEY_A);
1655 assert_eq!(launch.base_url, actual_base_url);
1656 assert_ne!(launch.api_key, KEY_B);
1657 assert!(!launch.base_url.contains("exfil.example.com"));
1658 }
1659
1660 #[test]
1661 fn config_same_identity_base_url_mutation_fails_closed() {
1662 let _env = seal_deepseek_env();
1663 let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
1664 let route = deepseek_turn_route(&config);
1665 // The endpoint the completed turn really used, so this test fails
1666 // closed on the mutation itself rather than on a stale literal.
1667 let actual_base_url = deepseek_actual_base_url(&config, &route);
1668 let authority =
1669 capture_route_authority(&route).expect("deepseek turn must capture authority");
1670
1671 // The web config surface repoints the SAME provider identity at a
1672 // different endpoint while the turn is still running.
1673 let mutated = deepseek_config(DEEPSEEK_KEY, "https://exfil.example.com/v1");
1674
1675 assert!(
1676 plan_suggestion_launch_with_config(
1677 &mutated,
1678 true,
1679 true,
1680 4,
1681 Some(config_snapshot(&route, &authority, &actual_base_url)),
1682 )
1683 .is_none(),
1684 "a same-identity endpoint mutation must send no context anywhere"
1685 );
1686 }
1687
1688 #[test]
1689 fn config_same_identity_api_key_mutation_fails_closed() {
1690 let _env = seal_deepseek_env();
1691 let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
1692 let route = deepseek_turn_route(&config);
1693 let actual_base_url = deepseek_actual_base_url(&config, &route);
1694 let authority =
1695 capture_route_authority(&route).expect("deepseek turn must capture authority");
1696
1697 // Same identity, same endpoint, different credential. Everything except
1698 // the key matches, so only the credential-generation gate can reject.
1699 let mutated = deepseek_config("sk-attacker-rotated", DEEPSEEK_BASE);
1700 assert_eq!(
1701 deepseek_actual_base_url(&mutated, &route),
1702 actual_base_url,
1703 "this test must isolate the credential rotation, not an endpoint change"
1704 );
1705
1706 assert!(
1707 plan_suggestion_launch_with_config(
1708 &mutated,
1709 true,
1710 true,
1711 4,
1712 Some(config_snapshot(&route, &authority, &actual_base_url)),
1713 )
1714 .is_none(),
1715 "a same-identity credential mutation must send no context anywhere"
1716 );
1717 }
1718
1719 #[test]
1720 fn config_selection_switch_cannot_redirect_the_completed_route() {
1721 let _env = seal_deepseek_env();
1722 let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
1723 let route = deepseek_turn_route(&config);
1724 let actual_base_url = deepseek_actual_base_url(&config, &route);
1725 let authority =
1726 capture_route_authority(&route).expect("deepseek turn must capture authority");
1727
1728 // Ordinary UI selection switch: the live provider is now OpenAI, with
1729 // its own key and endpoint. The completed DeepSeek turn must still
1730 // resolve DeepSeek — and must never reach the OpenAI route.
1731 let mut switched = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
1732 switched.provider = Some("openai".to_string());
1733 {
1734 let providers = switched
1735 .providers
1736 .get_or_insert_with(ProvidersConfig::default);
1737 providers.openai.api_key = Some("sk-openai-secret".to_string());
1738 providers.openai.base_url = Some("https://api.openai.com/v1".to_string());
1739 }
1740
1741 let snapshot = config_snapshot(&route, &authority, &actual_base_url);
1742 let launch = plan_suggestion_launch_with_config(&switched, true, true, 4, Some(snapshot))
1743 .unwrap_or_else(|| {
1744 panic!(
1745 "the completed deepseek route stays valid across a selection switch: {}",
1746 route_mismatch_report(&switched, &snapshot)
1747 )
1748 });
1749
1750 assert_eq!(launch.base_url, actual_base_url);
1751 assert_eq!(launch.api_key, DEEPSEEK_KEY);
1752 assert_ne!(launch.api_key, "sk-openai-secret");
1753 assert!(!launch.base_url.contains("openai"));
1754 }
1755
1756 #[test]
1757 fn config_unsupported_providers_capture_no_authority() {
1758 let _env = seal_deepseek_env();
1759 // A usable Chat Completions credential exists in this config, and
1760 // each route below is even handed a receipt. A Messages/Responses
1761 // completed route must still capture nothing.
1762 let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
1763
1764 for (provider, identity, model) in [
1765 (ProviderKind::Anthropic, "anthropic", "claude-sonnet-4"),
1766 (ProviderKind::OpenaiCodex, "openai-codex", "gpt-5.4"),
1767 (
1768 ProviderKind::DeepseekAnthropic,
1769 "deepseek-anthropic",
1770 "deepseek-chat",
1771 ),
1772 ] {
1773 let route = TurnRoute {
1774 provider,
1775 provider_identity: identity.to_string(),
1776 model: model.to_string(),
1777 auto_model: false,
1778 receipt: Some(receipt(
1779 provider,
1780 identity,
1781 model,
1782 DEEPSEEK_BASE,
1783 DEEPSEEK_KEY,
1784 )),
1785 billing: Some(codewhale_engine::core::events::RouteBillingEnvelope {
1786 billing_surface: None,
1787 endpoint_fingerprint: None,
1788 openrouter_vendor: None,
1789 provider_live_pricing: None,
1790 billing_mode: codewhale_engine::cost_status::RouteBillingMode::Unknown,
1791 dispatched_at: chrono::Utc::now(),
1792 }),
1793 base_url: DEEPSEEK_BASE.to_string(),
1794 billing_product: codewhale_engine::route_billing::RouteProduct::Unproven,
1795 };
1796 assert!(
1797 capture_route_authority(&route).is_none(),
1798 "{provider:?} must not capture a suggestion authority"
1799 );
1800 }
1801
1802 // The direct credential resolver refuses unsupported providers too, so
1803 // no later caller can reach a key through it.
1804 assert!(
1805 resolve_credentials_for_identity(
1806 &config,
1807 &(config).test_identity_for_kind(ProviderKind::DeepseekAnthropic),
1808 "deepseek-chat",
1809 )
1810 .is_none(),
1811 "DeepseekAnthropic must never reach a credential lookup"
1812 );
1813 }
1814
1815 #[test]
1816 fn route_without_a_receipt_captures_no_authority() {
1817 let _env = seal_deepseek_env();
1818 let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
1819 let mut route = deepseek_turn_route(&config);
1820 route.receipt = None;
1821 assert!(
1822 capture_route_authority(&route).is_none(),
1823 "a turn with no installed-client receipt has no provenance to trust"
1824 );
1825 }
1826
1827 #[test]
1828 fn receipt_describing_another_route_captures_no_authority() {
1829 let _env = seal_deepseek_env();
1830 let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
1831 let mut route = deepseek_turn_route(&config);
1832 // Same provider and identity, different wire model than the event's
1833 // own route: the chain is broken, not merely stale.
1834 route.receipt = Some(receipt(
1835 ProviderKind::Deepseek,
1836 "deepseek",
1837 "some-other-model",
1838 DEEPSEEK_BASE,
1839 DEEPSEEK_KEY,
1840 ));
1841 assert!(capture_route_authority(&route).is_none());
1842
1843 route.receipt = Some(receipt(
1844 ProviderKind::Deepseek,
1845 "deepseek-cn",
1846 &route.model,
1847 DEEPSEEK_BASE,
1848 DEEPSEEK_KEY,
1849 ));
1850 assert!(capture_route_authority(&route).is_none());
1851 }
1852
1853 #[test]
1854 fn config_requires_the_endpoint_the_turn_actually_used() {
1855 let _env = seal_deepseek_env();
1856 let config = deepseek_config(DEEPSEEK_KEY, DEEPSEEK_BASE);
1857 let route = deepseek_turn_route(&config);
1858 let actual_base_url = deepseek_actual_base_url(&config, &route);
1859 let authority =
1860 capture_route_authority(&route).expect("deepseek turn must capture authority");
1861
1862 // Control: with the endpoint the turn really used, this route launches.
1863 // Without it, the two negatives below would prove nothing.
1864 let baseline = config_snapshot(&route, &authority, &actual_base_url);
1865 assert!(
1866 plan_suggestion_launch_with_config(&config, true, true, 4, Some(baseline)).is_some(),
1867 "baseline route must launch: {}",
1868 route_mismatch_report(&config, &baseline)
1869 );
1870
1871 // `Event::TurnComplete` reported a different endpoint than the one the
1872 // receipt was minted from: the turn was not on this route.
1873 let mut snapshot = config_snapshot(&route, &authority, &actual_base_url);
1874 snapshot.actual_base_url = Some("https://exfil.example.com/v1");
1875 assert!(
1876 plan_suggestion_launch_with_config(&config, true, true, 4, Some(snapshot)).is_none(),
1877 "a completed turn on a different endpoint must fail closed"
1878 );
1879
1880 // A missing endpoint is missing provenance, not an implicit match.
1881 let mut snapshot = config_snapshot(&route, &authority, &actual_base_url);
1882 snapshot.actual_base_url = None;
1883 assert!(
1884 plan_suggestion_launch_with_config(&config, true, true, 4, Some(snapshot)).is_none(),
1885 "an absent turn endpoint must fail closed"
1886 );
1887 }
1888
1889 #[tokio::test]
1890 async fn oversized_suggestion_response_returns_none() {
1891 use tokio::io::{AsyncReadExt, AsyncWriteExt};
1892
1893 let oversized_json = serde_json::json!({
1894 "padding": "a".repeat(super::MAX_SUGGESTION_RESPONSE_BYTES + 1024),
1895 "choices": [{ "message": { "content": "Next step?" } }]
1896 })
1897 .to_string();
1898
1899 // With Content-Length header (fast-path rejection).
1900 let server = MockServer::start().await;
1901 Mock::given(method("POST"))
1902 .and(path("/v1/chat/completions"))
1903 .respond_with(ResponseTemplate::new(200).set_body_string(oversized_json.clone()))
1904 .expect(1)
1905 .mount(&server)
1906 .await;
1907 assert!(
1908 generate_suggestion(
1909 "fixture-key",
1910 &format!("{}/v1", server.uri()),
1911 "fixture/model",
1912 "User: hello",
1913 None,
1914 )
1915 .await
1916 .is_none()
1917 );
1918
1919 // Without Content-Length header (streaming byte-cap rejection).
1920 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1921 let addr = listener.local_addr().unwrap();
1922 let serve = tokio::spawn(async move {
1923 let (mut socket, _) = listener.accept().await.unwrap();
1924 let mut req = [0u8; 4096];
1925 let _ = socket.read(&mut req).await;
1926 let response = format!(
1927 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{oversized_json}"
1928 );
1929 let _ = socket.write_all(response.as_bytes()).await;
1930 let _ = socket.shutdown().await;
1931 });
1932 assert!(
1933 generate_suggestion(
1934 "fixture-key",
1935 &format!("http://{addr}/v1"),
1936 "fixture/model",
1937 "User: hello",
1938 None,
1939 )
1940 .await
1941 .is_none()
1942 );
1943 let _ = serve.await;
1944 }
1945
1946 #[tokio::test]
1947 async fn malformed_json_suggestion_response_logs_debug_and_returns_none() {
1948 use std::io::{Read, Seek, SeekFrom};
1949 use tracing::instrument::WithSubscriber;
1950
1951 let server = MockServer::start().await;
1952 Mock::given(method("POST"))
1953 .and(path("/v1/chat/completions"))
1954 .respond_with(ResponseTemplate::new(200).set_body_string("not-valid-json"))
1955 .expect(1)
1956 .mount(&server)
1957 .await;
1958
1959 let mut output = tempfile::tempfile().unwrap();
1960 let subscriber = tracing_subscriber::fmt()
1961 .without_time()
1962 .with_ansi(false)
1963 .with_max_level(tracing::Level::DEBUG)
1964 .with_writer(std::sync::Mutex::new(output.try_clone().unwrap()))
1965 .finish();
1966
1967 let suggestion = generate_suggestion(
1968 "fixture-key",
1969 &format!("{}/v1", server.uri()),
1970 "fixture/model",
1971 "User: hello",
1972 None,
1973 )
1974 .with_subscriber(subscriber)
1975 .await;
1976 assert!(suggestion.is_none());
1977
1978 output.seek(SeekFrom::Start(0)).unwrap();
1979 let mut logs = String::new();
1980 output.read_to_string(&mut logs).unwrap();
1981 assert!(
1982 logs.contains("prompt suggestion response is not valid JSON"),
1983 "{logs}"
1984 );
1985 }
1986 }
1987
1987 lines RUST