Repository navigation
Expand file tree
/
Copy pathfeedback_cmd.rs
More file actions
576 lines (491 loc) · 17.3 KB
/
Copy pathfeedback_cmd.rs
File metadata and controls
576 lines (491 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Feedback command for Cortex CLI.
//!
//! Provides feedback submission functionality:
//! - Submit bug reports
//! - Report good/bad AI results
//! - Submit general feedback
use anyhow::{Result, bail};
use clap::Parser;
use serde::Serialize;
use std::io::{self, Write};
use std::path::PathBuf;
/// Feedback CLI command.
#[derive(Debug, Parser)]
pub struct FeedbackCli {
#[command(subcommand)]
pub subcommand: Option<FeedbackSubcommand>,
/// Feedback message (if no subcommand)
#[arg(trailing_var_arg = true)]
pub message: Vec<String>,
}
/// Feedback subcommands.
#[derive(Debug, clap::Subcommand)]
pub enum FeedbackSubcommand {
/// Report a bug
Bug(FeedbackBugArgs),
/// Report a good AI result
#[command(visible_alias = "thumbs-up")]
Good(FeedbackResultArgs),
/// Report a bad AI result
#[command(visible_alias = "thumbs-down")]
Bad(FeedbackResultArgs),
/// Submit general feedback
#[command(visible_alias = "comment")]
Submit(FeedbackSubmitArgs),
/// View feedback history
History(FeedbackHistoryArgs),
}
/// Arguments for bug report.
#[derive(Debug, Parser)]
pub struct FeedbackBugArgs {
/// Bug description
#[arg(trailing_var_arg = true)]
pub description: Vec<String>,
/// Include recent logs with the report
#[arg(long)]
pub include_logs: bool,
/// Session ID to attach to the bug report
#[arg(long, short = 's')]
pub session: Option<String>,
/// Output as JSON (for scripting)
#[arg(long)]
pub json: bool,
}
/// Arguments for result feedback (good/bad).
#[derive(Debug, Parser)]
pub struct FeedbackResultArgs {
/// Comment about the result
#[arg(trailing_var_arg = true)]
pub comment: Vec<String>,
/// Session ID to attach
#[arg(long, short = 's')]
pub session: Option<String>,
}
/// Arguments for general feedback submission.
#[derive(Debug, Parser)]
pub struct FeedbackSubmitArgs {
/// Feedback message
#[arg(trailing_var_arg = true)]
pub message: Vec<String>,
/// Include recent logs
#[arg(long)]
pub include_logs: bool,
/// Session ID to attach
#[arg(long, short = 's')]
pub session: Option<String>,
/// Feedback category
#[arg(long, short = 'c')]
pub category: Option<String>,
}
/// Arguments for viewing feedback history.
#[derive(Debug, Parser)]
pub struct FeedbackHistoryArgs {
/// Number of entries to show
#[arg(long, short = 'n', default_value = "10")]
pub limit: usize,
/// Output as JSON
#[arg(long)]
pub json: bool,
}
/// Feedback entry for history.
#[derive(Debug, Serialize, serde::Deserialize)]
struct FeedbackEntry {
id: String,
timestamp: String,
category: String,
message: String,
#[serde(skip_serializing_if = "Option::is_none")]
session_id: Option<String>,
}
/// Get the feedback directory.
fn get_feedback_dir() -> PathBuf {
dirs::home_dir()
.map(|h| h.join(".cortex").join("feedback"))
.unwrap_or_else(|| PathBuf::from(".cortex/feedback"))
}
impl FeedbackCli {
/// Run the feedback command.
pub async fn run(self) -> Result<()> {
match self.subcommand {
Some(FeedbackSubcommand::Bug(args)) => run_bug(args).await,
Some(FeedbackSubcommand::Good(args)) => run_good(args).await,
Some(FeedbackSubcommand::Bad(args)) => run_bad(args).await,
Some(FeedbackSubcommand::Submit(args)) => run_submit(args).await,
Some(FeedbackSubcommand::History(args)) => run_history(args).await,
None => {
// Handle direct feedback message
let message = self.message.join(" ");
if message.is_empty() {
println!("Cortex Feedback");
println!("{}", "=".repeat(50));
println!();
println!("Submit feedback to help improve Cortex:");
println!();
println!(" cortex feedback bug <description> Report a bug");
println!(" cortex feedback good [comment] Report good result");
println!(" cortex feedback bad [comment] Report bad result");
println!(" cortex feedback submit <message> Submit general feedback");
println!();
println!("Options:");
println!(" --include-logs Include recent logs");
println!(" --session <id> Attach session to feedback");
println!();
println!("Example:");
println!(" cortex feedback bug \"AI gave wrong answer\" --session abc123");
} else {
// Submit as general feedback
run_submit(FeedbackSubmitArgs {
message: self.message,
include_logs: false,
session: None,
category: None,
})
.await?;
}
Ok(())
}
}
}
}
async fn run_bug(args: FeedbackBugArgs) -> Result<()> {
let description = args.description.join(" ");
if description.is_empty() {
// Interactive mode
println!("Bug Report");
println!("{}", "-".repeat(40));
println!("Please describe the bug you encountered.");
println!("Press Enter twice when done.");
println!();
let description = read_multiline_input()?;
if description.is_empty() {
bail!("Bug description cannot be empty.");
}
submit_feedback(
"bug",
&description,
args.session.as_deref(),
args.include_logs,
)
.await?;
} else {
submit_feedback(
"bug",
&description,
args.session.as_deref(),
args.include_logs,
)
.await?;
}
if args.json {
println!(
"{}",
serde_json::json!({
"status": "submitted",
"category": "bug"
})
);
} else {
println!("Thank you for reporting this bug!");
println!("Your feedback helps us improve Cortex.");
}
Ok(())
}
async fn run_good(args: FeedbackResultArgs) -> Result<()> {
let comment = args.comment.join(" ");
submit_feedback("good_result", &comment, args.session.as_deref(), false).await?;
println!("Thank you for the positive feedback!");
Ok(())
}
async fn run_bad(args: FeedbackResultArgs) -> Result<()> {
let comment = args.comment.join(" ");
if comment.is_empty() {
println!("What went wrong with the AI result?");
let comment = read_single_line()?;
submit_feedback("bad_result", &comment, args.session.as_deref(), false).await?;
} else {
submit_feedback("bad_result", &comment, args.session.as_deref(), false).await?;
}
println!("Thank you for the feedback! We'll work to improve.");
Ok(())
}
async fn run_submit(args: FeedbackSubmitArgs) -> Result<()> {
let message = args.message.join(" ");
if message.is_empty() {
// Interactive mode
println!("Submit Feedback");
println!("{}", "-".repeat(40));
println!("Please enter your feedback:");
println!();
let message = read_multiline_input()?;
if message.is_empty() {
bail!("Feedback message cannot be empty.");
}
let category = args.category.as_deref().unwrap_or("general");
submit_feedback(
category,
&message,
args.session.as_deref(),
args.include_logs,
)
.await?;
} else {
let category = args.category.as_deref().unwrap_or("general");
submit_feedback(
category,
&message,
args.session.as_deref(),
args.include_logs,
)
.await?;
}
println!("Thank you for your feedback!");
Ok(())
}
async fn run_history(args: FeedbackHistoryArgs) -> Result<()> {
let feedback_dir = get_feedback_dir();
if !feedback_dir.exists() {
if args.json {
println!("[]");
} else {
println!("No feedback history found.");
}
return Ok(());
}
let mut entries = Vec::new();
// Read feedback files
if let Ok(dir_entries) = std::fs::read_dir(&feedback_dir) {
for entry in dir_entries.flatten() {
let path = entry.path();
if path.extension().is_some_and(|e| e == "json")
&& let Ok(content) = std::fs::read_to_string(&path)
&& let Ok(entry) = serde_json::from_str::<FeedbackEntry>(&content)
{
entries.push(entry);
}
}
}
// Sort by timestamp (newest first)
entries.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
// Apply limit
entries.truncate(args.limit);
if args.json {
println!("{}", serde_json::to_string_pretty(&entries)?);
} else if entries.is_empty() {
println!("No feedback history found.");
} else {
println!("Feedback History:");
println!("{}", "-".repeat(60));
for entry in &entries {
println!("[{}] {} - {}", entry.timestamp, entry.category, entry.id);
let truncated = if entry.message.len() > 100 {
format!("{}...", &entry.message[..100])
} else {
entry.message.clone()
};
println!(" {}", truncated);
println!();
}
}
Ok(())
}
/// Submit feedback (save locally and optionally upload).
async fn submit_feedback(
category: &str,
message: &str,
session_id: Option<&str>,
include_logs: bool,
) -> Result<()> {
let feedback_dir = get_feedback_dir();
std::fs::create_dir_all(&feedback_dir)?;
let id = uuid::Uuid::new_v4().to_string();
let timestamp = chrono::Utc::now().to_rfc3339();
let entry = FeedbackEntry {
id: id.clone(),
timestamp: timestamp.clone(),
category: category.to_string(),
message: message.to_string(),
session_id: session_id.map(|s| s.to_string()),
};
// Save locally
let filename = format!("feedback-{}.json", &id[..8]);
let filepath = feedback_dir.join(&filename);
std::fs::write(&filepath, serde_json::to_string_pretty(&entry)?)?;
// Log the feedback
tracing::info!(
"Feedback submitted: category={}, id={}, include_logs={}",
category,
id,
include_logs
);
Ok(())
}
/// Read multiline input from stdin (ends with empty line).
fn read_multiline_input() -> Result<String> {
let stdin = io::stdin();
let mut lines = Vec::new();
loop {
print!("> ");
io::stdout().flush()?;
let mut line = String::new();
stdin.read_line(&mut line)?;
let trimmed = line.trim();
if trimmed.is_empty() {
break;
}
lines.push(trimmed.to_string());
}
Ok(lines.join("\n"))
}
/// Read a single line from stdin.
fn read_single_line() -> Result<String> {
print!("> ");
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_feedback_entry_serialization_with_session() {
let entry = FeedbackEntry {
id: "test-id-123".to_string(),
timestamp: "2024-01-01T00:00:00Z".to_string(),
category: "bug".to_string(),
message: "Test bug report message".to_string(),
session_id: Some("session-abc-456".to_string()),
};
let json = serde_json::to_string(&entry).expect("serialization should succeed");
assert!(json.contains("test-id-123"), "JSON should contain the id");
assert!(
json.contains("2024-01-01T00:00:00Z"),
"JSON should contain the timestamp"
);
assert!(json.contains("bug"), "JSON should contain the category");
assert!(
json.contains("Test bug report message"),
"JSON should contain the message"
);
assert!(
json.contains("session-abc-456"),
"JSON should contain the session_id"
);
assert!(
json.contains("session_id"),
"JSON should contain session_id field name"
);
}
#[test]
fn test_feedback_entry_serialization_without_session() {
let entry = FeedbackEntry {
id: "test-id-789".to_string(),
timestamp: "2024-06-15T12:30:00Z".to_string(),
category: "general".to_string(),
message: "General feedback without session".to_string(),
session_id: None,
};
let json = serde_json::to_string(&entry).expect("serialization should succeed");
assert!(json.contains("test-id-789"), "JSON should contain the id");
assert!(json.contains("general"), "JSON should contain the category");
assert!(
json.contains("General feedback without session"),
"JSON should contain the message"
);
// session_id should NOT appear when None due to skip_serializing_if
assert!(
!json.contains("session_id"),
"JSON should NOT contain session_id when None"
);
}
#[test]
fn test_feedback_entry_deserialization_with_session() {
let json = r#"{
"id": "deserialize-test-id",
"timestamp": "2024-03-20T10:15:30Z",
"category": "bad_result",
"message": "AI gave incorrect answer",
"session_id": "session-xyz-789"
}"#;
let entry: FeedbackEntry =
serde_json::from_str(json).expect("deserialization should succeed");
assert_eq!(entry.id, "deserialize-test-id");
assert_eq!(entry.timestamp, "2024-03-20T10:15:30Z");
assert_eq!(entry.category, "bad_result");
assert_eq!(entry.message, "AI gave incorrect answer");
assert_eq!(entry.session_id, Some("session-xyz-789".to_string()));
}
#[test]
fn test_feedback_entry_deserialization_without_session() {
let json = r#"{
"id": "no-session-id",
"timestamp": "2024-04-10T08:00:00Z",
"category": "good_result",
"message": "AI response was helpful"
}"#;
let entry: FeedbackEntry =
serde_json::from_str(json).expect("deserialization should succeed");
assert_eq!(entry.id, "no-session-id");
assert_eq!(entry.timestamp, "2024-04-10T08:00:00Z");
assert_eq!(entry.category, "good_result");
assert_eq!(entry.message, "AI response was helpful");
assert_eq!(entry.session_id, None);
}
#[test]
fn test_feedback_entry_roundtrip_with_session() {
let original = FeedbackEntry {
id: "roundtrip-test".to_string(),
timestamp: "2024-05-25T16:45:00Z".to_string(),
category: "bug".to_string(),
message: "Roundtrip test with special chars: é, ñ, 中文".to_string(),
session_id: Some("session-roundtrip".to_string()),
};
let json = serde_json::to_string(&original).expect("serialization should succeed");
let parsed: FeedbackEntry =
serde_json::from_str(&json).expect("deserialization should succeed");
assert_eq!(parsed.id, original.id);
assert_eq!(parsed.timestamp, original.timestamp);
assert_eq!(parsed.category, original.category);
assert_eq!(parsed.message, original.message);
assert_eq!(parsed.session_id, original.session_id);
}
#[test]
fn test_feedback_entry_roundtrip_without_session() {
let original = FeedbackEntry {
id: "roundtrip-no-session".to_string(),
timestamp: "2024-07-01T00:00:00Z".to_string(),
category: "general".to_string(),
message: "Roundtrip test without session".to_string(),
session_id: None,
};
let json = serde_json::to_string(&original).expect("serialization should succeed");
let parsed: FeedbackEntry =
serde_json::from_str(&json).expect("deserialization should succeed");
assert_eq!(parsed.id, original.id);
assert_eq!(parsed.timestamp, original.timestamp);
assert_eq!(parsed.category, original.category);
assert_eq!(parsed.message, original.message);
assert_eq!(parsed.session_id, original.session_id);
}
#[test]
fn test_feedback_entry_pretty_serialization() {
let entry = FeedbackEntry {
id: "pretty-test".to_string(),
timestamp: "2024-08-12T14:30:00Z".to_string(),
category: "bug".to_string(),
message: "Testing pretty print".to_string(),
session_id: Some("session-pretty".to_string()),
};
let pretty_json =
serde_json::to_string_pretty(&entry).expect("pretty serialization should succeed");
// Pretty JSON should contain newlines
assert!(
pretty_json.contains('\n'),
"Pretty JSON should contain newlines"
);
// Should still be valid and parseable
let parsed: FeedbackEntry =
serde_json::from_str(&pretty_json).expect("deserialization should succeed");
assert_eq!(parsed.id, entry.id);
}
}