返回 CodeWhale
parity_protocol.rs
根目录 / crates / protocol / tests / parity_protocol.rs
1 use codewhale_app_server_protocol::runtime::{
2 RUNTIME_EVENT_ENVELOPE_SCHEMA_VERSION, RuntimeEventEnvelope,
3 };
4 use codewhale_protocol::{
5 AppRequest, EventFrame, ThreadGoal, ThreadGoalProgressParams, ThreadGoalSetParams,
6 ThreadGoalStatus, ThreadListParams, ThreadRequest, ThreadResumeParams, ToolOutput,
7 UserInputAnswerEvent, UserInputOptionEvent, UserInputQuestionEvent, UserInputRequestEvent,
8 };
9 use serde_json::{Value, json};
10
11 #[test]
12 fn mcp_tool_output_public_shape_remains_source_compatible() {
13 let output = ToolOutput::Mcp {
14 result: json!({"content": []}),
15 };
16 let ToolOutput::Mcp { result } = output else {
17 panic!("constructed MCP output changed variant")
18 };
19 assert_eq!(result, json!({"content": []}));
20 }
21
22 #[test]
23 fn tool_output_success_accessor_has_function_and_mcp_parity() {
24 let cases = [
25 (
26 ToolOutput::Function {
27 body: Some(json!({"kind": "function-success"})),
28 success: true,
29 },
30 true,
31 ),
32 (
33 ToolOutput::Function {
34 body: Some(json!({"kind": "function-failure"})),
35 success: false,
36 },
37 false,
38 ),
39 (
40 ToolOutput::Mcp {
41 result: json!({"kind": "mcp-success", "isError": false}),
42 },
43 true,
44 ),
45 (
46 ToolOutput::Mcp {
47 result: json!({"kind": "mcp-failure", "isError": true}),
48 },
49 false,
50 ),
51 ];
52
53 assert_eq!(
54 serde_json::to_string(&cases[0].0).expect("serialize successful function output"),
55 r#"{"type":"function","body":{"kind":"function-success"},"success":true}"#,
56 "successful Function output must retain its existing wire shape"
57 );
58 for (output, expected) in cases {
59 assert_eq!(output.success(), expected, "output: {output:?}");
60 }
61 }
62
63 #[test]
64 fn mcp_is_error_round_trips_and_legacy_bytes_remain_successful() {
65 let failed = ToolOutput::Mcp {
66 result: json!({"message": "application failure", "isError": true}),
67 };
68 let encoded = serde_json::to_string(&failed).expect("serialize failed MCP output");
69 assert!(encoded.contains(r#""isError":true"#));
70 let decoded: ToolOutput = serde_json::from_str(&encoded).expect("round-trip MCP output");
71 assert!(!decoded.success());
72
73 let legacy = r#"{"type":"mcp","result":{"message":"legacy success"}}"#;
74 let decoded: ToolOutput = serde_json::from_str(legacy).expect("deserialize legacy MCP output");
75 assert!(decoded.success());
76 assert_eq!(
77 serde_json::to_string(&decoded).expect("re-serialize legacy MCP output"),
78 legacy,
79 "success=true must preserve the legacy MCP wire representation"
80 );
81 }
82
83 #[test]
84 fn mcp_is_error_metadata_fails_closed_when_present_but_not_boolean() {
85 for malformed in [
86 Value::Null,
87 json!("unknown"),
88 json!(1),
89 json!({"unexpected": true}),
90 json!([false]),
91 ] {
92 let output = ToolOutput::Mcp {
93 result: json!({"content": [], "isError": malformed}),
94 };
95 assert!(!output.success(), "malformed output: {output:?}");
96 }
97 }
98
99 #[test]
100 fn thread_resume_params_round_trip() {
101 let request = ThreadRequest::Resume(ThreadResumeParams {
102 operation_key: None,
103 thread_id: "thread-123".to_string(),
104 history: None,
105 path: None,
106 model: Some("deepseek-v4-pro".to_string()),
107 model_provider: Some("deepseek".to_string()),
108 cwd: None,
109 approval_policy: Some("on-request".to_string()),
110 sandbox: Some("workspace-write".to_string()),
111 config: None,
112 base_instructions: Some("base".to_string()),
113 developer_instructions: Some("dev".to_string()),
114 personality: Some("default".to_string()),
115 persist_extended_history: true,
116 });
117
118 let encoded = serde_json::to_string(&request).expect("serialize request");
119 let decoded: ThreadRequest = serde_json::from_str(&encoded).expect("deserialize request");
120 match decoded {
121 ThreadRequest::Resume(params) => {
122 assert_eq!(params.thread_id, "thread-123");
123 assert_eq!(params.model.as_deref(), Some("deepseek-v4-pro"));
124 assert!(params.persist_extended_history);
125 }
126 other => panic!("unexpected request: {other:?}"),
127 }
128 }
129
130 #[test]
131 fn thread_list_params_defaults_are_serializable() {
132 let request = ThreadRequest::List(ThreadListParams {
133 include_archived: false,
134 limit: Some(20),
135 });
136 let encoded = serde_json::to_string_pretty(&request).expect("serialize list request");
137 assert!(encoded.contains("include_archived"));
138 }
139
140 #[test]
141 fn event_frame_serialization_contains_expected_tag() {
142 let frame = EventFrame::TurnComplete {
143 turn_id: "turn-1".to_string(),
144 };
145 let encoded = serde_json::to_string(&frame).expect("serialize frame");
146 assert!(encoded.contains("turn_complete"));
147 }
148
149 #[test]
150 fn thread_goal_set_request_round_trip() {
151 let request = ThreadRequest::GoalSet(ThreadGoalSetParams {
152 thread_id: "thread-123".to_string(),
153 objective: "Release 0.8.59".to_string(),
154 token_budget: Some(42_000),
155 });
156
157 let encoded = serde_json::to_string(&request).expect("serialize goal request");
158 assert!(encoded.contains("goal_set"));
159 let decoded: ThreadRequest = serde_json::from_str(&encoded).expect("deserialize request");
160 match decoded {
161 ThreadRequest::GoalSet(params) => {
162 assert_eq!(params.thread_id, "thread-123");
163 assert_eq!(params.objective, "Release 0.8.59");
164 assert_eq!(params.token_budget, Some(42_000));
165 }
166 other => panic!("unexpected request: {other:?}"),
167 }
168 }
169
170 #[test]
171 fn thread_goal_event_serializes_status_and_accounting() {
172 let goal = ThreadGoal {
173 thread_id: "thread-123".to_string(),
174 goal_id: "goal-1".to_string(),
175 objective: "Release 0.8.59".to_string(),
176 status: ThreadGoalStatus::BudgetLimited,
177 token_budget: Some(42_000),
178 tokens_used: 42_001,
179 time_used_seconds: 3600,
180 continuation_count: 7,
181 last_gap_fingerprint: None,
182 repeated_gap_count: 0,
183 last_gap_pass: None,
184 pause_reason: None,
185 created_at: 1,
186 updated_at: 2,
187 };
188
189 let frame = EventFrame::ThreadGoalUpdated { goal };
190 let encoded = serde_json::to_value(&frame).expect("serialize goal event");
191 assert_eq!(encoded["event"], "thread_goal_updated");
192 assert_eq!(encoded["goal"]["status"], "budget_limited");
193 assert_eq!(encoded["goal"]["tokens_used"], 42_001);
194 assert_eq!(encoded["goal"]["continuation_count"], 7);
195 }
196
197 #[test]
198 fn thread_goal_progress_request_round_trip() {
199 let request = ThreadRequest::GoalRecordProgress(ThreadGoalProgressParams {
200 thread_id: "thread-123".to_string(),
201 token_delta: 750,
202 time_delta_seconds: 9,
203 record_continuation: true,
204 });
205
206 let encoded = serde_json::to_string(&request).expect("serialize goal progress request");
207 assert!(encoded.contains("goal_record_progress"));
208 let decoded: ThreadRequest = serde_json::from_str(&encoded).expect("deserialize request");
209 match decoded {
210 ThreadRequest::GoalRecordProgress(params) => {
211 assert_eq!(params.thread_id, "thread-123");
212 assert_eq!(params.token_delta, 750);
213 assert_eq!(params.time_delta_seconds, 9);
214 assert!(params.record_continuation);
215 }
216 other => panic!("unexpected request: {other:?}"),
217 }
218 }
219
220 #[test]
221 fn runtime_event_envelope_roundtrip() {
222 let input = json!({
223 "schema_version": 1,
224 "seq": 12,
225 "event": "item.delta",
226 "kind": "item.delta",
227 "thread_id": "thr_123",
228 "turn_id": "turn_456",
229 "item_id": "item_789",
230 "timestamp": "2026-02-11T20:18:49.123Z",
231 "created_at": "2026-02-11T20:18:49.123Z",
232 "payload": { "delta": "ok", "kind": "agent_message" },
233 });
234 let envelope: RuntimeEventEnvelope =
235 serde_json::from_value(input).expect("deserialize runtime event envelope");
236 assert_eq!(envelope.schema_version, 1);
237 assert_eq!(envelope.seq, 12);
238 assert_eq!(envelope.event, "item.delta");
239 assert_eq!(envelope.kind, "item.delta");
240 assert_eq!(envelope.thread_id, "thr_123");
241
242 let encoded = serde_json::to_value(&envelope).expect("serialize runtime event envelope");
243 assert_eq!(encoded["event"], encoded["kind"]);
244 assert_eq!(encoded["schema_version"], 1);
245 assert_eq!(encoded["seq"], 12);
246 assert_eq!(encoded["thread_id"], "thr_123");
247 assert_eq!(encoded["turn_id"], "turn_456");
248 assert_eq!(encoded["item_id"], "item_789");
249 assert_eq!(encoded["timestamp"], "2026-02-11T20:18:49.123Z");
250 assert_eq!(encoded["created_at"], "2026-02-11T20:18:49.123Z");
251 assert_eq!(
252 encoded["payload"],
253 json!({ "delta": "ok", "kind": "agent_message" })
254 );
255 }
256
257 #[test]
258 fn runtime_event_envelope_defaults_to_api_schema_version() {
259 let input = json!({
260 "seq": 15,
261 "event": "thread.started",
262 "kind": "thread.started",
263 "thread_id": "thr_default_version",
264 "timestamp": "2026-02-11T20:18:49.123Z",
265 "payload": {},
266 });
267 let envelope: RuntimeEventEnvelope = serde_json::from_value(input)
268 .expect("deserialize runtime event envelope without schema version");
269
270 assert_eq!(
271 envelope.schema_version,
272 RUNTIME_EVENT_ENVELOPE_SCHEMA_VERSION
273 );
274 }
275
276 #[test]
277 fn runtime_event_envelope_thread_level_keeps_turn_and_item_ids() {
278 let input = json!({
279 "schema_version": 1,
280 "seq": 14,
281 "event": "thread.started",
282 "kind": "thread.started",
283 "thread_id": "thr_thread",
284 "timestamp": "2026-02-11T20:18:49.123Z",
285 "payload": { "thread": { "id": "thr_thread" } },
286 });
287 let envelope: RuntimeEventEnvelope = serde_json::from_value(input)
288 .expect("deserialize runtime event envelope without thread-level turn/item ids");
289 assert!(envelope.turn_id.is_none());
290 assert!(envelope.item_id.is_none());
291
292 let encoded = serde_json::to_value(envelope).expect("serialize runtime event envelope");
293 assert!(encoded.get("turn_id").is_some());
294 assert!(encoded.get("item_id").is_some());
295 assert!(encoded["turn_id"].is_null());
296 assert!(encoded["item_id"].is_null());
297 }
298
299 #[test]
300 fn runtime_event_envelope_preserves_unknown_fields() {
301 let input: Value = json!({
302 "schema_version": 1,
303 "seq": 13,
304 "event": "turn.completed",
305 "kind": "turn.completed",
306 "thread_id": "thr_unknown",
307 "timestamp": "2026-02-11T20:18:49.123Z",
308 "payload": {},
309 "forward_compatibility_hint": "v2-ready",
310 });
311 let envelope: RuntimeEventEnvelope = serde_json::from_value(input.clone())
312 .expect("deserialize runtime event envelope with unknown field");
313 assert!(envelope.extra.contains_key("forward_compatibility_hint"));
314
315 let encoded = serde_json::to_value(envelope).expect("serialize runtime event envelope");
316 assert_eq!(encoded["forward_compatibility_hint"], "v2-ready");
317 assert_eq!(encoded["schema_version"], 1);
318 assert_eq!(encoded["seq"], 13);
319 assert_eq!(encoded["event"], "turn.completed");
320 assert_eq!(encoded["kind"], "turn.completed");
321 assert_eq!(encoded["thread_id"], "thr_unknown");
322 assert!(encoded["turn_id"].is_null());
323 assert!(encoded["item_id"].is_null());
324 }
325
326 #[test]
327 fn user_input_request_event_frame_round_trip() {
328 // issue #3102: the new EventFrame::UserInputRequest variant must tag as
329 // "user_input_request" and round-trip the full nested question schema,
330 // including the allow_free_text / multi_select booleans.
331 let frame = EventFrame::UserInputRequest {
332 request: UserInputRequestEvent {
333 call_id: "call-1".to_string(),
334 turn_id: "turn-1".to_string(),
335 request_id: "ui-1".to_string(),
336 require_typed_answers: true,
337 questions: vec![UserInputQuestionEvent {
338 header: "Scope".to_string(),
339 id: "scope".to_string(),
340 question: "Which surfaces?".to_string(),
341 detail: Some("Detailed plan".to_string()),
342 intent: Some(codewhale_protocol::UserInputIntentEvent::PlanReview {
343 approve: "All".into(),
344 call_id: Some("plan-call".into()),
345 }),
346 options: vec![
347 UserInputOptionEvent {
348 label: "TUI".to_string(),
349 description: "Modal flow".to_string(),
350 },
351 UserInputOptionEvent {
352 label: "All".to_string(),
353 description: "TUI + headless".to_string(),
354 },
355 ],
356 allow_free_text: true,
357 multi_select: true,
358 }],
359 },
360 };
361
362 let encoded = serde_json::to_value(&frame).expect("serialize user input frame");
363 assert_eq!(encoded["event"], "user_input_request");
364 assert_eq!(encoded["request"]["call_id"], "call-1");
365 assert_eq!(encoded["request"]["require_typed_answers"], true);
366 assert_eq!(
367 encoded["request"]["questions"][0]["detail"],
368 "Detailed plan"
369 );
370 assert_eq!(
371 encoded["request"]["questions"][0]["intent"]["kind"],
372 "plan-review"
373 );
374 assert_eq!(
375 encoded["request"]["questions"][0]["intent"]["call_id"],
376 "plan-call"
377 );
378 assert_eq!(encoded["request"]["request_id"], "ui-1");
379 assert_eq!(encoded["request"]["questions"][0]["header"], "Scope");
380 assert_eq!(encoded["request"]["questions"][0]["allow_free_text"], true);
381 assert_eq!(encoded["request"]["questions"][0]["multi_select"], true);
382 assert_eq!(
383 encoded["request"]["questions"][0]["options"][0]["label"],
384 "TUI"
385 );
386
387 // Round-trips back through serde.
388 let decoded: EventFrame =
389 serde_json::from_value(encoded).expect("deserialize user input frame");
390 let EventFrame::UserInputRequest { request } = decoded else {
391 panic!("expected user_input_request frame after round-trip");
392 };
393 assert_eq!(request.request_id, "ui-1");
394 assert_eq!(request.questions.len(), 1);
395 assert!(request.questions[0].allow_free_text);
396 assert!(request.questions[0].multi_select);
397 }
398
399 #[test]
400 fn user_input_request_event_defaults_flags_when_omitted() {
401 // Backwards compatibility: omitting allow_free_text/multi_select in the
402 // wire JSON must deserialize both to false (matching the TUI's leniency).
403 let input = json!({
404 "event": "user_input_request",
405 "request": {
406 "call_id": "c",
407 "turn_id": "t",
408 "request_id": "r",
409 "questions": [{
410 "header": "H",
411 "id": "i",
412 "question": "Q?",
413 "options": [
414 { "label": "A", "description": "a" },
415 { "label": "B", "description": "b" }
416 ]
417 }]
418 }
419 });
420 let decoded: EventFrame = serde_json::from_value(input).expect("deserialize without flags");
421 let EventFrame::UserInputRequest { request } = decoded else {
422 panic!("expected user_input_request frame");
423 };
424 assert!(!request.require_typed_answers);
425 assert_eq!(request.questions[0].detail, None);
426 assert_eq!(request.questions[0].intent, None);
427 assert!(!request.questions[0].allow_free_text);
428 assert!(!request.questions[0].multi_select);
429 }
430
431 #[test]
432 fn submit_user_input_app_request_round_trip() {
433 // issue #3102: the headless client→server reply variant must tag as
434 // "submit_user_input" and carry the answer list.
435 let req = AppRequest::SubmitUserInput {
436 request_id: "ui-1".to_string(),
437 answers: vec![UserInputAnswerEvent {
438 kind: Some(codewhale_protocol::UserInputAnswerKindEvent::Choice),
439 id: "scope".to_string(),
440 label: "All".to_string(),
441 value: "All".to_string(),
442 }],
443 };
444 let encoded = serde_json::to_string(&req).expect("serialize submit request");
445 assert!(encoded.contains("submit_user_input"));
446 assert!(encoded.contains("\"request_id\":\"ui-1\""));
447
448 let decoded: AppRequest = serde_json::from_str(&encoded).expect("deserialize submit request");
449 let AppRequest::SubmitUserInput {
450 request_id,
451 answers,
452 } = decoded
453 else {
454 panic!("expected submit_user_input after round-trip");
455 };
456 assert_eq!(request_id, "ui-1");
457 assert_eq!(answers.len(), 1);
458 assert_eq!(answers[0].label, "All");
459 assert_eq!(
460 answers[0].kind,
461 Some(codewhale_protocol::UserInputAnswerKindEvent::Choice)
462 );
463 }
464
465 #[test]
466 fn retained_thread_operation_keys_are_additive_and_survive_explicit_retry() {
467 for (method, params) in [
468 ("start", json!({})),
469 ("resume", json!({"thread_id":"thread-123"})),
470 ("fork", json!({"thread_id":"thread-123"})),
471 ] {
472 let legacy = json!({"type":method,"params":params});
473 // Use the enum's actual serde tag rather than a second fixture protocol.
474 let mut wire = match method {
475 "start" => serde_json::to_value(ThreadRequest::Start(
476 serde_json::from_value(json!({})).unwrap(),
477 ))
478 .unwrap(),
479 "resume" => serde_json::to_value(ThreadRequest::Resume(
480 serde_json::from_value(legacy["params"].clone()).unwrap(),
481 ))
482 .unwrap(),
483 _ => serde_json::to_value(ThreadRequest::Fork(
484 serde_json::from_value(legacy["params"].clone()).unwrap(),
485 ))
486 .unwrap(),
487 };
488 assert!(wire.get("operation_key").is_none());
489 wire["operation_key"] = json!("captured-client-intent");
490 let decoded: ThreadRequest = serde_json::from_value(wire).unwrap();
491 assert_eq!(
492 serde_json::to_value(decoded).unwrap()["operation_key"],
493 "captured-client-intent"
494 );
495 }
496 }
497
497 lines RUST