use crate::core::client::Client;
use crate::shared::{Error, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use tokio_util::sync::CancellationToken;
fn unwrap_bare_or_enveloped<T: serde::de::DeserializeOwned>(raw: Value, op: &str) -> Result<T> {
let observed_keys = || -> String {
match raw.as_object() {
Some(map) if !map.is_empty() => map.keys().cloned().collect::<Vec<_>>().join(","),
_ => "<none>".to_string(),
}
};
let inner = raw.as_object().and_then(|m| m.get("data")).cloned();
if let Ok(value) = serde_json::from_value::<T>(raw.clone()) {
return Ok(value);
}
if let Some(inner) = inner {
if let Ok(value) = serde_json::from_value::<T>(inner) {
return Ok(value);
}
}
Err(Error::other(format!(
"acosmi: {op}: gateway accepted the request but the response is missing required fields (observed keys: {})",
observed_keys()
)))
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BugReportResult {
pub feedback_id: String,
pub detail_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BugView {
pub id: String,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub platform: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub terminal: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(rename = "messageCount")]
pub message_count: i64,
#[serde(rename = "hasErrors")]
pub has_errors: bool,
pub status: String,
#[serde(
rename = "clientDatetime",
default,
skip_serializing_if = "Option::is_none"
)]
pub client_datetime: Option<String>,
#[serde(rename = "createdAt")]
pub created_at: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub errors: Option<Vec<Value>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub transcript: Option<Vec<Value>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub extras: Option<HashMap<String, Value>>,
}
impl Client {
pub async fn submit_bug_report(
&self,
report_data: &Value,
signal: Option<CancellationToken>,
) -> Result<BugReportResult> {
if report_data.is_null() {
return Err(Error::other("acosmi: reportData required"));
}
let content_str = serde_json::to_string(report_data)
.map_err(|e| Error::other(format!("acosmi: marshal reportData: {e}")))?;
let body = json!({ "content": content_str }).to_string();
let (raw, _) = self
.do_json_full::<Value>(
http::Method::POST,
"/crabcode_cli_feedback",
Some(&body),
signal,
)
.await?;
let raw = raw.ok_or_else(|| Error::other("/crabcode_cli_feedback: empty response body"))?;
unwrap_bare_or_enveloped(raw, "submit_bug_report")
}
pub async fn get_bug_report(
&self,
bug_id: &str,
signal: Option<CancellationToken>,
) -> Result<BugView> {
let trimmed = bug_id.trim();
if trimmed.is_empty() {
return Err(Error::other("acosmi: bugID required"));
}
let raw: Value = self
.do_public_json_full(&format!("/crabcode/bug/{trimmed}"), signal)
.await?;
unwrap_bare_or_enveloped(raw, "get_bug_report")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unwraps_bare_response_which_is_what_the_gateway_returns() {
let raw = serde_json::json!({
"feedback_id": "uuid-1",
"detail_url": "https://x/chat/crabcode/bug/uuid-1"
});
let r: BugReportResult = unwrap_bare_or_enveloped(raw, "submit_bug_report").unwrap();
assert_eq!(r.feedback_id, "uuid-1");
assert_eq!(r.detail_url, "https://x/chat/crabcode/bug/uuid-1");
}
#[test]
fn still_unwraps_envelope_response_so_a_gateway_change_does_not_regress() {
let raw = serde_json::json!({
"code": 0,
"msg": "",
"data": { "feedback_id": "uuid-2", "detail_url": "https://x/d" }
});
let r: BugReportResult = unwrap_bare_or_enveloped(raw, "submit_bug_report").unwrap();
assert_eq!(r.feedback_id, "uuid-2");
}
#[test]
fn missing_required_fields_errors_with_observed_keys() {
let raw = serde_json::json!({ "code": 0, "msg": "ok" });
let err = unwrap_bare_or_enveloped::<BugReportResult>(raw, "submit_bug_report")
.expect_err("must not silently succeed: the report is likely already stored");
let msg = err.to_string();
assert!(msg.contains("submit_bug_report"), "op missing from: {msg}");
assert!(msg.contains("code"), "observed keys missing from: {msg}");
assert!(msg.contains("msg"), "observed keys missing from: {msg}");
}
#[test]
fn bug_view_unwraps_bare_admin_response() {
let raw = serde_json::json!({
"id": "uuid-3",
"description": "boom",
"messageCount": 2,
"hasErrors": true,
"status": "new",
"createdAt": "2026-08-04T00:00:00Z"
});
let v: BugView = unwrap_bare_or_enveloped(raw, "get_bug_report").unwrap();
assert_eq!(v.id, "uuid-3");
assert_eq!(v.description, "boom");
}
#[test]
fn bug_report_result_wire_snake_case() {
let r: BugReportResult = serde_json::from_str(
r#"{"feedback_id":"uuid-1","detail_url":"https://x/chat/crabcode/bug/uuid-1"}"#,
)
.unwrap();
assert_eq!(r.feedback_id, "uuid-1");
assert_eq!(r.detail_url, "https://x/chat/crabcode/bug/uuid-1");
let back = serde_json::to_value(&r).unwrap();
assert_eq!(back["feedback_id"], "uuid-1");
assert_eq!(back["detail_url"], "https://x/chat/crabcode/bug/uuid-1");
}
#[test]
fn bug_view_camel_case_wire() {
let v: BugView = serde_json::from_str(
r#"{"id":"b1","description":"d","messageCount":3,"hasErrors":true,"status":"open","createdAt":"2026-05-01T00:00:00","extras":{"k":"v"}}"#,
)
.unwrap();
assert_eq!(v.id, "b1");
assert_eq!(v.message_count, 3);
assert!(v.has_errors);
assert_eq!(v.created_at, "2026-05-01T00:00:00");
assert!(v.extras.is_some());
}
}