1use crate::core::client::Client;
15use crate::shared::{Error, Result};
16use serde::{Deserialize, Serialize};
17use serde_json::{json, Value};
18use std::collections::HashMap;
19use tokio_util::sync::CancellationToken;
20
21fn unwrap_bare_or_enveloped<T: serde::de::DeserializeOwned>(raw: Value, op: &str) -> Result<T> {
36 let observed_keys = || -> String {
37 match raw.as_object() {
38 Some(map) if !map.is_empty() => map.keys().cloned().collect::<Vec<_>>().join(","),
39 _ => "<none>".to_string(),
40 }
41 };
42 let inner = raw.as_object().and_then(|m| m.get("data")).cloned();
43 if let Ok(value) = serde_json::from_value::<T>(raw.clone()) {
44 return Ok(value);
45 }
46 if let Some(inner) = inner {
47 if let Ok(value) = serde_json::from_value::<T>(inner) {
48 return Ok(value);
49 }
50 }
51 Err(Error::other(format!(
52 "acosmi: {op}: gateway accepted the request but the response is missing required fields (observed keys: {})",
53 observed_keys()
54 )))
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct BugReportResult {
60 pub feedback_id: String,
62 pub detail_url: String,
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct BugView {
72 pub id: String,
73 pub description: String,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub platform: Option<String>,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub terminal: Option<String>,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub version: Option<String>,
80 #[serde(rename = "messageCount")]
81 pub message_count: i64,
82 #[serde(rename = "hasErrors")]
83 pub has_errors: bool,
84 pub status: String,
85 #[serde(
86 rename = "clientDatetime",
87 default,
88 skip_serializing_if = "Option::is_none"
89 )]
90 pub client_datetime: Option<String>,
91 #[serde(rename = "createdAt")]
92 pub created_at: String,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub errors: Option<Vec<Value>>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub transcript: Option<Vec<Value>>,
97 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub extras: Option<HashMap<String, Value>>,
99}
100
101impl Client {
102 pub async fn submit_bug_report(
114 &self,
115 report_data: &Value,
116 signal: Option<CancellationToken>,
117 ) -> Result<BugReportResult> {
118 if report_data.is_null() {
119 return Err(Error::other("acosmi: reportData required"));
120 }
121 let content_str = serde_json::to_string(report_data)
122 .map_err(|e| Error::other(format!("acosmi: marshal reportData: {e}")))?;
123 let body = json!({ "content": content_str }).to_string();
124 let (raw, _) = self
125 .do_json_full::<Value>(
126 http::Method::POST,
127 "/crabcode_cli_feedback",
128 Some(&body),
129 signal,
130 )
131 .await?;
132 let raw = raw.ok_or_else(|| Error::other("/crabcode_cli_feedback: empty response body"))?;
133 unwrap_bare_or_enveloped(raw, "submit_bug_report")
134 }
135
136 pub async fn get_bug_report(
143 &self,
144 bug_id: &str,
145 signal: Option<CancellationToken>,
146 ) -> Result<BugView> {
147 let trimmed = bug_id.trim();
148 if trimmed.is_empty() {
149 return Err(Error::other("acosmi: bugID required"));
150 }
151 let raw: Value = self
153 .do_public_json_full(&format!("/crabcode/bug/{trimmed}"), signal)
154 .await?;
155 unwrap_bare_or_enveloped(raw, "get_bug_report")
156 }
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162
163 #[test]
170 fn unwraps_bare_response_which_is_what_the_gateway_returns() {
171 let raw = serde_json::json!({
172 "feedback_id": "uuid-1",
173 "detail_url": "https://x/chat/crabcode/bug/uuid-1"
174 });
175 let r: BugReportResult = unwrap_bare_or_enveloped(raw, "submit_bug_report").unwrap();
176 assert_eq!(r.feedback_id, "uuid-1");
177 assert_eq!(r.detail_url, "https://x/chat/crabcode/bug/uuid-1");
178 }
179
180 #[test]
181 fn still_unwraps_envelope_response_so_a_gateway_change_does_not_regress() {
182 let raw = serde_json::json!({
183 "code": 0,
184 "msg": "",
185 "data": { "feedback_id": "uuid-2", "detail_url": "https://x/d" }
186 });
187 let r: BugReportResult = unwrap_bare_or_enveloped(raw, "submit_bug_report").unwrap();
188 assert_eq!(r.feedback_id, "uuid-2");
189 }
190
191 #[test]
192 fn missing_required_fields_errors_with_observed_keys() {
193 let raw = serde_json::json!({ "code": 0, "msg": "ok" });
194 let err = unwrap_bare_or_enveloped::<BugReportResult>(raw, "submit_bug_report")
195 .expect_err("must not silently succeed: the report is likely already stored");
196 let msg = err.to_string();
197 assert!(msg.contains("submit_bug_report"), "op missing from: {msg}");
198 assert!(msg.contains("code"), "observed keys missing from: {msg}");
199 assert!(msg.contains("msg"), "observed keys missing from: {msg}");
200 }
201
202 #[test]
203 fn bug_view_unwraps_bare_admin_response() {
204 let raw = serde_json::json!({
205 "id": "uuid-3",
206 "description": "boom",
207 "messageCount": 2,
208 "hasErrors": true,
209 "status": "new",
210 "createdAt": "2026-08-04T00:00:00Z"
211 });
212 let v: BugView = unwrap_bare_or_enveloped(raw, "get_bug_report").unwrap();
213 assert_eq!(v.id, "uuid-3");
214 assert_eq!(v.description, "boom");
215 }
216
217 #[test]
218 fn bug_report_result_wire_snake_case() {
219 let r: BugReportResult = serde_json::from_str(
221 r#"{"feedback_id":"uuid-1","detail_url":"https://x/chat/crabcode/bug/uuid-1"}"#,
222 )
223 .unwrap();
224 assert_eq!(r.feedback_id, "uuid-1");
225 assert_eq!(r.detail_url, "https://x/chat/crabcode/bug/uuid-1");
226 let back = serde_json::to_value(&r).unwrap();
227 assert_eq!(back["feedback_id"], "uuid-1");
228 assert_eq!(back["detail_url"], "https://x/chat/crabcode/bug/uuid-1");
229 }
230
231 #[test]
232 fn bug_view_camel_case_wire() {
233 let v: BugView = serde_json::from_str(
234 r#"{"id":"b1","description":"d","messageCount":3,"hasErrors":true,"status":"open","createdAt":"2026-05-01T00:00:00","extras":{"k":"v"}}"#,
235 )
236 .unwrap();
237 assert_eq!(v.id, "b1");
238 assert_eq!(v.message_count, 3);
239 assert!(v.has_errors);
240 assert_eq!(v.created_at, "2026-05-01T00:00:00");
241 assert!(v.extras.is_some());
242 }
243}