返回 CodeWhale
extension_host_tests.rs
根目录 / crates / tui / src / commands / extension_host_tests.rs
1 //! Extension slash commands through the real command table and the TUI's
2 //! dispatch.
3 //!
4 //! These tests drive `crate::commands` (the user registry, `execute`, the
5 //! built-in table) and `crate::tui::app::App`, so they live on the commands
6 //! side of the runtime/UI boundary: the extension host is a runtime module and
7 //! its own tests may not depend on either (`scripts/check-command-crate-boundaries.py`).
8 //! They run the real Node host over the same fixtures the host's own tests use
9 //! and, where the table matters, install the real built-in command catalog
10 //! ([`CommandTable`]) in place of the host tests' stub.
11
12 use std::path::PathBuf;
13 use std::sync::Arc;
14
15 use super::CommandTable;
16 use codewhale_engine::command_catalog::CatalogGuard;
17 use codewhale_engine::extension_host::protocol::{RegisterKind, RegisterParams, RegisterSpecWire};
18 use codewhale_engine::extension_host::registry::{OwnerRegistry, OwnerState};
19 use codewhale_engine::extension_host::test_support::{
20 FixturePlugins, fake_authority, installed, node_for_tests, plugin_id,
21 };
22 use codewhale_engine::extension_host::tier::HostCohort;
23 use codewhale_plugins::activation::TestPolicyGuard;
24
25 /// The real catalog answers to every built-in name, every alias and the fixed
26 /// mode aliases the dispatcher handles ahead of the registry, and an extension
27 /// command cannot take any of them.
28 #[test]
29 fn the_real_built_in_catalog_refuses_every_name_alias_and_mode_alias() {
30 use codewhale_engine::command_catalog::CommandCatalog;
31 let catalog = CommandTable;
32 let rows = catalog.builtins();
33 let row = |name: &str| {
34 rows.iter()
35 .find(|row| row.name == name)
36 .expect("real command row")
37 };
38 let model = row("model");
39 assert_eq!(
40 model.discovery,
41 codewhale_command_contract::CommandDiscovery::Primary
42 );
43 assert!(!model.unlisted);
44 assert!(!model.usage.is_empty());
45 assert!(model.takes_arguments);
46 let profile = row("profile");
47 assert!(profile.requires_argument);
48 assert!(profile.requires_required_argument);
49 assert!(profile.composer_wants_trailing_space);
50 assert!(!profile.palette_runs_directly);
51 assert!(row("lane").unlisted);
52 assert!(row("goal").subcommands.iter().any(|verb| verb == "blocked"));
53 let mut owned = vec!["jihua".to_string()];
54 for info in crate::commands::command_infos() {
55 owned.push(info.name.to_string());
56 owned.extend(info.aliases.iter().map(|alias| (*alias).to_string()));
57 }
58 assert!(
59 crate::commands::command_infos()
60 .iter()
61 .any(|info| !info.aliases.is_empty()),
62 "some built-in has an alias"
63 );
64 for name in &owned {
65 assert!(catalog.answers_to(name), "/{name} is built in");
66 }
67 assert!(!catalog.answers_to("ext-echo"));
68
69 let _catalog = CatalogGuard::install(Arc::new(CommandTable));
70 let mut registry = OwnerRegistry::new();
71 let owner = registry
72 .begin_owner(
73 HostCohort::reviewed(),
74 "a",
75 "a",
76 Some(fake_authority("a")),
77 "hash-a",
78 )
79 .unwrap();
80 let register = |registry: &mut OwnerRegistry, name: &str| {
81 registry.register(&RegisterParams {
82 scope: None,
83 owner: owner.clone(),
84 kind: RegisterKind::Command,
85 spec: RegisterSpecWire {
86 name: name.to_string(),
87 description: "d".to_string(),
88 input_schema: None,
89 argument_hint: None,
90 },
91 })
92 };
93 for name in ["help", "trust", "model", "jihua", "zidong"]
94 .into_iter()
95 .map(str::to_string)
96 .chain(owned)
97 {
98 let in_grammar = name.starts_with(|c: char| c.is_ascii_lowercase())
99 && name.len() <= 64
100 && name
101 .chars()
102 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-');
103 if in_grammar {
104 let handle = register(&mut registry, &name).unwrap();
105 let _ = registry.mark_active(&owner);
106 let command = registry
107 .live_command(handle, "a", owner.generation)
108 .unwrap();
109 assert_ne!(command.name, name);
110 assert!(!catalog.answers_to(&command.name));
111 registry.unregister(&owner, handle);
112 } else {
113 assert!(
114 register(&mut registry, &name)
115 .unwrap_err()
116 .contains("invalid")
117 );
118 }
119 }
120 register(&mut registry, "ext-not-built-in").unwrap();
121 }
122
123 /// Commands registered by real plugins in a real host: what the user
124 /// registry loads, what dispatch returns, and what running each one gives.
125 #[tokio::test]
126 async fn extension_commands_run_end_to_end_through_the_user_command_registry() {
127 use crate::tui::app::{App, AppAction, TuiOptions};
128 use codewhale_engine::extension_host::command::CommandOutcome;
129
130 let Some(node) = node_for_tests("extension_commands_run_end_to_end") else {
131 return;
132 };
133 let _policy = TestPolicyGuard::extension_host(true);
134 let fixture = FixturePlugins::new(&["ext-commands"]).await;
135 let _catalog = CatalogGuard::install(Arc::new(CommandTable));
136 let manager = fixture.manager(node);
137 let _manager =
138 codewhale_engine::extension_host::TestManagerGuard::install(Arc::clone(&manager));
139 let engine = manager.attach(fixture.registry());
140 // Nothing is visible before the host has registered anything.
141 assert!(manager.live_command_names().is_empty());
142 engine.sync().await.unwrap();
143 let mut live = manager.live_command_names();
144 live.sort();
145 assert_eq!(
146 live,
147 [
148 "ext-ansi",
149 "ext-ask",
150 "ext-dsh",
151 "ext-echo",
152 "ext-fail",
153 "ext-slow",
154 "ext-throw"
155 ]
156 );
157 // Commands are not tools.
158 assert!(manager.live_tool_names().is_empty());
159 assert!(installed(&engine, fixture.workspace()).is_empty());
160
161 // The user registry loads them for this workspace (and no other).
162 let hint = |name: &str| {
163 crate::commands::user_registry::with_registry_for_plugins(
164 engine.plugin_view().as_ref(),
165 |registry| {
166 registry
167 .get(name)
168 .map(|command| (command.argument_hint.clone(), command.takes_arguments()))
169 },
170 )
171 };
172 assert_eq!(hint("ext-echo"), Some((Some("<text>".to_string()), true)));
173 assert_eq!(hint("ext-ask"), Some((Some("<topic>".to_string()), true)));
174 assert_eq!(hint("ext-fail"), Some((None, false)));
175 let other = fixture.workspace().join("elsewhere");
176 assert!(
177 crate::commands::user_registry::with_registry_for_workspace(Some(&other), |registry| {
178 registry.get("ext-echo").is_none()
179 }),
180 "another workspace never sees this workspace's extension commands"
181 );
182 // Discovery lists them.
183 let described = crate::commands::user_registry::with_registry_for_plugins(
184 engine.plugin_view().as_ref(),
185 |registry| {
186 registry
187 .iter()
188 .filter(|command| command.extension.is_some())
189 .count()
190 },
191 );
192 assert_eq!(described, 7);
193
194 // Dispatch is the ordinary slash-command path, and returns the action
195 // the UI loop runs; the arguments arrive trimmed.
196 let mut app = App::new(
197 TuiOptions {
198 workspace: fixture.workspace().to_path_buf(),
199 ..crate::tui::test_support::test_tui_options(fixture.workspace())
200 },
201 &codewhale_runtime::config::Config::default(),
202 );
203 let help = crate::commands::execute("/help ext-echo", &mut app);
204 assert!(
205 help.message
206 .as_deref()
207 .is_some_and(|text| text.contains("Echo the arguments.")),
208 "{help:?}"
209 );
210 let dispatched = |app: &mut App, input: &str| match crate::commands::execute(input, app).action
211 {
212 Some(AppAction::RunExtensionCommand {
213 command,
214 name,
215 input,
216 }) => (command, name, input),
217 other => panic!("{input}: expected an extension command action, got {other:?}"),
218 };
219 let (echo, name, args) = dispatched(&mut app, "/ext-echo hello there ");
220 assert_eq!(
221 (name.as_str(), args.as_str()),
222 ("ext-echo", "hello there")
223 );
224 assert_eq!(echo.origin, "extension:ext-commands");
225 assert_eq!(
226 codewhale_engine::extension_host::run_command(&echo, &args, None).await,
227 Ok(CommandOutcome::Show {
228 text: "echo: hello there".to_string()
229 })
230 );
231 let (ask, _, args) = dispatched(&mut app, "/EXT-ASK tokens");
232 assert_eq!(
233 codewhale_engine::extension_host::run_command(&ask, &args, None).await,
234 Ok(CommandOutcome::Submit {
235 prompt: "Summarize: tokens".to_string(),
236 note: Some("Asking the model.".to_string())
237 })
238 );
239 let (fail, _, args) = dispatched(&mut app, "/ext-fail");
240 assert_eq!(
241 codewhale_engine::extension_host::run_command(&fail, &args, None).await,
242 Err("unknown topic".to_string())
243 );
244 let (thrown, _, args) = dispatched(&mut app, "/ext-throw");
245 let error = codewhale_engine::extension_host::run_command(&thrown, &args, None)
246 .await
247 .unwrap_err();
248 assert!(
249 error.starts_with("failed:") && error.contains("boom"),
250 "{error}"
251 );
252 // Escape sequences never reach the transcript.
253 let (ansi, _, args) = dispatched(&mut app, "/ext-ansi");
254 assert_eq!(
255 codewhale_engine::extension_host::run_command(&ansi, &args, None).await,
256 Ok(CommandOutcome::Show {
257 text: "plain red end".to_string()
258 })
259 );
260 // The DSH-shaped `rawInput` keeps its leading separator.
261 let (dsh, _, args) = dispatched(&mut app, "/ext-dsh a b");
262 assert_eq!(
263 codewhale_engine::extension_host::run_command(&dsh, &args, None).await,
264 Ok(CommandOutcome::Show {
265 text: "\" a b\"".to_string()
266 })
267 );
268
269 // Disabling the plugin removes every command at once: the registry stops
270 // listing them, and the reference a user (or palette) still holds fails
271 // closed instead of reaching the host.
272 engine.set_plugins(fixture.disable("ext-commands"));
273 engine.sync().await.unwrap();
274 assert!(manager.live_command_names().is_empty());
275 assert_eq!(hint("ext-echo"), None);
276 let error = codewhale_engine::extension_host::run_command(&echo, "x", None)
277 .await
278 .unwrap_err();
279 assert!(
280 (error.contains("no longer registered") || error.contains("no longer selected")),
281 "{error}"
282 );
283 manager.shutdown().await;
284 }
285
286 /// Built-in names remain protected and plugin commands remain scoped;
287 /// a built-in collision is available under its plugin-specific name.
288 #[tokio::test]
289 async fn extension_commands_never_shadow_built_ins_or_other_plugins() {
290 let Some(node) = node_for_tests("extension_commands_never_shadow") else {
291 return;
292 };
293 let _policy = TestPolicyGuard::extension_host(true);
294 let fixture = FixturePlugins::new(&[
295 "ext-commands",
296 "commands-clash-builtin",
297 "commands-clash-plugin",
298 ])
299 .await;
300 let _catalog = CatalogGuard::install(Arc::new(CommandTable));
301 let manager = fixture.manager(node);
302 let _manager =
303 codewhale_engine::extension_host::TestManagerGuard::install(Arc::clone(&manager));
304 let engine = manager.attach(fixture.registry());
305 engine.sync().await.unwrap();
306 let state = |name: &str| manager.owner_state(&plugin_id(&fixture, name)).unwrap();
307 assert_eq!(state("commands-clash-builtin"), OwnerState::Active);
308 assert!(
309 manager
310 .live_command_names()
311 .contains(&"plugin-commands-clash-builtin-help".to_string())
312 );
313 // Distinct entry scopes may register the same spelling. The selected
314 // caller refuses ambiguity instead of choosing a global union winner.
315 assert_eq!(state("ext-commands"), OwnerState::Active);
316 assert_eq!(state("commands-clash-plugin"), OwnerState::Active);
317 assert_eq!(
318 manager
319 .live_command_names()
320 .iter()
321 .filter(|name| *name == "ext-echo")
322 .count(),
323 2
324 );
325 let selected = manager.commands_for_plugins(engine.plugin_view().as_ref());
326 let alias = selected
327 .iter()
328 .find(|entry| entry.registration.name == "plugin-commands-clash-builtin-help")
329 .unwrap();
330 assert_eq!(
331 codewhale_engine::extension_host::run_command(&alias.reference(), "", None).await,
332 Ok(
333 codewhale_engine::extension_host::command::CommandOutcome::Show {
334 text: "shadowed".into()
335 }
336 )
337 );
338 assert!(
339 !selected
340 .iter()
341 .any(|entry| entry.registration.name == "ext-echo")
342 );
343 assert!(!manager.live_command_names().contains(&"help".to_string()));
344 let diagnostics = manager.diagnostics().join("\n");
345 assert!(
346 diagnostics.contains("/plugin-commands-clash-builtin-help"),
347 "{diagnostics}"
348 );
349 manager.shutdown().await;
350
351 // The user registry is the last line: a command already defined by a
352 // markdown source, or by a built-in, wins the spelling and the extension
353 // one is left out with a load error naming why.
354 let mut registry = crate::commands::user_registry::UserCommandRegistry::from_loaded(vec![(
355 "ext-echo".to_string(),
356 "markdown wins".to_string(),
357 )]);
358 let entry = |name: &str| codewhale_engine::extension_host::command::ExtensionCommandEntry {
359 selection: None,
360 registration: codewhale_engine::extension_host::registry::CommandRegistration {
361 scope: None,
362 handle: 1,
363 owner: codewhale_config::OwnerRef {
364 plugin_id: "p".into(),
365 generation: 1,
366 owner_token: "t".into(),
367 },
368 cohort: HostCohort::reviewed(),
369 plugin_name: "p".into(),
370 content_hash: "h".into(),
371 name: name.to_string(),
372 declared_name: name.to_string(),
373 description: "d".into(),
374 argument_hint: None,
375 },
376 authority: fake_authority("p"),
377 workspace: PathBuf::from("/w"),
378 };
379 registry.load_extension_commands(vec![entry("ext-echo"), entry("help")]);
380 let errors: Vec<String> = registry
381 .load_errors()
382 .iter()
383 .map(|error| error.message.clone())
384 .collect();
385 assert!(
386 errors
387 .iter()
388 .any(|e| e.contains("'/ext-echo' collides with another command")),
389 "{errors:?}"
390 );
391 assert!(
392 errors
393 .iter()
394 .any(|e| e.contains("'/help' collides with a built-in command")),
395 "{errors:?}"
396 );
397 assert!(registry.get("ext-echo").unwrap().extension.is_none());
398 }
399
399 lines RUST