返回 CodeWhale
creator_acceptance.rs
根目录 / crates / tui / tests / cucumber / creator_acceptance.rs
1 use std::collections::HashSet;
2 use std::path::{Path, PathBuf};
3 use std::sync::{Arc, Mutex};
4 use std::time::Duration;
5
6 use codewhale_plugins::host_services::{AgentPosture, PersonVia, PluginApprover};
7 use codewhale_runtime::config::BundledSkillsConfig;
8 use serde_json::{Value, json};
9 use wiremock::matchers::{method, path};
10 use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};
11
12 use super::qa_harness::{
13 harness::{Harness, make_sealed_workspace},
14 keys,
15 };
16
17 const TEST_MODEL: &str = "acceptance-model";
18 const PTY_WAIT: Duration = Duration::from_secs(30);
19
20 fn discover_node_binary() -> PathBuf {
21 for var in ["NODE_BINARY", "CODEWHALE_NODE_BINARY"] {
22 if let Some(value) = std::env::var_os(var) {
23 let candidate = PathBuf::from(value);
24 if candidate.is_file() {
25 return candidate;
26 }
27 }
28 }
29 if let Some(path_var) = std::env::var_os("PATH") {
30 for dir in std::env::split_paths(&path_var) {
31 let candidate = dir.join("node");
32 if candidate.is_file() {
33 return candidate;
34 }
35 }
36 }
37 for candidate in [
38 Path::new("/opt/homebrew/bin/node"),
39 Path::new("/usr/local/bin/node"),
40 Path::new("/usr/bin/node"),
41 ] {
42 if candidate.is_file() {
43 return candidate.to_path_buf();
44 }
45 }
46 panic!("node binary required for creator_acceptance PTY tests");
47 }
48
49 fn tool_package_json() -> String {
50 json!({
51 "name": "@local/my-plugin",
52 "version": "1.0.0",
53 "private": true,
54 "type": "module",
55 "exports": { ".": "./index.js" },
56 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
57 })
58 .to_string()
59 }
60
61 fn tool_cordis_patch() -> &'static str {
62 "- insert:\n - id: my-plugin\n name: '@local/my-plugin'\n config: {}\n"
63 }
64
65 fn tool_index_js(reply: &str) -> String {
66 format!(
67 "export const inject = ['tools', 'storage']\n\
68 export function apply(ctx) {{\n \
69 ctx.tools.register({{\n \
70 name: 'loop_echo',\n \
71 description: 'Echo from creator PTY fixture.',\n \
72 parameters: {{\n \
73 type: 'object',\n \
74 properties: {{ note: {{ type: 'string' }} }},\n \
75 additionalProperties: false,\n }},\n \
76 execute: async (input) => {{\n \
77 if (input && typeof input.note === 'string') {{\n \
78 await ctx.storage.set('saved_note', input.note)\n \
79 }}\n \
80 return {{ reply: {reply:?}, saved: (await ctx.storage.get('saved_note')) ?? null }}\n \
81 }},\n }})\n\
82 }}\n"
83 )
84 }
85
86 fn sse_chunk(value: Value) -> String {
87 format!(
88 "data: {}\n\n",
89 serde_json::to_string(&value).expect("SSE JSON")
90 )
91 }
92
93 fn tool_call_sse(id: &str, tool_name: &str, arguments: &str) -> String {
94 [
95 sse_chunk(json!({
96 "id": "chatcmpl-tool",
97 "object": "chat.completion.chunk",
98 "model": TEST_MODEL,
99 "choices": [{
100 "index": 0,
101 "delta": {
102 "tool_calls": [{
103 "index": 0,
104 "id": id,
105 "type": "function",
106 "function": {
107 "name": tool_name,
108 "arguments": arguments
109 }
110 }]
111 },
112 "finish_reason": null
113 }]
114 })),
115 sse_chunk(json!({
116 "id": "chatcmpl-tool",
117 "object": "chat.completion.chunk",
118 "model": TEST_MODEL,
119 "choices": [{
120 "index": 0,
121 "delta": {},
122 "finish_reason": "tool_calls"
123 }],
124 "usage": {
125 "prompt_tokens": 10,
126 "completion_tokens": 2,
127 "total_tokens": 12
128 }
129 })),
130 "data: [DONE]\n\n".to_string(),
131 ]
132 .join("")
133 }
134
135 fn final_answer_sse(answer: &str) -> String {
136 [
137 sse_chunk(json!({
138 "id": "chatcmpl-final",
139 "object": "chat.completion.chunk",
140 "model": TEST_MODEL,
141 "choices": [{
142 "index": 0,
143 "delta": { "content": answer },
144 "finish_reason": null
145 }]
146 })),
147 sse_chunk(json!({
148 "id": "chatcmpl-final",
149 "object": "chat.completion.chunk",
150 "model": TEST_MODEL,
151 "choices": [{
152 "index": 0,
153 "delta": {},
154 "finish_reason": "stop"
155 }],
156 "usage": {
157 "prompt_tokens": 20,
158 "completion_tokens": 8,
159 "total_tokens": 28
160 }
161 })),
162 "data: [DONE]\n\n".to_string(),
163 ]
164 .join("")
165 }
166
167 fn sse_response(body: &str) -> ResponseTemplate {
168 ResponseTemplate::new(200)
169 .insert_header("content-type", "text/event-stream")
170 .insert_header("cache-control", "no-cache")
171 .set_body_string(body.to_string())
172 }
173
174 fn tool_messages(body: &Value) -> Vec<String> {
175 body.get("messages")
176 .and_then(Value::as_array)
177 .map(|msgs| {
178 msgs.iter()
179 .filter(|msg| msg.get("role").and_then(Value::as_str) == Some("tool"))
180 .filter_map(|msg| {
181 msg.get("content")
182 .and_then(Value::as_str)
183 .map(str::to_string)
184 })
185 .collect()
186 })
187 .unwrap_or_default()
188 }
189
190 fn extract_skill_base_dir(text: &str) -> PathBuf {
191 let marker = "Base directory for this skill: `";
192 let start = text
193 .find(marker)
194 .unwrap_or_else(|| panic!("missing base dir marker in:\n{text}"))
195 + marker.len();
196 let rest = &text[start..];
197 let end = rest
198 .find('`')
199 .unwrap_or_else(|| panic!("unclosed base dir backtick in:\n{text}"));
200 PathBuf::from(&rest[..end])
201 }
202
203 struct PtyFullAccessResponder {
204 pkg_dir: PathBuf,
205 captured: Arc<Mutex<Vec<Value>>>,
206 }
207
208 impl Respond for PtyFullAccessResponder {
209 fn respond(&self, request: &Request) -> ResponseTemplate {
210 let body: Value = request.body_json().expect("request JSON");
211 self.captured
212 .lock()
213 .expect("captured lock")
214 .push(body.clone());
215 let results = tool_messages(&body);
216 let sse = match results.len() {
217 0 => tool_call_sse(
218 "call_1",
219 "load_skill",
220 r#"{"name":"cordis-plugin-development"}"#,
221 ),
222 1 => {
223 let base_dir = extract_skill_base_dir(&results[0]);
224 tool_call_sse(
225 "call_2",
226 "read",
227 &json!({ "path": base_dir.join("templates/decoration/package.json") })
228 .to_string(),
229 )
230 }
231 2 => tool_call_sse(
232 "call_3",
233 "write",
234 &json!({
235 "path": self.pkg_dir.join("package.json"),
236 "content": tool_package_json(),
237 })
238 .to_string(),
239 ),
240 3 => tool_call_sse(
241 "call_4",
242 "write",
243 &json!({
244 "path": self.pkg_dir.join("cordis.patch.yml"),
245 "content": tool_cordis_patch(),
246 })
247 .to_string(),
248 ),
249 4 => tool_call_sse(
250 "call_5",
251 "write",
252 &json!({
253 "path": self.pkg_dir.join("index.js"),
254 "content": tool_index_js("pty-v1"),
255 })
256 .to_string(),
257 ),
258 5 => tool_call_sse(
259 "call_6",
260 "plugin_manager",
261 &json!({
262 "action": "install_bundle",
263 "target": self.pkg_dir,
264 })
265 .to_string(),
266 ),
267 6 => tool_call_sse("call_7", "loop_echo", r#"{"note":"from-pty-fa"}"#),
268 _ => final_answer_sse("CREATOR_PTY_FULL_ACCESS_DONE"),
269 };
270 sse_response(&sse)
271 }
272 }
273
274 struct PtyAskResponder {
275 pkg_dir: PathBuf,
276 captured: Arc<Mutex<Vec<Value>>>,
277 }
278
279 impl Respond for PtyAskResponder {
280 fn respond(&self, request: &Request) -> ResponseTemplate {
281 let body: Value = request.body_json().expect("request JSON");
282 self.captured
283 .lock()
284 .expect("captured lock")
285 .push(body.clone());
286 let results = tool_messages(&body);
287 let sse = match results.len() {
288 0 => tool_call_sse(
289 "call_1",
290 "load_skill",
291 r#"{"name":"cordis-plugin-development"}"#,
292 ),
293 1 => {
294 let base_dir = extract_skill_base_dir(&results[0]);
295 tool_call_sse(
296 "call_2",
297 "read",
298 &json!({ "path": base_dir.join("templates/decoration/package.json") })
299 .to_string(),
300 )
301 }
302 2 => tool_call_sse(
303 "call_3",
304 "plugin_manager",
305 &json!({
306 "action": "install_bundle",
307 "target": self.pkg_dir,
308 })
309 .to_string(),
310 ),
311 3 => tool_call_sse("call_4", "loop_echo", r#"{"note":"from-pty-ask"}"#),
312 _ => final_answer_sse("CREATOR_PTY_ASK_DONE"),
313 };
314 sse_response(&sse)
315 }
316 }
317
318 fn prepare_pty_workspace(node: &Path) -> (super::qa_harness::harness::SealedWorkspace, String) {
319 let workspace = make_sealed_workspace().expect("sealed workspace");
320 let codewhale_dir = workspace.home().join(".codewhale");
321 std::fs::create_dir_all(&codewhale_dir).expect("mkdir .codewhale");
322 std::fs::write(codewhale_dir.join(".onboarded"), "").expect("write .onboarded");
323 let skills_dir = codewhale_dir.join("skills");
324 codewhale_skills::install_system_skills(&skills_dir, &BundledSkillsConfig::default())
325 .expect("install system skills");
326 let node_toml = toml::Value::String(node.to_string_lossy().into_owned()).to_string();
327 let config_toml = format!(
328 "[notifications]\nmethod = \"off\"\ncompletion_sound = \"off\"\n\n[features]\nextension_host = true\nplugin_creator = true\n\n[extension_host]\nruntime = \"node\"\nnode = {node_toml}\n"
329 );
330 std::fs::write(codewhale_dir.join("config.toml"), config_toml).expect("write config.toml");
331 workspace.trust_workspace().expect("trust workspace");
332 codewhale_engine::test_support::install_project_cordis_skill_fixture(workspace.workspace());
333
334 let mut dirs = Vec::new();
335 if let Some(parent) = node.parent() {
336 dirs.push(parent.to_path_buf());
337 }
338 for base in ["/usr/bin", "/bin", "/usr/sbin", "/sbin"] {
339 dirs.push(PathBuf::from(base));
340 }
341 let mut seen = HashSet::new();
342 let deduped: Vec<PathBuf> = dirs
343 .into_iter()
344 .filter(|d| seen.insert(d.clone()))
345 .collect();
346 let path_env = std::env::join_paths(deduped)
347 .expect("join PATH")
348 .to_string_lossy()
349 .into_owned();
350 (workspace, path_env)
351 }
352
353 fn spawn_creator_tui(
354 workspace: &super::qa_harness::harness::SealedWorkspace,
355 path_env: &str,
356 server_uri: &str,
357 permission_mode: &str,
358 ) -> Harness {
359 let mut tui = Harness::builder(Harness::codewhale_binary())
360 .cwd(workspace.workspace())
361 .clear_env()
362 .seal_home(workspace.home())
363 .env("PATH", path_env)
364 .env("DEEPSEEK_API_KEY", "ci-pty-test-key")
365 .env("DEEPSEEK_BASE_URL", server_uri)
366 .env("CODEWHALE_BASE_URL", server_uri)
367 .env("DEEPSEEK_MODEL", TEST_MODEL)
368 .env("CODEWHALE_MODEL", TEST_MODEL)
369 .env("CODEWHALE_DISABLE_MODELS_DEV_FETCH", "1")
370 .env("CODEWHALE_NO_UPDATE_CHECK", "1")
371 .env("CODEWHALE_DISABLE_LOCAL_OLLAMA_PROBE", "1")
372 .env("NO_ANIMATIONS", "1")
373 .env("RUST_LOG", "warn")
374 .args([
375 "--workspace",
376 workspace.workspace().to_str().expect("workspace UTF-8"),
377 "--no-project-config",
378 "--skip-onboarding",
379 "--fresh",
380 "--conversation-mode",
381 "creator",
382 "--permission-mode",
383 permission_mode,
384 ])
385 .size(40, 120)
386 .spawn()
387 .expect("start creator TUI");
388 tui.wait_for_text("Creator mode", PTY_WAIT)
389 .expect("startup Creator mode");
390 tui.wait_for_idle(Duration::from_millis(250), Duration::from_secs(5))
391 .expect("startup idle");
392 tui
393 }
394
395 #[test]
396 fn creator_pty_full_access_installs_and_calls_its_tool() {
397 let node = discover_node_binary();
398 let (workspace, path_env) = prepare_pty_workspace(&node);
399 let pkg_dir = workspace.workspace().join("my-plugin");
400
401 let rt = tokio::runtime::Builder::new_multi_thread()
402 .worker_threads(2)
403 .enable_all()
404 .build()
405 .expect("tokio runtime");
406 let captured = Arc::new(Mutex::new(Vec::new()));
407 let server = rt.block_on(async {
408 let srv = MockServer::start().await;
409 Mock::given(method("GET"))
410 .and(path("/v1/models"))
411 .respond_with(
412 ResponseTemplate::new(200)
413 .insert_header("content-type", "application/json")
414 .set_body_json(json!({
415 "object": "list",
416 "data": [{ "id": TEST_MODEL, "object": "model" }]
417 })),
418 )
419 .mount(&srv)
420 .await;
421 Mock::given(method("POST"))
422 .and(path("/v1/chat/completions"))
423 .respond_with(PtyFullAccessResponder {
424 pkg_dir: pkg_dir.clone(),
425 captured: Arc::clone(&captured),
426 })
427 .mount(&srv)
428 .await;
429 srv
430 });
431
432 let mut tui = spawn_creator_tui(&workspace, &path_env, &server.uri(), "full-access");
433 tui.type_line("create and run loop_echo")
434 .expect("submit creator prompt");
435 tui.wait_for_text("CREATOR_PTY_FULL_ACCESS_DONE", PTY_WAIT)
436 .unwrap_or_else(|e| panic!("full access PTY did not finish: {e}\n{}", tui.diagnostics()));
437 tui.pump();
438 let frame = tui.frame().text();
439 assert!(
440 !frame.contains("Do you want to proceed?") && !frame.contains("[▾ m]"),
441 "unexpected approval prompt:\n{frame}"
442 );
443 tui.shutdown();
444
445 let state_raw = std::fs::read_to_string(workspace.home().join(".codewhale/plugins/state.json"))
446 .expect("read plugin state.json");
447 let state: Value = serde_json::from_str(&state_raw).expect("parse state.json");
448 let plugins = state["plugins"].as_object().expect("plugins map");
449 let (_, entry) = plugins
450 .iter()
451 .find(|(id, _)| id.ends_with("my-plugin"))
452 .expect("my-plugin entry");
453 assert_eq!(entry["enabled"], json!(true));
454 let approver: PluginApprover =
455 serde_json::from_value(entry["trust"]["approved_by"].clone()).expect("approved_by");
456 match approver {
457 PluginApprover::Agent(agent) => {
458 assert_eq!(agent.posture, AgentPosture::FullAccess);
459 }
460 other => panic!("expected Agent FullAccess approval, got {other:?}"),
461 }
462
463 drop(server);
464 rt.shutdown_timeout(Duration::from_secs(5));
465 }
466
467 #[test]
468 fn creator_pty_ask_card_yes_installs_and_calls_its_tool() {
469 let node = discover_node_binary();
470 let (workspace, path_env) = prepare_pty_workspace(&node);
471 let pkg_dir = workspace.workspace().join("my-plugin");
472 std::fs::create_dir_all(&pkg_dir).expect("mkdir pkg");
473 std::fs::write(pkg_dir.join("package.json"), tool_package_json()).expect("write pkg");
474 std::fs::write(pkg_dir.join("cordis.patch.yml"), tool_cordis_patch()).expect("write patch");
475 std::fs::write(pkg_dir.join("index.js"), tool_index_js("pty-ask-v1")).expect("write index");
476
477 let rt = tokio::runtime::Builder::new_multi_thread()
478 .worker_threads(2)
479 .enable_all()
480 .build()
481 .expect("tokio runtime");
482 let captured = Arc::new(Mutex::new(Vec::new()));
483 let server = rt.block_on(async {
484 let srv = MockServer::start().await;
485 Mock::given(method("GET"))
486 .and(path("/v1/models"))
487 .respond_with(
488 ResponseTemplate::new(200)
489 .insert_header("content-type", "application/json")
490 .set_body_json(json!({
491 "object": "list",
492 "data": [{ "id": TEST_MODEL, "object": "model" }]
493 })),
494 )
495 .mount(&srv)
496 .await;
497 Mock::given(method("POST"))
498 .and(path("/v1/chat/completions"))
499 .respond_with(PtyAskResponder {
500 pkg_dir: pkg_dir.clone(),
501 captured: Arc::clone(&captured),
502 })
503 .mount(&srv)
504 .await;
505 srv
506 });
507
508 let mut tui = spawn_creator_tui(&workspace, &path_env, &server.uri(), "ask");
509 tui.type_line("install and run loop_echo")
510 .expect("submit ask prompt");
511 tui.wait_for(
512 |frame| {
513 let text = frame.text();
514 text.contains("Allow")
515 && text.contains("Deny")
516 && (text.contains("Plugin manager") || text.contains("plugin_manager"))
517 && !text.contains("Use the loop_echo tool")
518 },
519 PTY_WAIT,
520 )
521 .unwrap_or_else(|e| {
522 panic!(
523 "first approval card did not appear: {e}\n{}",
524 tui.diagnostics()
525 )
526 });
527 tui.send(keys::key::ch('y'))
528 .expect("approve plugin_manager card");
529
530 tui.wait_for(
531 |frame| {
532 let text = frame.text();
533 text.contains("Allow")
534 && text.contains("Deny")
535 && text.contains("Use the loop_echo tool")
536 },
537 PTY_WAIT,
538 )
539 .unwrap_or_else(|e| {
540 panic!(
541 "loop_echo approval card did not appear: {e}\n{}",
542 tui.diagnostics()
543 )
544 });
545 tui.send(keys::key::ch('y'))
546 .expect("approve loop_echo card");
547
548 tui.wait_for_text("CREATOR_PTY_ASK_DONE", PTY_WAIT)
549 .unwrap_or_else(|e| panic!("ask PTY did not finish: {e}\n{}", tui.diagnostics()));
550 tui.shutdown();
551
552 let state_raw = std::fs::read_to_string(workspace.home().join(".codewhale/plugins/state.json"))
553 .expect("read plugin state.json");
554 let state: Value = serde_json::from_str(&state_raw).expect("parse state.json");
555 let plugins = state["plugins"].as_object().expect("plugins map");
556 let (_, entry) = plugins
557 .iter()
558 .find(|(id, _)| id.ends_with("my-plugin"))
559 .expect("my-plugin entry");
560 assert_eq!(entry["enabled"], json!(true));
561 let approver: PluginApprover =
562 serde_json::from_value(entry["trust"]["approved_by"].clone()).expect("approved_by");
563 assert_eq!(
564 approver,
565 PluginApprover::Person {
566 via: PersonVia::ApprovalCard,
567 }
568 );
569
570 drop(server);
571 rt.shutdown_timeout(Duration::from_secs(5));
572 }
573
573 lines RUST