Skip to content

Commit f647ce4

Browse files
chore: apply misc fixes and changes from the autocomplete repo (#2301)
- Adding extra debug auth checks - Fixing /editor and /compact argument parsing - Not including multi-line prompts in the chat hinting - Fixing broken build
1 parent 4414c5c commit f647ce4

File tree

4 files changed

+61
-77
lines changed

4 files changed

+61
-77
lines changed

crates/chat-cli/src/auth/builder_id.rs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ use time::OffsetDateTime;
4949
use tracing::{
5050
debug,
5151
error,
52+
info,
5253
trace,
5354
warn,
5455
};
@@ -302,6 +303,7 @@ impl BuilderIdToken {
302303

303304
/// Load the token from the keychain, refresh the token if it is expired and return it
304305
pub async fn load(database: &Database) -> Result<Option<Self>, AuthError> {
306+
trace!("loading builder id token from the secret store");
305307
match database.get_secret(Self::SECRET_KEY).await {
306308
Ok(Some(secret)) => {
307309
let token: Option<Self> = serde_json::from_str(&secret.0)?;
@@ -314,6 +316,7 @@ impl BuilderIdToken {
314316
trace!("token is expired, refreshing");
315317
token.refresh_token(&client, database, &region).await
316318
} else {
319+
trace!(?token, "found a valid token");
317320
Ok(Some(token))
318321
}
319322
},
@@ -342,6 +345,7 @@ impl BuilderIdToken {
342345
region: &Region,
343346
) -> Result<Option<Self>, AuthError> {
344347
let Some(refresh_token) = &self.refresh_token else {
348+
warn!("no refresh token was found");
345349
// if the token is expired and has no refresh token, delete it
346350
if let Err(err) = self.delete(database).await {
347351
error!(?err, "Failed to delete builder id token");
@@ -350,6 +354,7 @@ impl BuilderIdToken {
350354
return Ok(None);
351355
};
352356

357+
trace!("loading device registration from secret store");
353358
let registration = match DeviceRegistration::load_from_secret_store(database, region).await? {
354359
Some(registration) if registration.oauth_flow == self.oauth_flow => registration,
355360
// If the OIDC client registration is for a different oauth flow or doesn't exist, then
@@ -525,8 +530,22 @@ pub async fn poll_create_token(
525530

526531
pub async fn is_logged_in(database: &mut Database) -> bool {
527532
// Check for BuilderId if not using Sigv4
528-
std::env::var("AMAZON_Q_SIGV4").is_ok_and(|v| !v.is_empty())
529-
|| matches!(BuilderIdToken::load(database).await, Ok(Some(_)))
533+
if std::env::var("AMAZON_Q_SIGV4").is_ok_and(|v| !v.is_empty()) {
534+
debug!("logged in using sigv4 credentials");
535+
return true;
536+
}
537+
538+
match BuilderIdToken::load(database).await {
539+
Ok(Some(_)) => true,
540+
Ok(None) => {
541+
info!("not logged in - no valid token found");
542+
false
543+
},
544+
Err(err) => {
545+
warn!(?err, "failed to try to load a builder id token");
546+
false
547+
},
548+
}
530549
}
531550

532551
pub async fn logout(database: &mut Database) -> Result<(), AuthError> {

crates/chat-cli/src/cli/chat/cli/compact.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ To disable this behavior, run: `q settings chat.disableAutoCompaction true`"
3333
)]
3434
pub struct CompactArgs {
3535
/// The prompt to use when generating the summary
36-
prompt: Option<String>,
36+
prompt: Vec<String>,
3737
#[arg(long)]
3838
show_summary: bool,
3939
/// The number of user and assistant message pairs to exclude from the summarization.
@@ -51,8 +51,14 @@ pub struct CompactArgs {
5151
impl CompactArgs {
5252
pub async fn execute(self, os: &Os, session: &mut ChatSession) -> Result<ChatState, ChatError> {
5353
let default = CompactStrategy::default();
54+
let prompt = if self.prompt.is_empty() {
55+
None
56+
} else {
57+
Some(self.prompt.join(" "))
58+
};
59+
5460
session
55-
.compact_history(os, self.prompt, self.show_summary, CompactStrategy {
61+
.compact_history(os, prompt, self.show_summary, CompactStrategy {
5662
messages_to_exclude: self.messages_to_exclude.unwrap_or(default.messages_to_exclude),
5763
truncate_large_messages: self.truncate_large_messages.unwrap_or(default.truncate_large_messages),
5864
max_message_length: self.max_message_length.map_or(default.max_message_length, |v| {

crates/chat-cli/src/cli/chat/cli/editor.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,18 @@ use crate::cli::chat::{
1616
#[deny(missing_docs)]
1717
#[derive(Debug, PartialEq, Args)]
1818
pub struct EditorArgs {
19-
pub initial_text: Option<String>,
19+
pub initial_text: Vec<String>,
2020
}
2121

2222
impl EditorArgs {
2323
pub async fn execute(self, session: &mut ChatSession) -> Result<ChatState, ChatError> {
24-
let content = match open_editor(self.initial_text) {
24+
let initial_text = if self.initial_text.is_empty() {
25+
None
26+
} else {
27+
Some(self.initial_text.join(" "))
28+
};
29+
30+
let content = match open_editor(initial_text) {
2531
Ok(content) => content,
2632
Err(err) => {
2733
execute!(

crates/chat-cli/src/cli/chat/prompt.rs

Lines changed: 24 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -221,14 +221,7 @@ pub struct ChatHinter {
221221

222222
impl ChatHinter {
223223
/// Creates a new ChatHinter instance
224-
pub fn new(os: &Os) -> Self {
225-
// Default to disabled if setting doesn't exist
226-
let history_hints_enabled = os
227-
.database
228-
.settings
229-
.get_bool(Setting::ChatEnableHistoryHints)
230-
.unwrap_or(false);
231-
224+
pub fn new(history_hints_enabled: bool) -> Self {
232225
Self {
233226
history: Vec::new(),
234227
history_hints_enabled,
@@ -237,7 +230,8 @@ impl ChatHinter {
237230

238231
/// Updates the history with a new command
239232
pub fn update_history(&mut self, command: &str) {
240-
if !command.trim().is_empty() {
233+
let command = command.trim();
234+
if !command.is_empty() && !command.contains('\n') && !command.contains('\r') {
241235
self.history.push(command.to_string());
242236
}
243237
}
@@ -382,11 +376,19 @@ pub fn rl(
382376
.completion_type(CompletionType::List)
383377
.edit_mode(edit_mode)
384378
.build();
379+
380+
// Default to disabled if setting doesn't exist
381+
let history_hints_enabled = os
382+
.database
383+
.settings
384+
.get_bool(Setting::ChatEnableHistoryHints)
385+
.unwrap_or(false);
385386
let h = ChatHelper {
386387
completer: ChatCompleter::new(sender, receiver),
387-
hinter: ChatHinter::new(os),
388+
hinter: ChatHinter::new(history_hints_enabled),
388389
validator: MultiLineValidator,
389390
};
391+
390392
let mut rl = Editor::with_config(config)?;
391393
rl.set_helper(Some(h));
392394

@@ -417,27 +419,6 @@ mod tests {
417419
use rustyline::highlight::Highlighter;
418420

419421
use super::*;
420-
use crate::database::Settings;
421-
use crate::os::{
422-
Fs,
423-
Os,
424-
};
425-
426-
// Helper function to create a mock Os for testing
427-
fn create_mock_os() -> Os {
428-
let mut os = Os {
429-
database: crate::database::Database {
430-
pool: r2d2::Pool::builder()
431-
.build(r2d2_sqlite::SqliteConnectionManager::memory())
432-
.unwrap(),
433-
settings: Settings::default(),
434-
},
435-
fs: Fs::new(),
436-
env: crate::os::Env::new(),
437-
telemetry: crate::telemetry::Telemetry::new(),
438-
};
439-
os
440-
}
441422

442423
#[test]
443424
fn test_chat_completer_command_completion() {
@@ -484,10 +465,9 @@ mod tests {
484465
fn test_highlight_prompt_basic() {
485466
let (prompt_request_sender, _) = std::sync::mpsc::channel::<Option<String>>();
486467
let (_, prompt_response_receiver) = std::sync::mpsc::channel::<Vec<String>>();
487-
let mock_os = create_mock_os();
488468
let helper = ChatHelper {
489469
completer: ChatCompleter::new(prompt_request_sender, prompt_response_receiver),
490-
hinter: ChatHinter::new(&mock_os),
470+
hinter: ChatHinter::new(true),
491471
validator: MultiLineValidator,
492472
};
493473

@@ -501,10 +481,9 @@ mod tests {
501481
fn test_highlight_prompt_with_warning() {
502482
let (prompt_request_sender, _) = std::sync::mpsc::channel::<Option<String>>();
503483
let (_, prompt_response_receiver) = std::sync::mpsc::channel::<Vec<String>>();
504-
let mock_os = create_mock_os();
505484
let helper = ChatHelper {
506485
completer: ChatCompleter::new(prompt_request_sender, prompt_response_receiver),
507-
hinter: ChatHinter::new(&mock_os),
486+
hinter: ChatHinter::new(true),
508487
validator: MultiLineValidator,
509488
};
510489

@@ -518,10 +497,9 @@ mod tests {
518497
fn test_highlight_prompt_with_profile() {
519498
let (prompt_request_sender, _) = std::sync::mpsc::channel::<Option<String>>();
520499
let (_, prompt_response_receiver) = std::sync::mpsc::channel::<Vec<String>>();
521-
let mock_os = create_mock_os();
522500
let helper = ChatHelper {
523501
completer: ChatCompleter::new(prompt_request_sender, prompt_response_receiver),
524-
hinter: ChatHinter::new(&mock_os),
502+
hinter: ChatHinter::new(true),
525503
validator: MultiLineValidator,
526504
};
527505

@@ -535,10 +513,9 @@ mod tests {
535513
fn test_highlight_prompt_with_profile_and_warning() {
536514
let (prompt_request_sender, _) = std::sync::mpsc::channel::<Option<String>>();
537515
let (_, prompt_response_receiver) = std::sync::mpsc::channel::<Vec<String>>();
538-
let mock_os = create_mock_os();
539516
let helper = ChatHelper {
540517
completer: ChatCompleter::new(prompt_request_sender, prompt_response_receiver),
541-
hinter: ChatHinter::new(&mock_os),
518+
hinter: ChatHinter::new(true),
542519
validator: MultiLineValidator,
543520
};
544521

@@ -555,10 +532,9 @@ mod tests {
555532
fn test_highlight_prompt_invalid_format() {
556533
let (prompt_request_sender, _) = std::sync::mpsc::channel::<Option<String>>();
557534
let (_, prompt_response_receiver) = std::sync::mpsc::channel::<Vec<String>>();
558-
let mock_os = create_mock_os();
559535
let helper = ChatHelper {
560536
completer: ChatCompleter::new(prompt_request_sender, prompt_response_receiver),
561-
hinter: ChatHinter::new(&mock_os),
537+
hinter: ChatHinter::new(true),
562538
validator: MultiLineValidator,
563539
};
564540

@@ -570,8 +546,7 @@ mod tests {
570546

571547
#[test]
572548
fn test_chat_hinter_command_hint() {
573-
let mock_os = create_mock_os();
574-
let hinter = ChatHinter::new(&mock_os);
549+
let hinter = ChatHinter::new(true);
575550

576551
// Test hint for a command
577552
let line = "/he";
@@ -591,51 +566,29 @@ mod tests {
591566
let pos = line.len();
592567
let hint = hinter.hint(line, pos, &ctx);
593568
assert_eq!(hint, None);
594-
}
595-
596-
#[test]
597-
fn test_chat_hinter_history_hint_disabled() {
598-
let mock_os = create_mock_os();
599-
let mut hinter = ChatHinter::new(&mock_os); // Default is disabled
600-
601-
// Add some history
602-
hinter.update_history("Hello, world!");
603-
hinter.update_history("How are you?");
604569

605-
// Test hint from history - should be None since history hints are disabled
606-
let line = "How";
570+
// Test hint for a multi-line command
571+
let line = "/abcd\nefg";
607572
let pos = line.len();
608-
let empty_history = DefaultHistory::new();
609-
let ctx = Context::new(&empty_history);
610-
611573
let hint = hinter.hint(line, pos, &ctx);
612574
assert_eq!(hint, None);
613575
}
614576

615577
#[test]
616-
fn test_chat_hinter_history_hint_enabled() {
617-
let mut mock_os = create_mock_os();
618-
619-
// Enable history hints
620-
mock_os
621-
.database
622-
.settings
623-
.0
624-
.insert("chat.enableHistoryHints".to_string(), serde_json::Value::Bool(true));
625-
626-
let mut hinter = ChatHinter::new(&mock_os);
578+
fn test_chat_hinter_history_hint_disabled() {
579+
let mut hinter = ChatHinter::new(false);
627580

628581
// Add some history
629582
hinter.update_history("Hello, world!");
630583
hinter.update_history("How are you?");
631584

632-
// Test hint from history - should work since history hints are enabled
585+
// Test hint from history - should be None since history hints are disabled
633586
let line = "How";
634587
let pos = line.len();
635588
let empty_history = DefaultHistory::new();
636589
let ctx = Context::new(&empty_history);
637590

638591
let hint = hinter.hint(line, pos, &ctx);
639-
assert_eq!(hint, Some(" are you?".to_string()));
592+
assert_eq!(hint, None);
640593
}
641594
}

0 commit comments

Comments
 (0)