Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(ai): make stop button actually cancel the agent stream

Abeautifulsnowffc027935239
diff --git a/crates/dbx-core/src/agent_loop.rs b/crates/dbx-core/src/agent_loop.rs
index 5f3d1d7d65..f0a1fc4b90 100644
--- a/crates/dbx-core/src/agent_loop.rs
+++ b/crates/dbx-core/src/agent_loop.rs
@@ -16,7 +16,6 @@ use crate::token_usage::TokenUsage;
/// Maximum number of agent loop turns to prevent infinite loops.
const MAX_AGENT_TURNS: u32 = 30;
-const AGENT_CANCELLED_ERROR: &str = "Agent loop cancelled";
const MAX_TOOL_RESULT_CONTEXT_CHARS: usize = 12_000;
const TOOL_RESULT_HEAD_CHARS: usize = 4_000;
const TOOL_RESULT_TAIL_CHARS: usize = 4_000;
@@ -254,7 +253,7 @@ pub async fn run_agent_loop(
}
break;
}
- Err(err) if err == AGENT_CANCELLED_ERROR => {
+ Err(err) if err == ai::AGENT_CANCELLED_ERROR => {
final_text = take_text(&accumulated_text);
loop_exit = LoopExit::Cancelled;
break;
@@ -321,6 +320,14 @@ pub async fn run_agent_loop(
}
}
+ // Honor a cancellation that arrived after the stream finished but before we
+ // run the requested tools; otherwise a long execute_query would keep running.
+ if cancelled.notified().now_or_never().is_some() {
+ final_text = accumulated_text;
+ loop_exit = LoopExit::Cancelled;
+ break;
+ }
+
// Execute each tool call
// Emit all ToolCallStart events first
for tc in &collected_tool_calls {
@@ -631,7 +638,7 @@ async fn stream_with_tools(
) -> Result<(Vec<ToolCall>, Option<TokenUsage>), String> {
// Return early if the user cancelled before the LLM call started.
if cancelled.notified().now_or_never().is_some() {
- return Err(AGENT_CANCELLED_ERROR.to_string());
+ return Err(ai::AGENT_CANCELLED_ERROR.to_string());
}
ai::stream_with_tools(config, request, session_id, tools, cancelled, on_chunk).await
@@ -665,7 +672,7 @@ async fn run_agent_loop_text_only(
messages: &[AiMessage],
agent_ctx: &AgentLoopContext,
on_event: impl Fn(AgentEvent) + Send + Sync + 'static,
- _cancelled: &Notify,
+ cancelled: &Notify,
max_tokens: Option<u32>,
task_contract: Option<&AiTaskContract>,
) -> Result<String, String> {
@@ -673,6 +680,12 @@ async fn run_agent_loop_text_only(
// even without tool access.
let enriched_prompt = build_schema_prompt(agent_ctx, system_prompt).await;
+ // Honor a cancellation requested while loading schema context.
+ if cancelled.notified().now_or_never().is_some() {
+ on_event(AgentEvent::AgentEnd { input_tokens: None, output_tokens: None });
+ return Ok("Agent run was cancelled before producing output.".to_string());
+ }
+
let mut request = AiCompletionRequest {
config: config.clone(),
system_prompt: enriched_prompt,
@@ -683,7 +696,14 @@ async fn run_agent_loop_text_only(
for attempt in 0..=MAX_CONTRACT_REPAIR_ATTEMPTS {
// Use non-streaming completions so contract repair can suppress incomplete drafts.
- let result = ai::complete(&request).await?;
+ // Race the (non-cancellable) HTTP call against cancellation so Stop still works.
+ let result = tokio::select! {
+ result = ai::complete(&request) => result?,
+ _ = cancelled.notified() => {
+ on_event(AgentEvent::AgentEnd { input_tokens: None, output_tokens: None });
+ return Ok("Agent run was cancelled before producing output.".to_string());
+ }
+ };
match validate_final_answer(task_contract, &result) {
FinalAnswerCheck::Satisfied => {
on_event(AgentEvent::TextDelta { delta: result.clone() });
diff --git a/crates/dbx-core/src/ai.rs b/crates/dbx-core/src/ai.rs
index f2d68be46f..bc3dc6ffdb 100644
--- a/crates/dbx-core/src/ai.rs
+++ b/crates/dbx-core/src/ai.rs
@@ -34,6 +34,14 @@ pub async fn unregister_stream(session_id: &str) {
AI_STREAMS.write().await.remove(session_id);
}
+/// Error returned by streaming functions when the user cancels mid-stream.
+///
+/// `run_agent_loop` matches on this exact string to distinguish a cancellation
+/// from a normal completion and stop the loop cleanly. Streaming functions MUST
+/// return this (not `Ok`) when `cancelled` fires, otherwise the agent loop
+/// treats the truncated turn as a normal completion and keeps going.
+pub const AGENT_CANCELLED_ERROR: &str = "Agent loop cancelled";
+
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
@@ -1909,7 +1917,9 @@ async fn stream_claude_with_tools(
if finished { break; }
}
- _ = cancelled.notified() => { break; }
+ _ = cancelled.notified() => {
+ return Err(AGENT_CANCELLED_ERROR.to_string());
+ }
}
}
@@ -2049,7 +2059,9 @@ async fn stream_openai_with_tools(
if finished { break; }
}
- _ = cancelled.notified() => { break; }
+ _ = cancelled.notified() => {
+ return Err(AGENT_CANCELLED_ERROR.to_string());
+ }
}
}
@@ -2175,7 +2187,9 @@ async fn stream_responses_with_tools(
if finished { break; }
}
- _ = cancelled.notified() => { break; }
+ _ = cancelled.notified() => {
+ return Err(AGENT_CANCELLED_ERROR.to_string());
+ }
}
}
@@ -2321,7 +2335,9 @@ async fn stream_gemini_with_tools(
}
}
}
- _ = cancelled.notified() => { break; }
+ _ = cancelled.notified() => {
+ return Err(AGENT_CANCELLED_ERROR.to_string());
+ }
}
}