返回 CodeWhale
session_structcopy_host_tests.rs
根目录 / crates / tui / src / commands / session_structcopy_host_tests.rs
1 //! Real-host preservation fixtures, captured before FEAT-026 production edits.
2 //! These fixtures stay outside the portable session command closure.
3 use super::{CommandResult, execute};
4 use crate::tui::app::{App, TuiOptions};
5 use crate::tui::clipboard::ClipboardHandler;
6 use codewhale_engine::tools::plan::{PlanItemArg, StepStatus, UpdatePlanArgs};
7 use codewhale_localization::{Locale, tr};
8 use codewhale_models::{ContentBlock, ImageUrlContent, Message, Role, ToolCaller};
9 use codewhale_runtime::config::Config;
10 use serde_json::{Value, json};
11 use tempfile::TempDir;
12
13 fn app(temp: &TempDir) -> App {
14 let options = TuiOptions {
15 skills_dir: temp.path().join("skills"),
16 memory_path: temp.path().join("memory.md"),
17 mcp_config_path: temp.path().join("mcp.json"),
18 ..crate::tui::test_support::test_tui_options(temp.path())
19 };
20 let mut app = App::new(options, &Config::default());
21 app.ui_locale = Locale::En;
22 app.current_session_id = Some("structcopy-baseline-session".into());
23 app
24 }
25
26 fn call(name: &str) -> ContentBlock {
27 ContentBlock::ToolUse {
28 execution_id: None,
29 id: "call-golden".into(),
30 name: name.into(),
31 input: json!({"url":"https://alice:secret@example.test/path?token=x#frag", "api_key":"secret-value"}),
32 caller: Some(ToolCaller {
33 caller_type: "code_execution_20250825".into(),
34 tool_id: None,
35 }),
36 thought_signature: Some("private-call-signature".into()),
37 }
38 }
39
40 fn result(content: &str, is_error: Option<bool>) -> ContentBlock {
41 ContentBlock::ToolResult {
42 execution_id: None,
43 tool_use_id: "call-golden".into(),
44 content: content.into(),
45 is_error,
46 content_blocks: Some(vec![
47 json!({"type":"image","mime_type":"image/png","data":"private-base64"}),
48 json!({"type":"text","text":"visible tool text"}),
49 ]),
50 }
51 }
52
53 fn seed(app: &mut App) {
54 app.api_messages = std::sync::Arc::new(vec![
55 Message {
56 role: Role::System,
57 content: vec![ContentBlock::Text {
58 text: "hidden system instruction".into(),
59 cache_control: None,
60 }],
61 },
62 Message {
63 role: Role::Assistant,
64 content: vec![
65 ContentBlock::Text {
66 text: "visible text".into(),
67 cache_control: None,
68 },
69 ContentBlock::Thinking {
70 thinking: "hidden reasoning".into(),
71 signature: Some("hidden-signature".into()),
72 state: None,
73 redacted_data: None,
74 },
75 call("first-call"),
76 result("first-result", Some(false)),
77 ContentBlock::ImageUrl {
78 image_url: ImageUrlContent {
79 url: "data:image/png;base64,private".into(),
80 },
81 },
82 ContentBlock::ImageUrl {
83 image_url: ImageUrlContent {
84 url: "https://a:b@example.test/image.png?q=x#y".into(),
85 },
86 },
87 ContentBlock::ServerToolUse {
88 id: "server-only".into(),
89 name: "server".into(),
90 input: json!({"x":1}),
91 kind: None,
92 caller: None,
93 },
94 ContentBlock::ToolSearchToolResult {
95 tool_use_id: "search".into(),
96 content: json!({"matches":["one"]}),
97 },
98 ContentBlock::CodeExecutionToolResult {
99 tool_use_id: "exec".into(),
100 content: json!({"stdout":"ok"}),
101 },
102 ],
103 },
104 Message {
105 role: Role::User,
106 content: vec![result("last-result", None), call("last-call")],
107 },
108 ]);
109 app.plan_state.try_lock().unwrap().update(UpdatePlanArgs {
110 title: Some("Golden plan".into()),
111 objective: Some("Preserve output".into()),
112 context_summary: Some("Context".into()),
113 explanation: Some("Explanation".into()),
114 sources_used: vec!["source".into()],
115 critical_files: vec!["src/file.rs".into()],
116 constraints: vec!["read only".into()],
117 recommended_approach: Some("typed observations".into()),
118 verification_plan: Some("golden comparison".into()),
119 risks_and_unknowns: Some("unknown remains null".into()),
120 handoff_packet: Some("ready".into()),
121 replan_if: Vec::new(),
122 plan: vec![
123 PlanItemArg {
124 step: "first".into(),
125 status: StepStatus::Pending,
126 },
127 PlanItemArg {
128 step: "second".into(),
129 status: StepStatus::InProgress,
130 },
131 PlanItemArg {
132 step: "third".into(),
133 status: StepStatus::Completed,
134 },
135 ],
136 });
137 }
138
139 fn observation(result: CommandResult, app: &App) -> Value {
140 assert!(
141 result.action.is_none(),
142 "structcopy must never emit an action"
143 );
144 json!({"message":result.message,"is_error":result.is_error,"clipboard":app.clipboard.last_written_text()})
145 }
146
147 fn dispatch(app: &mut App, command: &str) -> Value {
148 app.clipboard = ClipboardHandler::new();
149 let before_messages = app.api_messages.clone();
150 let before_plan = app.plan_state.try_lock().unwrap().snapshot();
151 let before_session = app.current_session_id.clone();
152 let result = execute(command, app);
153 assert_eq!(app.api_messages, before_messages);
154 assert_eq!(app.plan_state.try_lock().unwrap().snapshot(), before_plan);
155 assert_eq!(app.current_session_id, before_session);
156 observation(result, app)
157 }
158
159 fn baseline_observations() -> Value {
160 let temp = TempDir::new().unwrap();
161 let mut app = app(&temp);
162 seed(&mut app);
163 let mut captures = serde_json::Map::new();
164 for (name, command) in [
165 ("turn_internal", "/structcopy turn 1 stdout"),
166 ("turn_blocks", "/structcopy turn 2 stdout"),
167 ("turn_unknown_result", "/structcopy turn 3 stdout"),
168 ("tool_duplicate_last", "/structcopy tool call-golden stdout"),
169 ("plan_full", "/structcopy plan stdout"),
170 ("usize_plus_and_stdout_case", "/structcopy turn +2 StDoUt"),
171 (
172 "server_tool_unavailable",
173 "/structcopy tool server-only stdout",
174 ),
175 ] {
176 captures.insert(name.into(), dispatch(&mut app, command));
177 }
178 // Upstream now refuses duplicate identities instead of selecting the last.
179 assert_eq!(captures["tool_duplicate_last"]["is_error"], true);
180 assert_eq!(captures["tool_duplicate_last"]["clipboard"], Value::Null);
181 app.api_messages = std::sync::Arc::new(vec![Message {
182 role: Role::Assistant,
183 content: vec![call("lonely")],
184 }]);
185 captures.insert(
186 "tool_missing_result".into(),
187 dispatch(&mut app, "/structcopy tool call-golden stdout"),
188 );
189 for (label, flag) in [
190 ("false", Some(false)),
191 ("true", Some(true)),
192 ("unknown", None),
193 ] {
194 // Each tri-state case has one result; accumulated duplicates are now
195 // rejected by upstream's execution-identity contract.
196 app.api_messages_mut()[0].content.truncate(1);
197 app.api_messages_mut()[0]
198 .content
199 .push(result("result", flag));
200 captures.insert(
201 format!("tool_error_{label}"),
202 dispatch(&mut app, "/structcopy tool call-golden stdout"),
203 );
204 }
205 seed(&mut app);
206 for (locale, label) in [(Locale::En, "en"), (Locale::ZhHans, "zh_hans")] {
207 app.ui_locale = locale;
208 for (index, command) in [
209 "/structcopy",
210 "/structcopy stdout",
211 "/structcopy turn 0",
212 "/structcopy turn -1",
213 "/structcopy turn 99999999999999999999999999",
214 "/structcopy Turn 1",
215 "/structcopy plan extra",
216 "/structcopy turn 99 stdout",
217 "/structcopy workflow absent stdout",
218 ]
219 .iter()
220 .enumerate()
221 {
222 captures.insert(
223 format!("{label}_error_{index}"),
224 dispatch(&mut app, command),
225 );
226 }
227 for (transport, clipboard) in [
228 ("native", ClipboardHandler::new()),
229 ("queued", ClipboardHandler::terminal_only_for_test()),
230 ("failed", ClipboardHandler::unavailable_for_test(false)),
231 ] {
232 app.clipboard = clipboard;
233 let value = execute("/structcopy turn 2", &mut app);
234 captures.insert(format!("{label}_{transport}"), observation(value, &app));
235 }
236 let plan = app.plan_state.clone();
237 let _guard = plan.try_lock().unwrap();
238 app.clipboard = ClipboardHandler::new();
239 let busy = execute("/structcopy plan stdout", &mut app);
240 assert!(busy.is_error);
241 assert!(app.clipboard.last_written_text().is_none());
242 captures.insert(format!("{label}_busy_plan"), observation(busy, &app));
243 }
244 app.ui_locale = Locale::En;
245 assert!(
246 !temp.path().join(".codewhale").exists(),
247 "missing workflow lookup created state"
248 );
249 codewhale_engine::tools::workflow::structcopy_test_seed_run(
250 temp.path(),
251 "golden-run",
252 "structcopy-baseline-session",
253 );
254 let mut workflow = dispatch(&mut app, "/structcopy workflow golden-run stdout");
255 let message = workflow["message"].as_str().unwrap();
256 let parsed: Value = serde_json::from_str(message).unwrap();
257 assert_eq!(parsed["object"]["leaf_count"], Value::Null);
258 // Only a volatile source timestamp is normalized. Keep the 13-byte width,
259 // so receipt payload_bytes still checks the exact baseline envelope.
260 let timestamp = parsed["object"]["started_at_ms"].as_u64().unwrap();
261 assert_eq!(timestamp.to_string().len(), 13);
262 workflow["message"] = Value::String(message.replace(
263 &format!("\"started_at_ms\":{timestamp}"),
264 "\"started_at_ms\":1700000000000",
265 ));
266 captures.insert("workflow_owned".into(), workflow);
267 app.current_session_id = Some("another-session".into());
268 captures.insert(
269 "workflow_wrong_owner".into(),
270 dispatch(&mut app, "/structcopy workflow golden-run stdout"),
271 );
272 app.current_session_id = None;
273 captures.insert(
274 "workflow_no_session".into(),
275 dispatch(&mut app, "/structcopy workflow golden-run stdout"),
276 );
277 let temp2 = TempDir::new().unwrap();
278 let mut empty = self::app(&temp2);
279 captures.insert(
280 "empty_plan".into(),
281 dispatch(&mut empty, "/structcopy plan stdout"),
282 );
283 captures.insert(
284 "empty_turn".into(),
285 dispatch(&mut empty, "/structcopy turn 1 stdout"),
286 );
287 let info = super::get_command_info("structcopy").unwrap();
288 use super::traits::CommandGroup;
289 captures.insert("metadata".into(),json!({
290 "name":info.name,"aliases":info.aliases,"usage":info.usage,
291 "description_en":tr(Locale::En,info.description_id),
292 "description_zh_hans":tr(Locale::ZhHans,info.description_id),
293 "session_order":super::session_group::SessionCommands.commands().iter().map(|c|c.info().name).collect::<Vec<_>>(),
294 "native_model_tool":codewhale_engine::core::engine::default_active_native_tool_names().contains(&"structcopy"),
295 }));
296 Value::Object(captures)
297 }
298
299 #[test]
300 fn structcopy_public_workflow_matches_frozen_baseline() {
301 let mut expected: Value = serde_json::from_str(
302 &std::fs::read_to_string(concat!(
303 env!("CARGO_MANIFEST_DIR"),
304 "/src/commands/fixtures/structcopy_baseline.json"
305 ))
306 .expect("frozen baseline fixture"),
307 )
308 .unwrap();
309 // Keep the original capture intact. Upstream's execution-identity change
310 // supersedes exactly its duplicate-last observation with safe refusal.
311 expected["tool_duplicate_last"] = expected["server_tool_unavailable"].clone();
312 // The integrated localization audit changed these four Chinese strings.
313 // Preserve the captured payloads and English receipts byte-for-byte.
314 for key in ["zh_hans_error_7", "zh_hans_native", "zh_hans_queued"] {
315 expected[key]["message"] = Value::String(
316 expected[key]["message"]
317 .as_str()
318 .unwrap()
319 .replace("轮次", "回合"),
320 );
321 }
322 expected["metadata"]["description_zh_hans"] =
323 Value::String("将一个会话对象复制为已脱敏的 JSON;不是模型工具".into());
324 assert_eq!(
325 baseline_observations(),
326 expected,
327 "observable structcopy behavior changed"
328 );
329 }
330
331 #[test]
332 fn structcopy_host_exposes_exact_authority_and_filters_private_data_before_crossing() {
333 use super::groups::session::StructcopyRegistration;
334 use codewhale_command_contract::facets::*;
335 use codewhale_command_contract::handler::{CommandCapabilities, CommandHandler, ContextParts};
336 use codewhale_command_contract::metadata::RegisterCommand;
337 let CommandHandler::Contextual { capabilities, .. } = StructcopyRegistration::handler() else {
338 panic!("contract registration required");
339 };
340 assert_eq!(
341 capabilities,
342 CommandCapabilities::SESSION_STRUCTCOPY.union(CommandCapabilities::PRESENTATION)
343 );
344 let tmp = TempDir::new().unwrap();
345 let mut app = app(&tmp);
346 seed(&mut app);
347 let mut bundle = app.command_contexts();
348 let ContextParts {
349 structcopy,
350 presentation,
351 session,
352 model,
353 cost,
354 mode_policy,
355 system_prompt,
356 skills,
357 workspace,
358 media,
359 memory,
360 project,
361 skill_group,
362 plugin,
363 lifecycle,
364 control,
365 export,
366 debug_receipts,
367 debug_change,
368 debug_history,
369 debug_diff,
370 debug_undo,
371 debug_diagnostics,
372 permissions,
373 config_status,
374 config,
375 pet,
376 trust,
377 login,
378 work_surface,
379 navigation,
380 voice_input,
381 } = bundle.contexts(capabilities).into_parts();
382 assert!(
383 permissions.is_none()
384 && config_status.is_none()
385 && config.is_none()
386 && pet.is_none()
387 && trust.is_none()
388 && login.is_none()
389 && work_surface.is_none()
390 && navigation.is_none()
391 && voice_input.is_none()
392 );
393 assert!(presentation.is_some());
394 assert!(
395 session.is_none()
396 && model.is_none()
397 && cost.is_none()
398 && mode_policy.is_none()
399 && system_prompt.is_none()
400 && skills.is_none()
401 && workspace.is_none()
402 && media.is_none()
403 && memory.is_none()
404 && project.is_none()
405 && skill_group.is_none()
406 && plugin.is_none()
407 && lifecycle.is_none()
408 && control.is_none()
409 && export.is_none()
410 && debug_receipts.is_none()
411 && debug_change.is_none()
412 && debug_history.is_none()
413 && debug_diff.is_none()
414 && debug_undo.is_none()
415 && debug_diagnostics.is_none()
416 );
417 let copy = structcopy.unwrap();
418 assert_eq!(copy.transcript_item(0), Err(StructcopyError::Unavailable));
419 assert_eq!(
420 copy.transcript_item(1).unwrap().content,
421 StructcopyContent::InternalContext
422 );
423 let visible = copy.transcript_item(2).unwrap();
424 let debug = format!("{visible:?}");
425 for forbidden in [
426 "hidden reasoning",
427 "hidden-signature",
428 "private-call-signature",
429 "private-base64",
430 "data:image",
431 ] {
432 assert!(!debug.contains(forbidden), "{debug}");
433 }
434 let StructcopyContent::Visible(blocks) = visible.content else {
435 panic!("visible blocks")
436 };
437 assert!(blocks.contains(&StructcopyBlock::ThinkingOmitted));
438 assert!(blocks.contains(&StructcopyBlock::ImageOmitted));
439 assert_eq!(
440 copy.tool_pair("call-golden"),
441 Err(StructcopyError::Unavailable)
442 );
443 assert_eq!(
444 copy.tool_pair("server-only"),
445 Err(StructcopyError::Unavailable)
446 );
447 assert_eq!(
448 copy.plan_snapshot().unwrap().title.as_deref(),
449 Some("Golden plan")
450 );
451 }
452
453 #[test]
454 fn structcopy_public_workflow_preserves_payload_across_locales_and_transports() {
455 use codewhale_localization::MessageId;
456 let temp = TempDir::new().unwrap();
457 let mut app = app(&temp);
458 seed(&mut app);
459 // This successful transport matrix needs a unique tool pair. Duplicate
460 // identities are exercised by the separate refusal regressions.
461 app.api_messages_mut()[2].content.clear();
462 codewhale_engine::tools::workflow::structcopy_test_seed_run(
463 temp.path(),
464 "transport-run",
465 "structcopy-baseline-session",
466 );
467 for (selector, kind) in [
468 ("turn 2", MessageId::CmdStructcopyKindTurn),
469 ("tool call-golden", MessageId::CmdStructcopyKindTool),
470 ("plan", MessageId::CmdStructcopyKindPlan),
471 (
472 "workflow transport-run",
473 MessageId::CmdStructcopyKindWorkflow,
474 ),
475 ] {
476 let command = format!("/structcopy {selector}");
477 let expected = dispatch(&mut app, &format!("{command} stdout"));
478 assert_eq!(expected["is_error"], false);
479 let payload = expected["message"].as_str().unwrap();
480 assert_eq!(expected["clipboard"], Value::Null);
481 for &locale in Locale::shipped() {
482 app.ui_locale = locale;
483 let stdout = dispatch(&mut app, &format!("{command} stdout"));
484 assert_eq!(stdout["message"], payload);
485 assert_eq!(stdout["clipboard"], Value::Null);
486 for (clipboard, id) in [
487 (
488 ClipboardHandler::new(),
489 MessageId::CmdStructcopyClipboardAccepted,
490 ),
491 (
492 ClipboardHandler::terminal_only_for_test(),
493 MessageId::CmdStructcopyClipboardQueued,
494 ),
495 ] {
496 app.clipboard = clipboard;
497 let before_messages = app.api_messages.clone();
498 let before_plan = app.plan_state.try_lock().unwrap().snapshot();
499 let before_session = app.current_session_id.clone();
500 let result = execute(&command, &mut app);
501 assert!(!result.is_error);
502 assert!(result.action.is_none());
503 assert_eq!(
504 result.message.as_deref(),
505 Some(
506 tr(locale, id)
507 .replace("{kind}", &tr(locale, kind))
508 .replace("{bytes}", &payload.len().to_string())
509 .as_str()
510 )
511 );
512 if id == MessageId::CmdStructcopyClipboardAccepted {
513 assert_eq!(app.clipboard.last_written_text(), Some(payload));
514 } else {
515 // Terminal writes are queued; this accessor observes native writes only.
516 assert!(app.clipboard.last_written_text().is_none());
517 }
518 assert_eq!(app.api_messages, before_messages);
519 assert_eq!(app.plan_state.try_lock().unwrap().snapshot(), before_plan);
520 assert_eq!(app.current_session_id, before_session);
521 }
522 }
523 }
524 }
525
525 lines RUST