返回 CodeWhale
test_cases_14.rs
根目录 / crates / engine / src / core / engine / tests / test_cases_14.rs
1 #[tokio::test]
2 async fn sync_session_projects_persisted_subagent_handoff_for_headless_restore() {
3 let tmp = tempdir().expect("tempdir");
4 let config = EngineConfig {
5 workspace: tmp.path().to_path_buf(),
6 model: "deepseek-v4-pro".to_string(),
7 ..Default::default()
8 };
9 let (engine, handle) = Engine::new(config, &Config::default());
10 let payload = concat!(
11 "Child result retained.\nCheckpoint: engine restore is covered.\n",
12 "<codewhale:subagent.done>{\"agent_id\":\"agent_headless\",",
13 "\"status\":\"completed\",\"summary_location\":\"previous_line\"}",
14 "</codewhale:subagent.done>",
15 );
16 let messages = vec![
17 Message {
18 role: Role::User,
19 content: vec![ContentBlock::Text {
20 text: "Keep the original task".to_string(),
21 cache_control: None,
22 }],
23 },
24 crate::runtime_handoff::subagent_completion_runtime_message(payload),
25 ];
26
27 let run = tokio::spawn(engine.run());
28 handle
29 .send(Op::SyncSession {
30 expected: None,
31 control: crate::core::ops::SessionControlId::new(),
32 session_id: Some("headless-resume".to_string()),
33 messages,
34 system_prompt: None,
35 system_prompt_override: false,
36 model: "deepseek-v4-pro".to_string(),
37 workspace: tmp.path().to_path_buf(),
38 mode: AppMode::Agent,
39 agent_preset: None,
40 })
41 .await
42 .expect("sync session");
43
44 let (tx, rx) = tokio::sync::oneshot::channel();
45 handle
46 .send(Op::GetSessionSnapshot {
47 tx: std::sync::Arc::new(std::sync::Mutex::new(Some(tx))),
48 })
49 .await
50 .expect("request snapshot");
51 let snapshot = tokio::time::timeout(Duration::from_secs(2), rx)
52 .await
53 .expect("snapshot response")
54 .expect("snapshot");
55
56 assert_eq!(snapshot.messages.len(), 2);
57 assert!(snapshot.messages[0].content.iter().any(
58 |block| matches!(block, ContentBlock::Text { text, .. } if text == "Keep the original task")
59 ));
60 let restored = codewhale_models::turn_classify::restored_subagent_checkpoint_display(
61 &snapshot.messages[1],
62 )
63 .expect("projected headless checkpoint");
64 assert!(restored.contains("agent_headless"));
65 assert!(restored.contains("Checkpoint: engine restore is covered."));
66 assert!(!restored.contains("runtime_event"));
67 assert!(!restored.contains("subagent.done"));
68
69 run.abort();
70 }
71
72 #[tokio::test]
73 async fn session_snapshot_records_the_literal_custom_table_id() {
74 let tmp = tempdir().expect("tempdir");
75 let api_config = codewhale_runtime::config::parse_config_base(
76 r#"provider = "custom"
77 [providers.custom]
78 kind = "openai-compatible"
79 base_url = "http://127.0.0.1:18180/v1"
80 model = "legacy-root-model"
81 auth_mode = "none"
82 "#,
83 )
84 .expect("canonical literal custom table");
85 let config = EngineConfig {
86 workspace: tmp.path().to_path_buf(),
87 model: "legacy-root-model".to_string(),
88 ..Default::default()
89 };
90 let (engine, handle) = Engine::new(config, &api_config);
91
92 let run = tokio::spawn(engine.run());
93 let (tx, rx) = tokio::sync::oneshot::channel();
94 handle
95 .send(Op::GetSessionSnapshot {
96 tx: std::sync::Arc::new(std::sync::Mutex::new(Some(tx))),
97 })
98 .await
99 .expect("request snapshot");
100 let snapshot = tokio::time::timeout(Duration::from_secs(2), rx)
101 .await
102 .expect("snapshot response")
103 .expect("snapshot");
104
105 // The literal route is the `[providers.custom]` table since #6394.
106 assert_eq!(snapshot.model_provider, "custom");
107 assert_eq!(snapshot.model_provider_id.as_deref(), Some("custom"));
108 run.abort();
109 }
110
111 #[tokio::test]
112 #[allow(clippy::await_holding_lock)]
113 async fn edit_last_turn_preserves_current_mode() {
114 use wiremock::matchers::{method, path};
115 use wiremock::{Mock, MockServer, ResponseTemplate};
116
117 // EditLastTurn dispatches a real replacement turn. Pin that turn to a
118 // local, completing SSE response instead of depending on whichever
119 // provider configuration or network state the parallel test process has.
120 let _lock = lock_test_env();
121 let home = tempdir().expect("home");
122 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
123 let _user_home = EnvVarGuard::set("HOME", home.path());
124 let _user_profile = EnvVarGuard::set("USERPROFILE", home.path());
125 let tmp = tempdir().expect("tempdir");
126 let server = MockServer::start().await;
127 let done_sse = concat!(
128 "data: {\"id\":\"chatcmpl-edit-mode\",\"choices\":[{\"index\":0,",
129 "\"delta\":{\"content\":\"Revised plan.\"},\"finish_reason\":null}]}\n\n",
130 "data: {\"id\":\"chatcmpl-edit-mode\",\"choices\":[{\"index\":0,",
131 "\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n",
132 "data: [DONE]\n\n",
133 );
134 Mock::given(method("POST"))
135 .and(path("/v1/chat/completions"))
136 .respond_with(
137 ResponseTemplate::new(200)
138 .insert_header("content-type", "text/event-stream")
139 .set_body_string(done_sse),
140 )
141 .expect(1)
142 .mount(&server)
143 .await;
144
145 let api_config =
146 Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri()));
147 let config = EngineConfig {
148 workspace: tmp.path().to_path_buf(),
149 model: "deepseek-v4-pro".to_string(),
150 snapshots_enabled: false,
151 subagents_enabled: false,
152 ..Default::default()
153 };
154 let (engine, handle) = Engine::new(config, &api_config);
155
156 let run = tokio::spawn(engine.run());
157 let seeded_messages = vec![
158 Message {
159 role: Role::User,
160 content: vec![ContentBlock::Text {
161 text: "draft the plan".to_string(),
162 cache_control: None,
163 }],
164 },
165 Message {
166 role: Role::Assistant,
167 content: vec![ContentBlock::Text {
168 text: "initial response".to_string(),
169 cache_control: None,
170 }],
171 },
172 ];
173 handle
174 .send(Op::SyncSession {
175 expected: None,
176 control: crate::core::ops::SessionControlId::new(),
177 session_id: Some("edit-mode-test".to_string()),
178 messages: seeded_messages,
179 system_prompt: None,
180 system_prompt_override: false,
181 model: "deepseek-v4-pro".to_string(),
182 workspace: tmp.path().to_path_buf(),
183 mode: AppMode::Agent,
184 agent_preset: None,
185 })
186 .await
187 .expect("sync session");
188 handle
189 .send(Op::ChangeMode {
190 mode: AppMode::Plan,
191 allow_shell: false,
192 trust_mode: false,
193 auto_approve: false,
194 approval_mode: ApprovalMode::Suggest,
195 configured_sandbox_mode: None,
196 })
197 .await
198 .expect("send plan mode");
199 handle
200 .send(Op::EditLastTurn {
201 new_message: "revise this in plan mode".to_string(),
202 submission_id: Some("sub-edit-1".to_string()),
203 })
204 .await
205 .expect("send edit");
206 // The replacement turn the edit replays must echo the edit's own
207 // correlation token, not the one of any earlier turn.
208 {
209 let mut rx = handle.rx_event.write().await;
210 loop {
211 let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
212 .await
213 .expect("timed out waiting for the edited turn")
214 .expect("engine event");
215 if let Event::TurnStarted { submission_id, .. } = event {
216 assert_eq!(
217 submission_id.as_deref(),
218 Some("sub-edit-1"),
219 "the edit's replacement turn must echo its correlation token"
220 );
221 break;
222 }
223 }
224 }
225
226 let (tx, rx) = tokio::sync::oneshot::channel();
227 handle
228 .send(Op::GetSessionSnapshot {
229 tx: std::sync::Arc::new(std::sync::Mutex::new(Some(tx))),
230 })
231 .await
232 .expect("request snapshot");
233 let snapshot = tokio::time::timeout(model_turn_event_timeout(), rx)
234 .await
235 .expect("snapshot response")
236 .expect("snapshot");
237
238 assert_eq!(snapshot.mode, "plan");
239
240 let requests = server
241 .received_requests()
242 .await
243 .expect("recorded replacement request");
244 assert_eq!(
245 requests.len(),
246 1,
247 "edit must dispatch exactly one replacement turn"
248 );
249 handle.send(Op::Shutdown).await.expect("shutdown engine");
250 run.await.expect("engine task");
251 }
252
253 #[tokio::test]
254 #[allow(clippy::await_holding_lock)]
255 async fn edit_last_turn_cuts_at_user_prompt_before_tool_results() {
256 use wiremock::matchers::{method, path};
257 use wiremock::{Mock, MockServer, ResponseTemplate};
258
259 // Tool results persist with role "user"; the edit cut must land on the
260 // last genuine user prompt, not on the trailing tool_result of the
261 // previous turn.
262 let _lock = lock_test_env();
263 let home = tempdir().expect("home");
264 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
265 let _user_home = EnvVarGuard::set("HOME", home.path());
266 let _user_profile = EnvVarGuard::set("USERPROFILE", home.path());
267 let tmp = tempdir().expect("tempdir");
268 let server = MockServer::start().await;
269 let done_sse = concat!(
270 "data: {\"id\":\"chatcmpl-edit-cut\",\"choices\":[{\"index\":0,",
271 "\"delta\":{\"content\":\"Revised answer.\"},\"finish_reason\":null}]}\n\n",
272 "data: {\"id\":\"chatcmpl-edit-cut\",\"choices\":[{\"index\":0,",
273 "\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n",
274 "data: [DONE]\n\n",
275 );
276 Mock::given(method("POST"))
277 .and(path("/v1/chat/completions"))
278 .respond_with(
279 ResponseTemplate::new(200)
280 .insert_header("content-type", "text/event-stream")
281 .set_body_string(done_sse),
282 )
283 .expect(1)
284 .mount(&server)
285 .await;
286
287 let api_config =
288 Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri()));
289 let config = EngineConfig {
290 workspace: tmp.path().to_path_buf(),
291 model: "deepseek-v4-pro".to_string(),
292 snapshots_enabled: false,
293 subagents_enabled: false,
294 ..Default::default()
295 };
296 let (engine, handle) = Engine::new(config, &api_config);
297
298 let run = tokio::spawn(engine.run());
299 let seeded_messages = vec![
300 Message {
301 role: Role::User,
302 content: vec![ContentBlock::Text {
303 text: "original prompt".to_string(),
304 cache_control: None,
305 }],
306 },
307 Message {
308 role: Role::Assistant,
309 content: vec![ContentBlock::ToolUse {
310 execution_id: None,
311 id: "call_1".to_string(),
312 name: "Bash".to_string(),
313 input: serde_json::json!({"command": "printf hi"}),
314 caller: None,
315 thought_signature: None,
316 }],
317 },
318 Message {
319 role: Role::User,
320 content: vec![ContentBlock::ToolResult {
321 execution_id: None,
322 tool_use_id: "call_1".to_string(),
323 content: "unique-tool-output-marker".to_string(),
324 is_error: None,
325 content_blocks: None,
326 }],
327 },
328 Message {
329 role: Role::Assistant,
330 content: vec![ContentBlock::Text {
331 text: "final answer".to_string(),
332 cache_control: None,
333 }],
334 },
335 ];
336 handle
337 .send(Op::SyncSession {
338 expected: None,
339 control: crate::core::ops::SessionControlId::new(),
340 session_id: Some("edit-cut-test".to_string()),
341 messages: seeded_messages,
342 system_prompt: None,
343 system_prompt_override: false,
344 model: "deepseek-v4-pro".to_string(),
345 workspace: tmp.path().to_path_buf(),
346 mode: AppMode::Agent,
347 agent_preset: None,
348 })
349 .await
350 .expect("sync session");
351 handle
352 .send(Op::EditLastTurn {
353 new_message: "edited prompt".to_string(),
354 submission_id: None,
355 })
356 .await
357 .expect("send edit");
358
359 // Ops are processed in order: once the snapshot arrives, the replacement
360 // turn has completed.
361 let (tx, rx) = tokio::sync::oneshot::channel();
362 handle
363 .send(Op::GetSessionSnapshot {
364 tx: std::sync::Arc::new(std::sync::Mutex::new(Some(tx))),
365 })
366 .await
367 .expect("request snapshot");
368 let snapshot = tokio::time::timeout(model_turn_event_timeout(), rx)
369 .await
370 .expect("snapshot response")
371 .expect("snapshot");
372
373 assert_eq!(
374 snapshot.messages.len(),
375 3,
376 "the whole previous turn (prompt, tool_use, tool_result, answer) must be cut: {:?}",
377 snapshot.messages
378 );
379 assert!(
380 crate::runtime_handoff::project_instructions_display(&snapshot.messages[1]).is_some(),
381 "the middle survivor is the turn's workspace-instructions record: {:?}",
382 snapshot.messages[1]
383 );
384 assert!(
385 snapshot.messages.iter().all(|message| !message
386 .content
387 .iter()
388 .any(|block| matches!(block, ContentBlock::ToolResult { .. }))),
389 "no tool_result may survive the cut: {:?}",
390 snapshot.messages
391 );
392 let replacement_text = message_text_of(&snapshot.messages[0]);
393 assert!(
394 replacement_text.contains("edited prompt"),
395 "first surviving message is the edited prompt: {replacement_text}"
396 );
397
398 let requests = server
399 .received_requests()
400 .await
401 .expect("recorded replacement request");
402 assert_eq!(requests.len(), 1);
403 let body = String::from_utf8(requests[0].body.clone()).expect("request body utf8");
404 assert!(body.contains("edited prompt"));
405 assert!(
406 !body.contains("original prompt"),
407 "old prompt must not leak into the replacement turn: {body}"
408 );
409 assert!(
410 !body.contains("unique-tool-output-marker"),
411 "tool round-trip must not leak into the replacement turn: {body}"
412 );
413
414 handle.send(Op::Shutdown).await.expect("shutdown engine");
415 run.await.expect("engine task");
416 }
417
418 #[tokio::test]
419 #[allow(clippy::await_holding_lock)]
420 async fn edit_last_turn_without_user_prompt_errors_and_sends_nothing() {
421 use wiremock::matchers::{method, path};
422 use wiremock::{Mock, MockServer, ResponseTemplate};
423
424 let _lock = lock_test_env();
425 let home = tempdir().expect("home");
426 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
427 let _user_home = EnvVarGuard::set("HOME", home.path());
428 let _user_profile = EnvVarGuard::set("USERPROFILE", home.path());
429 let tmp = tempdir().expect("tempdir");
430 let server = MockServer::start().await;
431 Mock::given(method("POST"))
432 .and(path("/v1/chat/completions"))
433 .respond_with(ResponseTemplate::new(200))
434 .expect(0)
435 .mount(&server)
436 .await;
437
438 let api_config =
439 Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri()));
440 let config = EngineConfig {
441 workspace: tmp.path().to_path_buf(),
442 model: "deepseek-v4-pro".to_string(),
443 snapshots_enabled: false,
444 subagents_enabled: false,
445 ..Default::default()
446 };
447 let (engine, handle) = Engine::new(config, &api_config);
448
449 let run = tokio::spawn(engine.run());
450 // History without any genuine user prompt: nothing to edit. The engine
451 // must surface an error instead of silently appending the message.
452 handle
453 .send(Op::SyncSession {
454 expected: None,
455 control: crate::core::ops::SessionControlId::new(),
456 session_id: Some("edit-no-user-test".to_string()),
457 messages: vec![Message {
458 role: Role::Assistant,
459 content: vec![ContentBlock::Text {
460 text: "assistant only".to_string(),
461 cache_control: None,
462 }],
463 }],
464 system_prompt: None,
465 system_prompt_override: false,
466 model: "deepseek-v4-pro".to_string(),
467 workspace: tmp.path().to_path_buf(),
468 mode: AppMode::Agent,
469 agent_preset: None,
470 })
471 .await
472 .expect("sync session");
473 handle
474 .send(Op::EditLastTurn {
475 new_message: "edited prompt".to_string(),
476 submission_id: Some("sub-edit-rejected".to_string()),
477 })
478 .await
479 .expect("send edit");
480
481 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
482 let mut saw_edit_error = false;
483 let mut saw_failed_terminal = false;
484 {
485 let mut events = handle.rx_event.write().await;
486 while let Ok(Some(event)) = tokio::time::timeout_at(deadline, events.recv()).await {
487 match event {
488 Event::TurnStarted { .. } => {
489 panic!("rejected edit must not start a turn");
490 }
491 Event::Error { envelope, .. } => {
492 assert_eq!(envelope.code, "edit_last_turn_no_user_prompt");
493 assert!(!envelope.recoverable);
494 assert!(
495 envelope.message.contains("no user message"),
496 "unexpected error: {}",
497 envelope.message
498 );
499 saw_edit_error = true;
500 }
501 Event::TurnComplete {
502 turn_id,
503 submission_id,
504 compaction_id,
505 status,
506 error,
507 ..
508 } => {
509 assert!(turn_id.is_none());
510 assert_eq!(submission_id.as_deref(), Some("sub-edit-rejected"));
511 assert!(compaction_id.is_none());
512 assert_eq!(status, TurnOutcomeStatus::Failed);
513 assert!(
514 error
515 .as_deref()
516 .is_some_and(|message| message.contains("no user message")),
517 "failed edit terminal must carry the rejection: {error:?}"
518 );
519 saw_failed_terminal = true;
520 break;
521 }
522 _ => {}
523 }
524 }
525 }
526 assert!(saw_edit_error, "edit without a user prompt must error out");
527 assert!(
528 saw_failed_terminal,
529 "edit rejection must complete the submitted host lifecycle"
530 );
531
532 let (tx, rx) = tokio::sync::oneshot::channel();
533 handle
534 .send(Op::GetSessionSnapshot {
535 tx: std::sync::Arc::new(std::sync::Mutex::new(Some(tx))),
536 })
537 .await
538 .expect("request snapshot");
539 let snapshot = tokio::time::timeout(Duration::from_secs(2), rx)
540 .await
541 .expect("snapshot response")
542 .expect("snapshot");
543 assert_eq!(
544 snapshot.messages.len(),
545 1,
546 "failed edit must not append the new message: {:?}",
547 snapshot.messages
548 );
549
550 // An unsupported latest user turn is still a history boundary. It must
551 // fail in place rather than falling through to the older text prompt and
552 // deleting a larger portion of the conversation.
553 let image_only_history = vec![
554 Message {
555 role: Role::User,
556 content: vec![ContentBlock::Text {
557 text: "older editable prompt".to_string(),
558 cache_control: None,
559 }],
560 },
561 Message {
562 role: Role::Assistant,
563 content: vec![ContentBlock::Text {
564 text: "older response".to_string(),
565 cache_control: None,
566 }],
567 },
568 Message {
569 role: Role::User,
570 content: vec![ContentBlock::ImageUrl {
571 image_url: codewhale_models::ImageUrlContent {
572 url: "data:image/png;base64,AAAA".to_string(),
573 },
574 }],
575 },
576 ];
577 handle
578 .send(Op::SyncSession {
579 expected: None,
580 control: crate::core::ops::SessionControlId::new(),
581 session_id: Some("edit-unsupported-user-test".to_string()),
582 messages: image_only_history.clone(),
583 system_prompt: None,
584 system_prompt_override: false,
585 model: "deepseek-v4-pro".to_string(),
586 workspace: tmp.path().to_path_buf(),
587 mode: AppMode::Agent,
588 agent_preset: None,
589 })
590 .await
591 .expect("sync unsupported user session");
592 handle
593 .send(Op::EditLastTurn {
594 new_message: "must not replace the older prompt".to_string(),
595 submission_id: None,
596 })
597 .await
598 .expect("send unsupported edit");
599
600 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
601 let mut saw_unsupported_error = false;
602 let mut saw_unsupported_terminal = false;
603 {
604 let mut events = handle.rx_event.write().await;
605 while let Ok(Some(event)) = tokio::time::timeout_at(deadline, events.recv()).await {
606 match event {
607 Event::Error { envelope, .. } => {
608 assert_eq!(envelope.code, "edit_last_turn_unsupported_user_content");
609 assert!(!envelope.recoverable);
610 saw_unsupported_error = true;
611 }
612 Event::TurnComplete { status, error, .. } => {
613 assert_eq!(status, TurnOutcomeStatus::Failed);
614 assert!(
615 error
616 .as_deref()
617 .is_some_and(|message| message
618 .contains("latest user message has no editable text")),
619 "unsupported edit terminal must carry the rejection: {error:?}"
620 );
621 saw_unsupported_terminal = true;
622 break;
623 }
624 _ => {}
625 }
626 }
627 }
628 assert!(saw_unsupported_error);
629 assert!(saw_unsupported_terminal);
630
631 let (tx, rx) = tokio::sync::oneshot::channel();
632 handle
633 .send(Op::GetSessionSnapshot {
634 tx: std::sync::Arc::new(std::sync::Mutex::new(Some(tx))),
635 })
636 .await
637 .expect("request unsupported snapshot");
638 let unsupported_snapshot = tokio::time::timeout(Duration::from_secs(2), rx)
639 .await
640 .expect("unsupported snapshot response")
641 .expect("unsupported snapshot");
642 assert_eq!(
643 unsupported_snapshot.messages, image_only_history,
644 "unsupported latest user content must leave the entire history unchanged"
645 );
646
647 let requests = server.received_requests().await.expect("recorded requests");
648 assert!(
649 requests.is_empty(),
650 "failed edit must not dispatch a provider turn"
651 );
652
653 handle.send(Op::Shutdown).await.expect("shutdown engine");
654 run.await.expect("engine task");
655 }
656
657 #[tokio::test]
658 async fn provider_runtime_status_reports_configured_zai_cap_without_client() {
659 let (engine, handle) = {
660 let _lock = lock_test_env();
661 let _zai_key = EnvVarGuard::remove("ZAI_API_KEY");
662 let _zai_alt_key = EnvVarGuard::remove("Z_AI_API_KEY");
663 let api_config = {
664 let __cw_config_init_3_0 = Some("zai".to_string());
665 let mut __cw_config_init_3_value: Config = Config::default();
666 __cw_config_init_3_value.provider = __cw_config_init_3_0;
667 __cw_config_init_3_value
668 };
669 Engine::new(EngineConfig::default(), &api_config)
670 };
671
672 let run = tokio::spawn(engine.run());
673 let status = tokio::time::timeout(Duration::from_secs(2), handle.get_provider_runtime_status())
674 .await
675 .expect("provider runtime status response")
676 .expect("provider runtime status");
677
678 assert_eq!(status.provider, ProviderKind::Zai);
679 assert_eq!(
680 status.request_concurrency_limit,
681 Some(codewhale_runtime::config::DEFAULT_ZAI_PROVIDER_MAX_CONCURRENCY)
682 );
683 assert_eq!(status.active_provider_requests, 0);
684
685 run.abort();
686 }
687
688 #[test]
689 fn detects_context_length_errors_from_provider_payloads() {
690 let msg = r#"SSE stream request failed: HTTP 400 Bad Request: {"error":{"message":"This model's maximum context length is 131072 tokens. However, you requested 153056 tokens (148960 in the messages, 4096 in the completion).","type":"invalid_request_error"}}"#;
691 assert!(is_context_length_error_message(msg));
692 // llama.cpp's server wording (#6374): a genuine overflow on a local route
693 // must enter the bounded recovery path too.
694 assert!(is_context_length_error_message(
695 r#"SSE stream request failed: HTTP 400 Bad Request: {"error":{"code":400,"message":"the request exceeds the available context size. try increasing the context size or enable context shift","type":"invalid_request_error"}}"#
696 ));
697 assert!(!is_context_length_error_message(
698 "SSE stream request failed: HTTP 400 Bad Request: model not found"
699 ));
700 assert!(!is_context_length_error_message(
701 "Model output truncated: provider stopped at max_tokens"
702 ));
703 assert!(!is_context_length_error_message(
704 "Model response incomplete: provider stop reason `length`"
705 ));
706 }
707
708 /// #6374: the exhausted-recovery message must name levers the reader has.
709 #[test]
710 fn context_overflow_exhausted_message_names_levers_that_exist_in_the_mode() {
711 let headless = super::context::context_overflow_exhausted_message(false, 2, 98_739, 97_280);
712 assert!(
713 !headless.contains("/compact") && !headless.contains("/clear"),
714 "a headless host has no command layer: {headless}"
715 );
716 assert!(
717 headless.contains("2 emergency compaction passes"),
718 "{headless}"
719 );
720 assert!(
721 headless.contains("CODEWHALE_MAX_OUTPUT_TOKENS"),
722 "{headless}"
723 );
724 let interactive = super::context::context_overflow_exhausted_message(true, 1, 98_739, 97_280);
725 assert!(
726 interactive.contains("/compact") && interactive.contains("/clear"),
727 "{interactive}"
728 );
729 assert!(
730 interactive.contains("1 emergency compaction pass "),
731 "{interactive}"
732 );
733 }
734
735 #[test]
736 fn context_budget_scenario() {
737 // Scenario consolidation of: context_budget_reserves_output_and_headroom, context_budget_uses_conservative_fallback_for_unknown_models, context_budget_uses_provider_effective_window_for_openai_codex
738 // from context_budget_reserves_output_and_headroom
739 {
740 // Serialize with other tests that mutate DEEPSEEK_MAX_OUTPUT_TOKENS so
741 // the internal effective_max_output_tokens() call sees a stable env.
742 let _lock = lock_test_env();
743 // Preflight reserves exactly the route-effective output request plus the
744 // shared safety headroom, even on a 1M route.
745 let budget = context_input_budget_for_provider(ProviderKind::Deepseek, "deepseek-v4-pro")
746 .expect("deepseek-v4-pro should have a known context window");
747 let v4_window: usize = 1_000_000;
748 let expected = v4_window
749 - effective_max_output_tokens_for_route(ProviderKind::Deepseek, "deepseek-v4-pro", None)
750 as usize
751 - 1_024usize;
752 assert_eq!(budget, expected);
753 }
754 // from context_budget_uses_conservative_fallback_for_unknown_models
755 {
756 let _lock = lock_test_env();
757 let budget = context_input_budget_for_provider(ProviderKind::Openai, "auto")
758 .expect("unknown/auto model ids should still get a conservative hard preflight budget");
759 let expected = 128_000usize
760 - effective_max_output_tokens_for_route(ProviderKind::Openai, "auto", None) as usize
761 - 1_024usize;
762 assert_eq!(budget, expected);
763 }
764 // from context_budget_uses_provider_effective_window_for_openai_codex
765 {
766 let _lock = lock_test_env();
767 let budget = context_input_budget_for_provider(ProviderKind::OpenaiCodex, "gpt-5.5")
768 .expect("OpenAI Codex should use a conservative fallback without route metadata");
769 let expected = usize::try_from(
770 codewhale_runtime::config::OPENAI_CODEX_EFFECTIVE_CONTEXT_WINDOW_TOKENS,
771 )
772 .expect("context window fits usize")
773 - crate::provider_lake::provider_capability(ProviderKind::OpenaiCodex, "gpt-5.5")
774 .max_output
775 .expect("Codex route publishes a deliberate conservative output cap")
776 as usize
777 - 1_024usize;
778 assert_eq!(budget, expected);
779 }
780 }
781
782 #[test]
783 fn route_context_scenario() {
784 // Scenario consolidation of: route_context_budget_uses_shared_budget_service, route_context_budget_prefers_resolved_route_limits
785 // from route_context_budget_uses_shared_budget_service
786 {
787 let _lock = lock_test_env();
788 let budget =
789 route_context_budget_for_provider(ProviderKind::OpenaiCodex, "gpt-5.5", 380_000)
790 .expect("OpenAI Codex should produce a route budget");
791
792 assert_eq!(
793 budget.window_tokens,
794 u64::from(codewhale_runtime::config::OPENAI_CODEX_EFFECTIVE_CONTEXT_WINDOW_TOKENS)
795 );
796 assert_eq!(
797 budget.output_cap_tokens,
798 u64::from(
799 crate::provider_lake::provider_capability(ProviderKind::OpenaiCodex, "gpt-5.5")
800 .max_output
801 .expect("Codex route publishes a deliberate conservative output cap")
802 )
803 );
804 assert_eq!(
805 budget.pressure,
806 codewhale_runtime::context_budget::PressureLevel::Critical
807 );
808 assert!(!budget.fits_additional(1));
809 }
810 // from route_context_budget_prefers_resolved_route_limits
811 {
812 let _lock = lock_test_env();
813 let limits = codewhale_config::route::RouteLimits {
814 context_tokens: Some(128_000),
815 input_tokens: None,
816 output_tokens: Some(32_768),
817 output_declared: false,
818 };
819 let budget = route_context_budget_for_route(
820 ProviderKind::Openrouter,
821 "deepseek/deepseek-v4-pro",
822 Some(limits),
823 60_000,
824 )
825 .expect("route limits should produce a budget");
826
827 assert_eq!(budget.window_tokens, 128_000);
828 assert_eq!(budget.output_cap_tokens, 32_768);
829 assert_eq!(budget.available_input_tokens, 34_208);
830 }
831 }
832
833 #[test]
834 fn route_input_limit_blocks_oversized_preflight_before_transport() {
835 let _lock = lock_test_env();
836 let limits = codewhale_config::route::RouteLimits {
837 context_tokens: Some(1_000_000),
838 input_tokens: Some(128_000),
839 output_tokens: Some(64_000),
840 output_declared: false,
841 };
842 let estimated_input = 200_000;
843 let budget = route_context_budget_for_route(
844 ProviderKind::Vllm,
845 "DeepSeek-V4-Flash",
846 Some(limits),
847 estimated_input,
848 )
849 .expect("resolved route limits should produce the turn-loop preflight budget");
850
851 assert_eq!(budget.window_tokens, 1_000_000);
852 assert_eq!(budget.output_cap_tokens, 64_000);
853 assert_eq!(budget.input_budget_ceiling, 128_000);
854 assert_eq!(budget.available_input_tokens, 0);
855 assert!(
856 estimated_input > usize::try_from(budget.input_budget_ceiling).unwrap(),
857 "the turn-loop preflight must recover before constructing a network request"
858 );
859 }
860
861 /// #6374: the preflight guard measured a ×1.5-inflated estimate against the
862 /// honest input ceiling, so a route refused at two thirds of its budget with
863 /// the request never leaving the machine. The window here is calibrated so the
864 /// honest estimate sits below the ceiling and the inflated one above it; the
865 /// turn must reach the model with its history untouched.
866 #[tokio::test]
867 async fn preflight_guard_measures_honest_input_against_the_input_ceiling() {
868 let _lock = lock_test_env();
869 let _output_env = ScopedDeepSeekMaxOutputTokens::unset();
870 let workspace = tempdir().expect("workspace");
871 let _home = EnvVarGuard::set("CODEWHALE_HOME", workspace.path());
872 let mock = std::sync::Arc::new(crate::llm_client::mock::MockLlmClient::new(vec![
873 crate::llm_client::mock::canned::simple_text_turn("continuing"),
874 ]));
875 let (mut engine, _handle) = Engine::new_with_model_client(
876 EngineConfig {
877 terminal_chrome_enabled: false,
878 ..deterministic_engine_config(workspace.path())
879 },
880 &Config::default(),
881 mock.clone(),
882 );
883 // Only the preflight guard is under test; the auto-compaction gate stays out.
884 engine.config.compaction.enabled = false;
885 let history: Vec<Message> = [
886 (Role::User, "x".repeat(120_000)),
887 (Role::Assistant, "y".repeat(100_000)),
888 (Role::User, "please continue".to_string()),
889 ]
890 .into_iter()
891 .map(|(role, text)| Message {
892 role,
893 content: vec![ContentBlock::Text {
894 text,
895 cache_control: None,
896 }],
897 })
898 .collect();
899 for message in &history {
900 engine.session.add_message(message.clone());
901 }
902 let system = engine.session.system_prompt.clone();
903 let honest = crate::compaction::estimate_input_tokens_for_pressure(&history, system.as_ref());
904 let inflated = crate::compaction::estimate_input_tokens_conservative(&history, system.as_ref());
905 assert!(
906 inflated > honest + 20_000,
907 "fixture must separate the estimators: honest {honest}, inflated {inflated}"
908 );
909 let output_cap = 4_096u64;
910 let target_ceiling = u64::try_from((honest + inflated) / 2).unwrap();
911 engine.active_route_limits = Some(codewhale_config::route::RouteLimits {
912 context_tokens: Some(
913 target_ceiling
914 + output_cap
915 + codewhale_runtime::context_budget::CONTEXT_HEADROOM_TOKENS,
916 ),
917 input_tokens: None,
918 output_tokens: Some(output_cap),
919 output_declared: false,
920 });
921 let ceiling = route_context_budget_for_route(
922 engine.api_provider,
923 &engine.session.model,
924 engine.active_route_limits,
925 0,
926 )
927 .expect("route limits produce a budget")
928 .input_budget_ceiling;
929 let ceiling = usize::try_from(ceiling).unwrap();
930 assert!(
931 honest < ceiling && ceiling < inflated,
932 "calibration: honest {honest} < ceiling {ceiling} < inflated {inflated}"
933 );
934
935 let registry =
936 crate::tools::ToolRegistry::new(crate::tools::spec::ToolContext::new(workspace.path()));
937 let catalog = registry.to_api_tools_with_cache(true);
938 let surface = crate::core::engine::tool_catalog::ToolSurfacePolicy::new(
939 registry,
940 Some(catalog),
941 codewhale_config::AppMode::Agent,
942 &engine.config.tools_always_load,
943 false,
944 None,
945 None,
946 Some(4),
947 crate::core::engine::tool_catalog::ToolMode::Direct,
948 );
949 let (status, error) = engine
950 .run_turn(
951 &mut crate::core::turn::TurnContext::new(8),
952 surface,
953 None,
954 None,
955 )
956 .await;
957 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
958 assert_eq!(
959 mock.call_count(),
960 1,
961 "the only model request is the turn itself, not an emergency compaction"
962 );
963 let request = mock.last_request().expect("the turn reached the model");
964 assert_eq!(
965 request.messages.len(),
966 history.len() + 1,
967 "history reached the model without an emergency compaction pass \
968 (plus preparation's workspace-instructions record)"
969 );
970 }
971
972 #[test]
973 fn kimi_catalog_output_ceiling_does_not_collapse_input_budget() {
974 let _lock = lock_test_env();
975 let _guard = ScopedDeepSeekMaxOutputTokens::unset();
976 let documented =
977 route_context_budget_for_route(ProviderKind::Moonshot, "kimi-k2.7-code", None, 0)
978 .expect("bundled Kimi limits should produce a budget");
979 assert_eq!(documented.window_tokens, 262_144);
980 assert_eq!(documented.output_cap_tokens, 32_768);
981 assert_eq!(documented.available_input_tokens, 228_352);
982
983 // #4368/#4378: Models.dev may report Kimi's full 262K context as both its
984 // context window and provider output ceiling. That ceiling must not be
985 // reserved as though every normal turn requested 262K of output; the
986 // integrated Kimi route cap is 32K.
987 let limits = codewhale_config::route::RouteLimits {
988 context_tokens: Some(262_144),
989 input_tokens: None,
990 output_tokens: Some(262_144),
991 output_declared: false,
992 };
993
994 let budget =
995 route_context_budget_for_route(ProviderKind::Moonshot, "kimi-k2.7-code", Some(limits), 0)
996 .expect("Kimi route limits should produce a budget");
997
998 assert_eq!(budget.window_tokens, 262_144);
999 assert_eq!(budget.output_cap_tokens, 32_768);
1000 assert_eq!(budget.available_input_tokens, 228_352);
1001 }
1002
1003 #[test]
1004 fn effective_max_scenario() {
1005 // Scenario consolidation of: effective_max_output_tokens_for_route_caps_to_route_output_limit, effective_max_output_tokens_for_route_caps_to_context_window, effective_max_output_tokens_for_route_keeps_tiny_window_positive, effective_max_output_tokens_caps_api_request_for_large_window_models, effective_max_output_tokens_env_override_rejects_zero_and_invalid
1006 // from effective_max_output_tokens_for_route_caps_to_route_output_limit
1007 {
1008 let _lock = lock_test_env();
1009 let limits = codewhale_config::route::RouteLimits {
1010 context_tokens: Some(1_000_000),
1011 input_tokens: None,
1012 output_tokens: Some(8_192),
1013 output_declared: false,
1014 };
1015
1016 assert_eq!(
1017 effective_max_output_tokens_for_route(
1018 ProviderKind::Deepseek,
1019 "deepseek-v4-pro",
1020 Some(limits),
1021 ),
1022 8_192
1023 );
1024 }
1025 // from effective_max_output_tokens_for_route_caps_to_context_window
1026 {
1027 let _lock = lock_test_env();
1028 let limits = codewhale_config::route::RouteLimits {
1029 context_tokens: Some(32_000),
1030 input_tokens: None,
1031 output_tokens: None,
1032 output_declared: false,
1033 };
1034
1035 let cap = effective_max_output_tokens_for_route(
1036 ProviderKind::Deepseek,
1037 "deepseek-v4-pro",
1038 Some(limits),
1039 );
1040
1041 assert!(cap < 32_000, "request cap must fit the configured window");
1042 assert!(
1043 cap > 0,
1044 "small configured windows should still allow output"
1045 );
1046 }
1047 // from effective_max_output_tokens_for_route_keeps_tiny_window_positive
1048 {
1049 let _lock = lock_test_env();
1050 let limits = codewhale_config::route::RouteLimits {
1051 context_tokens: Some(2_048),
1052 input_tokens: None,
1053 output_tokens: None,
1054 output_declared: false,
1055 };
1056
1057 assert_eq!(
1058 effective_max_output_tokens_for_route(
1059 ProviderKind::Deepseek,
1060 "deepseek-v4-pro",
1061 Some(limits),
1062 ),
1063 1
1064 );
1065 }
1066 // from effective_max_output_tokens_caps_api_request_for_large_window_models
1067 {
1068 // Serialize with other tests that mutate DEEPSEEK_MAX_OUTPUT_TOKENS so
1069 // v4_cap and flash_cap below see the same env state.
1070 let _lock = lock_test_env();
1071 // Hosted V4 documents a 384K capability ceiling in the bundled catalogue,
1072 // but a ceiling is not a safe no-config request size. The operator can
1073 // still request a larger value explicitly; the automatic request starts
1074 // at the ordinary 64K cap (#5516/#5518).
1075 let v4_cap = effective_max_output_tokens("deepseek-v4-pro");
1076 assert_eq!(
1077 v4_cap, 65_536,
1078 "hosted V4 must not turn the 384K capability maximum into the default request, got {v4_cap}"
1079 );
1080
1081 let flash_cap = effective_max_output_tokens("deepseek-v4-flash");
1082 assert_eq!(v4_cap, flash_cap);
1083 }
1084 // from effective_max_output_tokens_env_override_rejects_zero_and_invalid
1085 {
1086 let _lock = lock_test_env();
1087 // Establish the heuristic baseline with the env unset.
1088 let baseline = {
1089 let _guard = ScopedDeepSeekMaxOutputTokens::unset();
1090 effective_max_output_tokens("deepseek-v4-pro")
1091 };
1092 assert!(baseline > 0);
1093
1094 // 0, non-numeric, and empty values must all fall through to the heuristic
1095 // rather than producing a zero/garbage cap that would silently break
1096 // request budgeting.
1097 for raw in ["0", "abc", "", " ", "-1"] {
1098 let _guard = ScopedDeepSeekMaxOutputTokens::set(raw);
1099 assert_eq!(
1100 effective_max_output_tokens("deepseek-v4-pro"),
1101 baseline,
1102 "env={raw:?} should fall through to heuristic"
1103 );
1104 }
1105 }
1106 }
1107
1108 #[test]
1109 fn codex_route_without_output_metadata_uses_oauth_capability_floor() {
1110 let _lock = lock_test_env();
1111 let limits = codewhale_config::route::RouteLimits {
1112 context_tokens: Some(272_000),
1113 input_tokens: None,
1114 output_tokens: None,
1115 output_declared: false,
1116 };
1117
1118 assert_eq!(
1119 effective_max_output_tokens_for_route(ProviderKind::OpenaiCodex, "gpt-5.5", Some(limits)),
1120 4_096
1121 );
1122 let budget =
1123 route_context_budget_for_route(ProviderKind::OpenaiCodex, "gpt-5.5", Some(limits), 0)
1124 .expect("Codex route budget");
1125 assert_eq!(budget.output_cap_tokens, 4_096);
1126 }
1127
1128 #[test]
1129 fn reasoning_max_does_not_add_a_second_deepseek_v4_output_reservation() {
1130 let _lock = lock_test_env();
1131 let _codewhale = EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS");
1132 let _deepseek = EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS");
1133 let limits = codewhale_config::route::RouteLimits {
1134 context_tokens: Some(327_680),
1135 input_tokens: None,
1136 output_tokens: None,
1137 output_declared: false,
1138 };
1139 let cap = effective_max_output_tokens_for_route(
1140 ProviderKind::Vllm,
1141 "DeepSeek-V4-Flash",
1142 Some(limits),
1143 );
1144 let request = codewhale_core::request::prepare_primary_turn_request(
1145 codewhale_core::request::PrimaryTurnRequest {
1146 model: "DeepSeek-V4-Flash".to_string(),
1147 messages: Vec::new(),
1148 max_tokens: cap,
1149 system: None,
1150 tools: None,
1151 tool_choice: None,
1152 reasoning_effort: Some("max".to_string()),
1153 },
1154 );
1155 let budget = route_context_budget_for_route(
1156 ProviderKind::Vllm,
1157 "DeepSeek-V4-Flash",
1158 Some(limits),
1159 105_000,
1160 )
1161 .expect("max-reasoning vLLM route budget");
1162
1163 assert_eq!(request.reasoning_effort.as_deref(), Some("max"));
1164 assert_eq!(request.max_tokens, 65_536);
1165 assert_eq!(budget.output_cap_tokens, u64::from(request.max_tokens));
1166 assert_eq!(budget.input_budget_ceiling, 261_120);
1167 assert!(budget.available_input_tokens > 0);
1168 }
1169
1170 struct ScopedDeepSeekMaxOutputTokens {
1171 previous: Option<OsString>,
1172 }
1173
1174 impl ScopedDeepSeekMaxOutputTokens {
1175 fn set(value: &str) -> Self {
1176 let previous = std::env::var_os("DEEPSEEK_MAX_OUTPUT_TOKENS");
1177 // Safety: tests using this helper serialize with lock_test_env() and
1178 // restore the original value in Drop.
1179 unsafe {
1180 std::env::set_var("DEEPSEEK_MAX_OUTPUT_TOKENS", value);
1181 }
1182 Self { previous }
1183 }
1184
1185 fn unset() -> Self {
1186 let previous = std::env::var_os("DEEPSEEK_MAX_OUTPUT_TOKENS");
1187 // Safety: see set().
1188 unsafe {
1189 std::env::remove_var("DEEPSEEK_MAX_OUTPUT_TOKENS");
1190 }
1191 Self { previous }
1192 }
1193 }
1194
1195 impl Drop for ScopedDeepSeekMaxOutputTokens {
1196 fn drop(&mut self) {
1197 // Safety: tests using this helper serialize with lock_test_env().
1198 unsafe {
1199 if let Some(previous) = self.previous.take() {
1200 std::env::set_var("DEEPSEEK_MAX_OUTPUT_TOKENS", previous);
1201 } else {
1202 std::env::remove_var("DEEPSEEK_MAX_OUTPUT_TOKENS");
1203 }
1204 }
1205 }
1206 }
1207
1208 #[test]
1209 fn effective_max_output_tokens_env_override_returns_positive_value() {
1210 let _lock = lock_test_env();
1211 let _guard = ScopedDeepSeekMaxOutputTokens::set("16384");
1212
1213 // Override applies regardless of model — V4 hosted, V4 flash, and
1214 // self-hosted routes all return the env value verbatim before route clamps.
1215 assert_eq!(effective_max_output_tokens("deepseek-v4-pro"), 16_384);
1216 assert_eq!(effective_max_output_tokens("deepseek-v4-flash"), 16_384);
1217 assert_eq!(effective_max_output_tokens("qwen3-32b-256k"), 16_384);
1218 }
1219
1220 #[test]
1221 fn internal_context_budget_uses_the_wire_cap_across_window_sizes() {
1222 // Serialize with other tests that mutate DEEPSEEK_MAX_OUTPUT_TOKENS so
1223 // both branches below see a stable env.
1224 let _lock = lock_test_env();
1225 // Large routes use the same effective output cap that reaches the wire.
1226 let internal_budget =
1227 context_input_budget_for_provider(ProviderKind::Deepseek, "deepseek-v4-pro")
1228 .expect("V4 should have a known context window");
1229 let v4_window: usize = 1_000_000;
1230 let expected_internal = v4_window
1231 - effective_max_output_tokens_for_route(ProviderKind::Deepseek, "deepseek-v4-pro", None)
1232 as usize
1233 - 1_024usize;
1234 assert_eq!(internal_budget, expected_internal);
1235
1236 // A 256K self-hosted deployment uses the same rule and yields a usable
1237 // positive budget rather than silently disabling preflight/recovery.
1238 let small_window_budget =
1239 context_input_budget_for_provider(ProviderKind::Openai, "qwen3-32b-256k")
1240 .expect("a 256K-suffix model must yield Some budget via the effective-cap branch");
1241 let effective_output =
1242 effective_max_output_tokens_for_route(ProviderKind::Openai, "qwen3-32b-256k", None)
1243 as usize;
1244 let expected_small = 256_000 - effective_output - 1_024;
1245 assert_eq!(small_window_budget, expected_small);
1246 }
1247
1248 const ROUTE_128K: &str = "deepseek-v3.2-128k";
1249 const SESSION_6508: &str = "session-6508";
1250
1251 fn budget_128k() -> usize {
1252 crate::route_budget::route_inline_char_budget_for_route(
1253 ProviderKind::Deepseek,
1254 ROUTE_128K,
1255 None,
1256 )
1257 }
1258
1259 fn view_128k(tool_name: &str, output: &ToolResult) -> super::context::ToolResultContextView {
1260 super::context::tool_result_context_view(
1261 ProviderKind::Deepseek,
1262 ROUTE_128K,
1263 None,
1264 tool_name,
1265 output,
1266 )
1267 }
1268
1269 /// Run `f` with the spillover and session-artifact roots under a temp home.
1270 fn with_artifact_home<R>(f: impl FnOnce(&Path) -> R) -> R {
1271 let _spill_guard = crate::tools::truncate::TEST_SPILLOVER_GUARD
1272 .lock()
1273 .unwrap_or_else(|err| err.into_inner());
1274 let home = tempdir().expect("tempdir");
1275 let path = home.path().to_path_buf();
1276 crate::tools::truncate::with_test_home(&path, || f(&path))
1277 }
1278
1279 fn session_artifact_files(home: &Path) -> Vec<PathBuf> {
1280 let dir = home
1281 .join(".codewhale")
1282 .join("sessions")
1283 .join(SESSION_6508)
1284 .join("artifacts");
1285 fs::read_dir(dir)
1286 .map(|entries| entries.flatten().map(|entry| entry.path()).collect())
1287 .unwrap_or_default()
1288 }
1289
1290 #[test]
1291 fn under_budget_results_pass_through_whole_for_every_tool() {
1292 // #6508: one budget, sized by the route, decides what the model sees.
1293 // There is no per-tool-name soft limit: a web answer or a shell log that
1294 // fits the budget reaches the model byte for byte.
1295 // 3% of a 128K window is 15,360 characters (an operator opt-in can only
1296 // raise it; see route_budget's tests for the exact values).
1297 assert!(budget_128k() >= 15_360);
1298 let content = "w".repeat(14_000);
1299 let output = ToolResult::success(content.clone());
1300 for tool_name in [
1301 "exec_shell",
1302 "web_search",
1303 "Web",
1304 "web.run",
1305 "fetch_url",
1306 "read_file",
1307 "run_tests",
1308 ] {
1309 let view = view_128k(tool_name, &output);
1310 assert_eq!(view.text, content, "{tool_name} was cut under the budget");
1311 assert!(!view.needs_full_output_artifact);
1312 }
1313 }
1314
1315 #[test]
1316 fn over_budget_result_without_a_saved_copy_says_so_and_asks_for_one() {
1317 // The view never writes. Without a saved copy it asks the engine for
1318 // one, and until then it promises no ref it cannot honour.
1319 let raw = "shell line\n".repeat(4_000);
1320 let output = ToolResult::success(raw.clone());
1321 let view = view_128k("exec_shell", &output);
1322
1323 assert!(view.needs_full_output_artifact);
1324 assert!(view.text.chars().count() <= budget_128k());
1325 assert!(view.text.contains("the full output could not be saved"));
1326 assert!(view.text.contains("no tool call reaches this copy"));
1327 assert!(!view.text.contains("retrieve_tool_result"));
1328 }
1329
1330 #[test]
1331 fn oversized_tool_output_is_recoverable_before_serial_and_parallel_fanout() {
1332 use crate::llm_client::mock::{MockLlmClient, canned};
1333 use crate::tools::spec::{ToolCapability, ToolSpec};
1334
1335 struct OutputTool {
1336 parallel: bool,
1337 content: String,
1338 }
1339 #[async_trait::async_trait]
1340 impl ToolSpec for OutputTool {
1341 fn name(&self) -> &str {
1342 "fixture_output"
1343 }
1344 fn description(&self) -> &str {
1345 "Return output below the spill threshold."
1346 }
1347 fn input_schema(&self) -> Value {
1348 json!({"type": "object"})
1349 }
1350 fn capabilities(&self) -> Vec<ToolCapability> {
1351 vec![ToolCapability::ReadOnly]
1352 }
1353 fn supports_parallel(&self) -> bool {
1354 self.parallel
1355 }
1356 async fn execute(&self, _: Value, _: &ToolContext) -> Result<ToolResult, ToolError> {
1357 Ok(ToolResult::success(self.content.clone()))
1358 }
1359 }
1360
1361 with_artifact_home(|home| {
1362 tokio::runtime::Builder::new_current_thread()
1363 .enable_all()
1364 .build()
1365 .unwrap()
1366 .block_on(async {
1367 let raw = format!("{}MIDDLE{}", "h".repeat(5_000), "t".repeat(5_000));
1368 assert!(raw.len() < crate::tools::truncate::SPILLOVER_THRESHOLD_BYTES);
1369 for (parallel, count) in [(true, 1), (true, 2), (false, 1)] {
1370 let calls = [
1371 ("call-one", "fixture_output", "{}"),
1372 ("call-two", "fixture_output", "{}"),
1373 ];
1374 let mock = Arc::new(MockLlmClient::new(vec![
1375 tool_batch_turn(&calls[..count]),
1376 canned::simple_text_turn("done"),
1377 ]));
1378 let (mut engine, handle) = Engine::new_with_model_client(
1379 deterministic_engine_config(home),
1380 &Config::default(),
1381 mock.clone(),
1382 );
1383 engine.active_route_limits = Some(codewhale_config::route::RouteLimits {
1384 context_tokens: Some(64_000),
1385 input_tokens: None,
1386 output_tokens: Some(4_096),
1387 output_declared: false,
1388 });
1389 let mut registry = crate::tools::ToolRegistry::new(ToolContext::new(home));
1390 registry.register(Arc::new(OutputTool {
1391 parallel,
1392 content: raw.clone(),
1393 }));
1394 let tools = Some(registry.to_api_tools_with_cache(true));
1395 let surface = test_tool_surface(&engine, registry, tools, AppMode::Agent);
1396 let mut turn = crate::core::turn::TurnContext::new(4);
1397 let (status, error) = engine.run_turn(&mut turn, surface, None, None).await;
1398 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
1399 let requests = mock.captured_requests();
1400 assert_eq!(requests.len(), 2);
1401 let mut events = handle.rx_event.write().await;
1402 let mut completed = 0;
1403 while let Ok(event) = events.try_recv() {
1404 let Event::ToolCallComplete {
1405 result, model_call, ..
1406 } = event
1407 else {
1408 continue;
1409 };
1410 let output = result.expect("tool succeeded");
1411 assert_eq!(output.content, raw, "UI keeps the complete output");
1412 let metadata = output
1413 .metadata
1414 .expect("output must be preserved before fanout");
1415 let path = metadata["artifact_path"].as_str().expect("artifact path");
1416 assert_eq!(fs::read_to_string(path).unwrap(), raw);
1417 let reference = metadata["artifact_id"].as_str().unwrap();
1418 let results =
1419 guardian_tool_results(&requests[1], &model_call.unwrap().provider_id);
1420 assert_eq!(results.len(), 1);
1421 let (text, _) = results[0];
1422 assert!(text.len() <= 7_680, "64K route inline budget");
1423 assert!(!text.contains("MIDDLE"));
1424 assert!(text.contains("retrieve_tool_result"));
1425 assert!(text.contains(reference), "model and UI share the artifact");
1426 completed += 1;
1427 }
1428 assert_eq!(completed, count);
1429 }
1430 });
1431 });
1432 }
1433
1434 #[test]
1435 fn over_budget_result_writes_the_full_output_and_names_its_ref() {
1436 with_artifact_home(|home| {
1437 let raw = format!("FIRST LINE\n{}LAST LINE", "shell line\n".repeat(4_000));
1438 let mut output = ToolResult::success(raw.clone());
1439 assert!(view_128k("exec_shell", &output).needs_full_output_artifact);
1440
1441 assert!(
1442 crate::tools::truncate::preserve_full_output_for_model_context(
1443 &mut output,
1444 "call-over",
1445 "exec_shell",
1446 SESSION_6508,
1447 )
1448 );
1449 // The UI cell keeps the whole result; only metadata changed.
1450 assert_eq!(output.content, raw);
1451
1452 let view = view_128k("exec_shell", &output);
1453 assert!(!view.needs_full_output_artifact);
1454 assert!(view.text.chars().count() <= budget_128k());
1455 assert!(view.text.starts_with("FIRST LINE"));
1456 assert!(view.text.ends_with("LAST LINE"));
1457 assert!(view.text.contains("omitted range recovery:"));
1458 assert!(view.text.contains("ref=\"art_call-over\""));
1459
1460 let files = session_artifact_files(home);
1461 assert_eq!(files.len(), 1);
1462 assert_eq!(fs::read_to_string(&files[0]).expect("artifact"), raw);
1463 });
1464 }
1465
1466 #[test]
1467 fn spilled_preview_is_refit_not_recut() {
1468 // Spillover already saved the full output and left a ~40 KB preview. The
1469 // model view re-fits that preview to the budget with the same ref, and no
1470 // second artifact (which could only hold the preview) is written.
1471 with_artifact_home(|home| {
1472 let raw = format!(
1473 "HEAD START\n{}TAIL END",
1474 "spilled output line\n".repeat(16_000)
1475 );
1476 let mut output = ToolResult::success(raw.clone());
1477 assert!(
1478 crate::tools::truncate::apply_spillover_with_artifact(
1479 &mut output,
1480 "call-spill",
1481 "exec_shell",
1482 SESSION_6508,
1483 )
1484 .is_some()
1485 );
1486 assert_eq!(session_artifact_files(home).len(), 1);
1487
1488 let view = view_128k("exec_shell", &output);
1489 assert!(!view.needs_full_output_artifact);
1490 assert!(view.text.chars().count() <= budget_128k());
1491 assert!(view.text.starts_with("HEAD START"));
1492 assert!(view.text.ends_with("TAIL END"));
1493 assert_eq!(
1494 view.text.matches("omitted range recovery:").count(),
1495 1,
1496 "exactly one footer: {}",
1497 &view.text[..200]
1498 );
1499 assert!(view.text.contains("ref=\"art_call-spill\""));
1500 assert_eq!(session_artifact_files(home).len(), 1);
1501 });
1502 }
1503
1504 #[test]
1505 fn legacy_spill_without_ref_says_no_tool_call_reaches_it() {
1506 let head = "h".repeat(32 * 1024);
1507 let tail = "t".repeat(8 * 1024);
1508 let preview = format!("{head}\n\n… footer …\n\n…\n{tail}");
1509 let output = ToolResult::success(preview).with_metadata(json!({
1510 "spillover_path": "/tmp/tool_outputs/call-legacy.txt",
1511 "retained_head_bytes": head.len(),
1512 "retained_tail_bytes": tail.len(),
1513 "original_byte_count": 300_000,
1514 "truncated": true
1515 }));
1516
1517 let view = view_128k("exec_shell", &output);
1518 assert!(!view.needs_full_output_artifact);
1519 assert!(view.text.chars().count() <= budget_128k());
1520 assert!(view.text.contains("/tmp/tool_outputs/call-legacy.txt"));
1521 assert!(view.text.contains("no tool call reaches this copy"));
1522 assert!(!view.text.contains("retrieve_tool_result"));
1523 }
1524
1525 #[test]
1526 fn structured_run_tests_summary_is_recoverable_and_leads_with_failures() {
1527 with_artifact_home(|home| {
1528 let stdout = format!(
1529 "{}test result: FAILED. 1 failed",
1530 "test ok ... ok\n".repeat(3_000)
1531 );
1532 let raw = json!({
1533 "success": false,
1534 "exit_code": 101,
1535 "stdout": stdout,
1536 "stderr": "",
1537 "command": "(cd /repo && cargo test)"
1538 })
1539 .to_string();
1540 let mut output = ToolResult::success(raw.clone()).with_metadata(json!({
1541 "summary": "1 test failed: tools::git::tests::diff_keeps_the_last_file"
1542 }));
1543 assert!(view_128k("run_tests", &output).needs_full_output_artifact);
1544 assert!(
1545 crate::tools::truncate::preserve_full_output_for_model_context(
1546 &mut output,
1547 "call-tests",
1548 "run_tests",
1549 SESSION_6508,
1550 )
1551 );
1552
1553 let view = view_128k("run_tests", &output);
1554 assert!(!view.needs_full_output_artifact);
1555 assert!(view.text.chars().count() <= budget_128k());
1556 let failures = view
1557 .text
1558 .find("failure summary: 1 test failed: tools::git::tests::diff_keeps_the_last_file")
1559 .expect("failure summary inline");
1560 assert!(failures < view.text.find("stdout:").expect("stdout"));
1561 assert!(view.text.contains("test result: FAILED"));
1562 assert!(view.text.contains("ref=\"art_call-tests\""));
1563
1564 let files = session_artifact_files(home);
1565 assert_eq!(files.len(), 1);
1566 assert_eq!(fs::read_to_string(&files[0]).expect("artifact"), raw);
1567 });
1568 }
1569
1570 #[test]
1571 fn display_compaction_never_writes_artifacts() {
1572 // The TUI builds its API-message copy with the same pure view.
1573 with_artifact_home(|home| {
1574 let output = ToolResult::success("x".repeat(60_000));
1575 let text = compact_tool_result_for_route(
1576 ProviderKind::Deepseek,
1577 ROUTE_128K,
1578 None,
1579 "exec_shell",
1580 &output,
1581 );
1582 assert!(text.chars().count() <= budget_128k());
1583 assert!(session_artifact_files(home).is_empty());
1584 });
1585 }
1586
1587 #[test]
1588 fn evidence_bounded_preview_is_not_recompacted() {
1589 // The adaptive evidence envelope already produced an honest bounded
1590 // preview (head + footer with the recovery path + tail). The context
1591 // compactor must pass it through untouched, even beyond the 12K hard
1592 // limit — re-compacting would strip the recovery contract.
1593 let content = format!(
1594 "{}\n\n… 19.0 KiB of output omitted (123 lines) — full output at /tmp/art_call.txt; read it back with the read_file tool or with sed line ranges\n\n…\n{}",
1595 "h".repeat(32 * 1024),
1596 "t".repeat(8 * 1024)
1597 );
1598 let output = ToolResult::success(content.clone()).with_metadata(json!({
1599 "evidence_available": true,
1600 "truncated": true,
1601 "spillover_path": "/tmp/art_call.txt"
1602 }));
1603
1604 let context = compact_tool_result_for_context("deepseek-v3.2-128k", "Bash", &output);
1605 assert_eq!(context, content);
1606 assert!(context.contains("full output at /tmp/art_call.txt"));
1607 }
1608
1609 #[test]
1610 fn budgeted_read_result_is_not_truncated_a_second_time_by_the_context_compactor() {
1611 // C05: `read` bounds itself to an explicit per-call byte budget. The 12K
1612 // context hard limit used to re-truncate that bounded result into a 900-
1613 // char snippet, discarding both the content and the continuation footer.
1614 let content = format!(
1615 "{}\n\n[Showing lines 1-100 of 2000 (100000-byte output budget). Use offset=101 to continue.]",
1616 "r".repeat(90_000)
1617 );
1618 let budgeted = ToolResult::success(content.clone()).with_metadata(json!({
1619 "evidence_routing": "inline",
1620 "read_budget_bytes": 100_000
1621 }));
1622 let passed_through = compact_tool_result_for_context("deepseek-v3.2-128k", "read", &budgeted);
1623 assert_eq!(passed_through, content);
1624 assert!(passed_through.contains("Use offset=101 to continue"));
1625
1626 // The same bytes without a declared budget still take the ordinary path,
1627 // which is what proves the metadata (not the tool name) did the work.
1628 let unbudgeted = ToolResult::success(content.clone());
1629 let compacted = compact_tool_result_for_context("deepseek-v3.2-128k", "read", &unbudgeted);
1630 assert!(compacted.contains(codewhale_tools::names::SPILLOVER_RECOVERY_HINT));
1631 assert!(compacted.len() < content.len());
1632
1633 // A result that overran its own declared budget is not exempt.
1634 let overrun = ToolResult::success(content).with_metadata(json!({
1635 "read_budget_bytes": 1_000
1636 }));
1637 let compacted_overrun = compact_tool_result_for_context("deepseek-v3.2-128k", "read", &overrun);
1638 assert!(compacted_overrun.contains(codewhale_tools::names::SPILLOVER_RECOVERY_HINT));
1639 }
1640
1641 #[test]
1642 fn codex_tool_retention_uses_oauth_route_window_not_asmall_contract_model_window() {
1643 let content = "route-effective context\n".repeat(900);
1644 let output = ToolResult::success(content.clone());
1645 let limits = codewhale_config::route::RouteLimits {
1646 context_tokens: Some(272_000),
1647 input_tokens: None,
1648 output_tokens: None,
1649 output_declared: false,
1650 };
1651
1652 // The budget follows the route's 272K window (3% of it, 32,640
1653 // characters), so this 21.6K result reaches the model whole.
1654 assert!(
1655 crate::route_budget::route_inline_char_budget_for_route(
1656 ProviderKind::OpenaiCodex,
1657 "gpt-5.5",
1658 Some(limits),
1659 ) >= 32_640
1660 );
1661 let context = compact_tool_result_for_route(
1662 ProviderKind::OpenaiCodex,
1663 "gpt-5.5",
1664 Some(limits),
1665 "read_file",
1666 &output,
1667 );
1668
1669 assert_eq!(context, content.trim());
1670 }
1671
1671 lines RUST