返回 CodeWhale
extension_hooks.rs
根目录 / crates / engine / src / core / engine / tests / extension_hooks.rs
1 //! Real programmable host listeners on the actual Engine admission path.
2 use super::*;
3 use crate::llm_client::mock::{MockLlmClient, canned};
4
5 #[tokio::test]
6 async fn typescript_mod_rewrites_denies_and_regates_native_tools_on_the_real_engine() {
7 let Some(node) =
8 crate::extension_host::test_support::node_for_tests("typescript_mod_real_engine")
9 else {
10 return;
11 };
12 let _policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(true);
13 let fixture = crate::extension_host::test_support::FixturePlugins::new(&["hook-policy"]).await;
14 for (name, text) in [
15 ("before.txt", "original"),
16 ("after.txt", "rewritten content"),
17 ("blocked.txt", "must not be returned"),
18 ("malformed.txt", "must not be returned"),
19 ("throw.txt", "must not be returned"),
20 ("rewrite-action.txt", "original read"),
21 ] {
22 fs::write(fixture.workspace().join(name), text).unwrap();
23 }
24 let manager = fixture.manager(node);
25 let warm = manager.attach(fixture.registry());
26 warm.sync().await.expect("real host activation");
27 let _manager = crate::extension_host::TestManagerGuard::install(Arc::clone(&manager));
28 let mock = Arc::new(MockLlmClient::new(vec![
29 canned::tool_call_turn("rewrite", "read", r#"{"path":"before.txt"}"#),
30 canned::tool_call_turn("deny", "read", r#"{"path":"blocked.txt"}"#),
31 canned::tool_call_turn("malformed", "read", r#"{"path":"malformed.txt"}"#),
32 canned::tool_call_turn("throw", "read", r#"{"path":"throw.txt"}"#),
33 canned::tool_call_turn(
34 "action",
35 "Git",
36 r#"{"action":"log","path":"rewrite-action.txt"}"#,
37 ),
38 canned::simple_text_turn("Finished checking the mod."),
39 canned::tool_call_turn("after-disable", "read", r#"{"path":"before.txt"}"#),
40 canned::simple_text_turn("The mod is disabled."),
41 ]));
42 let config = Config::default();
43 let mut engine_config = deterministic_engine_config(fixture.workspace());
44 engine_config.features.enable(Feature::ExtensionHost);
45 engine_config.plugin_registry = Some(fixture.registry());
46 let (engine, handle) = Engine::new_with_model_client(engine_config, &config, mock.clone());
47 manager.reconcile().await.unwrap();
48 let task = tokio::spawn(engine.run());
49 handle
50 .send(external_user_message_op(
51 "Check the programmable mod",
52 AppMode::Agent,
53 &config,
54 ))
55 .await
56 .unwrap();
57 let mut outcomes = HashMap::new();
58 let mut approvals = 0;
59 let mut rx = handle.rx_event.write().await;
60 loop {
61 match tokio::time::timeout(model_turn_event_timeout(), rx.recv())
62 .await
63 .unwrap()
64 .unwrap()
65 {
66 Event::ApprovalRequired { id, input, .. } => {
67 approvals += 1;
68 assert_eq!(
69 input,
70 serde_json::json!({
71 "action": "fetch", "remote": "origin"
72 }),
73 "the approval must be for the re-prepared revised fetch"
74 );
75 handle.deny_tool_call(id).await.unwrap();
76 }
77 Event::ToolCallComplete {
78 model_call: Some(call),
79 result,
80 ..
81 } => {
82 outcomes.insert(call.provider_id, result);
83 }
84 Event::TurnComplete { status, error, .. } => {
85 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
86 break;
87 }
88 _ => {}
89 }
90 }
91 assert!(
92 outcomes
93 .remove("rewrite")
94 .unwrap()
95 .unwrap()
96 .content
97 .contains("rewritten content")
98 );
99 assert!(
100 outcomes
101 .remove("deny")
102 .unwrap()
103 .unwrap_err()
104 .to_string()
105 .contains("blocked by fixture")
106 );
107 for id in ["malformed", "throw"] {
108 assert!(
109 outcomes
110 .remove(id)
111 .unwrap()
112 .unwrap_err()
113 .to_string()
114 .contains("returned no verdict")
115 );
116 }
117 assert!(outcomes.remove("action").unwrap().is_err());
118 assert_eq!(approvals, 1, "only the revised write needs an approval");
119 assert!(!fixture.workspace().join("rewritten.txt").exists());
120 let first_request = mock.captured_requests().into_iter().next().unwrap();
121 let first_prompt = first_request
122 .messages
123 .iter()
124 .find_map(crate::runtime_handoff::extension_prompt_contributions_display)
125 .expect("the authored prompt contribution is delivered as a complete runtime snapshot");
126 assert!(first_prompt.contains("Use the repository style guide when preparing release notes."));
127 assert!(first_prompt.contains("repo-style"));
128 drop(rx);
129 let disabled = fixture.disable("hook-policy");
130 crate::extension_host::plugins_changed(disabled);
131 manager.reconcile().await.unwrap();
132 handle
133 .send(external_user_message_op(
134 "Read again after disabling",
135 AppMode::Agent,
136 &config,
137 ))
138 .await
139 .unwrap();
140 let mut rx = handle.rx_event.write().await;
141 let mut original = false;
142 loop {
143 match tokio::time::timeout(model_turn_event_timeout(), rx.recv())
144 .await
145 .unwrap()
146 .unwrap()
147 {
148 Event::ToolCallComplete {
149 model_call: Some(call),
150 result: Ok(result),
151 ..
152 } if call.provider_id == "after-disable" => {
153 original = result.content.contains("original")
154 && !result.content.contains("rewritten content");
155 }
156 Event::ApprovalRequired { .. } => panic!("disabled hook cannot request approval"),
157 Event::TurnComplete { status, error, .. } => {
158 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
159 break;
160 }
161 _ => {}
162 }
163 }
164 assert!(original, "disabled listener must not rewrite the next turn");
165 let after_disable = mock.last_request().unwrap();
166 let latest_context = after_disable
167 .messages
168 .iter()
169 .rev()
170 .find_map(crate::runtime_handoff::extension_prompt_contributions_display)
171 .expect("disabling the authored section records a withdrawn runtime snapshot");
172 assert!(latest_context.contains("All earlier plugin prompt contributions are withdrawn"));
173 assert!(
174 !latest_context.contains("Use the repository style guide when preparing release notes.")
175 );
176 assert!(!latest_context.contains("repo-style"));
177 drop(rx);
178 handle.send(Op::Shutdown).await.unwrap();
179 task.await.unwrap();
180 manager.shutdown().await;
181 }
182
182 lines RUST