Skip to content

Commit 0482129

Browse files
committed
Merge branch 'main' into fixBugss
2 parents 1b3d2a0 + 6dcb273 commit 0482129

File tree

6 files changed

+58
-27
lines changed

6 files changed

+58
-27
lines changed

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ pub const MAX_CURRENT_WORKING_DIRECTORY_LEN: usize = 256;
77
/// Limit to send the number of messages as part of chat.
88
pub const MAX_CONVERSATION_STATE_HISTORY_LEN: usize = 250;
99

10-
pub const MAX_TOOL_RESPONSE_SIZE: usize = 800_000;
10+
/// Actual service limit is 800_000
11+
pub const MAX_TOOL_RESPONSE_SIZE: usize = 600_000;
1112

12-
/// TODO: Use this to gracefully handle user message sizes.
13-
#[allow(dead_code)]
13+
/// Actual service limit is 600_000
1414
pub const MAX_USER_MESSAGE_SIZE: usize = 600_000;
1515

1616
/// In tokens

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use super::consts::{
2525
DUMMY_TOOL_NAME,
2626
MAX_CHARS,
2727
MAX_CONVERSATION_STATE_HISTORY_LEN,
28+
MAX_USER_MESSAGE_SIZE,
2829
};
2930
use super::context::ContextManager;
3031
use super::hooks::{
@@ -50,7 +51,10 @@ use super::tools::{
5051
ToolOrigin,
5152
ToolSpec,
5253
};
53-
use super::util::serde_value_to_document;
54+
use super::util::{
55+
serde_value_to_document,
56+
truncate_safe,
57+
};
5458
use crate::api_client::model::{
5559
AssistantResponseMessage,
5660
ChatMessage,
@@ -527,6 +531,13 @@ impl ConversationState {
527531
}
528532
}
529533

534+
/// Whether or not it is possible to create a summary out of this conversation state.
535+
///
536+
/// Currently only checks if we have enough messages in the history to create a summary out of.
537+
pub async fn can_create_summary_request(&mut self) -> bool {
538+
self.backend_conversation_state(false, true).await.history.len() >= 2
539+
}
540+
530541
/// Returns a [FigConversationState] capable of replacing the history of the current
531542
/// conversation with a summary generated by the model.
532543
pub async fn create_summary_request(&mut self, custom_prompt: Option<impl AsRef<str>>) -> FigConversationState {
@@ -633,7 +644,8 @@ impl ConversationState {
633644
// something is set.
634645
tool_content.push_str("<tool result redacted>");
635646
}
636-
user.content = UserMessageContent::Prompt { prompt: tool_content };
647+
let prompt = truncate_safe(&tool_content, MAX_USER_MESSAGE_SIZE).to_string();
648+
user.content = UserMessageContent::Prompt { prompt };
637649
}
638650
}
639651
}

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

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -958,26 +958,36 @@ impl ChatContext {
958958
// Errors from attempting to send too large of a conversation history. In
959959
// this case, attempt to automatically compact the history for the user.
960960
crate::api_client::ApiClientError::ContextWindowOverflow => {
961-
let history_too_small = self
962-
.conversation_state
963-
.backend_conversation_state(false, true)
964-
.await
965-
.history
966-
.len()
967-
< 2;
968-
if history_too_small {
969-
print_err!(
970-
"Your conversation is too large - try reducing the size of
971-
the context being passed",
972-
err
973-
);
961+
if !self.conversation_state.can_create_summary_request().await {
962+
execute!(
963+
self.output,
964+
style::SetForegroundColor(Color::Red),
965+
style::Print("Your conversation is too large to continue.\n"),
966+
style::SetForegroundColor(Color::Reset),
967+
style::Print(format!("• Run {} to analyze your context usage\n", "/usage".green())),
968+
style::Print(format!(
969+
"• Run {} to reset your conversation state\n",
970+
"/clear".green()
971+
)),
972+
style::SetAttribute(Attribute::Reset),
973+
style::Print("\n\n"),
974+
)?;
975+
self.conversation_state.reset_next_user_message();
974976
return Ok(ChatState::PromptUser {
975977
tool_uses: None,
976978
pending_tool_index: None,
977979
skip_printing_tools: false,
978980
});
979981
}
980982

983+
execute!(
984+
self.output,
985+
style::SetForegroundColor(Color::Yellow),
986+
style::Print("The context window has overflowed, summarizing the history..."),
987+
style::SetAttribute(Attribute::Reset),
988+
style::Print("\n\n"),
989+
)?;
990+
981991
return Ok(ChatState::CompactHistory {
982992
tool_uses: None,
983993
pending_tool_index: None,
@@ -1223,8 +1233,10 @@ impl ChatContext {
12231233
// Check token usage and display warnings if needed
12241234
if pending_tool_index.is_none() {
12251235
// Only display warnings when not waiting for tool approval
1226-
if let Err(e) = self.display_char_warnings().await {
1227-
warn!("Failed to display character limit warnings: {}", e);
1236+
if self.conversation_state.can_create_summary_request().await {
1237+
if let Err(e) = self.display_char_warnings().await {
1238+
warn!("Failed to display character limit warnings: {}", e);
1239+
}
12281240
}
12291241
}
12301242

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,8 +400,8 @@ impl ToolManagerBuilder {
400400
let msg = eyre::eyre!(msg);
401401
let total = loading_servers.len();
402402
queue_incomplete_load_message(complete, total, &msg, &mut output)?;
403-
output.flush()?;
404403
}
404+
execute!(output, style::Print("\n"),)?;
405405
break;
406406
},
407407
},

crates/q_cli/src/cli/mod.rs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,12 @@ pub enum CliRootCommands {
200200
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
201201
args: Vec<String>,
202202
},
203+
/// Model Context Protocol (MCP)
204+
Mcp {
205+
/// Args for the MCP subcommand (passed through to `qchat mcp …`)
206+
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
207+
args: Vec<String>,
208+
},
203209
/// Inline shell completions
204210
#[command(subcommand)]
205211
Inline(inline::InlineSubcommand),
@@ -235,6 +241,7 @@ impl CliRootCommands {
235241
CliRootCommands::Version { .. } => "version",
236242
CliRootCommands::Dashboard => "dashboard",
237243
CliRootCommands::Chat { .. } => "chat",
244+
CliRootCommands::Mcp { .. } => "mcp",
238245
CliRootCommands::Inline(_) => "inline",
239246
}
240247
}
@@ -344,15 +351,16 @@ impl Cli {
344351
CliRootCommands::Telemetry(subcommand) => subcommand.execute().await,
345352
CliRootCommands::Version { changelog } => Self::print_version(changelog),
346353
CliRootCommands::Dashboard => launch_dashboard(false).await,
347-
CliRootCommands::Chat { args } => Self::execute_chat(Some(args), true).await,
354+
CliRootCommands::Chat { args } => Self::execute_chat("chat", Some(args), true).await,
355+
CliRootCommands::Mcp { args } => Self::execute_chat("mcp", Some(args), true).await,
348356
CliRootCommands::Inline(subcommand) => subcommand.execute(&cli_context).await,
349357
},
350358
// Root command
351-
None => Self::execute_chat(None, true).await,
359+
None => Self::execute_chat("chat", None, true).await,
352360
}
353361
}
354362

355-
pub async fn execute_chat(args: Option<Vec<String>>, enforce_login: bool) -> Result<ExitCode> {
363+
pub async fn execute_chat(subcmd: &str, args: Option<Vec<String>>, enforce_login: bool) -> Result<ExitCode> {
356364
if enforce_login {
357365
assert_logged_in().await?;
358366
}
@@ -369,8 +377,7 @@ impl Cli {
369377
}
370378

371379
let mut cmd = tokio::process::Command::new(home_local_bin()?.join(CHAT_BINARY_NAME));
372-
cmd.arg("chat");
373-
380+
cmd.arg(subcmd);
374381
if let Some(args) = args {
375382
cmd.args(args);
376383
}

crates/q_cli/src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ fn main() -> Result<ExitCode> {
4343

4444
// Hack as clap doesn't expose a custom command help.
4545
if subcommand.as_deref() == Some("chat") && args.any(|arg| ["--help", "-h"].contains(&arg.as_str())) {
46-
runtime.block_on(cli::Cli::execute_chat(Some(vec!["--help".to_owned()]), true))?;
46+
runtime.block_on(cli::Cli::execute_chat("chat", Some(vec!["--help".to_owned()]), true))?;
4747
}
4848

4949
let parsed = match cli::Cli::try_parse() {

0 commit comments

Comments
 (0)