Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat: reasoning and tool call improvements (#8572)

Akarshan Biswas4e1293f4bcfc
diff --git a/extensions/rag-extension/src/index.test.ts b/extensions/rag-extension/src/index.test.ts
index 1555f99ca..78b973884 100644
--- a/extensions/rag-extension/src/index.test.ts
+++ b/extensions/rag-extension/src/index.test.ts
@@ -206,6 +206,21 @@ describe('retrieve', () => {
expect(res.error).toBe('db down')
expect(res.content[0].text).toContain('Retrieve failed')
})
+
+ // Rust plugin errors arrive as { VariantName: "message" }; the message is
+ // what the model can act on, not the wrapper.
+ it('unwraps a plugin error variant instead of dumping its JSON', async () => {
+ extMgr().get.mockReturnValue({
+ searchCollection: vi
+ .fn()
+ .mockRejectedValue({ InvalidInput: 'embedding is empty' }),
+ })
+ extMgr().getByName.mockReturnValue({
+ embed: vi.fn().mockResolvedValue({ data: [{ embedding: [1], index: 0 }] }),
+ })
+ const res = await ext.callTool('retrieve', { thread_id: 't1', query: 'q' })
+ expect(res.error).toBe('embedding is empty')
+ })
})
describe('getChunks', () => {
diff --git a/extensions/rag-extension/src/index.ts b/extensions/rag-extension/src/index.ts
index 2c075c4b0..cff4ff5fc 100644
--- a/extensions/rag-extension/src/index.ts
+++ b/extensions/rag-extension/src/index.ts
@@ -288,7 +288,12 @@ export default class RagExtension extends RAGExtension {
} else if (typeof e === 'string') {
msg = e
} else if (e && typeof e === 'object') {
- msg = JSON.stringify(e)
+ // Rust plugin errors arrive as { VariantName: "message" }.
+ const values = Object.values(e as Record<string, unknown>)
+ msg =
+ values.length === 1 && typeof values[0] === 'string'
+ ? values[0]
+ : JSON.stringify(e)
}
return {
error: msg,
diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs
index f00633073..b1f006df9 100644
--- a/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs
+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs
@@ -284,6 +284,10 @@ pub fn insert_chunks(
.unwrap_or(-1);
for ch in chunks.into_iter() {
+ // Reject unusable vectors before they reach either table: a non-finite
+ // value poisons cosine_similarity on the linear path and sqlite-vec
+ // silently drops the row on the ANN path.
+ validate_embedding(&ch.embedding)?;
current_order += 1;
let emb = to_le_bytes_vec(&ch.embedding);
let chunk_id = Uuid::new_v4().to_string();
@@ -296,11 +300,16 @@ pub fn insert_chunks(
let rowid: i64 = tx
.prepare("SELECT rowid FROM chunks WHERE id=?1")?
.query_row(params![chunk_id], |r| r.get(0))?;
- let json_vec = serde_json::to_string(&ch.embedding).unwrap_or("[]".to_string());
- let _ = tx.execute(
+ let json_vec = embedding_to_json(&ch.embedding)?;
+ // Tolerated, not propagated: an existing chunks_vec built for a
+ // different dimension (the embedding model changed) rejects the
+ // row, and linear search still serves it.
+ if let Err(e) = tx.execute(
"INSERT OR REPLACE INTO chunks_vec(rowid, embedding) VALUES (?1, ?2)",
params![rowid, json_vec],
- );
+ ) {
+ println!("[VectorDB] ✗ Failed to index chunk in chunks_vec: {}", e);
+ }
}
}
@@ -331,6 +340,31 @@ pub fn delete_file(conn: &Connection, file_id: &str) -> Result<(), VectorDBError
// Search Operations
// ============================================================================
+// sqlite-vec parses a bound vector as JSON. serde_json writes a non-finite
+// float as `null` and sqlite-vec then fails with only "JSON parsing error", so
+// reject the vector here while the offending element can still be named.
+fn embedding_to_json(embedding: &[f32]) -> Result<String, VectorDBError> {
+ validate_embedding(embedding)?;
+ Ok(serde_json::to_string(embedding)?)
+}
+
+fn validate_embedding(embedding: &[f32]) -> Result<(), VectorDBError> {
+ if embedding.is_empty() {
+ return Err(VectorDBError::InvalidInput(
+ "embedding is empty; the embedding model returned no vector".to_string(),
+ ));
+ }
+ if let Some(i) = embedding.iter().position(|v| !v.is_finite()) {
+ return Err(VectorDBError::InvalidInput(format!(
+ "embedding has a non-finite value ({}) at index {} of {}; the embedding model returned an unusable vector",
+ embedding[i],
+ i,
+ embedding.len()
+ )));
+ }
+ Ok(())
+}
+
pub fn search_collection(
conn: &Connection,
query_embedding: &[f32],
@@ -340,6 +374,11 @@ pub fn search_collection(
vec_loaded: bool,
file_ids: Option<Vec<String>>,
) -> Result<Vec<SearchResult>, VectorDBError> {
+ // Both paths need this: sqlite-vec fails opaquely on a non-finite value,
+ // and cosine_similarity turns it into a NaN score that silently fails the
+ // threshold, so retrieval would just come back empty.
+ validate_embedding(query_embedding)?;
+
let has_vec = if vec_loaded {
conn
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='chunks_vec'")
@@ -370,7 +409,7 @@ fn search_ann(
limit: usize,
file_ids: Option<Vec<String>>,
) -> Result<Vec<SearchResult>, VectorDBError> {
- let json_vec = serde_json::to_string(&query_embedding).unwrap_or("[]".to_string());
+ let json_vec = embedding_to_json(query_embedding)?;
// Build query with optional file_id filtering
let query = if let Some(ref ids) = file_ids {
@@ -629,3 +668,84 @@ pub fn chunk_text(text: String, chunk_size: usize, chunk_overlap: usize) -> Vec<
chunks
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn serializes_a_finite_embedding() {
+ assert_eq!(embedding_to_json(&[0.5, -0.25]).unwrap(), "[0.5,-0.25]");
+ }
+
+ // serde_json writes a non-finite float as `null`, which sqlite-vec rejects
+ // with an opaque "JSON parsing error". Catch it here with a usable message.
+ #[test]
+ fn rejects_non_finite_values() {
+ for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
+ let err = embedding_to_json(&[0.1, bad, 0.3]).unwrap_err();
+ let msg = err.to_string();
+ assert!(matches!(err, VectorDBError::InvalidInput(_)), "{msg}");
+ assert!(msg.contains("index 1"), "{msg}");
+ }
+ assert_eq!(serde_json::to_string(&f32::NAN).unwrap(), "null");
+ }
+
+ // How a non-finite value reaches us at all: a JSON number past f32::MAX is
+ // cast, not rejected, so an embedding of 1e39 arrives over IPC as infinity.
+ #[test]
+ fn json_numbers_past_f32_max_arrive_as_infinity() {
+ assert_eq!(
+ serde_json::from_str::<Vec<f32>>("[1e39]").unwrap(),
+ vec![f32::INFINITY]
+ );
+ }
+
+ // The linear path has no JSON step, so it needs its own guard or a NaN
+ // query silently returns zero matches instead of reporting the bad vector.
+ #[test]
+ fn linear_search_rejects_a_non_finite_query() {
+ let conn = Connection::open_in_memory().unwrap();
+ create_schema(&conn, 3).unwrap();
+ let err = search_collection(
+ &conn,
+ &[0.1, f32::NAN, 0.3],
+ 5,
+ 0.0,
+ Some("linear".to_string()),
+ false,
+ None,
+ )
+ .unwrap_err();
+ assert!(matches!(err, VectorDBError::InvalidInput(_)), "{err}");
+ }
+
+ #[test]
+ fn insert_rejects_a_non_finite_embedding() {
+ let conn = Connection::open_in_memory().unwrap();
+ create_schema(&conn, 3).unwrap();
+ let err = insert_chunks(
+ &conn,
+ "f1",
+ vec![MinimalChunkInput {
+ text: "hello".to_string(),
+ embedding: vec![0.1, f32::INFINITY, 0.3],
+ }],
+ false,
+ )
+ .unwrap_err();
+ assert!(matches!(err, VectorDBError::InvalidInput(_)), "{err}");
+ let count: i64 = conn
+ .query_row("SELECT COUNT(*) FROM chunks", [], |r| r.get(0))
+ .unwrap();
+ assert_eq!(count, 0);
+ }
+
+ #[test]
+ fn rejects_an_empty_embedding() {
+ assert!(matches!(
+ embedding_to_json(&[]).unwrap_err(),
+ VectorDBError::InvalidInput(_)
+ ));
+ }
+}
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rs
index d36443769..216b63965 100644
--- a/src-tauri/src/core/mcp/commands.rs
+++ b/src-tauri/src/core/mcp/commands.rs
@@ -15,7 +15,7 @@ use crate::core::{
};
use crate::core::{
mcp::models::ToolWithServer,
- state::{RunningServiceEnum, SharedMcpServers},
+ state::{RunningMcpService, SharedMcpServers},
};
use std::{collections::HashSet, fs, time::Duration};
@@ -219,16 +219,8 @@ pub async fn deactivate_mcp_server<R: Runtime>(
// Release the lock before calling cancel
drop(servers_map);
- match service {
- RunningServiceEnum::NoInit(service) => {
- log::info!("Stopping server {name}...");
- service.cancel().await.map_err(|e| e.to_string())?;
- }
- RunningServiceEnum::WithInit(service) => {
- log::info!("Stopping server {name} with initialization...");
- service.cancel().await.map_err(|e| e.to_string())?;
- }
- }
+ log::info!("Stopping server {name}...");
+ service.cancel().await.map_err(|e| e.to_string())?;
let child_pid = {
let mut pids = state.mcp_server_pids.lock().await;
@@ -300,14 +292,7 @@ async fn remove_mcp_server_entry(
let mut servers = mcp_servers.lock().await;
if let Some(service) = servers.remove(server_name) {
log::warn!("Removing MCP server {server_name} from connected servers");
- match service {
- RunningServiceEnum::NoInit(s) => {
- let _ = s.cancel().await;
- }
- RunningServiceEnum::WithInit(s) => {
- let _ = s.cancel().await;
- }
- }
+ let _ = service.cancel().await;
true
} else {
false
@@ -436,7 +421,7 @@ pub async fn call_tool(
let servers = state.mcp_servers.lock().await;
// If server_name is provided, only check that specific server
- let servers_to_check: Vec<(&String, &crate::core::state::RunningServiceEnum)> =
+ let servers_to_check: Vec<(&String, &RunningMcpService)> =
if let Some(ref server) = server_name {
servers.iter().filter(|(name, _)| *name == server).collect()
} else {
@@ -728,7 +713,7 @@ enum PingResult {
ToolNotAvailable,
}
-async fn try_ping_tool(service: &RunningServiceEnum) -> PingResult {
+async fn try_ping_tool(service: &RunningMcpService) -> PingResult {
let result = timeout(
Duration::from_secs(3),
service.call_tool(CallToolRequestParam {
@@ -764,7 +749,7 @@ async fn try_ping_tool(service: &RunningServiceEnum) -> PingResult {
}
}
-async fn try_browser_snapshot_tool(service: &RunningServiceEnum) -> Result<bool, String> {
+async fn try_browser_snapshot_tool(service: &RunningMcpService) -> Result<bool, String> {
let result = timeout(
// Snapshot tool is very time-consuming
// Extend timeout to make sure the tool call has enough time to succeed
diff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rs
index eb52e8a47..8c7edeaaa 100644
--- a/src-tauri/src/core/mcp/helpers.rs
+++ b/src-tauri/src/core/mcp/helpers.rs
@@ -20,7 +20,8 @@ use tokio::{
use crate::core::{
app::commands::get_jan_data_folder_path,
mcp::models::{McpServerConfig, McpSettings},
- state::{AppState, RunningServiceEnum, SharedMcpServers},
+ mcp::progress::JanClientHandler,
+ state::{AppState, RunningMcpService, SharedMcpServers},
};
use jan_utils::{can_override_npx, can_override_uvx};
@@ -233,14 +234,7 @@ pub async fn monitor_mcp_server_handle<R: Runtime>(
{
let mut servers = servers_state.lock().await;
if let Some(service) = servers.remove(&name) {
- match service {
- RunningServiceEnum::NoInit(service) => {
- let _ = service.cancel().await;
- }
- RunningServiceEnum::WithInit(service) => {
- let _ = service.cancel().await;
- }
- }
+ let _ = service.cancel().await;
}
}
{
@@ -462,17 +456,15 @@ async fn schedule_mcp_start_task<R: Runtime>(
icons: None,
},
};
- let client = client_info.serve(transport).await.inspect_err(|e| {
+ let handler = JanClientHandler::new(client_info, name.clone(), app.clone());
+ let client = handler.serve(transport).await.inspect_err(|e| {
log::error!("client error: {e:?}");
});
match client {
Ok(client) => {
log::info!("Connected to server: {:?}", client.peer_info());
- servers
- .lock()
- .await
- .insert(name.clone(), RunningServiceEnum::WithInit(client));
+ servers.lock().await.insert(name.clone(), client);
emit_mcp_update_event(&app, &name);
}
@@ -532,7 +524,8 @@ async fn schedule_mcp_start_task<R: Runtime>(
icons: None,
},
};
- let client = client_info.serve(transport).await.map_err(|e| {
+ let handler = JanClientHandler::new(client_info, name.clone(), app.clone());
+ let client = handler.serve(transport).await.map_err(|e| {
log::error!("client error: {e:?}");
e.to_string()
});
@@ -540,10 +533,7 @@ async fn schedule_mcp_start_task<R: Runtime>(
match client {
Ok(client) => {
log::info!("Connected to server: {:?}", client.peer_info());
- servers
- .lock()
- .await
- .insert(name.clone(), RunningServiceEnum::WithInit(client));
+ servers.lock().await.insert(name.clone(), client);
emit_mcp_update_event(&app, &name);
}
@@ -664,7 +654,11 @@ async fn schedule_mcp_start_task<R: Runtime>(
pids.insert(name.clone(), pid);
}
- match ().serve(process).await {
+ // ClientInfo::default() is exactly what the previous `()` handler
+ // sent on initialize, so the handshake is unchanged.
+ let handler =
+ JanClientHandler::new(ClientInfo::default(), name.clone(), app.clone());
+ match handler.serve(process).await {
Ok(server) => break (server, stderr),
Err(e) => {
// The child often crashes here with a write EPIPE while
@@ -720,7 +714,7 @@ async fn schedule_mcp_start_task<R: Runtime>(
servers
.lock()
.await
- .insert(name.clone(), RunningServiceEnum::NoInit(server));
+ .insert(name.clone(), server);
log::info!("Server {name} started successfully.");
// Wait a short time to verify the server is stable before marking as connected
@@ -1183,7 +1177,7 @@ pub async fn stop_mcp_servers_with_context<R: Runtime>(
let pids = state.mcp_server_pids.lock().await;
pids.clone()
};
- let servers_to_stop: Vec<(String, RunningServiceEnum, Option<u16>)> = {
+ let servers_to_stop: Vec<(String, RunningMcpService, Option<u16>)> = {
let mut servers_map = state.mcp_servers.lock().await;
let keys: Vec<String> = servers_map.keys().cloned().collect();
@@ -1225,12 +1219,7 @@ pub async fn stop_mcp_servers_with_context<R: Runtime>(
let child_pid = pids_snapshot.get(&name).copied();
tauri::async_runtime::spawn(async move {
- let cancel_future = async {
- match service {
- RunningServiceEnum::NoInit(service) => service.cancel().await,
- RunningServiceEnum::WithInit(service) => service.cancel().await,
- }
- };
+ let cancel_future = service.cancel();
let success = tokio::time::timeout(per_server_timeout, cancel_future)
.await
diff --git a/src-tauri/src/core/mcp/mod.rs b/src-tauri/src/core/mcp/mod.rs
index aa49f1860..1cbd96886 100644
--- a/src-tauri/src/core/mcp/mod.rs
+++ b/src-tauri/src/core/mcp/mod.rs
@@ -3,6 +3,7 @@ pub mod constants;
pub mod helpers;
pub mod lockfile;
pub mod models;
+pub mod progress;
#[cfg(test)]
mod tests;
diff --git a/src-tauri/src/core/mcp/progress.rs b/src-tauri/src/core/mcp/progress.rs
new file mode 100644
index 000000000..6de6eb3ef
--- /dev/null
+++ b/src-tauri/src/core/mcp/progress.rs
@@ -0,0 +1,136 @@
+use rmcp::{
+ handler::client::ClientHandler,
+ model::{ClientInfo, ProgressNotificationParam},
+ service::NotificationContext,
+ RoleClient,
+};
+use serde::Serialize;
+use std::sync::Arc;
+use tauri::{AppHandle, Emitter, Runtime};
+
+/// Event name the frontend listens on for MCP tool progress.
+pub const MCP_TOOL_PROGRESS_EVENT: &str = "mcp-tool-progress";
+
+/// A `notifications/progress` update from an MCP server.
+///
+/// The notification carries no tool name -- only the progress token, which rmcp
+/// generates per request and does not surface on the plain `call_tool` path --
+/// so the server is the only identity here. Tools execute one at a time, so the
+/// frontend attaches this to the call it already knows is running.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolProgress {
+ pub server: String,
+ pub progress: f64,
+ pub total: Option<f64>,
+ pub message: Option<String>,
+ /// Percentage, only when the server reported a usable total.
+ pub percent: Option<f64>,
+}
+
+pub fn tool_progress(server: &str, params: &ProgressNotificationParam) -> ToolProgress {
+ // A zero or negative total would make the ratio meaningless or divide by
+ // zero, and a server may report progress past a stale total.
+ let percent = params
+ .total
+ .filter(|total| *total > 0.0)
+ .map(|total| (params.progress / total * 100.0).clamp(0.0, 100.0));
+
+ ToolProgress {
+ server: server.to_string(),
+ progress: params.progress,
+ total: params.total,
+ message: params.message.clone(),
+ percent,
+ }
+}
+
+/// Emits one progress update. Erases the Tauri runtime parameter, which would
+/// otherwise spread from the handler through the shared MCP server map and
+/// every function that touches it.
+type ProgressSink = Arc<dyn Fn(ToolProgress) + Send + Sync>;
+
+/// Client handler for one MCP server connection.
+///
+/// Exists so progress notifications are observed at all: rmcp routes them to
+/// the handler, and the previous `()` handler dropped them.
+#[derive(Clone)]
+pub struct JanClientHandler {
+ info: ClientInfo,
+ server: String,
+ emit: ProgressSink,
+}
+
+impl JanClientHandler {
+ pub fn new<R: Runtime>(info: ClientInfo, server: String, app: AppHandle<R>) -> Self {
+ let name = server.clone();
+ let emit: ProgressSink = Arc::new(move |payload| {
+ if let Err(e) = app.emit(MCP_TOOL_PROGRESS_EVENT, &payload) {
+ log::warn!("Failed to emit MCP progress for {name}: {e}");
+ }
+ });
+ Self { info, server, emit }
+ }
+}
+
+impl ClientHandler for JanClientHandler {
+ fn get_info(&self) -> ClientInfo {
+ self.info.clone()
+ }
+
+ async fn on_progress(
+ &self,
+ params: ProgressNotificationParam,
+ _context: NotificationContext<RoleClient>,
+ ) {
+ (self.emit)(tool_progress(&self.server, &params));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use rmcp::model::{NumberOrString, ProgressToken};
+
+ fn params(progress: f64, total: Option<f64>) -> ProgressNotificationParam {
+ ProgressNotificationParam {
+ progress_token: ProgressToken(NumberOrString::Number(1)),
+ progress,
+ total,
+ message: None,
+ }
+ }
+
+ #[test]
+ fn computes_a_percentage_when_the_total_is_known() {
+ assert_eq!(tool_progress("s", &params(25.0, Some(50.0))).percent, Some(50.0));
+ }
+
+ #[test]
+ fn reports_no_percentage_without_a_total() {
+ let p = tool_progress("s", &params(7.0, None));
+ assert_eq!(p.percent, None);
+ assert_eq!(p.progress, 7.0);
+ }
+
+ // Servers are only required to increase `progress`; the total can be stale
+ // or absent, and a zero total would divide by zero.
+ #[test]
+ fn survives_an_unusable_total() {
+ assert_eq!(tool_progress("s", &params(5.0, Some(0.0))).percent, None);
+ assert_eq!(tool_progress("s", &params(5.0, Some(-1.0))).percent, None);
+ assert_eq!(
+ tool_progress("s", &params(80.0, Some(50.0))).percent,
+ Some(100.0)
+ );
+ }
+
+ #[test]
+ fn carries_the_server_and_message_through() {
+ let mut p = params(1.0, Some(4.0));
+ p.message = Some("indexing".to_string());
+ let payload = tool_progress("github", &p);
+ assert_eq!(payload.server, "github");
+ assert_eq!(payload.message.as_deref(), Some("indexing"));
+ }
+}
diff --git a/src-tauri/src/core/state.rs b/src-tauri/src/core/state.rs
index fa9061bbb..4d3eac6fc 100644
--- a/src-tauri/src/core/state.rs
+++ b/src-tauri/src/core/state.rs
@@ -6,12 +6,9 @@ use std::{
use crate::core::{
downloads::models::DownloadManagerState,
mcp::models::{McpSettings, ToolWithServer},
+ mcp::progress::JanClientHandler,
};
-use rmcp::{
- model::{CallToolRequestParam, CallToolResult, InitializeRequestParam, Tool},
- service::RunningService,
- RoleClient, ServiceError,
-};
+use rmcp::{service::RunningService, RoleClient};
use tokio::sync::{oneshot, Mutex, Notify};
/// Server handle type for managing the proxy server lifecycle
@@ -54,11 +51,10 @@ pub struct ProviderCustomHeader {
pub value: String,
}
-pub enum RunningServiceEnum {
- NoInit(RunningService<RoleClient, ()>),
- WithInit(RunningService<RoleClient, InitializeRequestParam>),
-}
-pub type SharedMcpServers = Arc<Mutex<HashMap<String, RunningServiceEnum>>>;
+/// Every connection uses the same handler, so that progress notifications are
+/// observed at all -- rmcp drops them on the `()` handler.
+pub type RunningMcpService = RunningService<RoleClient, JanClientHandler>;
+pub type SharedMcpServers = Arc<Mutex<HashMap<String, RunningMcpService>>>;
pub struct AppState {
pub app_token: Option<String>,
@@ -115,20 +111,3 @@ impl Default for AppState {
}
}
-impl RunningServiceEnum {
- pub async fn list_all_tools(&self) -> Result<Vec<Tool>, ServiceError> {
- match self {
- Self::NoInit(s) => s.list_all_tools().await,
- Self::WithInit(s) => s.list_all_tools().await,
- }
- }
- pub async fn call_tool(
- &self,
- params: CallToolRequestParam,
- ) -> Result<CallToolResult, ServiceError> {
- match self {
- Self::NoInit(s) => s.call_tool(params).await,
- Self::WithInit(s) => s.call_tool(params).await,
- }
- }
-}
diff --git a/web-app/src/components/WebCitationChip.tsx b/web-app/src/components/WebCitationChip.tsx
index 3af7b4671..9b1218326 100644
--- a/web-app/src/components/WebCitationChip.tsx
+++ b/web-app/src/components/WebCitationChip.tsx
@@ -6,17 +6,7 @@ import {
} from '@/components/ui/hover-card'
import { useWebCitationStore } from '@/stores/web-citation-store'
import { cn } from '@/lib/utils'
-
-const hostOf = (url: string) => {
- try {
- return new URL(url).hostname.replace(/^www\./, '')
- } catch {
- return url
- }
-}
-
-const faviconOf = (host: string) =>
- `https://www.google.com/s2/favicons?domain=${host}&sz=64`
+import { faviconForUrl, hostOf } from '@/lib/webUrl'
export const WebCitationChip = memo(
({ messageId, url }: { messageId?: string; url: string }) => {
@@ -24,7 +14,7 @@ export const WebCitationChip = memo(
messageId ? s.byMessageId[messageId]?.[url] : undefined
)
const host = hostOf(url)
- const favicon = citation?.favicon || faviconOf(host)
+ const favicon = citation?.favicon || faviconForUrl(url)
return (
<HoverCard openDelay={80} closeDelay={120}>
<HoverCardTrigger asChild>
diff --git a/web-app/src/components/WebSourcesRow.tsx b/web-app/src/components/WebSourcesRow.tsx
index 5537e9355..f5f4e1895 100644
--- a/web-app/src/components/WebSourcesRow.tsx
+++ b/web-app/src/components/WebSourcesRow.tsx
@@ -3,17 +3,7 @@ import { useTranslation } from '@/i18n/react-i18next-compat'
import { ChevronRightIcon } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Citations, type WebCitation } from '@/components/Citations'
-
-const hostOf = (url: string) => {
- try {
- return new URL(url).hostname.replace(/^www\./, '')
- } catch {
- return url
- }
-}
-
-const faviconOf = (url: string) =>
- `https://www.google.com/s2/favicons?domain=${hostOf(url)}&sz=64`
+import { faviconForUrl } from '@/lib/webUrl'
export const WebSourcesRow = memo(
({ citations }: { citations: WebCitation[] }) => {
@@ -47,7 +37,7 @@ export const WebSourcesRow = memo(
{preview.map((c) => (
<img
key={c.url}
- src={c.favicon || faviconOf(c.url)}
+ src={c.favicon || faviconForUrl(c.url)}
alt=""
className="size-4 rounded-full border border-border/60 bg-white object-contain"
/>
diff --git a/web-app/src/components/ai-elements/__tests__/chain-of-thought-duration.test.tsx b/web-app/src/components/ai-elements/__tests__/chain-of-thought-duration.test.tsx
new file mode 100644
index 000000000..bcc0f9877
--- /dev/null
+++ b/web-app/src/components/ai-elements/__tests__/chain-of-thought-duration.test.tsx
@@ -0,0 +1,104 @@
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { render, screen, act } from '@testing-library/react'
+import '@testing-library/jest-dom'
+import type { ReactNode } from 'react'
+
+vi.mock('streamdown', () => ({
+ Streamdown: ({ children }: { children: string }) => <span>{children}</span>,
+}))
+vi.mock('../shimmer', () => ({
+ Shimmer: ({ children }: { children: ReactNode }) => (
+ <span data-testid="shimmer">{children}</span>
+ ),
+}))
+// Surface the interpolated duration, which the shared mock in
+// chain-of-thought.test.tsx deliberately drops.
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (key: string, o?: Record<string, unknown>) =>
+ o?.duration !== undefined
+ ? `${key}(${o.duration})`
+ : o?.count !== undefined
+ ? `${o.count}`
+ : key,
+ }),
+}))
+
+import { ChainOfThought, ChainOfThoughtHeader } from '../chain-of-thought'
+
+const Trace = ({ streaming }: { streaming: boolean }) => (
+ <ChainOfThought isStreaming={streaming}>
+ <ChainOfThoughtHeader completedVariant="worked" />
+ </ChainOfThought>
+)
+
+const label = () =>
+ screen.getByText(/chat:reasoning/).textContent?.replace(/\s+/g, ' ')
+
+const advanceTo = (ms: number) =>
+ act(() => {
+ vi.setSystemTime(ms)
+ })
+
+describe('ChainOfThought duration', () => {
+ const start = () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(1_000_000)
+ }
+ afterEach(() => vi.useRealTimers())
+
+ it('reports how long the trace ran', () => {
+ start()
+ const { rerender } = render(<Trace streaming />)
+ advanceTo(1_005_000)
+ rerender(<Trace streaming={false} />)
+ expect(label()).toBe('chat:reasoning.workedFor(5)')
+ })
+
+ it('converts past a minute', () => {
+ start()
+ const { rerender } = render(<Trace streaming />)
+ advanceTo(1_090_000)
+ rerender(<Trace streaming={false} />)
+ expect(label()).toBe('chat:reasoning.workedFor(1 30)')
+ })
+
+ // A reloaded thread never streamed in this session, so there is no measured
+ // duration to report.
+ it('says "a while" when it never streamed', () => {
+ start()
+ render(<Trace streaming={false} />)
+ expect(label()).toBe('chat:reasoning.workedForAWhile')
+ })
+
+ // A trace that starts and finishes inside one tick measured 0s, and the
+ // header treats 0 as "still going", so it shimmered "Thinking..." forever.
+ it('does not get stuck shimmering when the trace finishes instantly', () => {
+ start()
+ const { rerender } = render(<Trace streaming />)
+ rerender(<Trace streaming={false} />)
+ expect(screen.queryByTestId('shimmer')).not.toBeInTheDocument()
+ expect(label()).toBe('chat:reasoning.workedFor(1)')
+ })
+
+ // An agentic turn reasons, answers, then reasons again. Each window used to
+ // overwrite the last, so the header reported only the final one.
+ it('accumulates across every reasoning window in the turn', () => {
+ start()
+ const { rerender } = render(<Trace streaming />)
+ advanceTo(1_010_000)
+ rerender(<Trace streaming={false} />)
+ expect(label()).toBe('chat:reasoning.workedFor(10)')
+
+ rerender(<Trace streaming />)
+ advanceTo(1_012_000)
+ rerender(<Trace streaming={false} />)
+ expect(label()).toBe('chat:reasoning.workedFor(12)')
+ })
+
+ it('keeps shimmering while the trace is still running', () => {
+ start()
+ render(<Trace streaming />)
+ expect(screen.getByTestId('shimmer')).toBeInTheDocument()
+ })
+})
diff --git a/web-app/src/components/ai-elements/__tests__/chain-of-thought.test.tsx b/web-app/src/components/ai-elements/__tests__/chain-of-thought.test.tsx
index e14dae2e5..441da9125 100644
--- a/web-app/src/components/ai-elements/__tests__/chain-of-thought.test.tsx
+++ b/web-app/src/components/ai-elements/__tests__/chain-of-thought.test.tsx
@@ -26,6 +26,10 @@ vi.mock('../shimmer', () => ({
),
}))
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
describe('ChainOfThought', () => {
it('renders children inside a Collapsible, defaults open', () => {
render(
@@ -102,14 +106,23 @@ describe('ChainOfThought', () => {
})
describe('ChainOfThoughtHeader', () => {
- it('shows "Reasoning..." shimmer when isStreaming=true', () => {
+ it('shows the default reasoning shimmer when isStreaming=true', () => {
render(
<ChainOfThought isStreaming={true}>
<ChainOfThoughtHeader />
</ChainOfThought>
)
expect(screen.getByTestId('shimmer')).toBeInTheDocument()
- expect(screen.getByText('Reasoning...')).toBeInTheDocument()
+ expect(screen.getByText('chat:reasoning.label')).toBeInTheDocument()
+ })
+
+ it('prefers an explicit streamingLabel over the default', () => {
+ render(
+ <ChainOfThought isStreaming={true}>
+ <ChainOfThoughtHeader streamingLabel="Web search..." />
+ </ChainOfThought>
+ )
+ expect(screen.getByText('Web search...')).toBeInTheDocument()
})
it('shows title when provided and not streaming', () => {
@@ -129,7 +142,45 @@ describe('ChainOfThoughtHeader', () => {
</ChainOfThought>
)
expect(
- screen.getByText('Thought for a few seconds')
+ screen.getByText('chat:reasoning.thoughtForAWhile')
+ ).toBeInTheDocument()
+ })
+
+ it('uses the worked phrasing when the trace ran tools', () => {
+ render(
+ <ChainOfThought isStreaming={false}>
+ <ChainOfThoughtHeader completedVariant="worked" />
+ </ChainOfThought>
+ )
+ expect(
+ screen.getByText('chat:reasoning.workedForAWhile')
+ ).toBeInTheDocument()
+ })
+
+ it('navigates instead of collapsing when navDirection is set', () => {
+ const onNavigate = vi.fn()
+ render(
+ <ChainOfThought isStreaming={true}>
+ <ChainOfThoughtHeader navDirection="right" onNavigate={onNavigate} />
+ </ChainOfThought>
+ )
+ const button = screen.getByRole('button', {
+ name: 'chat:reasoning.showFullTimeline',
+ })
+ button.click()
+ expect(onNavigate).toHaveBeenCalledTimes(1)
+ // A nav header must not also toggle the collapsible.
+ expect(button).not.toHaveAttribute('data-state')
+ })
+
+ it('labels the back direction distinctly', () => {
+ render(
+ <ChainOfThought isStreaming={true}>
+ <ChainOfThoughtHeader navDirection="left" onNavigate={() => {}} />
+ </ChainOfThought>
+ )
+ expect(
+ screen.getByRole('button', { name: 'chat:reasoning.showCurrentStep' })
).toBeInTheDocument()
})
@@ -142,9 +193,7 @@ describe('ChainOfThoughtHeader', () => {
</ChainOfThought>
)
expect(screen.getByText('Custom header')).toBeInTheDocument()
- expect(
- screen.queryByText(/Thought for/)
- ).not.toBeInTheDocument()
+ expect(screen.queryByText(/thoughtFor/)).not.toBeInTheDocument()
})
})
diff --git a/web-app/src/components/ai-elements/__tests__/reasoning-timeline.test.tsx b/web-app/src/components/ai-elements/__tests__/reasoning-timeline.test.tsx
new file mode 100644
index 000000000..e5d1d13b6
--- /dev/null
+++ b/web-app/src/components/ai-elements/__tests__/reasoning-timeline.test.tsx
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import '@testing-library/jest-dom'
+
+import { ReasoningActiveStep, StepRow } from '../reasoning-timeline'
+import { REASONING_STEP_MAX_CHARS } from '@/lib/reasoning'
+
+describe('ReasoningActiveStep', () => {
+ it('renders nothing for empty text', () => {
+ const { container } = render(<ReasoningActiveStep text="" />)
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ // Regression: models that stream reasoning without blank lines produced a
+ // single ever-growing step, so there was never a settled one to show and the
+ // trace looked frozen until the context ran out.
+ it('settles a step from text that has no paragraph break at all', () => {
+ const blob = `${'word '.repeat(REASONING_STEP_MAX_CHARS)}tail`
+ const { container } = render(<ReasoningActiveStep text={blob} />)
+ expect(container).not.toBeEmptyDOMElement()
+ expect(screen.queryByText(/tail$/)).not.toBeInTheDocument()
+ })
+
+ it('settles a step from single-newline-only text', () => {
+ const blob = `${'a line of reasoning\n'.repeat(60)}tail`
+ const { container } = render(<ReasoningActiveStep text={blob} />)
+ expect(container).not.toBeEmptyDOMElement()
+ })
+
+ it('shows the previous paragraph, not the one being written', () => {
+ render(<ReasoningActiveStep text={'settled thought\n\nbeing written'} />)
+ expect(screen.getByText('settled thought')).toBeInTheDocument()
+ expect(screen.queryByText('being written')).not.toBeInTheDocument()
+ })
+
+ it('renders nothing until a first step has settled', () => {
+ const { container } = render(<ReasoningActiveStep text="only just begun" />)
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('follows the step being written in live mode', () => {
+ render(
+ <ReasoningActiveStep
+ text={'settled thought\n\nbeing written'}
+ mode="live"
+ />
+ )
+ expect(screen.getByText('being written')).toBeInTheDocument()
+ expect(screen.queryByText('settled thought')).not.toBeInTheDocument()
+ })
+
+ it('renders the first step immediately in live mode', () => {
+ render(<ReasoningActiveStep text="only just begun" mode="live" />)
+ expect(screen.getByText('only just begun')).toBeInTheDocument()
+ })
+})
+
+describe('StepRow', () => {
+ it('renders plain step text', () => {
+ render(
+ <ol>
+ <StepRow text="a step" />
+ </ol>
+ )
+ expect(screen.getByText('a step')).toBeInTheDocument()
+ })
+
+ it('hosts arbitrary children instead of text', () => {
+ render(
+ <ol>
+ <StepRow>
+ <span>tool card</span>
+ </StepRow>
+ </ol>
+ )
+ expect(screen.getByText('tool card')).toBeInTheDocument()
+ })
+
+ it('renders a custom marker when provided', () => {
+ render(
+ <ol>
+ <StepRow marker={<span data-testid="marker" />} text="done" />
+ </ol>
+ )
+ expect(screen.getByTestId('marker')).toBeInTheDocument()
+ })
+})
diff --git a/web-app/src/components/ai-elements/__tests__/tool-runtime.test.tsx b/web-app/src/components/ai-elements/__tests__/tool-runtime.test.tsx
new file mode 100644
index 000000000..5c9f5ca22
--- /dev/null
+++ b/web-app/src/components/ai-elements/__tests__/tool-runtime.test.tsx
@@ -0,0 +1,117 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, render, screen } from '@testing-library/react'
+import '@testing-library/jest-dom'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ `${key}:${options?.count ?? ''}`,
+ }),
+}))
+
+import { ToolElapsed, ToolProgressRow } from '../tool-runtime'
+import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
+
+describe('ToolProgressRow', () => {
+ beforeEach(() => {
+ useToolCallRuntime.getState().reset()
+ })
+
+ const start = (id: string) => {
+ const runtime = useToolCallRuntime.getState()
+ runtime.enqueue([id])
+ runtime.markRunning(id)
+ }
+
+ it('renders nothing until the server reports progress', () => {
+ start('tc1')
+ const { container } = render(<ToolProgressRow toolCallId="tc1" />)
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('shows the message the server sent', () => {
+ start('tc1')
+ useToolCallRuntime
+ .getState()
+ .reportProgress({ server: 's', progress: 1, message: 'Indexing repo' })
+ render(<ToolProgressRow toolCallId="tc1" />)
+ expect(screen.getByText('Indexing repo')).toBeInTheDocument()
+ })
+
+ it('fills the bar to the reported percentage', () => {
+ start('tc1')
+ useToolCallRuntime
+ .getState()
+ .reportProgress({ server: 's', progress: 3, total: 4, percent: 75 })
+ render(<ToolProgressRow toolCallId="tc1" />)
+ const bar = screen.getByRole('progressbar')
+ expect(bar).toHaveAttribute('aria-valuenow', '75')
+ expect(bar.querySelector('div')).toHaveStyle({ width: '75%' })
+ })
+
+ // Servers may report progress with no total; a bar would imply a completion
+ // fraction nobody sent.
+ it('reports the count instead of a bar when there is no total', () => {
+ start('tc1')
+ useToolCallRuntime
+ .getState()
+ .reportProgress({ server: 's', progress: 12 })
+ render(<ToolProgressRow toolCallId="tc1" />)
+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
+ expect(screen.getByText('12')).toBeInTheDocument()
+ })
+
+ it('renders nothing once the call settles', () => {
+ start('tc1')
+ useToolCallRuntime
+ .getState()
+ .reportProgress({ server: 's', progress: 1, message: 'Indexing repo' })
+ useToolCallRuntime.getState().markSettled('tc1')
+ const { container } = render(<ToolProgressRow toolCallId="tc1" />)
+ expect(container).toBeEmptyDOMElement()
+ })
+})
+
+describe('ToolElapsed', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(1_000_000)
+ })
+ afterEach(() => vi.useRealTimers())
+
+ it('renders nothing before the call starts', () => {
+ const { container } = render(<ToolElapsed />)
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('shows the final duration of a settled call', () => {
+ render(<ToolElapsed startedAt={1_000_000} endedAt={1_012_000} />)
+ expect(screen.getByText('common:duration.seconds:12')).toBeInTheDocument()
+ })
+
+ it('counts up while the call is running', () => {
+ render(<ToolElapsed startedAt={1_000_000} />)
+ expect(screen.getByText('common:duration.seconds:0')).toBeInTheDocument()
+ act(() => {
+ vi.advanceTimersByTime(3000)
+ })
+ expect(screen.getByText('common:duration.seconds:3')).toBeInTheDocument()
+ })
+
+ it('stops counting once the call settles', () => {
+ const { rerender } = render(<ToolElapsed startedAt={1_000_000} />)
+ rerender(<ToolElapsed startedAt={1_000_000} endedAt={1_002_000} />)
+ act(() => {
+ vi.advanceTimersByTime(60_000)
+ })
+ expect(screen.getByText('common:duration.seconds:2')).toBeInTheDocument()
+ })
+
+ // "Used foo 0s" is noise; a sub-second call just has no duration worth showing.
+ it('omits a duration that rounds to zero', () => {
+ const { container } = render(
+ <ToolElapsed startedAt={1_000_000} endedAt={1_000_400} />
+ )
+ expect(container).toBeEmptyDOMElement()
+ })
+})
diff --git a/web-app/src/components/ai-elements/__tests__/tool.test.tsx b/web-app/src/components/ai-elements/__tests__/tool.test.tsx
new file mode 100644
index 000000000..e4e431977
--- /dev/null
+++ b/web-app/src/components/ai-elements/__tests__/tool.test.tsx
@@ -0,0 +1,327 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import '@testing-library/jest-dom'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) => {
+ const named = options?.tool ?? options?.server
+ return named ? `${key}:${named}` : key
+ },
+ }),
+}))
+
+const approvalState: { pending: Record<string, unknown> } = { pending: {} }
+const resolveApproval = vi.fn()
+vi.mock('@/hooks/useToolApprovalRequests', () => ({
+ useToolApprovalRequests: (selector: (s: unknown) => unknown) =>
+ selector({ ...approvalState, resolveApproval }),
+}))
+
+vi.mock('../code-block', () => ({
+ CodeBlock: ({ code }: { code: string }) => (
+ <pre data-testid="code-block">{code}</pre>
+ ),
+}))
+
+vi.mock('@/containers/CopyButton', () => ({
+ CopyButton: ({ text }: { text: string }) => (
+ <button data-testid="copy" data-text={text} />
+ ),
+}))
+
+import {
+ Tool,
+ ToolApprovalActions,
+ ToolContent,
+ ToolHeader,
+ ToolInput,
+ ToolOutput,
+} from '../tool'
+import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
+
+const resolver = (input: string) => Promise.resolve(input)
+
+// The approval mock is module state; leaving a pending entry behind would make
+// every later header render as awaiting approval.
+beforeEach(() => {
+ approvalState.pending = {}
+ resolveApproval.mockClear()
+})
+
+const renderHeader = (props: Partial<React.ComponentProps<typeof ToolHeader>> = {}) =>
+ render(
+ <Tool state="output-available" toolCallId="tc1" messageId="m1">
+ <ToolHeader
+ title="read_file"
+ type="tool-read_file"
+ state="output-available"
+ {...props}
+ />
+ </Tool>
+ )
+
+const renderApproval = (pending: Record<string, unknown>) => {
+ approvalState.pending = pending
+ return render(
+ <Tool state="input-available" toolCallId="tc1" messageId="m1" defaultOpen>
+ <ToolApprovalActions />
+ </Tool>
+ )
+}
+
+describe('ToolApprovalActions', () => {
+ beforeEach(() => {
+ resolveApproval.mockClear()
+ approvalState.pending = {}
+ })
+
+ it('renders nothing when no approval is pending', () => {
+ renderApproval({})
+ expect(
+ screen.queryByText('tools:toolApproval.deny')
+ ).not.toBeInTheDocument()
+ })
+
+ // Trusting a server tool-by-tool is the same decision repeated, so "always"
+ // offers the server rather than the single tool.
+ it('offers to trust the whole server by name', () => {
+ renderApproval({
+ tc1: { toolCallId: 'tc1', toolName: 'create_issue', serverName: 'github' },
+ })
+ expect(
+ screen.getByText('tools:toolApproval.allowServerAlways:github')
+ ).toBeInTheDocument()
+ expect(
+ screen.queryByText(/tools:toolApproval.allowToolAlways/)
+ ).not.toBeInTheDocument()
+ })
+
+ it('falls back to the tool name when it has no server', () => {
+ renderApproval({ tc1: { toolCallId: 'tc1', toolName: 'do_thing' } })
+ expect(
+ screen.getByText('tools:toolApproval.allowToolAlways:do_thing')
+ ).toBeInTheDocument()
+ })
+
+ it('grants each scope the reader picked', () => {
+ renderApproval({
+ tc1: { toolCallId: 'tc1', toolName: 'create_issue', serverName: 'github' },
+ })
+ fireEvent.click(screen.getByText('tools:toolApproval.allowOnce'))
+ fireEvent.click(screen.getByText('tools:toolApproval.allowInThread'))
+ fireEvent.click(
+ screen.getByText('tools:toolApproval.allowServerAlways:github')
+ )
+ fireEvent.click(screen.getByText('tools:toolApproval.deny'))
+ expect(resolveApproval.mock.calls.map((c) => c[1])).toEqual([
+ 'allow-once',
+ 'allow-thread',
+ 'allow-always',
+ 'deny',
+ ])
+ })
+})
+
+describe('ToolHeader runtime state', () => {
+ beforeEach(() => {
+ useToolCallRuntime.getState().reset()
+ })
+
+ // A queued call and a running one are both `input-available`, so without the
+ // queue the header claims every pending call is already running.
+ it('says a call is queued until the executor reaches it', () => {
+ useToolCallRuntime.getState().enqueue(['tc1'])
+ renderHeader({ state: 'input-available' })
+ expect(screen.getByText(/tools:toolCall.queued/)).toBeInTheDocument()
+ expect(screen.queryByText(/tools:toolCall.running/)).not.toBeInTheDocument()
+ })
+
+ it('counts the calls waiting ahead of it', () => {
+ useToolCallRuntime.getState().enqueue(['a', 'b', 'tc1'])
+ renderHeader({ state: 'input-available' })
+ expect(screen.getByText('tools:toolCall.queuedPosition')).toBeInTheDocument()
+ })
+
+ it('omits the position for the call that runs next', () => {
+ useToolCallRuntime.getState().enqueue(['tc1', 'b'])
+ renderHeader({ state: 'input-available' })
+ expect(
+ screen.queryByText('tools:toolCall.queuedPosition')
+ ).not.toBeInTheDocument()
+ })
+
+ it('switches to running once the executor starts it', () => {
+ useToolCallRuntime.getState().enqueue(['tc1'])
+ useToolCallRuntime.getState().markRunning('tc1')
+ renderHeader({ state: 'input-available' })
+ expect(screen.getByText(/tools:toolCall.running/)).toBeInTheDocument()
+ })
+
+ it('shows how long a finished call took', () => {
+ const runtime = useToolCallRuntime.getState()
+ runtime.enqueue(['tc1'])
+ runtime.markRunning('tc1')
+ vi.setSystemTime(Date.now() + 5000)
+ runtime.markSettled('tc1')
+ renderHeader({ state: 'output-available' })
+ expect(screen.getByText('common:duration.seconds')).toBeInTheDocument()
+ })
+})
+
+describe('ToolHeader', () => {
+ it('shows where the call came from', () => {
+ renderHeader({ origin: 'filesystem' })
+ expect(screen.getByText('filesystem')).toBeInTheDocument()
+ })
+
+ it('previews the arguments inline', () => {
+ renderHeader({ input: { path: 'src/app.ts' } })
+ expect(screen.getByText('path: src/app.ts')).toBeInTheDocument()
+ })
+
+ it('previews arguments that are still mid-stream', () => {
+ renderHeader({ input: { path: 'src/ap' } })
+ expect(screen.getByText('path: src/ap')).toBeInTheDocument()
+ })
+
+ it('renders no preview when there are no arguments', () => {
+ renderHeader({ input: {} })
+ expect(screen.getByText(/tools:toolCall.used/)).toBeInTheDocument()
+ })
+})
+
+const renderInput = (input: unknown) =>
+ render(
+ <Tool state="input-available" toolCallId="tc1" messageId="m1" defaultOpen>
+ <ToolContent>
+ <ToolInput input={input} />
+ </ToolContent>
+ </Tool>
+ )
+
+describe('ToolInput', () => {
+ it('renders object arguments as key/value rows', () => {
+ renderInput({ path: 'src/app.ts', limit: 5 })
+ expect(screen.getByText('path')).toBeInTheDocument()
+ expect(screen.getByText('src/app.ts')).toBeInTheDocument()
+ expect(screen.queryByTestId('code-block')).not.toBeInTheDocument()
+ })
+
+ it('toggles to raw JSON and back', () => {
+ renderInput({ path: 'src/app.ts' })
+ fireEvent.click(screen.getByText('tools:toolCall.viewRaw'))
+ expect(screen.getByTestId('code-block')).toHaveTextContent('"path"')
+ fireEvent.click(screen.getByText('tools:toolCall.viewTable'))
+ expect(screen.queryByTestId('code-block')).not.toBeInTheDocument()
+ })
+
+ it('copies the pretty-printed arguments', () => {
+ renderInput({ path: 'a.ts' })
+ expect(screen.getByTestId('copy')).toHaveAttribute(
+ 'data-text',
+ '{\n "path": "a.ts"\n}'
+ )
+ })
+
+ it('falls back to the raw block for non-object arguments', () => {
+ renderInput('not json at all')
+ expect(screen.getByTestId('code-block')).toHaveTextContent('not json at all')
+ expect(screen.queryByText('tools:toolCall.viewRaw')).not.toBeInTheDocument()
+ })
+})
+
+const renderOutput = (
+ props: Partial<React.ComponentProps<typeof ToolOutput>> = {}
+) =>
+ render(
+ <Tool state="output-available" toolCallId="tc1" messageId="m1" defaultOpen>
+ <ToolContent>
+ <ToolOutput
+ output="short result"
+ errorText={undefined}
+ resolver={resolver}
+ {...props}
+ />
+ </ToolContent>
+ </Tool>
+ )
+
+describe('ToolOutput', () => {
+ it('offers no expand control for a short payload', () => {
+ renderOutput()
+ expect(screen.queryByText('tools:toolCall.showMore')).not.toBeInTheDocument()
+ })
+
+ it('expands and collapses a long payload', () => {
+ renderOutput({ output: 'x'.repeat(2000) })
+ fireEvent.click(screen.getByText('tools:toolCall.viewRaw'))
+ fireEvent.click(screen.getByText('tools:toolCall.showMore'))
+ expect(screen.getByText('tools:toolCall.showLess')).toBeInTheDocument()
+ fireEvent.click(screen.getByText('tools:toolCall.showLess'))
+ expect(screen.getByText('tools:toolCall.showMore')).toBeInTheDocument()
+ })
+
+ // Native web search / RAG results render as citation cards, which live
+ // outside the scroll box, so an expand toggle would be inert.
+ it('offers no expand control for citation output', () => {
+ renderOutput({
+ output: {
+ kind: 'web',
+ query: 'q',
+ results: Array.from({ length: 12 }, (_, i) => ({
+ url: `https://example.com/${i}`,
+ title: `Result ${i}`,
+ text: 'x'.repeat(120),
+ })),
+ },
+ })
+ expect(screen.queryByText('tools:toolCall.showMore')).not.toBeInTheDocument()
+ })
+
+ it('leads with a summary and hides the raw payload', () => {
+ renderOutput({
+ output: { content: [{ type: 'text', text: 'first line\nrest' }] },
+ })
+ expect(screen.getByText('tools:toolCall.summaryText')).toBeInTheDocument()
+ expect(screen.queryByTestId('code-block')).not.toBeInTheDocument()
+ })
+
+ it('reveals the raw payload on demand', () => {
+ renderOutput({
+ output: { content: [{ type: 'text', text: 'first line' }] },
+ })
+ fireEvent.click(screen.getByText('tools:toolCall.viewRaw'))
+ expect(screen.getByTestId('code-block')).toBeInTheDocument()
+ fireEvent.click(screen.getByText('tools:toolCall.hideRaw'))
+ expect(screen.queryByTestId('code-block')).not.toBeInTheDocument()
+ })
+
+ // Expanding is meaningless while the payload is summarised away.
+ it('offers expansion only once the raw payload is shown', () => {
+ renderOutput({ output: 'x'.repeat(2000) })
+ expect(screen.queryByText('tools:toolCall.showMore')).not.toBeInTheDocument()
+ fireEvent.click(screen.getByText('tools:toolCall.viewRaw'))
+ expect(screen.getByText('tools:toolCall.showMore')).toBeInTheDocument()
+ })
+
+ it('copies the error text when the call failed', () => {
+ renderOutput({ output: undefined, errorText: 'boom' })
+ expect(screen.getByTestId('copy')).toHaveAttribute('data-text', 'boom')
+ })
+
+ it('renders nothing without output or error', () => {
+ const { container } = render(
+ <Tool state="input-available" toolCallId="tc1" messageId="m1" defaultOpen>
+ <ToolContent>
+ <ToolOutput
+ output={undefined}
+ errorText={undefined}
+ resolver={resolver}
+ />
+ </ToolContent>
+ </Tool>
+ )
+ expect(container).not.toHaveTextContent('tools:toolCall.result')
+ })
+})
diff --git a/web-app/src/components/ai-elements/chain-of-thought.tsx b/web-app/src/components/ai-elements/chain-of-thought.tsx
index 7d4580ad4..0ec53d531 100644
--- a/web-app/src/components/ai-elements/chain-of-thought.tsx
+++ b/web-app/src/components/ai-elements/chain-of-thought.tsx
@@ -9,6 +9,8 @@ import { cn } from '@/lib/utils'
import {
SparklesIcon,
ChevronDownIcon,
+ ChevronLeftIcon,
+ ChevronRightIcon,
CheckCircle2Icon,
CircleDotIcon,
CircleIcon,
@@ -25,6 +27,8 @@ import {
useState,
} from 'react'
import { Streamdown } from 'streamdown'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { formatCompactDuration } from '@/lib/duration'
import { Shimmer } from './shimmer'
// ── Types ──────────────────────────────────────────────────────────────────
@@ -104,7 +108,7 @@ export const ChainOfThought = memo(
}
const [startTime, setStartTime] = useState<number | null>(null)
- const [duration, setDuration] = useState<number | undefined>(undefined)
+ const [elapsedMs, setElapsedMs] = useState<number | undefined>(undefined)
useEffect(() => {
if (isStreaming) {
@@ -112,11 +116,21 @@ export const ChainOfThought = memo(
setStartTime(Date.now())
}
} else if (startTime !== null) {
- setDuration(Math.ceil((Date.now() - startTime) / MS_IN_S))
+ // Accumulated, not replaced: an agentic turn reasons, answers, then
+ // reasons again, and each window is part of the same trace.
+ const window = Date.now() - startTime
+ setElapsedMs((previous) => (previous ?? 0) + window)
setStartTime(null)
}
}, [isStreaming, startTime])
+ // Rounded up to at least a second: a trace that begins and ends inside one
+ // tick still ran, and a zero would read as "still going" below.
+ const duration =
+ elapsedMs === undefined
+ ? undefined
+ : Math.max(1, Math.ceil(elapsedMs / MS_IN_S))
+
const contextValue = useMemo(
() => ({ isStreaming, isOpen, setIsOpen, duration }),
[isStreaming, isOpen, setIsOpen, duration]
@@ -150,51 +164,106 @@ export type ChainOfThoughtHeaderProps = ComponentProps<
title?: string
/** Label shown while streaming, e.g. "Working...". Defaults to "Reasoning...". */
streamingLabel?: string
- /** Past-tense verb for the completed state, e.g. "Worked". Defaults to "Thought". */
- completedVerb?: string
+ /** Which past-tense phrasing to use once the trace is complete. */
+ completedVariant?: 'thought' | 'worked'
+ /**
+ * Turns the header into a view switch instead of a collapse toggle: the
+ * chevron points the way it navigates, e.g. `right` to drill into the full
+ * timeline and `left` to come back.
+ */
+ navDirection?: 'left' | 'right'
+ onNavigate?: () => void
}
+const COMPLETED_KEYS = {
+ thought: {
+ aWhile: 'chat:reasoning.thoughtForAWhile',
+ withDuration: 'chat:reasoning.thoughtFor',
+ },
+ worked: {
+ aWhile: 'chat:reasoning.workedForAWhile',
+ withDuration: 'chat:reasoning.workedFor',
+ },
+} as const
+
export const ChainOfThoughtHeader = memo(
({
className,
title,
- streamingLabel = 'Reasoning...',
- completedVerb = 'Thought',
+ streamingLabel,
+ completedVariant = 'thought',
+ navDirection,
+ onNavigate,
children,
...props
}: ChainOfThoughtHeaderProps) => {
+ const { t } = useTranslation()
const { isStreaming, isOpen, duration } = useChainOfThought()
- return (
- <CollapsibleTrigger
- className={cn(
- 'flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground',
- className
- )}
- {...props}
- >
- {children ?? (
- <>
- <SparklesIcon className="size-4" />
- {isStreaming || duration === 0 ? (
- <Shimmer duration={1}>{streamingLabel}</Shimmer>
- ) : title ? (
- <p>{title}</p>
- ) : duration === undefined ? (
- <p>{completedVerb} for a few seconds</p>
- ) : (
- <p>
- {completedVerb} for {duration} seconds
- </p>
- )}
- <ChevronDownIcon
- className={cn(
- 'size-4 transition-transform',
- isOpen ? 'rotate-180' : 'rotate-0'
- )}
- />
- </>
+ const keys = COMPLETED_KEYS[completedVariant]
+ const completedLabel =
+ duration === undefined
+ ? t(keys.aWhile)
+ : t(keys.withDuration, { duration: formatCompactDuration(duration, t) })
+
+ const rowClassName = cn(
+ 'flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground',
+ className
+ )
+
+ if (children) {
+ return (
+ <CollapsibleTrigger className={rowClassName} {...props}>
+ {children}
+ </CollapsibleTrigger>
+ )
+ }
+
+ const label = (
+ <>
+ <SparklesIcon className="size-4" />
+ {isStreaming ? (
+ <Shimmer duration={1}>
+ {streamingLabel ?? t('chat:reasoning.label')}
+ </Shimmer>
+ ) : title ? (
+ <p>{title}</p>
+ ) : (
+ <p>{completedLabel}</p>
)}
+ </>
+ )
+
+ if (navDirection) {
+ const navLabel =
+ navDirection === 'right'
+ ? t('chat:reasoning.showFullTimeline')
+ : t('chat:reasoning.showCurrentStep')
+ return (
+ <button
+ type="button"
+ className={rowClassName}
+ onClick={onNavigate}
+ aria-label={navLabel}
+ title={navLabel}
+ {...props}
+ >
+ {navDirection === 'left' && <ChevronLeftIcon className="size-4" />}
+ {label}
+ {navDirection === 'right' && <ChevronRightIcon className="size-4" />}
+ </button>
+ )
+ }
+
+ return (
+ <CollapsibleTrigger className={rowClassName} {...props}>
+ {label}
+ <ChevronDownIcon
+ className={cn(
+ 'size-4 transition-transform',
+ isOpen ? 'rotate-180' : 'rotate-0'
+ )}
+ />
</CollapsibleTrigger>
)
}
diff --git a/web-app/src/components/ai-elements/reasoning-timeline.tsx b/web-app/src/components/ai-elements/reasoning-timeline.tsx
index d81384726..357777c30 100644
--- a/web-app/src/components/ai-elements/reasoning-timeline.tsx
+++ b/web-app/src/components/ai-elements/reasoning-timeline.tsx
@@ -1,7 +1,7 @@
import { memo } from 'react'
import type React from 'react'
import { cn } from '@/lib/utils'
-import { splitReasoningParagraphs } from '@/lib/reasoning'
+import { segmentReasoningSteps } from '@/lib/reasoning'
type StepRowProps = {
text?: string
@@ -48,34 +48,38 @@ export const StepRow = ({
</li>
)
+export type ReasoningStepMode = 'settled' | 'live'
+
/**
- * While reasoning streams, show only the most recently *completed* paragraph as
- * plain text — never the paragraph currently being written. As the model
- * finishes each paragraph and starts the next, the derived last-completed
- * paragraph swaps, so exactly one bounded block is visible at a time instead of
- * the whole growing trace.
+ * One bounded block of a streaming reasoning trace, rather than the whole
+ * growing text. `settled` shows the last step the model actually finished, so
+ * the condensed view does not shift under the reader; `live` shows the step
+ * being written, so tokens appear as they arrive. Steps are budget-bounded, so
+ * either mode advances even when the model never emits a paragraph break.
*/
-export const ReasoningActiveStep = memo(({ text }: { text: string }) => {
- const steps = splitReasoningParagraphs(text)
- // The final element is the in-progress paragraph; the one before it is the
- // last paragraph the model has actually finished.
- const completed = steps.slice(0, -1)
- const current = completed[completed.length - 1] ?? ''
- if (!current) return null
- // Key by paragraph index so each swap remounts the block, replaying the
- // fade/collapse enter transition as one paragraph gives way to the next.
- return (
- <div
- key={completed.length}
- dir="auto"
- className={cn(
- 'select-text whitespace-pre-wrap wrap-break-word text-sm text-main-view-fg/70',
- 'animate-in fade-in-0 slide-in-from-top-1 duration-300 ease-out'
- )}
- >
- {current}
- </div>
- )
-})
+export const ReasoningActiveStep = memo(
+ ({ text, mode = 'settled' }: { text: string; mode?: ReasoningStepMode }) => {
+ const steps = segmentReasoningSteps(text)
+ // The final element is always the step in progress.
+ const index = mode === 'live' ? steps.length - 1 : steps.length - 2
+ const current = index >= 0 ? steps[index] : undefined
+ if (!current) return null
+ // Key by step index so each swap remounts the block, replaying the
+ // fade/collapse enter transition as one step gives way to the next. A step
+ // keeps its key while it grows, so it is not remounted on every token.
+ return (
+ <div
+ key={index}
+ dir="auto"
+ className={cn(
+ 'select-text whitespace-pre-wrap wrap-break-word text-sm text-main-view-fg/70',
+ 'animate-in fade-in-0 slide-in-from-top-1 duration-300 ease-out'
+ )}
+ >
+ {current}
+ </div>
+ )
+ }
+)
ReasoningActiveStep.displayName = 'ReasoningActiveStep'
diff --git a/web-app/src/components/ai-elements/tool-runtime.tsx b/web-app/src/components/ai-elements/tool-runtime.tsx
new file mode 100644
index 000000000..5a7e2b423
--- /dev/null
+++ b/web-app/src/components/ai-elements/tool-runtime.tsx
@@ -0,0 +1,106 @@
+import { memo, useEffect, useState } from 'react'
+import { cn } from '@/lib/utils'
+import { formatCompactDuration } from '@/lib/duration'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
+
+/**
+ * Seconds since `startedAt`, ticking while the call is in flight and frozen at
+ * `endedAt` once it settles.
+ */
+function useElapsedSeconds(
+ startedAt?: number,
+ endedAt?: number
+): number | undefined {
+ const isRunning = startedAt !== undefined && endedAt === undefined
+ const [now, setNow] = useState(() => Date.now())
+
+ useEffect(() => {
+ if (!isRunning) return
+ setNow(Date.now())
+ const id = setInterval(() => setNow(Date.now()), 1000)
+ return () => clearInterval(id)
+ }, [isRunning, startedAt])
+
+ if (startedAt === undefined) return undefined
+ return Math.max(0, ((endedAt ?? now) - startedAt) / 1000)
+}
+
+export type ToolElapsedProps = {
+ startedAt?: number
+ endedAt?: number
+ className?: string
+}
+
+export const ToolElapsed = memo(
+ ({ startedAt, endedAt, className }: ToolElapsedProps) => {
+ const { t } = useTranslation()
+ const seconds = useElapsedSeconds(startedAt, endedAt)
+
+ if (seconds === undefined) return null
+ // A settled call under a second has no duration worth reporting; a running
+ // one still shows 0s, so the timer is visibly live from the start.
+ if (endedAt !== undefined && seconds < 1) return null
+
+ return (
+ <span className={cn('shrink-0 tabular-nums text-xs', className)}>
+ {formatCompactDuration(seconds, t)}
+ </span>
+ )
+ }
+)
+
+ToolElapsed.displayName = 'ToolElapsed'
+
+export type ToolProgressRowProps = {
+ toolCallId?: string
+ className?: string
+}
+
+/**
+ * Live progress from an MCP server. Most servers never send
+ * `notifications/progress`, so this renders only once one does.
+ */
+export const ToolProgressRow = memo(
+ ({ toolCallId, className }: ToolProgressRowProps) => {
+ const { t } = useTranslation()
+ const update = useToolCallRuntime((s) =>
+ toolCallId ? s.progress[toolCallId] : undefined
+ )
+
+ if (!update) return null
+
+ const label = update.message ?? t('tools:toolCall.working')
+
+ return (
+ <div className={cn('mt-2 flex flex-col gap-1', className)}>
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <span className="min-w-0 truncate">{label}</span>
+ <span className="ml-auto shrink-0 tabular-nums">
+ {update.percent === undefined
+ ? // No total means no completion fraction to show, so report the
+ // raw count the server is counting up.
+ Math.round(update.progress)
+ : `${Math.round(update.percent)}%`}
+ </span>
+ </div>
+ {update.percent !== undefined && (
+ <div
+ role="progressbar"
+ aria-valuenow={Math.round(update.percent)}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ className="h-1 w-full overflow-hidden rounded-full bg-main-view-fg/10"
+ >
+ <div
+ className="h-full rounded-full bg-accent transition-[width] duration-300 ease-out"
+ style={{ width: `${update.percent}%` }}
+ />
+ </div>
+ )}
+ </div>
+ )
+ }
+)
+
+ToolProgressRow.displayName = 'ToolProgressRow'
diff --git a/web-app/src/components/ai-elements/tool.tsx b/web-app/src/components/ai-elements/tool.tsx
index fd80d5be3..6b68e3eb4 100644
--- a/web-app/src/components/ai-elements/tool.tsx
+++ b/web-app/src/components/ai-elements/tool.tsx
@@ -11,6 +11,7 @@ import { ChevronDownIcon, WrenchIcon } from 'lucide-react'
import type { ComponentProps, ReactNode } from 'react'
import {
createContext,
+ Fragment,
isValidElement,
memo,
useContext,
@@ -20,13 +21,26 @@ import {
useState,
} from 'react'
import { CodeBlock } from './code-block'
+import { CopyButton } from '@/containers/CopyButton'
+import {
+ isPlainObject,
+ parseToolInput,
+ stringifyToolInput,
+ summarizeToolInput,
+} from '@/lib/toolInputSummary'
+import { summarizeToolOutput } from '@/lib/toolOutputSummary'
import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'
+import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
+import { ToolElapsed } from './tool-runtime'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { Button } from '@/components/ui/button'
import { ShieldAlertIcon } from 'lucide-react'
import { Citations } from '@/components/Citations'
import { parseCitationsFromToolOutput } from '@/lib/citation-parser'
+/** Payloads shorter than this fit the collapsed box, so no expand control. */
+const OUTPUT_EXPAND_THRESHOLD = 600
+
type ToolContextValue = {
isOpen: boolean
setIsOpen: (open: boolean) => void
@@ -112,57 +126,115 @@ export type ToolHeaderProps = {
state: ToolUIPart['state']
type: ToolUIPart['type']
className?: string
+ /** Where the tool came from (web provider, documents, MCP server name). */
+ origin?: string
+ /** Arguments, previewed inline so a collapsed call still says what it did. */
+ input?: ToolUIPart['input']
}
+type TranslateFn = (key: string, options?: Record<string, unknown>) => string
+
const getStatusText = (
+ t: TranslateFn,
status: ToolUIPart['state'],
toolName: string,
- awaitingApproval: boolean
+ awaitingApproval: boolean,
+ isQueued: boolean
) => {
const isRunning = status === 'input-streaming' || status === 'input-available'
const hasError = status === 'output-error' || status === 'output-denied'
+ const tool = toolName.replaceAll('_', ' ')
if (awaitingApproval) {
- return `Awaiting approval: ${toolName.replaceAll('_', ' ')}`
+ return t('tools:toolCall.awaitingApproval', { tool })
+ }
+ // Tools run one at a time, so a pending call is only "running" once the
+ // executor has actually reached it.
+ if (isQueued) {
+ return t('tools:toolCall.queued', { tool })
}
if (isRunning) {
- return `Running ${toolName.replaceAll('_', ' ')}...`
+ return t('tools:toolCall.running', { tool })
}
if (hasError) {
- return `${toolName.replaceAll('_', ' ')} failed`
+ return t('tools:toolCall.failed', { tool })
}
- return `Used ${toolName.replaceAll('_', ' ')}`
+ return t('tools:toolCall.used', { tool })
}
export const ToolHeader = memo(
- ({ className, title, state, type }: ToolHeaderProps) => {
+ ({ className, title, state, type, origin, input }: ToolHeaderProps) => {
+ const { t } = useTranslation()
const { isOpen, toolCallId } = useTool()
const awaitingApproval = useToolApprovalRequests((s) =>
toolCallId ? Boolean(s.pending[toolCallId]) : false
)
const toolName = title ?? type.split('-').slice(1).join('-')
+ const summary = useMemo(() => summarizeToolInput(input), [input])
+ // Position in the pending queue, or -1 once the executor has reached it.
+ const queuePosition = useToolCallRuntime((s) =>
+ toolCallId ? s.queue.indexOf(toolCallId) : -1
+ )
+ const startedAt = useToolCallRuntime((s) =>
+ toolCallId ? s.timings[toolCallId]?.startedAt : undefined
+ )
+ const endedAt = useToolCallRuntime((s) =>
+ toolCallId ? s.timings[toolCallId]?.endedAt : undefined
+ )
return (
<CollapsibleTrigger
className={cn(
- 'cursor-pointer flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors capitalize', !isOpen && 'hover:bg-secondary',
+ 'cursor-pointer flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors',
+ !isOpen && 'hover:bg-secondary',
className
)}
>
{awaitingApproval ? (
- <ShieldAlertIcon className="size-4 text-amber-500" />
+ <ShieldAlertIcon className="size-4 shrink-0 text-amber-500" />
) : (
- <WrenchIcon className="size-4" />
+ <WrenchIcon className="size-4 shrink-0" />
)}
- <span className={cn(awaitingApproval && 'text-amber-600 dark:text-amber-400')}>
- {getStatusText(state, toolName, awaitingApproval)}
- </span>
- <ChevronDownIcon
+ <span
className={cn(
- 'size-4 transition-transform',
- isOpen ? 'rotate-180' : 'rotate-0'
+ 'shrink-0 capitalize',
+ awaitingApproval && 'text-amber-600 dark:text-amber-400'
+ )}
+ >
+ {getStatusText(
+ t,
+ state,
+ toolName,
+ awaitingApproval,
+ queuePosition >= 0
)}
- />
+ </span>
+ {origin && (
+ <span className="shrink-0 text-muted-foreground/60">{origin}</span>
+ )}
+ {summary && (
+ <span className="min-w-0 truncate text-left font-mono text-xs text-muted-foreground/60">
+ {summary}
+ </span>
+ )}
+ <span className="ml-auto flex shrink-0 items-center gap-2">
+ {queuePosition > 0 && (
+ <span className="text-xs text-muted-foreground/60">
+ {t('tools:toolCall.queuedPosition', { count: queuePosition })}
+ </span>
+ )}
+ <ToolElapsed
+ startedAt={startedAt}
+ endedAt={endedAt}
+ className="text-muted-foreground/60"
+ />
+ <ChevronDownIcon
+ className={cn(
+ 'size-4 shrink-0 transition-transform',
+ isOpen ? 'rotate-180' : 'rotate-0'
+ )}
+ />
+ </span>
</CollapsibleTrigger>
)
}
@@ -191,32 +263,63 @@ export type ToolInputProps = ComponentProps<'div'> & {
input: ToolUIPart['input']
}
+/** Table cells keep nested values readable rather than collapsing them. */
+const formatParamValue = (value: unknown): string =>
+ typeof value === 'string' ? value : stringifyToolInput(value)
+
export const ToolInput = memo(
({ className, input, ...props }: ToolInputProps) => {
- const formatted = useMemo(() => {
- let value: unknown = input
- if (typeof value === 'string') {
- try {
- value = JSON.parse(value)
- } catch {
- return value as string
- }
- }
- try {
- return JSON.stringify(value, null, 2)
- } catch {
- return String(value)
- }
- }, [input])
+ const { t } = useTranslation()
+ const [showRaw, setShowRaw] = useState(false)
+
+ const parsed = useMemo(() => parseToolInput(input), [input])
+ const formatted = useMemo(() => stringifyToolInput(parsed), [parsed])
+ const rows = useMemo(
+ () => (isPlainObject(parsed) ? Object.entries(parsed) : []),
+ [parsed]
+ )
+ const asTable = rows.length > 0 && !showRaw
return (
<div className={cn('space-y-2', className)} {...props}>
- <h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
- Parameters
- </h4>
- <div className="rounded-md max-h-40 overflow-auto border ">
- <CodeBlock code={formatted} language="json" />
+ <div className="flex items-center gap-1">
+ <h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
+ {t('tools:toolCall.parameters')}
+ </h4>
+ <div className="ml-auto flex items-center gap-1">
+ {rows.length > 0 && (
+ <Button
+ variant="ghost"
+ size="sm"
+ type="button"
+ onClick={() => setShowRaw((raw) => !raw)}
+ >
+ {showRaw
+ ? t('tools:toolCall.viewTable')
+ : t('tools:toolCall.viewRaw')}
+ </Button>
+ )}
+ <CopyButton text={formatted} />
+ </div>
</div>
+ {asTable ? (
+ <dl className="grid grid-cols-[minmax(0,8rem)_minmax(0,1fr)] gap-x-3 gap-y-1.5">
+ {rows.map(([key, value]) => (
+ <Fragment key={key}>
+ <dt className="truncate font-mono text-xs text-muted-foreground/70">
+ {key}
+ </dt>
+ <dd className="min-w-0 max-h-24 overflow-auto whitespace-pre-wrap wrap-break-word font-mono text-xs">
+ {formatParamValue(value)}
+ </dd>
+ </Fragment>
+ ))}
+ </dl>
+ ) : (
+ <div className="rounded-md max-h-40 overflow-auto border">
+ <CodeBlock code={formatted} language="json" />
+ </div>
+ )}
</div>
)
}
@@ -253,12 +356,26 @@ export const ToolApprovalActions = memo(() => {
>
{t('tools:toolApproval.allowOnce')}
</Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => resolveApproval(toolCallId, 'allow-thread')}
+ >
+ {t('tools:toolApproval.allowInThread')}
+ </Button>
<Button
size="sm"
autoFocus
onClick={() => resolveApproval(toolCallId, 'allow-always')}
>
- {t('tools:toolApproval.alwaysAllow')}
+ {/* Trusting a server tool-by-tool is the same decision repeated. */}
+ {pending.serverName
+ ? t('tools:toolApproval.allowServerAlways', {
+ server: pending.serverName,
+ })
+ : t('tools:toolApproval.allowToolAlways', {
+ tool: pending.toolName,
+ })}
</Button>
</div>
</div>
@@ -330,12 +447,36 @@ export const ToolOutput = memo(
citationOffset = 0,
...props
}: ToolOutputProps) => {
+ const { t } = useTranslation()
const { messageId } = useTool()
+ const [expanded, setExpanded] = useState(false)
+ const [showRaw, setShowRaw] = useState(false)
const citationPayload = useMemo(
() => (output ? parseCitationsFromToolOutput(output) : null),
[output]
)
+ // Generic results lead with a description of what came back; the payload
+ // itself is one click away rather than dumped as JSON.
+ const summary = useMemo(
+ () => (citationPayload || errorText ? undefined : summarizeToolOutput(output)),
+ [citationPayload, errorText, output]
+ )
+
+ const copyText = useMemo(
+ () => (errorText ? errorText : stringifyToolInput(output)),
+ [errorText, output]
+ )
+ // Only offer expansion for payloads long enough to be clipped. Citation
+ // output (native web search, RAG) renders as cards outside the scroll box,
+ // so there is no height for the control to act on.
+ const isLong =
+ !citationPayload && copyText.length > OUTPUT_EXPAND_THRESHOLD
+ const boxClassName = cn(
+ 'rounded-md overflow-auto border',
+ expanded ? 'max-h-[32rem]' : 'max-h-40'
+ )
+
const Output = useMemo(() => {
if (!(output || errorText)) {
return null
@@ -354,7 +495,7 @@ export const ToolOutput = memo(
// Handle string output
if (typeof output === 'string') {
return (
- <div className="max-h-40 overflow-auto rounded-md border ">
+ <div className={boxClassName}>
<CodeBlock code={output} language="json" />
</div>
)
@@ -383,10 +524,7 @@ export const ToolOutput = memo(
{textItems.length > 0 && (
<div className="space-y-2">
{textItems.map((item, index) => (
- <div
- key={index}
- className="rounded-md max-h-40 overflow-auto border "
- >
+ <div key={index} className={boxClassName}>
<CodeBlock code={item.text || ''} language="markdown" />
</div>
))}
@@ -423,7 +561,7 @@ export const ToolOutput = memo(
return (
<div className="space-y-4">
{nonImageOutput.length > 0 && (
- <div className="rounded-md max-h-40 overflow-auto rounded-md border ">
+ <div className={boxClassName}>
<CodeBlock
code={JSON.stringify(nonImageOutput, null, 2)}
language="json"
@@ -448,7 +586,7 @@ export const ToolOutput = memo(
}
return (
- <div className="rounded-md max-h-40 overflow-auto border ">
+ <div className={boxClassName}>
<CodeBlock
code={JSON.stringify(output, null, 2)}
language="json"
@@ -459,14 +597,22 @@ export const ToolOutput = memo(
// Handle regular object
return (
- <div className="rounded-md max-h-40 overflow-auto border ">
+ <div className={boxClassName}>
<CodeBlock code={JSON.stringify(output, null, 2)} language="json" />
</div>
)
}
return <div>{output as ReactNode}</div>
- }, [output, errorText, resolver, citationPayload, messageId, citationOffset])
+ }, [
+ output,
+ errorText,
+ resolver,
+ citationPayload,
+ messageId,
+ citationOffset,
+ boxClassName,
+ ])
if (!(output || errorText)) {
return null
@@ -474,16 +620,50 @@ export const ToolOutput = memo(
return (
<div className={cn('space-y-2 mt-4', className)} {...props}>
- <h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
- {errorText ? 'Error' : 'Result'}
- </h4>
+ <div className="flex items-center gap-1">
+ <h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
+ {errorText ? t('tools:toolCall.error') : t('tools:toolCall.result')}
+ </h4>
+ <div className="ml-auto flex items-center gap-1">
+ {summary && (
+ <Button
+ variant="ghost"
+ size="sm"
+ type="button"
+ onClick={() => setShowRaw((raw) => !raw)}
+ >
+ {showRaw
+ ? t('tools:toolCall.hideRaw')
+ : t('tools:toolCall.viewRaw')}
+ </Button>
+ )}
+ {isLong && (!summary || showRaw) && (
+ <Button
+ variant="ghost"
+ size="sm"
+ type="button"
+ onClick={() => setExpanded((open) => !open)}
+ >
+ {expanded
+ ? t('tools:toolCall.showLess')
+ : t('tools:toolCall.showMore')}
+ </Button>
+ )}
+ <CopyButton text={copyText} />
+ </div>
+ </div>
+ {summary && (
+ <p className="text-sm text-muted-foreground">
+ {t(summary.key, summary.values)}
+ </p>
+ )}
<div className="rounded-md overflow-hidden">
{errorText && (
<div className="m-2 p-2 bg-destructive/10 text-destructive rounded-md">
{errorText}
</div>
)}
- {Output}
+ {(!summary || showRaw) && Output}
</div>
</div>
)
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 7c27a72c9..678c78203 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -1,22 +1,15 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
-import { memo, useState, useCallback, useEffect, cloneElement } from 'react'
+import { memo, useState, useCallback, useEffect, useMemo } from 'react'
import type { UIMessage, ChatStatus } from 'ai'
import { RenderMarkdown } from './RenderMarkdown'
import { cn } from '@/lib/utils'
-import { twMerge } from 'tailwind-merge'
+import { ChainOfThoughtGroup } from './message/ChainOfThoughtGroup'
import {
- ChainOfThought,
- ChainOfThoughtContent,
- ChainOfThoughtHeader,
-} from '@/components/ai-elements/chain-of-thought'
-import {
- Tool,
- ToolApprovalActions,
- ToolContent,
- ToolHeader,
- ToolInput,
- ToolOutput,
-} from '@/components/ai-elements/tool'
+ CHAT_STATUS,
+ CONTENT_TYPE,
+ type MessagePartLike,
+ type PartEntry,
+} from './message/types'
import { CopyButton } from './CopyButton'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { formatDate } from '@/utils/formatDate'
@@ -27,17 +20,14 @@ import {
IconRefresh,
IconPlayerPlay,
IconPaperclip,
- IconArrowDown,
IconAlertTriangle,
IconChevronLeft,
IconChevronRight,
- IconCircleCheck,
} from '@tabler/icons-react'
import { EditMessageDialog } from '@/containers/dialogs/EditMessageDialog'
import { DeleteMessageDialog } from '@/containers/dialogs/DeleteMessageDialog'
import TokenSpeedIndicator from '@/containers/TokenSpeedIndicator'
import { extractFilesFromPrompt, FileMetadata } from '@/lib/fileMetadata'
-import { useMemo } from 'react'
import { Button } from '@/components/ui/button'
import { PromptProgress } from '@/components/PromptProgress'
import { useServiceHub } from '@/hooks/useServiceHub'
@@ -48,30 +38,6 @@ import { useGroundingStore } from '@/stores/grounding-store'
import { useWebCitationStore } from '@/stores/web-citation-store'
import { WebSourcesRow } from '@/components/WebSourcesRow'
import { injectCitationMarkers } from '@/lib/grounding'
-import {
- ReasoningActiveStep,
- StepRow,
-} from '@/components/ai-elements/reasoning-timeline'
-import { splitReasoningParagraphs } from '@/lib/reasoning'
-
-const CHAT_STATUS = {
- STREAMING: 'streaming',
- SUBMITTED: 'submitted',
-} as const
-
-const CONTENT_TYPE = {
- TEXT: 'text',
- FILE: 'file',
- REASONING: 'reasoning',
-} as const
-
-// Turn a tool identifier (e.g. "web_search", "exa_search") into a readable
-// label for the streaming step header (e.g. "Web search").
-function humanizeToolName(name: string): string {
- const spaced = name.replace(/[_-]+/g, ' ').trim()
- if (!spaced) return 'tool'
- return spaced.charAt(0).toUpperCase() + spaced.slice(1)
-}
export type MessageItemProps = {
message: UIMessage
@@ -88,8 +54,6 @@ export type MessageItemProps = {
onDelete?: (messageId: string) => void
versionInfo?: { index: number; count: number }
onSwitchVersion?: (messageId: string, dir: -1 | 1) => void
- assistant?: { avatar?: React.ReactNode; name?: string }
- showAssistant?: boolean
isAnimating?: boolean
hideActions?: boolean
}
@@ -366,15 +330,7 @@ export const MessageItem = memo(
)
}
- const renderFilePart = (
- part: {
- type: 'file'
- filename?: string
- url?: string
- mediaType?: string
- },
- partIndex: number
- ) => {
+ const renderFilePart = (part: MessagePartLike, partIndex: number) => {
const isImage = part.mediaType?.startsWith('image/')
const isAudio =
part.mediaType === 'audio/wav' || part.mediaType === 'audio/mpeg'
@@ -454,266 +410,8 @@ export const MessageItem = memo(
return null
}
- const renderToolInline = (part: any, partIndex: number) => {
- if (!part.type.startsWith('tool-') || !('state' in part)) {
- return null
- }
-
- const toolName = part.type.split('-').slice(1).join('-')
- return (
- <Tool
- key={`${message.id}-${partIndex}`}
- state={part.state}
- toolCallId={part.toolCallId}
- messageId={message.id}
- className="mb-1"
- >
- <ToolHeader
- title={toolName}
- type={`tool-${toolName}` as `tool-${string}`}
- state={part.state}
- />
- <ToolContent title={toolName}>
- {part.input && <ToolInput input={part.input} />}
- <ToolApprovalActions />
- {part.output && (
- <ToolOutput
- output={part.output}
- resolver={(input) => Promise.resolve(input)}
- errorText={undefined}
- citationOffset={citationOffsets.get(partIndex) ?? 0}
- />
- )}
- {part.state === 'output-error' && (
- <ToolOutput
- output={undefined}
- errorText={part.error || part.errorText || 'Tool execution failed'}
- resolver={(input) => Promise.resolve(input)}
- />
- )}
- </ToolContent>
- </Tool>
- )
- }
-
- type PartEntry = { part: any; index: number }
-
- const renderCotGroup = (
- entries: PartEntry[],
- groupKey: string,
- hasFollowingContent: boolean
- ) => {
- const hasTools = entries.some((e) => e.part.type.startsWith('tool-'))
-
- const lastEntryIndex = entries[entries.length - 1].index
- const groupIsStreaming =
- isStreaming && lastEntryIndex === message.parts.length - 1
-
- // While streaming, surface only the latest step (current reasoning
- // paragraph or tool call) so each step replaces the previous one rather
- // than the whole trace scrolling by. The full trace renders once done.
- const isMeaningfulEntry = ({ part }: PartEntry) => {
- if (part.type === CONTENT_TYPE.REASONING || part.type === CONTENT_TYPE.TEXT) {
- return Boolean(part.text && part.text.trim())
- }
- return part.type.startsWith('tool-') && 'state' in part
- }
- const meaningful = entries.filter(isMeaningfulEntry)
- // While streaming, show only the latest step — but never truncate away a
- // tool part that is awaiting the user's approval, or its approve/deny
- // controls would never mount and the run would hang (multi-tool turns).
- const lastMeaningful = meaningful[meaningful.length - 1]
- const visibleEntries =
- groupIsStreaming && meaningful.length > 0
- ? meaningful.filter((e) => {
- if (e === lastMeaningful) return true
- const toolCallId = (e.part as { toolCallId?: string }).toolCallId
- return Boolean(toolCallId && pendingApprovals[toolCallId])
- })
- : entries
-
- // Streaming label reflects the current step, not whether the whole trace
- // ever used a tool — otherwise it sticks on "Using tools…" once the model
- // resumes reasoning after a tool call.
- const currentStepIsTool =
- meaningful.length > 0 &&
- meaningful[meaningful.length - 1].part.type.startsWith('tool-')
-
- const currentToolLabel = currentStepIsTool
- ? humanizeToolName(
- meaningful[meaningful.length - 1].part.type
- .split('-')
- .slice(1)
- .join('-')
- )
- : ''
-
- // Only reasoning text is worth expanding for — a tool-only step collapses
- // to the header. While streaming that means the current step is a
- // reasoning paragraph that has completed at least once (something for
- // ReasoningActiveStep to render); once done, any reasoning text qualifies.
- const hasDisplayableContent = groupIsStreaming
- ? lastMeaningful?.part.type === CONTENT_TYPE.REASONING &&
- splitReasoningParagraphs(lastMeaningful.part.text ?? '').length >= 2
- : entries.some(
- (e) =>
- e.part.type === CONTENT_TYPE.REASONING &&
- Boolean(e.part.text && e.part.text.trim())
- )
-
- // Force open only while a tool awaits approval — its approve/deny controls
- // live inside the collapsible and must stay mounted. A running (already
- // approved) tool does not force it open, so tool-only steps collapse.
- const forceOpen = awaitingApproval
- const shouldCollapse = hasFollowingContent || !hasDisplayableContent
-
- // Done/historical: flatten every entry (reasoning paragraphs, tool calls,
- // interstitial text, files) into steps on a single continuous dotted rail,
- // so a tool call between two reasoning paragraphs stays threaded instead of
- // restarting the rail.
- const renderTimeline = (rows: PartEntry[]) => {
- const steps: React.ReactNode[] = []
- for (const { part, index: partIndex } of rows) {
- if (part.type === CONTENT_TYPE.REASONING) {
- for (const [pi, para] of splitReasoningParagraphs(
- part.text ?? ''
- ).entries()) {
- steps.push(
- <StepRow key={`${message.id}-r-${partIndex}-${pi}`} text={para} />
- )
- }
- continue
- }
- if (part.type === CONTENT_TYPE.TEXT) {
- if (!part.text || part.text.trim() === '') continue
- steps.push(
- <StepRow key={`${message.id}-it-${partIndex}`} text={part.text} />
- )
- continue
- }
- if (part.type === CONTENT_TYPE.FILE) {
- const node = renderFilePart(part, partIndex)
- if (node)
- steps.push(
- <StepRow key={`${message.id}-f-${partIndex}`}>{node}</StepRow>
- )
- continue
- }
- const toolNode = renderToolInline(part, partIndex)
- if (toolNode)
- steps.push(
- <StepRow key={`${message.id}-t-${partIndex}`}>{toolNode}</StepRow>
- )
- }
- if (steps.length === 0) return null
- steps.push(
- <StepRow
- key={`${message.id}-done`}
- marker={
- <IconCircleCheck className="size-4 text-muted-foreground/60" />
- }
- text={t('chat:done')}
- />
- )
- return (
- <ol className="relative flex flex-col gap-2.5">
- {steps.map((step, i) =>
- step && typeof step === 'object' && 'props' in step
- ? cloneElement(step as React.ReactElement<{ connector?: boolean }>, {
- connector: i < steps.length - 1,
- })
- : step
- )}
- </ol>
- )
- }
-
- return (
- <ChainOfThought
- key={groupKey}
- className="w-full text-muted-foreground"
- isStreaming={groupIsStreaming}
- shouldCollapse={shouldCollapse}
- forceOpen={forceOpen}
- defaultOpen={hasDisplayableContent && !hasFollowingContent}
- >
- <ChainOfThoughtHeader
- streamingLabel={
- currentStepIsTool ? `${currentToolLabel}...` : 'Thinking'
- }
- completedVerb={hasTools ? 'Worked' : 'Thought'}
- />
- <ChainOfThoughtContent>
- {groupIsStreaming
- ? visibleEntries.map(({ part, index: partIndex }) => {
- if (part.type === CONTENT_TYPE.REASONING) {
- const partIsStreaming =
- isStreaming && partIndex === message.parts.length - 1
-
- // Streaming: show only the current paragraph as a single
- // active step (bounded height, swaps as each paragraph
- // completes).
- if (partIsStreaming) {
- return (
- <div
- key={`${message.id}-r-${partIndex}`}
- className="relative"
- >
- <div
- ref={reasoningContainerRef}
- onScroll={onReasoningScroll}
- className={twMerge(
- 'w-full overflow-auto relative max-h-40',
- '[scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden'
- )}
- >
- <ReasoningActiveStep text={part.text} />
- </div>
- {!isReasoningAtBottom && (
- <Button
- className="absolute bottom-2 left-[50%] translate-x-[-50%] rounded-full size-7 z-10"
- onClick={onReasoningScrollToBottom}
- size="icon"
- type="button"
- variant="outline"
- >
- <IconArrowDown className="size-3" />
- </Button>
- )}
- </div>
- )
- }
-
- return null
- }
-
- if (part.type === CONTENT_TYPE.TEXT) {
- if (!part.text || part.text.trim() === '') return null
- return (
- <div
- key={`${message.id}-it-${partIndex}`}
- dir="auto"
- className="select-text whitespace-pre-wrap wrap-break-word text-sm text-main-view-fg/70"
- >
- {part.text}
- </div>
- )
- }
-
- if (part.type === CONTENT_TYPE.FILE) {
- return renderFilePart(part, partIndex)
- }
-
- return renderToolInline(part, partIndex)
- })
- : renderTimeline(visibleEntries)}
- </ChainOfThoughtContent>
- </ChainOfThought>
- )
- }
-
const renderedParts = useMemo(() => {
- const parts = message.parts as any[]
+ const parts = message.parts as MessagePartLike[]
const elements: React.ReactNode[] = []
const isCotPart = (t: string) =>
t === CONTENT_TYPE.REASONING || t.startsWith('tool-')
@@ -726,18 +424,27 @@ export const MessageItem = memo(
const flushCot = (hasFollowing: boolean) => {
if (cotEntries.length === 0) return
elements.push(
- renderCotGroup(
- cotEntries,
- `${message.id}-cot-${groupSeq++}`,
- hasFollowing
- )
+ <ChainOfThoughtGroup
+ key={`${message.id}-cot-${groupSeq++}`}
+ entries={cotEntries}
+ messageId={message.id}
+ totalParts={parts.length}
+ isStreaming={isStreaming}
+ hasFollowingContent={hasFollowing}
+ awaitingApproval={awaitingApproval}
+ citationOffsets={citationOffsets}
+ reasoningContainerRef={reasoningContainerRef}
+ isReasoningAtBottom={isReasoningAtBottom}
+ onReasoningScroll={onReasoningScroll}
+ onReasoningScrollToBottom={onReasoningScrollToBottom}
+ />
)
cotEntries = []
}
for (let i = 0; i < parts.length; i++) {
const part = parts[i]
- const t = part.type as string
+ const t = part.type
if (isCotPart(t)) {
cotEntries.push({ part, index: i })
continue
@@ -752,13 +459,20 @@ export const MessageItem = memo(
}
if (t === CONTENT_TYPE.FILE) {
flushCot(true)
- elements.push(renderFilePart(part as any, i))
+ elements.push(renderFilePart(part, i))
}
}
flushCot(false)
return elements
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [message.parts, isStreaming, isReasoningAtBottom, grounding])
+ }, [
+ message.parts,
+ isStreaming,
+ isReasoningAtBottom,
+ grounding,
+ awaitingApproval,
+ citationOffsets,
+ ])
const versionNav =
versionInfo && versionInfo.count > 1 && onSwitchVersion ? (
@@ -959,7 +673,6 @@ export const MessageItem = memo(
prevProps.isFirstMessage === nextProps.isFirstMessage &&
prevProps.isLastMessage === nextProps.isLastMessage &&
prevProps.status === nextProps.status &&
- prevProps.showAssistant === nextProps.showAssistant &&
prevProps.hideActions === nextProps.hideActions &&
prevProps.versionInfo?.index === nextProps.versionInfo?.index &&
prevProps.versionInfo?.count === nextProps.versionInfo?.count
diff --git a/web-app/src/containers/dialogs/ToolApproval.tsx b/web-app/src/containers/dialogs/ToolApproval.tsx
deleted file mode 100644
index 527bfc7bc..000000000
--- a/web-app/src/containers/dialogs/ToolApproval.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@/components/ui/dialog'
-import { Button } from '@/components/ui/button'
-import { useToolApproval } from '@/hooks/useToolApproval'
-import { AlertTriangle } from 'lucide-react'
-import { useTranslation } from '@/i18n/react-i18next-compat'
-
-export default function ToolApproval() {
- const { t } = useTranslation()
- const { isModalOpen, modalProps, setModalOpen } = useToolApproval()
-
- if (!modalProps) {
- return null
- }
-
- const { toolName, toolParameters, onApprove, onDeny } = modalProps
-
- const handleAllowOnce = () => {
- onApprove(true) // true = allow once only
- }
-
- const handleAllow = () => {
- onApprove(false) // false = remember for this thread
- }
-
- const handleDeny = () => {
- onDeny()
- }
-
- const handleDialogOpen = (open: boolean) => {
- setModalOpen(open)
- if (!open) {
- onDeny()
- }
- }
-
- return (
- <Dialog open={isModalOpen} onOpenChange={handleDialogOpen}>
- <DialogContent showCloseButton={false}>
- <DialogHeader>
- <div className="flex items-start gap-3">
- <div className="shrink-0 text-muted-foreground">
- <AlertTriangle className="size-4" />
- </div>
- <div>
- <DialogTitle>{t('tools:toolApproval.title')}</DialogTitle>
- <DialogDescription className="mt-1 text-muted-foreground">
- {t('tools:toolApproval.description')}{' '}
- <span className="font-semibold">{toolName}</span>.&nbsp;
- <span className="text-sm">
- {t('tools:toolApproval.permissionScope')}
- </span>
- </DialogDescription>
- </div>
- </div>
- </DialogHeader>
-
- {toolParameters && Object.keys(toolParameters).length > 0 && (
- <div className="bg-background p-2 border rounded-lg overflow-x-scroll">
- <h4 className="text-sm font-medium mb-2">
- {t('tools:toolApproval.parameters')}
- </h4>
- <div className="relative bg-secondary rounded-md p-2 text-sm font-mono border overflow-x-auto">
- <pre className="whitespace-pre-wrap">
- {JSON.stringify(toolParameters, null, 2)}
- </pre>
- </div>
- </div>
- )}
-
- <div className="p-2 border bg-secondary rounded-lg">
- <p className="text-xs text-muted-foreground leading-relaxed">
- {t('tools:toolApproval.securityNotice')}
- </p>
- </div>
-
- <DialogFooter className="flex flex-col gap-2 sm:flex-row sm:justify-between">
- <Button
- variant="ghost"
- size="sm"
- onClick={handleDeny}
- className="flex-1 text-right sm:flex-none"
- >
- {t('tools:toolApproval.deny')}
- </Button>
- <div className="flex flex-col sm:flex-row gap-2 items-center">
- <Button
- variant="ghost"
- size="sm"
- onClick={handleAllowOnce}
- >
- {t('tools:toolApproval.allowOnce')}
- </Button>
- <Button
- variant="default"
- size="sm"
- onClick={handleAllow}
- autoFocus
- className="capitalize"
- >
- {t('tools:toolApproval.alwaysAllow')}
- </Button>
- </div>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/web-app/src/containers/message/ChainOfThoughtGroup.tsx b/web-app/src/containers/message/ChainOfThoughtGroup.tsx
new file mode 100644
index 000000000..ae6e72bfd
--- /dev/null
+++ b/web-app/src/containers/message/ChainOfThoughtGroup.tsx
@@ -0,0 +1,296 @@
+import { cloneElement, memo, useState } from 'react'
+import { twMerge } from 'tailwind-merge'
+import { IconArrowDown, IconCircleCheck } from '@tabler/icons-react'
+import {
+ ChainOfThought,
+ ChainOfThoughtContent,
+ ChainOfThoughtHeader,
+} from '@/components/ai-elements/chain-of-thought'
+import {
+ ReasoningActiveStep,
+ StepRow,
+} from '@/components/ai-elements/reasoning-timeline'
+import { Button } from '@/components/ui/button'
+import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'
+import {
+ findRunningToolCallId,
+ useToolCallRuntime,
+} from '@/hooks/useToolCallRuntime'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { segmentReasoningSteps } from '@/lib/reasoning'
+import { ToolCallCard } from './ToolCallCard'
+import { CONTENT_TYPE, isToolPart, type PartEntry } from './types'
+
+// Turn a tool identifier (e.g. "web_search", "exa_search") into a readable
+// label for the streaming step header (e.g. "Web search").
+function humanizeToolName(name: string): string {
+ const spaced = name.replace(/[_-]+/g, ' ').trim()
+ if (!spaced) return 'tool'
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)
+}
+
+export type ChainOfThoughtGroupProps = {
+ /** Reasoning and tool parts belonging to this trace, in message order. */
+ entries: PartEntry[]
+ messageId: string
+ /** Total parts on the message, used to detect the currently streaming part. */
+ totalParts: number
+ isStreaming: boolean
+ /** An answer follows this trace, so it should auto-collapse. */
+ hasFollowingContent: boolean
+ /** Any tool on the message awaits approval; pins the trace open. */
+ awaitingApproval: boolean
+ citationOffsets: Map<number, number>
+ reasoningContainerRef?: React.RefObject<HTMLDivElement | null>
+ isReasoningAtBottom?: boolean
+ onReasoningScroll?: () => void
+ onReasoningScrollToBottom?: () => void
+}
+
+export const ChainOfThoughtGroup = memo(
+ ({
+ entries,
+ messageId,
+ totalParts,
+ isStreaming,
+ hasFollowingContent,
+ awaitingApproval,
+ citationOffsets,
+ reasoningContainerRef,
+ isReasoningAtBottom,
+ onReasoningScroll,
+ onReasoningScrollToBottom,
+ }: ChainOfThoughtGroupProps) => {
+ const { t } = useTranslation()
+ const pendingApprovals = useToolApprovalRequests((s) => s.pending)
+ const runningToolCallId = useToolCallRuntime((s) => findRunningToolCallId(s.timings))
+ const [view, setView] = useState<'condensed' | 'extended'>('condensed')
+
+ if (entries.length === 0) return null
+
+ const hasTools = entries.some((e) => isToolPart(e.part))
+
+ const lastEntryIndex = entries[entries.length - 1].index
+ const groupIsStreaming = isStreaming && lastEntryIndex === totalParts - 1
+ // The extended timeline only exists while streaming; once the turn ends the
+ // full rail is what renders anyway.
+ const isExtended = groupIsStreaming && view === 'extended'
+
+ // While streaming, surface only the latest step (current reasoning
+ // paragraph or tool call) so each step replaces the previous one rather
+ // than the whole trace scrolling by. The full trace renders once done.
+ const isMeaningfulEntry = ({ part }: PartEntry) => {
+ if (part.type === CONTENT_TYPE.REASONING) {
+ return Boolean(part.text && part.text.trim())
+ }
+ return isToolPart(part)
+ }
+ const meaningful = entries.filter(isMeaningfulEntry)
+ // Tools execute one at a time, so with several calls in a turn the last
+ // part is the one at the back of the queue. Follow the call actually doing
+ // the work; before execution starts nothing is running and the newest part
+ // is still the right thing to show as it streams in.
+ const running = runningToolCallId
+ ? meaningful.find((e) => e.part.toolCallId === runningToolCallId)
+ : undefined
+ const lastMeaningful = running ?? meaningful[meaningful.length - 1]
+ // While streaming, show only the current step — but never truncate away a
+ // tool part that is awaiting the user's approval, or its approve/deny
+ // controls would never mount and the run would hang (multi-tool turns).
+ const visibleEntries =
+ groupIsStreaming && meaningful.length > 0
+ ? meaningful.filter((e) => {
+ if (e === lastMeaningful) return true
+ const toolCallId = e.part.toolCallId
+ return Boolean(toolCallId && pendingApprovals[toolCallId])
+ })
+ : entries
+
+ // Streaming label reflects the current step, not whether the whole trace
+ // ever used a tool — otherwise it sticks on "Using tools…" once the model
+ // resumes reasoning after a tool call.
+ const currentStepIsTool = Boolean(
+ lastMeaningful && isToolPart(lastMeaningful.part)
+ )
+
+ const currentToolLabel = currentStepIsTool
+ ? humanizeToolName(lastMeaningful.part.type.split('-').slice(1).join('-'))
+ : ''
+
+ // While streaming, expand for a tool call -- its card carries the live
+ // search/address bar and the result, all of which sit inside this
+ // collapsible -- or for reasoning that has a settled step to show, i.e. the
+ // trace has advanced past its first step. Once done, any reasoning text
+ // qualifies. An answer following the trace still collapses it, so the card
+ // does not linger once the model moves on.
+ const hasDisplayableContent = groupIsStreaming
+ ? currentStepIsTool ||
+ (lastMeaningful?.part.type === CONTENT_TYPE.REASONING &&
+ segmentReasoningSteps(lastMeaningful.part.text ?? '').length >= 2)
+ : entries.some(
+ (e) =>
+ e.part.type === CONTENT_TYPE.REASONING &&
+ Boolean(e.part.text && e.part.text.trim())
+ )
+
+ // Pinned open while a tool awaits approval — its approve/deny controls live
+ // inside the collapsible and must stay mounted even if an answer has
+ // started. The extended view always has the live step to show, so it must
+ // not be collapsed out from under the reader who just opened it.
+ const shouldCollapse =
+ hasFollowingContent || !(hasDisplayableContent || isExtended)
+
+ // Done/historical: flatten every entry (reasoning paragraphs, tool calls)
+ // into steps on a single continuous dotted rail, so a tool call between two
+ // reasoning paragraphs stays threaded instead of restarting the rail.
+ // `live` keeps the in-progress step as the trailing row and drops the Done
+ // marker, so the same rail serves the extended streaming view.
+ const renderTimeline = (rows: PartEntry[], live: boolean) => {
+ const steps: React.ReactNode[] = []
+ for (const { part, index: partIndex } of rows) {
+ if (part.type === CONTENT_TYPE.REASONING) {
+ const text = part.text ?? ''
+ const segments = segmentReasoningSteps(text)
+ const isLivePart = live && partIndex === totalParts - 1
+ const settled = isLivePart ? segments.slice(0, -1) : segments
+ for (const [pi, para] of settled.entries()) {
+ steps.push(
+ <StepRow key={`${messageId}-r-${partIndex}-${pi}`} text={para} />
+ )
+ }
+ if (isLivePart && segments.length > 0) {
+ steps.push(
+ <StepRow key={`${messageId}-rl-${partIndex}`}>
+ <ReasoningActiveStep text={text} mode="live" />
+ </StepRow>
+ )
+ }
+ continue
+ }
+ if (isToolPart(part)) {
+ steps.push(
+ <StepRow key={`${messageId}-t-${partIndex}`}>
+ <ToolCallCard
+ part={part}
+ messageId={messageId}
+ citationOffset={citationOffsets.get(partIndex) ?? 0}
+ className="mb-1"
+ />
+ </StepRow>
+ )
+ }
+ }
+ if (steps.length === 0) return null
+ if (!live) {
+ steps.push(
+ <StepRow
+ key={`${messageId}-done`}
+ marker={
+ <IconCircleCheck className="size-4 text-muted-foreground/60" />
+ }
+ text={t('chat:done')}
+ />
+ )
+ }
+ return (
+ <ol className="relative flex flex-col gap-2.5">
+ {steps.map((step, i) =>
+ step && typeof step === 'object' && 'props' in step
+ ? cloneElement(step as React.ReactElement<{ connector?: boolean }>, {
+ connector: i < steps.length - 1,
+ })
+ : step
+ )}
+ </ol>
+ )
+ }
+
+ // Auto-followed viewport: the parent's scroll hook keeps it pinned to the
+ // newest content until the reader scrolls up.
+ const autoFollowBox = (content: React.ReactNode, maxHeight: string) => (
+ <div className="relative">
+ <div
+ ref={reasoningContainerRef}
+ onScroll={onReasoningScroll}
+ className={twMerge(
+ 'w-full overflow-auto relative',
+ maxHeight,
+ '[scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden'
+ )}
+ >
+ {content}
+ </div>
+ {!isReasoningAtBottom && (
+ <Button
+ className="absolute bottom-2 left-[50%] translate-x-[-50%] rounded-full size-7 z-10"
+ onClick={onReasoningScrollToBottom}
+ size="icon"
+ type="button"
+ variant="outline"
+ >
+ <IconArrowDown className="size-3" />
+ </Button>
+ )}
+ </div>
+ )
+
+ // Condensed: the settled step only, so the text does not shift mid-read.
+ // 5 lines of text-sm (1.25rem line-height).
+ const renderCondensed = () =>
+ visibleEntries.map(({ part, index: partIndex }) => {
+ if (part.type === CONTENT_TYPE.REASONING) {
+ if (partIndex !== totalParts - 1) return null
+ return (
+ <div key={`${messageId}-r-${partIndex}`}>
+ {autoFollowBox(
+ <ReasoningActiveStep text={part.text ?? ''} />,
+ 'max-h-[6.25rem]'
+ )}
+ </div>
+ )
+ }
+
+ return (
+ <ToolCallCard
+ key={`${messageId}-t-${partIndex}`}
+ part={part}
+ messageId={messageId}
+ citationOffset={citationOffsets.get(partIndex) ?? 0}
+ className="mb-1"
+ />
+ )
+ })
+
+ return (
+ <ChainOfThought
+ className="w-full text-muted-foreground"
+ isStreaming={groupIsStreaming}
+ shouldCollapse={shouldCollapse}
+ forceOpen={awaitingApproval}
+ defaultOpen={hasDisplayableContent && !hasFollowingContent}
+ >
+ <ChainOfThoughtHeader
+ streamingLabel={
+ currentStepIsTool
+ ? t('chat:reasoning.usingTool', { tool: currentToolLabel })
+ : t('chat:reasoning.thinking')
+ }
+ completedVariant={hasTools ? 'worked' : 'thought'}
+ navDirection={
+ groupIsStreaming ? (isExtended ? 'left' : 'right') : undefined
+ }
+ onNavigate={() => setView(isExtended ? 'condensed' : 'extended')}
+ />
+ <ChainOfThoughtContent>
+ {!groupIsStreaming
+ ? renderTimeline(entries, false)
+ : isExtended
+ ? autoFollowBox(renderTimeline(entries, true), 'max-h-80')
+ : renderCondensed()}
+ </ChainOfThoughtContent>
+ </ChainOfThought>
+ )
+ }
+)
+
+ChainOfThoughtGroup.displayName = 'ChainOfThoughtGroup'
diff --git a/web-app/src/containers/message/RagToolWidget.tsx b/web-app/src/containers/message/RagToolWidget.tsx
new file mode 100644
index 000000000..8f4a7657f
--- /dev/null
+++ b/web-app/src/containers/message/RagToolWidget.tsx
@@ -0,0 +1,104 @@
+import { memo, useMemo } from 'react'
+import type { ToolUIPart } from 'ai'
+import { FileSearchIcon } from 'lucide-react'
+import { Shimmer } from '@/components/ai-elements/shimmer'
+import { Citations } from '@/components/Citations'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { parseCitationsFromToolOutput } from '@/lib/citation-parser'
+import { isToolRunning, type ToolCallBar } from '@/lib/toolPresentation'
+import { ToolBar } from './ToolBar'
+
+export type RagToolWidgetProps = {
+ bar: Extract<ToolCallBar, { variant: 'documents' }>
+ state: ToolUIPart['state']
+ output?: ToolUIPart['output']
+ errorText?: string
+ messageId?: string
+ citationOffset?: number
+}
+
+/**
+ * A document retrieval reads as a search over your own files: the query fills
+ * in as the model writes it, then the matched snippets render as citation
+ * cards, which already resolve file names and scores.
+ */
+export const RagToolWidget = memo(
+ ({
+ bar,
+ state,
+ output,
+ errorText,
+ messageId,
+ citationOffset = 0,
+ }: RagToolWidgetProps) => {
+ const { t } = useTranslation()
+ const running = isToolRunning(state)
+
+ const payload = useMemo(() => {
+ if (!output) return undefined
+ const parsed = parseCitationsFromToolOutput(output)
+ return parsed?.kind === 'rag' && parsed.citations.length > 0
+ ? parsed
+ : undefined
+ }, [output])
+
+ const scopeLabel = [
+ bar.count !== undefined
+ ? t('tools:toolCall.resultLimit', { count: bar.count })
+ : undefined,
+ bar.fileCount !== undefined
+ ? t('tools:toolCall.fileFilter', { count: bar.fileCount })
+ : undefined,
+ ]
+ .filter(Boolean)
+ .join(' ')
+
+ return (
+ <div className="space-y-2">
+ <ToolBar
+ icon={<FileSearchIcon className="size-4" />}
+ value={bar.query}
+ placeholder={t('tools:toolCall.documentsPlaceholder')}
+ typing={running}
+ trailing={
+ scopeLabel ? (
+ <span className="shrink-0 text-xs text-muted-foreground/70">
+ {scopeLabel}
+ </span>
+ ) : undefined
+ }
+ />
+
+ {errorText && (
+ <div className="rounded-md bg-destructive/10 px-2 py-1.5 text-sm text-destructive">
+ {errorText}
+ </div>
+ )}
+
+ {running && !errorText && (
+ <div className="px-2 text-sm">
+ <Shimmer duration={1}>
+ {t('tools:toolCall.searchingDocuments')}
+ </Shimmer>
+ </div>
+ )}
+
+ {!running &&
+ !errorText &&
+ (payload ? (
+ <Citations
+ payload={payload}
+ anchorPrefix={messageId ? `cite-${messageId}` : undefined}
+ indexOffset={citationOffset}
+ />
+ ) : (
+ <p className="px-2 text-sm text-muted-foreground/70">
+ {t('tools:toolCall.noMatches')}
+ </p>
+ ))}
+ </div>
+ )
+ }
+)
+
+RagToolWidget.displayName = 'RagToolWidget'
diff --git a/web-app/src/containers/message/ToolBar.tsx b/web-app/src/containers/message/ToolBar.tsx
new file mode 100644
index 000000000..f1698c84c
--- /dev/null
+++ b/web-app/src/containers/message/ToolBar.tsx
@@ -0,0 +1,45 @@
+import { cn } from '@/lib/utils'
+
+/** Blinking block that reads as the model typing into the bar. */
+const Caret = () => (
+ <span className="ml-0.5 inline-block h-[1.05em] w-[2px] translate-y-[0.15em] animate-pulse bg-foreground/70" />
+)
+
+export type ToolBarProps = {
+ icon: React.ReactNode
+ value: string
+ placeholder: string
+ /** Show the caret: the model is still writing this argument. */
+ typing: boolean
+ mono?: boolean
+ trailing?: React.ReactNode
+}
+
+/**
+ * Input-bar chrome shared by the native tool widgets, so a web search reads as
+ * a search bar and a fetch as an address bar. The value is whatever has
+ * streamed in so far, which is why the caret matters.
+ */
+export const ToolBar = ({
+ icon,
+ value,
+ placeholder,
+ typing,
+ mono,
+ trailing,
+}: ToolBarProps) => (
+ <div className="flex items-center gap-2 rounded-full border bg-card/40 px-3 py-1.5">
+ <span className="shrink-0 text-muted-foreground">{icon}</span>
+ <span
+ className={cn(
+ 'min-w-0 flex-1 truncate text-sm',
+ mono && 'font-mono text-xs',
+ !value && 'text-muted-foreground/60'
+ )}
+ >
+ {value || placeholder}
+ {typing && <Caret />}
+ </span>
+ {trailing}
+ </div>
+)
diff --git a/web-app/src/containers/message/ToolCallCard.tsx b/web-app/src/containers/message/ToolCallCard.tsx
new file mode 100644
index 000000000..41e06d60a
--- /dev/null
+++ b/web-app/src/containers/message/ToolCallCard.tsx
@@ -0,0 +1,120 @@
+import { memo } from 'react'
+import {
+ Tool,
+ ToolApprovalActions,
+ ToolContent,
+ ToolHeader,
+ ToolInput,
+ ToolOutput,
+} from '@/components/ai-elements/tool'
+import { ToolProgressRow } from '@/components/ai-elements/tool-runtime'
+import { useToolOrigin } from '@/hooks/useToolOrigin'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { describeNativeToolCall } from '@/lib/toolPresentation'
+import { isToolPart, type MessagePartLike } from './types'
+import { RagToolWidget } from './RagToolWidget'
+import { WebToolWidget } from './WebToolWidget'
+
+const identityResolver = (input: string) => Promise.resolve(input)
+
+export type ToolCallCardProps = {
+ part: MessagePartLike
+ messageId: string
+ /** Citation count from earlier tool calls in this turn, for continuous numbering. */
+ citationOffset?: number
+ className?: string
+}
+
+export const ToolCallCard = memo(
+ ({ part, messageId, citationOffset = 0, className }: ToolCallCardProps) => {
+ const { t } = useTranslation()
+ const toolName = part.type.split('-').slice(1).join('-')
+ const origin = useToolOrigin(toolName)
+ if (!isToolPart(part)) return null
+
+ const isError = part.state === 'output-error'
+ // Native families get a fixed label; web search and MCP name their source.
+ const originLabel =
+ origin === undefined
+ ? undefined
+ : origin.kind === 'web-fetch'
+ ? t('tools:toolCall.originWeb')
+ : origin.kind === 'rag'
+ ? t('tools:toolCall.originDocuments')
+ : origin.detail
+
+ const errorText = isError
+ ? part.error || part.errorText || t('tools:toolCall.executionFailed')
+ : undefined
+
+ // Native tools present as an input bar that fills in as the arguments
+ // stream, so it stays visible instead of hiding behind the collapsible;
+ // the raw payload is still one click away in the header.
+ const bar = describeNativeToolCall(origin, toolName, part.input)
+
+ return (
+ <Tool
+ state={part.state}
+ toolCallId={part.toolCallId}
+ messageId={messageId}
+ className={className}
+ >
+ <ToolHeader
+ title={toolName}
+ type={`tool-${toolName}` as `tool-${string}`}
+ state={part.state}
+ origin={originLabel}
+ // The widget's bar already shows the arguments; previewing them in
+ // the header too prints the same text twice, one line apart.
+ input={bar ? undefined : part.input}
+ />
+ <ToolProgressRow toolCallId={part.toolCallId} />
+ {bar && (
+ <div className="mt-2">
+ {bar.variant === 'documents' ? (
+ <RagToolWidget
+ bar={bar}
+ state={part.state}
+ output={part.output}
+ errorText={errorText}
+ messageId={messageId}
+ citationOffset={citationOffset}
+ />
+ ) : (
+ <WebToolWidget
+ bar={bar}
+ state={part.state}
+ output={part.output}
+ errorText={errorText}
+ />
+ )}
+ </div>
+ )}
+ <ToolContent title={toolName}>
+ {Boolean(part.input) && <ToolInput input={part.input} />}
+ <ToolApprovalActions />
+ {/* The widget already presents the result for native tools. */}
+ {!bar &&
+ (isError ? (
+ <ToolOutput
+ output={undefined}
+ errorText={errorText}
+ resolver={identityResolver}
+ />
+ ) : (
+ Boolean(part.output) && (
+ <ToolOutput
+ output={part.output}
+ errorText={undefined}
+ resolver={identityResolver}
+ citationOffset={citationOffset}
+ />
+ )
+ ))}
+ </ToolContent>
+ </Tool>
+ )
+ }
+)
+
+ToolCallCard.displayName = 'ToolCallCard'
diff --git a/web-app/src/containers/message/WebToolWidget.tsx b/web-app/src/containers/message/WebToolWidget.tsx
new file mode 100644
index 000000000..89c267437
--- /dev/null
+++ b/web-app/src/containers/message/WebToolWidget.tsx
@@ -0,0 +1,154 @@
+import { memo, useMemo } from 'react'
+import type { ToolUIPart } from 'ai'
+import { GlobeIcon, SearchIcon } from 'lucide-react'
+import { Shimmer } from '@/components/ai-elements/shimmer'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { parseCitationsFromToolOutput } from '@/lib/citation-parser'
+import {
+ isToolRunning,
+ parseWebFetchOutput,
+ type ToolCallBar,
+} from '@/lib/toolPresentation'
+import { faviconForUrl, hostOf } from '@/lib/webUrl'
+import { ToolBar } from './ToolBar'
+
+const Favicon = ({ url }: { url: string }) => (
+ <img
+ src={faviconForUrl(url)}
+ alt=""
+ className="size-4 shrink-0 rounded-full border border-border/60 bg-white object-contain"
+ />
+)
+
+const ResultRow = ({
+ url,
+ title,
+}: {
+ url: string
+ title?: string
+}) => (
+ <a
+ href={url}
+ target="_blank"
+ rel="noreferrer noopener"
+ className="flex items-center gap-2 rounded-md px-2 py-1.5 no-underline transition-colors hover:bg-secondary"
+ title={url}
+ >
+ <Favicon url={url} />
+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">
+ {title || hostOf(url)}
+ </span>
+ <span className="shrink-0 text-xs text-muted-foreground/70">
+ {hostOf(url)}
+ </span>
+ </a>
+)
+
+export type WebToolWidgetProps = {
+ bar: Extract<ToolCallBar, { variant: 'search' | 'address' }>
+ state: ToolUIPart['state']
+ output?: ToolUIPart['output']
+ errorText?: string
+}
+
+/**
+ * Native web tool calls rendered as the thing they are: a search bar the model
+ * types a query into, or an address bar it navigates to, followed by the
+ * results. Replaces the raw argument/response JSON for these two tools.
+ */
+export const WebToolWidget = memo(
+ ({ bar, state, output, errorText }: WebToolWidgetProps) => {
+ const { t } = useTranslation()
+ const running = isToolRunning(state)
+
+ const searchResults = useMemo(() => {
+ if (bar.variant !== 'search' || !output) return []
+ const parsed = parseCitationsFromToolOutput(output)
+ return parsed?.kind === 'web' ? parsed.citations : []
+ }, [bar.variant, output])
+
+ const page = useMemo(
+ () => (bar.variant === 'address' && output ? parseWebFetchOutput(output) : undefined),
+ [bar.variant, output]
+ )
+
+ return (
+ <div className="space-y-2">
+ {bar.variant === 'search' ? (
+ <ToolBar
+ icon={<SearchIcon className="size-4" />}
+ value={bar.query}
+ placeholder={t('tools:toolCall.searchPlaceholder')}
+ typing={running}
+ trailing={
+ bar.count !== undefined && (
+ <span className="shrink-0 text-xs text-muted-foreground/70">
+ {t('tools:toolCall.resultLimit', { count: bar.count })}
+ </span>
+ )
+ }
+ />
+ ) : (
+ <ToolBar
+ icon={<GlobeIcon className="size-4" />}
+ value={bar.url}
+ placeholder={t('tools:toolCall.addressPlaceholder')}
+ typing={running}
+ mono
+ trailing={bar.url ? <Favicon url={bar.url} /> : undefined}
+ />
+ )}
+
+ {errorText && (
+ <div className="rounded-md bg-destructive/10 px-2 py-1.5 text-sm text-destructive">
+ {errorText}
+ </div>
+ )}
+
+ {running && !errorText && (
+ <div className="px-2 text-sm">
+ <Shimmer duration={1}>
+ {bar.variant === 'search'
+ ? t('tools:toolCall.searching')
+ : t('tools:toolCall.opening')}
+ </Shimmer>
+ </div>
+ )}
+
+ {!running && !errorText && bar.variant === 'search' && (
+ searchResults.length > 0 ? (
+ <div className="flex flex-col">
+ {searchResults.map((citation) => (
+ <ResultRow
+ key={citation.url}
+ url={citation.url}
+ title={citation.title}
+ />
+ ))}
+ </div>
+ ) : (
+ <p className="px-2 text-sm text-muted-foreground/70">
+ {t('tools:toolCall.noResults')}
+ </p>
+ )
+ )}
+
+ {!running && !errorText && page && (
+ <div className="space-y-1.5">
+ {page.url && <ResultRow url={page.url} title={page.title} />}
+ <div className="max-h-40 overflow-auto whitespace-pre-wrap wrap-break-word rounded-md border px-2 py-1.5 text-xs text-muted-foreground">
+ {page.content}
+ </div>
+ {page.truncated && (
+ <p className="px-2 text-xs text-muted-foreground/70">
+ {t('tools:toolCall.contentTruncated')}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ )
+ }
+)
+
+WebToolWidget.displayName = 'WebToolWidget'
diff --git a/web-app/src/containers/message/__tests__/ChainOfThoughtGroup.test.tsx b/web-app/src/containers/message/__tests__/ChainOfThoughtGroup.test.tsx
new file mode 100644
index 000000000..b8ad54922
--- /dev/null
+++ b/web-app/src/containers/message/__tests__/ChainOfThoughtGroup.test.tsx
@@ -0,0 +1,183 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import '@testing-library/jest-dom'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+vi.mock('@/hooks/useToolApprovalRequests', () => ({
+ useToolApprovalRequests: (selector: (s: unknown) => unknown) =>
+ selector({ pending: {} }),
+}))
+
+vi.mock('streamdown', () => ({
+ Streamdown: ({ children }: { children: string }) => <span>{children}</span>,
+}))
+
+vi.mock('@/components/ai-elements/tool', () => ({
+ Tool: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="tool">{children}</div>
+ ),
+ ToolContent: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ ToolHeader: ({ title }: { title: string }) => (
+ <div data-testid="tool-header">{title}</div>
+ ),
+ ToolInput: () => null,
+ ToolOutput: () => null,
+ ToolApprovalActions: () => null,
+}))
+
+import { ChainOfThoughtGroup } from '../ChainOfThoughtGroup'
+import { REASONING_STEP_MAX_CHARS } from '@/lib/reasoning'
+import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
+
+beforeEach(() => {
+ useToolCallRuntime.getState().reset()
+})
+
+// Long enough to have settled at least one step plus an in-progress tail.
+const LONG_TEXT = `${'word '.repeat(REASONING_STEP_MAX_CHARS)}tailtoken`
+
+const renderGroup = (
+ overrides: Partial<React.ComponentProps<typeof ChainOfThoughtGroup>> = {}
+) => {
+ const parts = [{ type: 'reasoning', text: LONG_TEXT }]
+ return render(
+ <ChainOfThoughtGroup
+ entries={parts.map((part, index) => ({ part, index }))}
+ messageId="m1"
+ totalParts={parts.length}
+ isStreaming
+ hasFollowingContent={false}
+ awaitingApproval={false}
+ citationOffsets={new Map()}
+ {...overrides}
+ />
+ )
+}
+
+const navButton = () =>
+ screen.queryByRole('button', { name: 'chat:reasoning.showFullTimeline' })
+const backButton = () =>
+ screen.queryByRole('button', { name: 'chat:reasoning.showCurrentStep' })
+
+describe('ChainOfThoughtGroup view switching', () => {
+ it('starts condensed with a forward affordance while streaming', () => {
+ renderGroup()
+ expect(navButton()).toBeInTheDocument()
+ expect(backButton()).not.toBeInTheDocument()
+ // Condensed shows the settled step, never the tail being written. Assert the
+ // settled text is present too, so the exclusion below is meaningful rather
+ // than an artefact of a collapsed panel.
+ expect(screen.getByText(/^word word/)).toBeInTheDocument()
+ expect(screen.queryByText(/tailtoken/)).not.toBeInTheDocument()
+ })
+
+ it('switches to the extended timeline and follows the live step', () => {
+ renderGroup()
+ fireEvent.click(navButton()!)
+ expect(screen.getByText(/tailtoken/)).toBeInTheDocument()
+ expect(backButton()).toBeInTheDocument()
+ })
+
+ it('returns to the condensed view', () => {
+ renderGroup()
+ fireEvent.click(navButton()!)
+ fireEvent.click(backButton()!)
+ expect(screen.queryByText(/tailtoken/)).not.toBeInTheDocument()
+ expect(navButton()).toBeInTheDocument()
+ })
+
+ it('omits the Done marker while still streaming', () => {
+ renderGroup()
+ fireEvent.click(navButton()!)
+ expect(screen.queryByText('chat:done')).not.toBeInTheDocument()
+ })
+
+ it('shows earlier tool calls that the condensed view truncates away', () => {
+ const parts = [
+ { type: 'tool-alpha', state: 'output-available', toolCallId: 'a' },
+ { type: 'reasoning', text: LONG_TEXT },
+ ]
+ renderGroup({
+ entries: parts.map((part, index) => ({ part, index })),
+ totalParts: parts.length,
+ })
+ expect(screen.queryByTestId('tool-header')).not.toBeInTheDocument()
+ fireEvent.click(navButton()!)
+ expect(screen.getByTestId('tool-header')).toHaveTextContent('alpha')
+ })
+
+ // The tool card (and its live search/address bar) lives inside the
+ // collapsible, so a collapsed frame hides the call entirely while it runs.
+ it('expands the frame while a tool call is in flight', () => {
+ const parts = [
+ { type: 'reasoning', text: LONG_TEXT },
+ { type: 'tool-web_search', state: 'input-streaming', toolCallId: 'tc1' },
+ ]
+ renderGroup({
+ entries: parts.map((part, index) => ({ part, index })),
+ totalParts: parts.length,
+ })
+ expect(screen.getByTestId('tool-header')).toHaveTextContent('web_search')
+ })
+
+ it('stays expanded once the tool result arrives', () => {
+ const parts = [
+ { type: 'reasoning', text: LONG_TEXT },
+ {
+ type: 'tool-web_search',
+ state: 'output-available',
+ toolCallId: 'tc1',
+ output: 'ok',
+ },
+ ]
+ renderGroup({
+ entries: parts.map((part, index) => ({ part, index })),
+ totalParts: parts.length,
+ })
+ expect(screen.getByTestId('tool-header')).toBeInTheDocument()
+ })
+
+ // Calls execute one at a time, so with several in a turn the last part is the
+ // one at the back of the queue. Showing it would report "queued" while the
+ // call actually doing the work is hidden.
+ it('shows the running call, not the last one queued', () => {
+ const parts = [
+ { type: 'tool-alpha', state: 'input-available', toolCallId: 'a' },
+ { type: 'tool-beta', state: 'input-available', toolCallId: 'b' },
+ ]
+ useToolCallRuntime.getState().enqueue(['a', 'b'])
+ useToolCallRuntime.getState().markRunning('a')
+ renderGroup({
+ entries: parts.map((part, index) => ({ part, index })),
+ totalParts: parts.length,
+ })
+ expect(screen.getByTestId('tool-header')).toHaveTextContent('alpha')
+ })
+
+ // Before execution starts nothing is running, so the newest part is still
+ // the right thing to show as it streams in.
+ it('shows the newest call while the arguments are still streaming', () => {
+ const parts = [
+ { type: 'tool-alpha', state: 'input-available', toolCallId: 'a' },
+ { type: 'tool-beta', state: 'input-streaming', toolCallId: 'b' },
+ ]
+ renderGroup({
+ entries: parts.map((part, index) => ({ part, index })),
+ totalParts: parts.length,
+ })
+ expect(screen.getByTestId('tool-header')).toHaveTextContent('beta')
+ })
+
+ it('renders the completed rail with a Done marker and no view switch', () => {
+ renderGroup({ isStreaming: false })
+ expect(navButton()).not.toBeInTheDocument()
+ expect(backButton()).not.toBeInTheDocument()
+ expect(screen.getByText('chat:done')).toBeInTheDocument()
+ expect(screen.getByText(/tailtoken/)).toBeInTheDocument()
+ })
+})
diff --git a/web-app/src/containers/message/__tests__/RagToolWidget.test.tsx b/web-app/src/containers/message/__tests__/RagToolWidget.test.tsx
new file mode 100644
index 000000000..c862d6784
--- /dev/null
+++ b/web-app/src/containers/message/__tests__/RagToolWidget.test.tsx
@@ -0,0 +1,103 @@
+import { describe, expect, it, vi } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import '@testing-library/jest-dom'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options?.count !== undefined ? `${key}:${options.count}` : key,
+ }),
+}))
+
+vi.mock('@/components/ai-elements/shimmer', () => ({
+ Shimmer: ({ children }: { children: React.ReactNode }) => (
+ <span data-testid="shimmer">{children}</span>
+ ),
+}))
+
+vi.mock('@/components/Citations', () => ({
+ Citations: ({ payload }: { payload: { citations: unknown[] } }) => (
+ <div data-testid="citations">{payload.citations.length}</div>
+ ),
+}))
+
+import { RagToolWidget } from '../RagToolWidget'
+
+const bar = { variant: 'documents', query: 'refund policy' } as const
+
+const ragOutput = {
+ kind: 'rag',
+ query: 'refund policy',
+ citations: [
+ { id: 'c1', text: 'thirty days', score: 0.9, file_id: 'f1' },
+ { id: 'c2', text: 'no refunds after', score: 0.8, file_id: 'f1' },
+ ],
+}
+
+describe('RagToolWidget', () => {
+ it('shows the query as the model writes it', () => {
+ render(
+ <RagToolWidget
+ bar={{ variant: 'documents', query: 'refund pol' }}
+ state="input-streaming"
+ />
+ )
+ expect(screen.getByText(/refund pol/)).toBeInTheDocument()
+ expect(screen.getByTestId('shimmer')).toHaveTextContent(
+ 'tools:toolCall.searchingDocuments'
+ )
+ })
+
+ it('shows a documents placeholder before the query arrives', () => {
+ render(
+ <RagToolWidget
+ bar={{ variant: 'documents', query: '' }}
+ state="input-streaming"
+ />
+ )
+ expect(
+ screen.getByText('tools:toolCall.documentsPlaceholder')
+ ).toBeInTheDocument()
+ })
+
+ it('renders matched passages as citations', () => {
+ render(
+ <RagToolWidget bar={bar} state="output-available" output={ragOutput} />
+ )
+ expect(screen.getByTestId('citations')).toHaveTextContent('2')
+ expect(screen.queryByTestId('shimmer')).not.toBeInTheDocument()
+ })
+
+ it('reports when nothing matched', () => {
+ render(
+ <RagToolWidget
+ bar={bar}
+ state="output-available"
+ output={{ kind: 'rag', citations: [] }}
+ />
+ )
+ expect(screen.getByText('tools:toolCall.noMatches')).toBeInTheDocument()
+ })
+
+ it('surfaces the top_k and file filter the model chose', () => {
+ render(
+ <RagToolWidget
+ bar={{ variant: 'documents', query: 'q', count: 4, fileCount: 2 }}
+ state="input-available"
+ />
+ )
+ expect(
+ screen.getByText(/tools:toolCall.resultLimit:4/)
+ ).toBeInTheDocument()
+ expect(screen.getByText(/tools:toolCall.fileFilter:2/)).toBeInTheDocument()
+ })
+
+ it('shows an error instead of results', () => {
+ render(
+ <RagToolWidget bar={bar} state="output-error" errorText="index missing" />
+ )
+ expect(screen.getByText('index missing')).toBeInTheDocument()
+ expect(screen.queryByTestId('citations')).not.toBeInTheDocument()
+ expect(screen.queryByText('tools:toolCall.noMatches')).not.toBeInTheDocument()
+ })
+})
diff --git a/web-app/src/containers/message/__tests__/ToolCallCard.test.tsx b/web-app/src/containers/message/__tests__/ToolCallCard.test.tsx
new file mode 100644
index 000000000..cde9ac795
--- /dev/null
+++ b/web-app/src/containers/message/__tests__/ToolCallCard.test.tsx
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import '@testing-library/jest-dom'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options?.tool ? `${key}:${options.tool}` : key,
+ }),
+}))
+
+vi.mock('@/hooks/useToolApprovalRequests', () => ({
+ useToolApprovalRequests: (selector: (s: unknown) => unknown) =>
+ selector({ pending: {} }),
+}))
+
+const origin = vi.fn()
+vi.mock('@/hooks/useToolOrigin', () => ({
+ useToolOrigin: () => origin(),
+}))
+
+vi.mock('../WebToolWidget', () => ({
+ WebToolWidget: ({ bar }: { bar: { query?: string } }) => (
+ <div data-testid="web-widget">{bar.query}</div>
+ ),
+}))
+
+vi.mock('../RagToolWidget', () => ({
+ RagToolWidget: () => <div data-testid="rag-widget" />,
+}))
+
+import { ToolCallCard } from '../ToolCallCard'
+
+describe('ToolCallCard', () => {
+ // The widget already shows the query in its search bar, so repeating it in
+ // the header renders the same text twice, one line apart.
+ it('leaves the argument preview to the widget when one renders', () => {
+ origin.mockReturnValue({ kind: 'web-search', detail: 'Exa' })
+ render(
+ <ToolCallCard
+ part={{
+ type: 'tool-web_search',
+ state: 'output-error',
+ toolCallId: 'tc1',
+ input: { query: 'deepfake prevention news' },
+ errorText: 'rate limited',
+ }}
+ messageId="m1"
+ />
+ )
+ expect(screen.getByTestId('web-widget')).toHaveTextContent(
+ 'deepfake prevention news'
+ )
+ expect(
+ screen.queryByText('query: deepfake prevention news')
+ ).not.toBeInTheDocument()
+ })
+
+ // Without a widget the header preview is the only thing describing the call
+ // while it is collapsed.
+ it('previews the arguments in the header for a tool with no widget', () => {
+ origin.mockReturnValue({ kind: 'mcp', detail: 'github' })
+ render(
+ <ToolCallCard
+ part={{
+ type: 'tool-create_issue',
+ state: 'output-available',
+ toolCallId: 'tc2',
+ input: { title: 'Bug' },
+ output: 'done',
+ }}
+ messageId="m1"
+ />
+ )
+ expect(screen.getByText('title: Bug')).toBeInTheDocument()
+ })
+})
diff --git a/web-app/src/containers/message/__tests__/WebToolWidget.test.tsx b/web-app/src/containers/message/__tests__/WebToolWidget.test.tsx
new file mode 100644
index 000000000..1f793dcc2
--- /dev/null
+++ b/web-app/src/containers/message/__tests__/WebToolWidget.test.tsx
@@ -0,0 +1,126 @@
+import { describe, expect, it, vi } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import '@testing-library/jest-dom'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options?.count !== undefined ? `${key}:${options.count}` : key,
+ }),
+}))
+
+vi.mock('@/components/ai-elements/shimmer', () => ({
+ Shimmer: ({ children }: { children: React.ReactNode }) => (
+ <span data-testid="shimmer">{children}</span>
+ ),
+}))
+
+import { WebToolWidget } from '../WebToolWidget'
+
+const searchBar = { variant: 'search', query: 'rust async' } as const
+const addressBar = { variant: 'address', url: 'https://a.dev/x' } as const
+
+const webOutput = {
+ kind: 'web',
+ query: 'rust async',
+ results: [
+ { url: 'https://doc.rust-lang.org/book', title: 'The Book' },
+ { url: 'https://tokio.rs/guide', title: 'Tokio Guide' },
+ ],
+}
+
+describe('WebToolWidget search variant', () => {
+ it('shows the query as it streams in', () => {
+ render(<WebToolWidget bar={{ variant: 'search', query: 'rust as' }} state="input-streaming" />)
+ expect(screen.getByText(/rust as/)).toBeInTheDocument()
+ expect(screen.getByTestId('shimmer')).toHaveTextContent(
+ 'tools:toolCall.searching'
+ )
+ })
+
+ it('shows a placeholder before the query arrives', () => {
+ render(<WebToolWidget bar={{ variant: 'search', query: '' }} state="input-streaming" />)
+ expect(
+ screen.getByText('tools:toolCall.searchPlaceholder')
+ ).toBeInTheDocument()
+ })
+
+ it('lists results with a favicon and host once they arrive', () => {
+ render(
+ <WebToolWidget bar={searchBar} state="output-available" output={webOutput} />
+ )
+ expect(screen.getByText('The Book')).toBeInTheDocument()
+ expect(screen.getByText('Tokio Guide')).toBeInTheDocument()
+ expect(screen.getByText('tokio.rs')).toBeInTheDocument()
+ const link = screen.getByTitle('https://tokio.rs/guide')
+ expect(link).toHaveAttribute('href', 'https://tokio.rs/guide')
+ expect(screen.queryByTestId('shimmer')).not.toBeInTheDocument()
+ })
+
+ it('reports an empty result set', () => {
+ render(
+ <WebToolWidget
+ bar={searchBar}
+ state="output-available"
+ output={{ kind: 'web', query: 'q', results: [] }}
+ />
+ )
+ expect(screen.getByText('tools:toolCall.noResults')).toBeInTheDocument()
+ })
+
+ it('shows the result limit when the model asked for one', () => {
+ render(
+ <WebToolWidget
+ bar={{ variant: 'search', query: 'q', count: 3 }}
+ state="input-available"
+ />
+ )
+ expect(screen.getByText('tools:toolCall.resultLimit:3')).toBeInTheDocument()
+ })
+})
+
+describe('WebToolWidget address variant', () => {
+ it('shows the url while fetching', () => {
+ render(<WebToolWidget bar={addressBar} state="input-available" />)
+ expect(screen.getByText(/https:\/\/a\.dev\/x/)).toBeInTheDocument()
+ expect(screen.getByTestId('shimmer')).toHaveTextContent(
+ 'tools:toolCall.opening'
+ )
+ })
+
+ it('renders the fetched page with its title and body', () => {
+ render(
+ <WebToolWidget
+ bar={addressBar}
+ state="output-available"
+ output={'Title: Async Rust\nURL: https://a.dev/x\n\npage body'}
+ />
+ )
+ expect(screen.getByText('Async Rust')).toBeInTheDocument()
+ expect(screen.getByText('page body')).toBeInTheDocument()
+ })
+
+ it('flags truncated content', () => {
+ render(
+ <WebToolWidget
+ bar={addressBar}
+ state="output-available"
+ output={'Title: T\nURL: https://a.dev\n\nbody\n\n[content truncated]'}
+ />
+ )
+ expect(
+ screen.getByText('tools:toolCall.contentTruncated')
+ ).toBeInTheDocument()
+ })
+})
+
+describe('WebToolWidget errors', () => {
+ it('shows the error instead of results or progress', () => {
+ render(
+ <WebToolWidget bar={searchBar} state="output-error" errorText="rate limited" />
+ )
+ expect(screen.getByText('rate limited')).toBeInTheDocument()
+ expect(screen.queryByTestId('shimmer')).not.toBeInTheDocument()
+ expect(screen.queryByText('tools:toolCall.noResults')).not.toBeInTheDocument()
+ })
+})
diff --git a/web-app/src/containers/message/types.ts b/web-app/src/containers/message/types.ts
new file mode 100644
index 000000000..13514b18f
--- /dev/null
+++ b/web-app/src/containers/message/types.ts
@@ -0,0 +1,36 @@
+import type { ToolUIPart } from 'ai'
+
+export const CHAT_STATUS = {
+ STREAMING: 'streaming',
+ SUBMITTED: 'submitted',
+} as const
+
+export const CONTENT_TYPE = {
+ TEXT: 'text',
+ FILE: 'file',
+ REASONING: 'reasoning',
+} as const
+
+/** Minimal shape shared by the message-part renderers. */
+export type MessagePartLike = {
+ type: string
+ text?: string
+ state?: ToolUIPart['state']
+ toolCallId?: string
+ input?: ToolUIPart['input']
+ output?: ToolUIPart['output']
+ errorText?: string
+ error?: string
+ filename?: string
+ url?: string
+ mediaType?: string
+}
+
+export type PartEntry = { part: MessagePartLike; index: number }
+
+/** A tool part carrying the lifecycle state the SDK attaches once it is live. */
+export type ToolPartLike = MessagePartLike & { state: ToolUIPart['state'] }
+
+/** A tool part only renders once the SDK has attached a lifecycle state. */
+export const isToolPart = (part: MessagePartLike): part is ToolPartLike =>
+ part.type.startsWith('tool-') && part.state !== undefined
diff --git a/web-app/src/hooks/__tests__/useMcpToolProgress.test.ts b/web-app/src/hooks/__tests__/useMcpToolProgress.test.ts
new file mode 100644
index 000000000..754ed2241
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useMcpToolProgress.test.ts
@@ -0,0 +1,85 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderHook } from '@testing-library/react'
+
+const listen = vi.fn()
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceHub: () => ({ events: () => ({ listen }) }),
+}))
+
+const isTauri = vi.fn(() => true)
+vi.mock('@/lib/platform/utils', () => ({
+ isPlatformTauri: () => isTauri(),
+}))
+
+import {
+ MCP_TOOL_PROGRESS_EVENT,
+ useMcpToolProgress,
+} from '../useMcpToolProgress'
+import { useToolCallRuntime } from '../useToolCallRuntime'
+
+const update = { server: 'github', progress: 2, total: 4, percent: 50 }
+
+describe('useMcpToolProgress', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ isTauri.mockReturnValue(true)
+ useToolCallRuntime.getState().reset()
+ listen.mockResolvedValue(() => {})
+ })
+
+ it('records an update against the running call', async () => {
+ let handler: ((e: { payload: unknown }) => void) | undefined
+ listen.mockImplementation(async (_event: string, fn: typeof handler) => {
+ handler = fn
+ return () => {}
+ })
+ const runtime = useToolCallRuntime.getState()
+ runtime.enqueue(['a'])
+ runtime.markRunning('a')
+
+ renderHook(() => useMcpToolProgress())
+ await vi.waitFor(() => expect(handler).toBeTypeOf('function'))
+ handler!({ payload: update })
+
+ expect(useToolCallRuntime.getState().progress['a']).toMatchObject(update)
+ })
+
+ it('subscribes to the event the Rust handler emits', () => {
+ renderHook(() => useMcpToolProgress())
+ expect(listen).toHaveBeenCalledWith(
+ MCP_TOOL_PROGRESS_EVENT,
+ expect.any(Function)
+ )
+ })
+
+ it('unsubscribes on unmount', async () => {
+ const unlisten = vi.fn()
+ listen.mockResolvedValue(unlisten)
+ const { unmount } = renderHook(() => useMcpToolProgress())
+ await vi.waitFor(() => expect(listen).toHaveBeenCalled())
+ unmount()
+ expect(unlisten).toHaveBeenCalled()
+ })
+
+ // listen() is async, so a short-lived mount can resolve after teardown and
+ // leave the subscription behind.
+ it('unsubscribes when listen resolves after unmount', async () => {
+ const unlisten = vi.fn()
+ let resolve: ((fn: () => void) => void) | undefined
+ listen.mockReturnValue(
+ new Promise<() => void>((r) => {
+ resolve = r
+ })
+ )
+ const { unmount } = renderHook(() => useMcpToolProgress())
+ unmount()
+ resolve!(unlisten)
+ await vi.waitFor(() => expect(unlisten).toHaveBeenCalled())
+ })
+
+ it('does not subscribe outside Tauri', () => {
+ isTauri.mockReturnValue(false)
+ renderHook(() => useMcpToolProgress())
+ expect(listen).not.toHaveBeenCalled()
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useToolApproval.test.ts b/web-app/src/hooks/__tests__/useToolApproval.test.ts
index 2db153543..21318267c 100644
--- a/web-app/src/hooks/__tests__/useToolApproval.test.ts
+++ b/web-app/src/hooks/__tests__/useToolApproval.test.ts
@@ -25,9 +25,9 @@ describe('useToolApproval', () => {
// Reset store state to defaults
useToolApproval.setState({
approvedTools: {},
+ approvedServers: [],
+ approvedToolsGlobal: [],
allowAllMCPPermissions: false,
- isModalOpen: false,
- modalProps: null,
})
})
@@ -35,14 +35,13 @@ describe('useToolApproval', () => {
const { result } = renderHook(() => useToolApproval())
expect(result.current.approvedTools).toEqual({})
+ expect(result.current.approvedServers).toEqual([])
+ expect(result.current.approvedToolsGlobal).toEqual([])
expect(result.current.allowAllMCPPermissions).toBe(false)
- expect(result.current.isModalOpen).toBe(false)
- expect(result.current.modalProps).toBe(null)
expect(typeof result.current.approveToolForThread).toBe('function')
+ expect(typeof result.current.approveServer).toBe('function')
+ expect(typeof result.current.approveToolEverywhere).toBe('function')
expect(typeof result.current.isToolApproved).toBe('function')
- expect(typeof result.current.showApprovalModal).toBe('function')
- expect(typeof result.current.closeModal).toBe('function')
- expect(typeof result.current.setModalOpen).toBe('function')
expect(typeof result.current.setAllowAllMCPPermissions).toBe('function')
})
@@ -155,179 +154,57 @@ describe('useToolApproval', () => {
})
})
- describe('closeModal', () => {
- it('should close the modal and reset props', () => {
+ describe('approveServer', () => {
+ it('approves every tool from that server, in any thread', () => {
const { result } = renderHook(() => useToolApproval())
- // First set modal to open state
act(() => {
- result.current.setModalOpen(true)
+ result.current.approveServer('github')
})
- expect(result.current.isModalOpen).toBe(true)
-
- // Then close the modal
- act(() => {
- result.current.closeModal()
- })
-
- expect(result.current.isModalOpen).toBe(false)
- expect(result.current.modalProps).toBe(null)
+ expect(
+ result.current.isToolApproved('thread-1', 'create_issue', 'github')
+ ).toBe(true)
+ expect(
+ result.current.isToolApproved('thread-9', 'list_repos', 'github')
+ ).toBe(true)
})
- })
- describe('setModalOpen', () => {
- it('should set modal open state to true', () => {
+ it('leaves other servers alone', () => {
const { result } = renderHook(() => useToolApproval())
act(() => {
- result.current.setModalOpen(true)
+ result.current.approveServer('github')
})
- expect(result.current.isModalOpen).toBe(true)
+ expect(
+ result.current.isToolApproved('thread-1', 'read_file', 'filesystem')
+ ).toBe(false)
})
- it('should set modal open state to false and call closeModal', () => {
+ it('does not duplicate a server approved twice', () => {
const { result } = renderHook(() => useToolApproval())
- // Set up initial state
act(() => {
- result.current.setModalOpen(true)
- })
-
- // Mock modalProps to verify they get reset
- useToolApproval.setState({
- modalProps: {
- toolName: 'test-tool',
- threadId: 'test-thread',
- onApprove: vi.fn(),
- onDeny: vi.fn(),
- },
+ result.current.approveServer('github')
+ result.current.approveServer('github')
})
- // Set to false should trigger closeModal
- act(() => {
- result.current.setModalOpen(false)
- })
-
- expect(result.current.isModalOpen).toBe(false)
- expect(result.current.modalProps).toBe(null)
+ expect(result.current.approvedServers).toEqual(['github'])
})
})
- describe('showApprovalModal', () => {
- it('should return true immediately if tool is already approved', async () => {
+ describe('approveToolEverywhere', () => {
+ it('approves the tool in every thread', () => {
const { result } = renderHook(() => useToolApproval())
- // First approve the tool
act(() => {
- result.current.approveToolForThread('thread-1', 'tool-a')
+ result.current.approveToolEverywhere('tool-a')
})
- // Then show approval modal
- let approvalResult: boolean
- await act(async () => {
- approvalResult = await result.current.showApprovalModal('tool-a', 'thread-1')
- })
-
- expect(approvalResult!).toBe(true)
- expect(result.current.isModalOpen).toBe(false)
- })
-
- it('should open modal and set up modal props for non-approved tool', async () => {
- const { result } = renderHook(() => useToolApproval())
-
- // Start the async operation
- let approvalPromise: Promise<boolean>
-
- act(() => {
- approvalPromise = result.current.showApprovalModal('tool-a', 'thread-1')
- })
-
- // Check that modal is open and props are set
- expect(result.current.isModalOpen).toBe(true)
- expect(result.current.modalProps).not.toBe(null)
- expect(result.current.modalProps?.toolName).toBe('tool-a')
- expect(result.current.modalProps?.threadId).toBe('thread-1')
- expect(typeof result.current.modalProps?.onApprove).toBe('function')
- expect(typeof result.current.modalProps?.onDeny).toBe('function')
-
- // Resolve by calling onDeny
- act(() => {
- result.current.modalProps?.onDeny()
- })
-
- const approvalResult = await approvalPromise!
- expect(approvalResult).toBe(false)
- expect(result.current.isModalOpen).toBe(false)
- expect(result.current.modalProps).toBe(null)
- })
-
- it('should resolve with true when onApprove is called with allowOnce=true', async () => {
- const { result } = renderHook(() => useToolApproval())
-
- // Start the async operation
- let approvalPromise: Promise<boolean>
-
- act(() => {
- approvalPromise = result.current.showApprovalModal('tool-a', 'thread-1')
- })
-
- // Call onApprove with allowOnce=true
- act(() => {
- result.current.modalProps?.onApprove(true)
- })
-
- const approvalResult = await approvalPromise!
- expect(approvalResult).toBe(true)
- expect(result.current.isModalOpen).toBe(false)
- expect(result.current.modalProps).toBe(null)
- // Tool should NOT be added to approved tools when allowOnce=true
- expect(result.current.isToolApproved('thread-1', 'tool-a')).toBe(false)
- })
-
- it('should resolve with true and approve tool when onApprove is called with allowOnce=false', async () => {
- const { result } = renderHook(() => useToolApproval())
-
- // Start the async operation
- let approvalPromise: Promise<boolean>
-
- act(() => {
- approvalPromise = result.current.showApprovalModal('tool-a', 'thread-1')
- })
-
- // Call onApprove with allowOnce=false
- act(() => {
- result.current.modalProps?.onApprove(false)
- })
-
- const approvalResult = await approvalPromise!
- expect(approvalResult).toBe(true)
- expect(result.current.isModalOpen).toBe(false)
- expect(result.current.modalProps).toBe(null)
- // Tool should be added to approved tools when allowOnce=false
expect(result.current.isToolApproved('thread-1', 'tool-a')).toBe(true)
- })
-
- it('should resolve with false when onDeny is called', async () => {
- const { result } = renderHook(() => useToolApproval())
-
- // Start the async operation
- let approvalPromise: Promise<boolean>
-
- act(() => {
- approvalPromise = result.current.showApprovalModal('tool-a', 'thread-1')
- })
-
- // Call onDeny
- act(() => {
- result.current.modalProps?.onDeny()
- })
-
- const approvalResult = await approvalPromise!
- expect(approvalResult).toBe(false)
- expect(result.current.isModalOpen).toBe(false)
- expect(result.current.modalProps).toBe(null)
+ expect(result.current.isToolApproved('thread-2', 'tool-a')).toBe(true)
+ expect(result.current.isToolApproved('thread-1', 'tool-b')).toBe(false)
})
})
@@ -345,99 +222,4 @@ describe('useToolApproval', () => {
expect(result2.current.allowAllMCPPermissions).toBe(true)
})
})
-
- describe('complex scenarios', () => {
- it('should handle multiple sequential approval requests', async () => {
- const { result } = renderHook(() => useToolApproval())
-
- // First request
- let firstPromise: Promise<boolean>
- act(() => {
- firstPromise = result.current.showApprovalModal('tool-a', 'thread-1')
- })
-
- act(() => {
- result.current.modalProps?.onApprove(false)
- })
-
- const firstResult = await firstPromise!
- expect(firstResult).toBe(true)
- expect(result.current.isToolApproved('thread-1', 'tool-a')).toBe(true)
-
- // Second request for same tool should resolve immediately
- let secondPromise: Promise<boolean>
- act(() => {
- secondPromise = result.current.showApprovalModal('tool-a', 'thread-1')
- })
-
- const secondResult = await secondPromise!
- expect(secondResult).toBe(true)
- expect(result.current.isModalOpen).toBe(false)
- })
-
- it('should handle approval for different tools in same thread', async () => {
- const { result } = renderHook(() => useToolApproval())
-
- // Approve tool-a permanently
- let firstPromise: Promise<boolean>
- act(() => {
- firstPromise = result.current.showApprovalModal('tool-a', 'thread-1')
- })
-
- act(() => {
- result.current.modalProps?.onApprove(false)
- })
-
- await firstPromise!
- expect(result.current.isToolApproved('thread-1', 'tool-a')).toBe(true)
-
- // Approve tool-b once only
- let secondPromise: Promise<boolean>
- act(() => {
- secondPromise = result.current.showApprovalModal('tool-b', 'thread-1')
- })
-
- act(() => {
- result.current.modalProps?.onApprove(true)
- })
-
- await secondPromise!
- expect(result.current.isToolApproved('thread-1', 'tool-b')).toBe(false)
-
- // Verify final state
- expect(result.current.approvedTools['thread-1']).toEqual(['tool-a'])
- })
-
- it('should handle denial and subsequent approval', async () => {
- const { result } = renderHook(() => useToolApproval())
-
- // First request - deny
- let firstPromise: Promise<boolean>
- act(() => {
- firstPromise = result.current.showApprovalModal('tool-a', 'thread-1')
- })
-
- act(() => {
- result.current.modalProps?.onDeny()
- })
-
- const firstResult = await firstPromise!
- expect(firstResult).toBe(false)
- expect(result.current.isToolApproved('thread-1', 'tool-a')).toBe(false)
-
- // Second request - approve
- let secondPromise: Promise<boolean>
- act(() => {
- secondPromise = result.current.showApprovalModal('tool-a', 'thread-1')
- })
-
- act(() => {
- result.current.modalProps?.onApprove(false)
- })
-
- const secondResult = await secondPromise!
- expect(secondResult).toBe(true)
- expect(result.current.isToolApproved('thread-1', 'tool-a')).toBe(true)
- })
- })
})
diff --git a/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts b/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts
index eca41c3c7..d2f23cff5 100644
--- a/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts
+++ b/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts
@@ -23,6 +23,8 @@ describe('useToolApprovalRequests', () => {
useToolApprovalRequests.setState({ pending: {} })
useToolApproval.setState({
approvedTools: {},
+ approvedServers: [],
+ approvedToolsGlobal: [],
allowAllMCPPermissions: false,
})
})
@@ -85,19 +87,85 @@ describe('useToolApprovalRequests', () => {
expect(result.current.pending['tc1']).toBeUndefined()
})
- it('resolveApproval allow-always resolves true and persists the tool for the thread', async () => {
+ it('resolveApproval allow-thread persists the tool for that thread only', async () => {
const { result } = renderHook(() => useToolApprovalRequests())
let p: Promise<boolean>
act(() => {
p = result.current.requestApproval('tc1', 'tool-a', 'thread-1')
})
+ act(() => {
+ result.current.resolveApproval('tc1', 'allow-thread')
+ })
+
+ await expect(p!).resolves.toBe(true)
+ const approval = useToolApproval.getState()
+ expect(approval.isToolApproved('thread-1', 'tool-a')).toBe(true)
+ expect(approval.isToolApproved('thread-2', 'tool-a')).toBe(false)
+ })
+
+ // "Always" has to mean always, which is what the thread scope could not say.
+ it('resolveApproval allow-always trusts the whole server, in every thread', async () => {
+ const { result } = renderHook(() => useToolApprovalRequests())
+
+ let p: Promise<boolean>
+ act(() => {
+ p = result.current.requestApproval('tc1', 'tool-a', 'thread-1', 'github')
+ })
act(() => {
result.current.resolveApproval('tc1', 'allow-always')
})
await expect(p!).resolves.toBe(true)
- expect(useToolApproval.getState().isToolApproved('thread-1', 'tool-a')).toBe(true)
+ const approval = useToolApproval.getState()
+ expect(approval.isToolApproved('thread-2', 'other-tool', 'github')).toBe(
+ true
+ )
+ expect(approval.isToolApproved('thread-2', 'tool-a', 'gitlab')).toBe(false)
+ })
+
+ it('resolveApproval allow-always falls back to the tool when it has no server', async () => {
+ const { result } = renderHook(() => useToolApprovalRequests())
+
+ let p: Promise<boolean>
+ act(() => {
+ p = result.current.requestApproval('tc1', 'tool-a', 'thread-1')
+ })
+ act(() => {
+ result.current.resolveApproval('tc1', 'allow-always')
+ })
+
+ await expect(p!).resolves.toBe(true)
+ const approval = useToolApproval.getState()
+ expect(approval.isToolApproved('thread-2', 'tool-a')).toBe(true)
+ expect(approval.isToolApproved('thread-2', 'tool-b')).toBe(false)
+ })
+
+ it('auto-resolves true when the tool comes from an already trusted server', async () => {
+ act(() => {
+ useToolApproval.getState().approveServer('github')
+ })
+ const { result } = renderHook(() => useToolApprovalRequests())
+
+ let p: Promise<boolean>
+ act(() => {
+ p = result.current.requestApproval('tc1', 'tool-a', 'thread-1', 'github')
+ })
+
+ await expect(p!).resolves.toBe(true)
+ expect(result.current.pending['tc1']).toBeUndefined()
+ })
+
+ it('keeps the server on the pending entry so the prompt can name it', () => {
+ const { result } = renderHook(() => useToolApprovalRequests())
+
+ act(() => {
+ result.current.requestApproval('tc1', 'tool-a', 'thread-1', 'github')
+ })
+
+ expect(result.current.pending['tc1']).toMatchObject({
+ serverName: 'github',
+ })
})
it('resolveApproval deny resolves false', async () => {
diff --git a/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts b/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts
new file mode 100644
index 000000000..9dd905fef
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts
@@ -0,0 +1,137 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ findRunningToolCallId,
+ useToolCallRuntime,
+} from '../useToolCallRuntime'
+
+const store = () => useToolCallRuntime.getState()
+
+describe('useToolCallRuntime', () => {
+ beforeEach(() => {
+ store().reset()
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-07-31T10:00:00Z'))
+ })
+
+ it('reports the position of each waiting call', () => {
+ store().enqueue(['a', 'b', 'c'])
+ expect(store().queue).toEqual(['a', 'b', 'c'])
+ })
+
+ // Position has to be read from the live queue, not a stored index, or every
+ // entry keeps its original number as the ones ahead of it finish.
+ it('moves the remaining calls up as each one starts', () => {
+ store().enqueue(['a', 'b', 'c'])
+ store().markRunning('a')
+ expect(store().queue).toEqual(['b', 'c'])
+ store().markRunning('b')
+ expect(store().queue).toEqual(['c'])
+ })
+
+ it('records how long a call took', () => {
+ store().enqueue(['a'])
+ store().markRunning('a')
+ vi.advanceTimersByTime(4200)
+ store().markSettled('a')
+ const timing = store().timings['a']
+ expect(timing.endedAt! - timing.startedAt!).toBe(4200)
+ })
+
+ // A denied tool never runs, so it must still leave the queue or the calls
+ // behind it stay stuck reporting a position.
+ it('drops a call that settled without ever running', () => {
+ store().enqueue(['a', 'b'])
+ store().markSettled('a')
+ expect(store().queue).toEqual(['b'])
+ expect(store().timings['a'].startedAt).toBeUndefined()
+ })
+
+ // Cards from earlier turns stay on screen, so their durations have to
+ // outlive the turn that produced them.
+ it('keeps earlier durations when a new turn is enqueued', () => {
+ store().enqueue(['a'])
+ store().markRunning('a')
+ vi.advanceTimersByTime(2000)
+ store().markSettled('a')
+ store().enqueue(['b'])
+ expect(store().timings['a'].endedAt).toBeDefined()
+ expect(store().queue).toEqual(['b'])
+ })
+
+ // An aborted turn leaves calls in the queue that will never run; left there
+ // they keep claiming they are waiting their turn.
+ it('clears calls left waiting when a turn is abandoned', () => {
+ store().enqueue(['a', 'b'])
+ store().markRunning('a')
+ store().settleRemaining()
+ expect(store().queue).toEqual([])
+ expect(store().timings['b'].endedAt).toBeDefined()
+ expect(store().timings['b'].startedAt).toBeUndefined()
+ })
+
+ // The notification carries no tool call id, so it lands on the call the
+ // store already knows is running.
+ describe('reportProgress', () => {
+ const update = { server: 'github', progress: 3, total: 10, percent: 30 }
+
+ it('attaches an update to the running call', () => {
+ store().enqueue(['a', 'b'])
+ store().markRunning('a')
+ store().reportProgress(update)
+ expect(store().progress['a']).toMatchObject({ progress: 3, percent: 30 })
+ expect(store().progress['b']).toBeUndefined()
+ })
+
+ it('ignores an update when nothing is running', () => {
+ store().enqueue(['a'])
+ store().reportProgress(update)
+ expect(store().progress).toEqual({})
+ })
+
+ it('replaces the previous update rather than accumulating', () => {
+ store().enqueue(['a'])
+ store().markRunning('a')
+ store().reportProgress(update)
+ store().reportProgress({ ...update, progress: 7, percent: 70 })
+ expect(store().progress['a'].progress).toBe(7)
+ })
+
+ // A finished call has nothing left to report, and a stale bar under a
+ // completed result reads as though it is still working.
+ it('drops the update when the call settles', () => {
+ store().enqueue(['a'])
+ store().markRunning('a')
+ store().reportProgress(update)
+ store().markSettled('a')
+ expect(store().progress['a']).toBeUndefined()
+ })
+ })
+
+ // A turn can be severed mid-flight (HMR in dev, a reload, a crashed
+ // executor), leaving a call marked running that never settles. Since timings
+ // outlive their turn, that phantom would stay "running" forever: its elapsed
+ // timer keeps ticking, the condensed trace follows it, and MCP progress
+ // attaches to it instead of the real call.
+ it('settles a call stranded by an abandoned turn when the next one starts', () => {
+ store().enqueue(['old'])
+ store().markRunning('old')
+ store().enqueue(['new'])
+
+ expect(store().timings['old'].endedAt).toBeDefined()
+ expect(findRunningToolCallId(store().timings)).toBeUndefined()
+ })
+
+ it('reports the running call, ignoring settled ones', () => {
+ store().enqueue(['a', 'b'])
+ store().markRunning('a')
+ store().markSettled('a')
+ store().markRunning('b')
+ expect(findRunningToolCallId(store().timings)).toBe('b')
+ })
+
+ it('ignores transitions for calls it does not know about', () => {
+ store().markRunning('ghost')
+ store().markSettled('ghost')
+ expect(store().timings['ghost']).toBeUndefined()
+ })
+})
diff --git a/web-app/src/hooks/useMcpToolProgress.ts b/web-app/src/hooks/useMcpToolProgress.ts
new file mode 100644
index 000000000..75b7dc56e
--- /dev/null
+++ b/web-app/src/hooks/useMcpToolProgress.ts
@@ -0,0 +1,44 @@
+import { useEffect } from 'react'
+import { useServiceHub } from '@/hooks/useServiceHub'
+import { isPlatformTauri } from '@/lib/platform/utils'
+import {
+ useToolCallRuntime,
+ type ToolProgressUpdate,
+} from '@/hooks/useToolCallRuntime'
+import type { UnlistenFn } from '@/services/events/types'
+
+/** Emitted by the Rust MCP client handler; see core/mcp/progress.rs. */
+export const MCP_TOOL_PROGRESS_EVENT = 'mcp-tool-progress'
+
+/**
+ * Feeds MCP `notifications/progress` into the tool-call runtime. Mounted once
+ * at the root: the update carries no tool call id, so it is attached to the
+ * call currently running rather than routed to a particular card.
+ */
+export function useMcpToolProgress() {
+ const serviceHub = useServiceHub()
+
+ useEffect(() => {
+ if (!isPlatformTauri()) return
+
+ let unlisten: UnlistenFn | undefined
+ let cancelled = false
+
+ void serviceHub
+ .events()
+ .listen<ToolProgressUpdate>(MCP_TOOL_PROGRESS_EVENT, ({ payload }) => {
+ useToolCallRuntime.getState().reportProgress(payload)
+ })
+ .then((fn) => {
+ // listen() resolves after unmount if the component was short-lived,
+ // which would otherwise leave the subscription behind.
+ if (cancelled) fn()
+ else unlisten = fn
+ })
+
+ return () => {
+ cancelled = true
+ unlisten?.()
+ }
+ }, [serviceHub])
+}
diff --git a/web-app/src/hooks/useToolApproval.ts b/web-app/src/hooks/useToolApproval.ts
index 998241d0b..cc2104da4 100644
--- a/web-app/src/hooks/useToolApproval.ts
+++ b/web-app/src/hooks/useToolApproval.ts
@@ -3,25 +3,23 @@ import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
import { backendStorage } from '@/lib/backendStorage'
-export type ToolApprovalModalProps = {
- toolName: string
- threadId: string
- toolParameters?: object
- onApprove: (allowOnce: boolean) => void
- onDeny: () => void
-}
-
type ToolApprovalState = {
+ /** threadId -> tool names trusted for that conversation only. */
approvedTools: Record<string, string[]>
+ /** MCP servers trusted in every conversation, tools included. */
+ approvedServers: string[]
+ /** Tools trusted in every conversation, for tools with no server. */
+ approvedToolsGlobal: string[]
allowAllMCPPermissions: boolean
- isModalOpen: boolean
- modalProps: ToolApprovalModalProps | null
approveToolForThread: (threadId: string, toolName: string) => void
- isToolApproved: (threadId: string, toolName: string) => boolean
- showApprovalModal: (toolName: string, threadId: string, toolParameters?: object) => Promise<boolean>
- closeModal: () => void
- setModalOpen: (open: boolean) => void
+ approveServer: (serverName: string) => void
+ approveToolEverywhere: (toolName: string) => void
+ isToolApproved: (
+ threadId: string,
+ toolName: string,
+ serverName?: string
+ ) => boolean
setAllowAllMCPPermissions: (allow: boolean) => void
}
@@ -29,9 +27,9 @@ export const useToolApproval = create<ToolApprovalState>()(
persist(
(set, get) => ({
approvedTools: {},
+ approvedServers: [],
+ approvedToolsGlobal: [],
allowAllMCPPermissions: false,
- isModalOpen: false,
- modalProps: null,
approveToolForThread: (threadId: string, toolName: string) => {
set((state) => ({
@@ -45,62 +43,33 @@ export const useToolApproval = create<ToolApprovalState>()(
}))
},
- isToolApproved: (threadId: string, toolName: string) => {
- const state = get()
- return state.approvedTools[threadId]?.includes(toolName) || false
- },
-
- showApprovalModal: (toolName: string, threadId: string, toolParameters?: object) => {
- return new Promise<boolean>((resolve) => {
- const state = get()
-
- // Auto-approve if the user has enabled auto-approval setting
- if (state.allowAllMCPPermissions) {
- resolve(true)
- return
- }
-
- // Check if tool is already approved for this thread
- if (state.isToolApproved(threadId, toolName)) {
- resolve(true)
- return
- }
-
- set({
- isModalOpen: true,
- modalProps: {
- toolName,
- threadId,
- toolParameters,
- onApprove: (allowOnce: boolean) => {
- if (!allowOnce) {
- // If not "allow once", add to approved tools for this thread
- get().approveToolForThread(threadId, toolName)
- }
- get().closeModal()
- resolve(true)
- },
- onDeny: () => {
- get().closeModal()
- resolve(false)
- },
- },
- })
- })
+ approveServer: (serverName: string) => {
+ set((state) =>
+ state.approvedServers.includes(serverName)
+ ? state
+ : { approvedServers: [...state.approvedServers, serverName] }
+ )
},
- closeModal: () => {
- set({
- isModalOpen: false,
- modalProps: null,
- })
+ approveToolEverywhere: (toolName: string) => {
+ set((state) =>
+ state.approvedToolsGlobal.includes(toolName)
+ ? state
+ : { approvedToolsGlobal: [...state.approvedToolsGlobal, toolName] }
+ )
},
- setModalOpen: (open: boolean) => {
- set({ isModalOpen: open })
- if (!open) {
- get().closeModal()
+ isToolApproved: (
+ threadId: string,
+ toolName: string,
+ serverName?: string
+ ) => {
+ const state = get()
+ if (state.approvedToolsGlobal.includes(toolName)) return true
+ if (serverName && state.approvedServers.includes(serverName)) {
+ return true
}
+ return state.approvedTools[threadId]?.includes(toolName) || false
},
setAllowAllMCPPermissions: (allow: boolean) => {
@@ -114,6 +83,8 @@ export const useToolApproval = create<ToolApprovalState>()(
// Only persist approved tools and global permission setting, not modal state
partialize: (state) => ({
approvedTools: state.approvedTools,
+ approvedServers: state.approvedServers,
+ approvedToolsGlobal: state.approvedToolsGlobal,
allowAllMCPPermissions: state.allowAllMCPPermissions,
}),
}
diff --git a/web-app/src/hooks/useToolApprovalRequests.ts b/web-app/src/hooks/useToolApprovalRequests.ts
index a9a1d45b3..eea59af6a 100644
--- a/web-app/src/hooks/useToolApprovalRequests.ts
+++ b/web-app/src/hooks/useToolApprovalRequests.ts
@@ -5,10 +5,20 @@ export type PendingApproval = {
toolCallId: string
toolName: string
threadId: string
+ /** MCP server the tool belongs to, so the prompt can offer to trust it. */
+ serverName?: string
resolve: (approved: boolean) => void
}
-export type ApprovalDecision = 'allow-once' | 'allow-always' | 'deny'
+/**
+ * Scope of the grant. `allow-always` trusts the tool's whole server when it has
+ * one, since trusting a server tool-by-tool is the same decision repeated.
+ */
+export type ApprovalDecision =
+ | 'allow-once'
+ | 'allow-thread'
+ | 'allow-always'
+ | 'deny'
type ToolApprovalRequestsState = {
// In-flight per-tool-call approval prompts. Kept out of the persisted
@@ -19,7 +29,8 @@ type ToolApprovalRequestsState = {
requestApproval: (
toolCallId: string,
toolName: string,
- threadId: string
+ threadId: string,
+ serverName?: string
) => Promise<boolean>
resolveApproval: (toolCallId: string, decision: ApprovalDecision) => void
clearPendingForThread: (threadId: string) => void
@@ -29,21 +40,27 @@ export const useToolApprovalRequests = create<ToolApprovalRequestsState>()(
(set, get) => ({
pending: {},
- requestApproval: (toolCallId, toolName, threadId) => {
+ requestApproval: (toolCallId, toolName, threadId, serverName) => {
return new Promise<boolean>((resolve) => {
const settings = useToolApproval.getState()
if (settings.allowAllMCPPermissions) {
resolve(true)
return
}
- if (settings.isToolApproved(threadId, toolName)) {
+ if (settings.isToolApproved(threadId, toolName, serverName)) {
resolve(true)
return
}
set((s) => ({
pending: {
...s.pending,
- [toolCallId]: { toolCallId, toolName, threadId, resolve },
+ [toolCallId]: {
+ toolCallId,
+ toolName,
+ threadId,
+ serverName,
+ resolve,
+ },
},
}))
})
@@ -52,8 +69,15 @@ export const useToolApprovalRequests = create<ToolApprovalRequestsState>()(
resolveApproval: (toolCallId, decision) => {
const entry = get().pending[toolCallId]
if (!entry) return
- if (decision === 'allow-always') {
- useToolApproval.getState().approveToolForThread(entry.threadId, entry.toolName)
+ const approval = useToolApproval.getState()
+ if (decision === 'allow-thread') {
+ approval.approveToolForThread(entry.threadId, entry.toolName)
+ } else if (decision === 'allow-always') {
+ if (entry.serverName) {
+ approval.approveServer(entry.serverName)
+ } else {
+ approval.approveToolEverywhere(entry.toolName)
+ }
}
set((s) => {
const next = { ...s.pending }
diff --git a/web-app/src/hooks/useToolCallRuntime.ts b/web-app/src/hooks/useToolCallRuntime.ts
new file mode 100644
index 000000000..baab3d4c5
--- /dev/null
+++ b/web-app/src/hooks/useToolCallRuntime.ts
@@ -0,0 +1,143 @@
+import { create } from 'zustand'
+
+export type ToolCallTiming = {
+ /** Unset until the executor reaches this call. */
+ startedAt?: number
+ endedAt?: number
+}
+
+/** A `notifications/progress` update from an MCP server. */
+export type ToolProgressUpdate = {
+ server: string
+ progress: number
+ total?: number
+ message?: string
+ /** Only set when the server reported a usable total. */
+ percent?: number
+}
+
+/** The readable half of the store, for selectors defined outside it. */
+export type ToolCallRuntimeSnapshot = {
+ /**
+ * Calls the executor has not reached yet, in execution order. Position is
+ * read from here rather than stored per call, so entries move up as the ones
+ * ahead of them start.
+ */
+ queue: string[]
+ timings: Record<string, ToolCallTiming>
+ /** Latest progress update per call, cleared when the call settles. */
+ progress: Record<string, ToolProgressUpdate>
+}
+
+type ToolCallRuntimeState = ToolCallRuntimeSnapshot & {
+ /**
+ * Starts a turn. Earlier timings are kept: their cards are still on screen
+ * and would otherwise lose the duration they had been showing.
+ */
+ enqueue: (toolCallIds: string[]) => void
+ markRunning: (toolCallId: string) => void
+ markSettled: (toolCallId: string) => void
+ /**
+ * Records an MCP progress update against the running call. The notification
+ * carries no tool call id, so the running call is the only thing it can
+ * belong to -- well defined because tools execute one at a time.
+ */
+ reportProgress: (update: ToolProgressUpdate) => void
+ /** Ends a turn: nothing still queued will run, so stop showing it as waiting. */
+ settleRemaining: () => void
+ reset: () => void
+}
+
+/**
+ * The call currently executing, if any. Returns a primitive, so it is safe to
+ * use directly as a store selector.
+ */
+export function findRunningToolCallId(
+ timings: Record<string, ToolCallTiming>
+): string | undefined {
+ for (const [id, timing] of Object.entries(timings)) {
+ if (timing.startedAt !== undefined && timing.endedAt === undefined) {
+ return id
+ }
+ }
+ return undefined
+}
+
+/**
+ * Timing and queue position for in-flight tool calls -- the two things the SDK
+ * message part cannot express, since a queued call and a running one are both
+ * `input-available`. Status itself stays derived from the part, so it is not
+ * duplicated here.
+ */
+export const useToolCallRuntime = create<ToolCallRuntimeState>()((set) => ({
+ queue: [],
+ timings: {},
+ progress: {},
+
+ enqueue: (toolCallIds) =>
+ set((s) => {
+ const timings = { ...s.timings }
+ // A turn cannot start while a call from the previous one is still
+ // running, so anything left running was stranded by a severed turn (HMR
+ // in dev, a reload, a crashed executor). Left alone it keeps ticking and
+ // steals the running slot from every later call.
+ const stranded = findRunningToolCallId(timings)
+ if (stranded) {
+ timings[stranded] = { ...timings[stranded], endedAt: Date.now() }
+ }
+ return {
+ queue: [...toolCallIds],
+ timings: {
+ ...timings,
+ ...Object.fromEntries(toolCallIds.map((id) => [id, {}])),
+ },
+ }
+ }),
+
+ markRunning: (toolCallId) =>
+ set((s) =>
+ s.timings[toolCallId]
+ ? {
+ queue: s.queue.filter((id) => id !== toolCallId),
+ timings: {
+ ...s.timings,
+ [toolCallId]: { ...s.timings[toolCallId], startedAt: Date.now() },
+ },
+ }
+ : s
+ ),
+
+ markSettled: (toolCallId) =>
+ set((s) => {
+ if (!s.timings[toolCallId]) return s
+ const progress = { ...s.progress }
+ delete progress[toolCallId]
+ return {
+ queue: s.queue.filter((id) => id !== toolCallId),
+ timings: {
+ ...s.timings,
+ [toolCallId]: { ...s.timings[toolCallId], endedAt: Date.now() },
+ },
+ progress,
+ }
+ }),
+
+ reportProgress: (update) =>
+ set((s) => {
+ const running = findRunningToolCallId(s.timings)
+ return running ? { progress: { ...s.progress, [running]: update } } : s
+ }),
+
+ settleRemaining: () =>
+ set((s) => {
+ if (s.queue.length === 0) return s
+ const now = Date.now()
+ const timings = { ...s.timings }
+ for (const id of s.queue) {
+ timings[id] = { ...timings[id], endedAt: now }
+ }
+ return { queue: [], timings }
+ }),
+
+ reset: () => set({ queue: [], timings: {}, progress: {} }),
+}))
diff --git a/web-app/src/hooks/useToolOrigin.ts b/web-app/src/hooks/useToolOrigin.ts
new file mode 100644
index 000000000..eec052be1
--- /dev/null
+++ b/web-app/src/hooks/useToolOrigin.ts
@@ -0,0 +1,29 @@
+import { useMemo } from 'react'
+import { useAppState } from '@/hooks/useAppState'
+import { getProviderMeta, useWebSearchConfig } from '@/hooks/useWebSearchConfig'
+import { resolveToolOrigin, type ToolOrigin } from '@/lib/toolOrigin'
+
+/**
+ * Resolve which family a tool call belongs to. Each selector returns a
+ * primitive so a refreshed-but-equivalent tool list does not re-render every
+ * card on screen.
+ */
+export const useToolOrigin = (toolName: string): ToolOrigin | undefined => {
+ const mcpServer = useAppState(
+ (s) => s.tools.find((tool) => tool.name === toolName)?.server
+ )
+ const isRagTool = useAppState((s) => s.ragToolNames.has(toolName))
+ const webSearchProviderLabel = useWebSearchConfig(
+ (s) => getProviderMeta(s.searchProvider).label
+ )
+
+ return useMemo(
+ () =>
+ resolveToolOrigin(toolName, {
+ mcpServer,
+ isRagTool,
+ webSearchProviderLabel,
+ }),
+ [toolName, mcpServer, isRagTool, webSearchProviderLabel]
+ )
+}
diff --git a/web-app/src/lib/__tests__/duration.test.ts b/web-app/src/lib/__tests__/duration.test.ts
new file mode 100644
index 000000000..4790fa2ab
--- /dev/null
+++ b/web-app/src/lib/__tests__/duration.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest'
+import { formatCompactDuration } from '../duration'
+
+// Mirrors the compact unit strings in locales/en/common.json.
+const t = (key: string, options?: Record<string, unknown>) => {
+ const unit = { seconds: 's', minutes: 'm', hours: 'h' }[
+ key.split('.')[1] as 'seconds' | 'minutes' | 'hours'
+ ]
+ return `${options?.count}${unit}`
+}
+
+const format = (seconds: number) => formatCompactDuration(seconds, t)
+
+describe('formatCompactDuration', () => {
+ it('renders sub-minute durations in seconds', () => {
+ expect(format(0)).toBe('0s')
+ expect(format(1)).toBe('1s')
+ expect(format(59)).toBe('59s')
+ })
+
+ it('switches to minutes at 60 seconds', () => {
+ expect(format(60)).toBe('1m')
+ expect(format(90)).toBe('1m 30s')
+ expect(format(3599)).toBe('59m 59s')
+ })
+
+ it('omits a zero remainder', () => {
+ expect(format(120)).toBe('2m')
+ expect(format(7200)).toBe('2h')
+ })
+
+ it('switches to hours at 3600 seconds', () => {
+ expect(format(3600)).toBe('1h')
+ expect(format(4800)).toBe('1h 20m')
+ })
+
+ it('drops seconds at hour scale to keep the label short', () => {
+ expect(format(3661)).toBe('1h 1m')
+ })
+
+ it('floors fractional input and clamps negatives', () => {
+ expect(format(1.9)).toBe('1s')
+ expect(format(-5)).toBe('0s')
+ })
+})
diff --git a/web-app/src/lib/__tests__/reasoning.test.ts b/web-app/src/lib/__tests__/reasoning.test.ts
index dc1850f13..7936da2ca 100644
--- a/web-app/src/lib/__tests__/reasoning.test.ts
+++ b/web-app/src/lib/__tests__/reasoning.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest'
-import { splitReasoningParagraphs } from '../reasoning'
+import {
+ REASONING_STEP_MAX_CHARS,
+ segmentReasoningSteps,
+ splitReasoningParagraphs,
+} from '../reasoning'
describe('splitReasoningParagraphs', () => {
it('returns [] for empty/whitespace input', () => {
@@ -36,3 +40,106 @@ describe('splitReasoningParagraphs', () => {
expect(splitReasoningParagraphs('a \n \nb')).toEqual(['a', 'b'])
})
})
+
+describe('segmentReasoningSteps', () => {
+ const repeat = (unit: string, times: number) => unit.repeat(times)
+
+ it('returns [] for empty/whitespace input', () => {
+ expect(segmentReasoningSteps('')).toEqual([])
+ expect(segmentReasoningSteps(' \n \n ')).toEqual([])
+ })
+
+ it('leaves text below the budget as a single step', () => {
+ expect(segmentReasoningSteps('one short thought')).toEqual([
+ 'one short thought',
+ ])
+ })
+
+ it('still honours blank-line paragraph boundaries', () => {
+ expect(segmentReasoningSteps('first\n\nsecond')).toEqual([
+ 'first',
+ 'second',
+ ])
+ })
+
+ // The bug: a model that never emits a blank line produced exactly one step,
+ // so the "last completed step" was always empty and the UI stayed static for
+ // the whole run.
+ it('subdivides an unbroken blob so completed steps exist', () => {
+ const blob = repeat('word ', 400).trim()
+ const steps = segmentReasoningSteps(blob)
+ expect(steps.length).toBeGreaterThan(1)
+ expect(steps.slice(0, -1).every((s) => s.trim().length > 0)).toBe(true)
+ })
+
+ it('subdivides a single-newline-only trace', () => {
+ const blob = repeat('a line of reasoning\n', 60).trim()
+ const steps = segmentReasoningSteps(blob)
+ expect(steps.length).toBeGreaterThan(1)
+ })
+
+ it('keeps every step within the budget', () => {
+ const blob = repeat('word ', 400).trim()
+ for (const step of segmentReasoningSteps(blob)) {
+ expect(step.length).toBeLessThanOrEqual(REASONING_STEP_MAX_CHARS)
+ }
+ })
+
+ it('prefers a sentence boundary when one is in range', () => {
+ const sentence = `${repeat('x', REASONING_STEP_MAX_CHARS - 60)}. `
+ const steps = segmentReasoningSteps(sentence + repeat('y', 200))
+ expect(steps[0]).toBe(`${repeat('x', REASONING_STEP_MAX_CHARS - 60)}.`)
+ })
+
+ it('falls back to a newline when no sentence boundary is in range', () => {
+ const head = `${repeat('x', REASONING_STEP_MAX_CHARS - 60)}\n`
+ const steps = segmentReasoningSteps(head + repeat('y', 200))
+ expect(steps[0]).toBe(repeat('x', REASONING_STEP_MAX_CHARS - 60))
+ })
+
+ it('falls back to a word boundary when no sentence or newline is in range', () => {
+ const steps = segmentReasoningSteps(repeat('word ', 400).trim())
+ expect(steps[0].endsWith('word')).toBe(true)
+ })
+
+ // CJK and other unspaced scripts have no whitespace to break on; a hard cut
+ // is the only way to keep steps advancing.
+ it('hard-cuts text that has no break opportunity at all', () => {
+ const steps = segmentReasoningSteps(repeat('你', 900))
+ expect(steps.length).toBeGreaterThan(1)
+ expect(steps[0].length).toBe(REASONING_STEP_MAX_CHARS)
+ })
+
+ it('ignores a break candidate too early to be a useful step', () => {
+ // A lone sentence end near the start must not emit a 2-char step.
+ const steps = segmentReasoningSteps(`ok. ${repeat('y ', 400)}`.trim())
+ expect(steps[0]).not.toBe('ok.')
+ })
+
+ // Guards the subdivision loop: a break offset of 0 would never consume input.
+ it('terminates on a degenerate budget', () => {
+ const steps = segmentReasoningSteps('a b. c\nd', 1)
+ expect(steps.join('')).not.toBe('')
+ expect(steps.every((s) => s.trim().length > 0)).toBe(true)
+ })
+
+ it('never emits blank steps', () => {
+ const steps = segmentReasoningSteps(
+ `first\n\n\n${repeat('word ', 400)}\n\n \n\nlast`
+ )
+ expect(steps.every((s) => s.trim().length > 0)).toBe(true)
+ })
+
+ // The caller re-segments the whole accumulated text on every streaming tick,
+ // so completed steps must not shift as more tokens arrive.
+ it('keeps earlier steps stable as the text grows', () => {
+ const full = repeat('word ', 500).trim()
+ let previous = segmentReasoningSteps(full.slice(0, 500))
+ for (let end = 600; end <= full.length; end += 100) {
+ const next = segmentReasoningSteps(full.slice(0, end))
+ const settled = previous.slice(0, -1)
+ expect(next.slice(0, settled.length)).toEqual(settled)
+ previous = next
+ }
+ })
+})
diff --git a/web-app/src/lib/__tests__/toolInputSummary.test.ts b/web-app/src/lib/__tests__/toolInputSummary.test.ts
new file mode 100644
index 000000000..f940b66e2
--- /dev/null
+++ b/web-app/src/lib/__tests__/toolInputSummary.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from 'vitest'
+import {
+ isPlainObject,
+ parseToolInput,
+ stringifyToolInput,
+ summarizeToolInput,
+} from '../toolInputSummary'
+
+describe('parseToolInput', () => {
+ it('passes objects through untouched', () => {
+ const input = { a: 1 }
+ expect(parseToolInput(input)).toBe(input)
+ })
+
+ it('parses a JSON string', () => {
+ expect(parseToolInput('{"a":1}')).toEqual({ a: 1 })
+ })
+
+ it('leaves unparseable text as-is', () => {
+ expect(parseToolInput('not json')).toBe('not json')
+ })
+
+ // Arguments stream in, so the UI sees truncated JSON mid-call.
+ it('leaves a half-streamed JSON fragment as text', () => {
+ expect(parseToolInput('{"path":"src/ap')).toBe('{"path":"src/ap')
+ })
+})
+
+describe('isPlainObject', () => {
+ it('rejects arrays and null', () => {
+ expect(isPlainObject([])).toBe(false)
+ expect(isPlainObject(null)).toBe(false)
+ expect(isPlainObject({})).toBe(true)
+ })
+})
+
+describe('stringifyToolInput', () => {
+ it('pretty-prints objects', () => {
+ expect(stringifyToolInput({ a: 1 })).toBe('{\n "a": 1\n}')
+ })
+
+ it('returns strings unchanged', () => {
+ expect(stringifyToolInput('plain')).toBe('plain')
+ })
+
+ it('survives circular structures', () => {
+ const circular: Record<string, unknown> = {}
+ circular.self = circular
+ expect(() => stringifyToolInput(circular)).not.toThrow()
+ })
+})
+
+describe('summarizeToolInput', () => {
+ it('is empty for missing input', () => {
+ expect(summarizeToolInput(undefined)).toBe('')
+ expect(summarizeToolInput(null)).toBe('')
+ expect(summarizeToolInput({})).toBe('')
+ })
+
+ it('renders scalar arguments as key: value pairs', () => {
+ expect(summarizeToolInput({ path: 'src/app.ts', limit: 5 })).toBe(
+ 'path: src/app.ts, limit: 5'
+ )
+ })
+
+ it('keeps false and null visible', () => {
+ expect(summarizeToolInput({ recursive: false, cursor: null })).toBe(
+ 'recursive: false, cursor: null'
+ )
+ })
+
+ it('collapses nested values to a shape hint', () => {
+ expect(summarizeToolInput({ files: ['a', 'b'], opts: { deep: true } })).toBe(
+ 'files: [2], opts: {...}'
+ )
+ })
+
+ it('flattens newlines out of multi-line arguments', () => {
+ expect(summarizeToolInput({ body: 'line one\n\nline two' })).toBe(
+ 'body: line one line two'
+ )
+ })
+
+ it('skips undefined values', () => {
+ expect(summarizeToolInput({ a: undefined, b: 1 })).toBe('b: 1')
+ })
+
+ it('truncates with an ascii ellipsis', () => {
+ const summary = summarizeToolInput({ q: 'x'.repeat(200) }, 20)
+ expect(summary).toHaveLength(20)
+ expect(summary.endsWith('...')).toBe(true)
+ })
+
+ it('summarizes a JSON string argument', () => {
+ expect(summarizeToolInput('{"path":"a.ts"}')).toBe('path: a.ts')
+ })
+
+ it('summarizes a bare string argument', () => {
+ expect(summarizeToolInput('just text')).toBe('just text')
+ })
+})
diff --git a/web-app/src/lib/__tests__/toolOrigin.test.ts b/web-app/src/lib/__tests__/toolOrigin.test.ts
new file mode 100644
index 000000000..9642b0f64
--- /dev/null
+++ b/web-app/src/lib/__tests__/toolOrigin.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest'
+import { resolveToolOrigin } from '../toolOrigin'
+
+const context = {
+ isRagTool: false,
+ webSearchProviderLabel: 'Exa',
+}
+
+describe('resolveToolOrigin', () => {
+ it('attributes web_search to the configured provider', () => {
+ expect(resolveToolOrigin('web_search', context)).toEqual({
+ kind: 'web-search',
+ detail: 'Exa',
+ })
+ })
+
+ it('tracks a provider change', () => {
+ expect(
+ resolveToolOrigin('web_search', {
+ ...context,
+ webSearchProviderLabel: 'Tavily',
+ })
+ ).toEqual({ kind: 'web-search', detail: 'Tavily' })
+ })
+
+ it('recognises web_fetch', () => {
+ expect(resolveToolOrigin('web_fetch', context)).toEqual({
+ kind: 'web-fetch',
+ })
+ })
+
+ it('recognises a RAG tool', () => {
+ expect(
+ resolveToolOrigin('search_documents', { ...context, isRagTool: true })
+ ).toEqual({ kind: 'rag' })
+ })
+
+ it('names the MCP server for a server tool', () => {
+ expect(
+ resolveToolOrigin('read_file', { ...context, mcpServer: 'filesystem' })
+ ).toEqual({ kind: 'mcp', detail: 'filesystem' })
+ })
+
+ // Mirrors the thread route's execution order, where native web tools are
+ // dispatched before any MCP tool of the same name.
+ it('prefers the native web tool over a same-named MCP tool', () => {
+ expect(
+ resolveToolOrigin('web_search', { ...context, mcpServer: 'someserver' })
+ ).toEqual({ kind: 'web-search', detail: 'Exa' })
+ })
+
+ it('prefers RAG over MCP when both somehow match', () => {
+ expect(
+ resolveToolOrigin('search_documents', {
+ ...context,
+ isRagTool: true,
+ mcpServer: 'someserver',
+ })
+ ).toEqual({ kind: 'rag' })
+ })
+
+ it('is undefined for an unknown tool', () => {
+ expect(resolveToolOrigin('mystery', context)).toBeUndefined()
+ })
+})
diff --git a/web-app/src/lib/__tests__/toolOutputSummary.test.ts b/web-app/src/lib/__tests__/toolOutputSummary.test.ts
new file mode 100644
index 000000000..6f5bcbbc0
--- /dev/null
+++ b/web-app/src/lib/__tests__/toolOutputSummary.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest'
+import { summarizeToolOutput } from '../toolOutputSummary'
+
+describe('summarizeToolOutput', () => {
+ it('is undefined with no output', () => {
+ expect(summarizeToolOutput(undefined)).toBeUndefined()
+ expect(summarizeToolOutput(null)).toBeUndefined()
+ })
+
+ it('previews the first meaningful line of a string', () => {
+ expect(summarizeToolOutput('\n\n hello there \nsecond line')).toEqual({
+ key: 'tools:toolCall.summaryText',
+ values: { preview: 'hello there' },
+ })
+ })
+
+ it('truncates a long first line', () => {
+ const summary = summarizeToolOutput('x'.repeat(400))
+ expect(String(summary?.values?.preview)).toHaveLength(140)
+ expect(String(summary?.values?.preview).endsWith('...')).toBe(true)
+ })
+
+ it('reports an empty string as empty', () => {
+ expect(summarizeToolOutput(' \n ')).toEqual({
+ key: 'tools:toolCall.summaryEmpty',
+ })
+ })
+
+ it('previews a single text block from the MCP envelope', () => {
+ expect(
+ summarizeToolOutput({ content: [{ type: 'text', text: 'one result' }] })
+ ).toEqual({
+ key: 'tools:toolCall.summaryText',
+ values: { preview: 'one result' },
+ })
+ })
+
+ it('counts multiple text blocks alongside the preview', () => {
+ expect(
+ summarizeToolOutput({
+ content: [
+ { type: 'text', text: 'first' },
+ { type: 'text', text: 'second' },
+ ],
+ })
+ ).toEqual({
+ key: 'tools:toolCall.summaryTextBlocks',
+ values: { count: 2, preview: 'first' },
+ })
+ })
+
+ it('counts non-text blocks separately', () => {
+ expect(
+ summarizeToolOutput({
+ content: [
+ { type: 'text', text: 'caption' },
+ { type: 'image', data: 'base64' },
+ ],
+ })
+ ).toEqual({
+ key: 'tools:toolCall.summaryBlocks',
+ values: { text: 1, other: 1 },
+ })
+ })
+
+ it('treats an empty envelope as empty', () => {
+ expect(summarizeToolOutput({ content: [] })).toEqual({
+ key: 'tools:toolCall.summaryEmpty',
+ })
+ })
+
+ it('counts array items', () => {
+ expect(summarizeToolOutput([1, 2, 3])).toEqual({
+ key: 'tools:toolCall.summaryItems',
+ values: { count: 3 },
+ })
+ expect(summarizeToolOutput([])).toEqual({
+ key: 'tools:toolCall.summaryEmpty',
+ })
+ })
+
+ it('names an objects fields, capped at four', () => {
+ expect(
+ summarizeToolOutput({ a: 1, b: 2, c: 3, d: 4, e: 5 })
+ ).toEqual({
+ key: 'tools:toolCall.summaryFields',
+ values: { count: 5, fields: 'a, b, c, d' },
+ })
+ })
+
+ it('treats an empty object as empty', () => {
+ expect(summarizeToolOutput({})).toEqual({
+ key: 'tools:toolCall.summaryEmpty',
+ })
+ })
+})
diff --git a/web-app/src/lib/__tests__/toolPresentation.test.ts b/web-app/src/lib/__tests__/toolPresentation.test.ts
new file mode 100644
index 000000000..611372375
--- /dev/null
+++ b/web-app/src/lib/__tests__/toolPresentation.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from 'vitest'
+import { describeNativeToolCall, parseWebFetchOutput } from '../toolPresentation'
+
+const search = { kind: 'web-search', detail: 'Exa' } as const
+const fetchOrigin = { kind: 'web-fetch' } as const
+
+describe('describeNativeToolCall', () => {
+ it('builds a search bar from the query', () => {
+ expect(describeNativeToolCall(search, 'web_search', { query: 'rust async', count: 5 })).toEqual(
+ { variant: 'search', query: 'rust async', count: 5 }
+ )
+ })
+
+ // Arguments stream in a character at a time; a partial query must still show.
+ it('accepts a partially streamed query', () => {
+ expect(describeNativeToolCall(search, 'web_search', { query: 'rust as' })).toEqual({
+ variant: 'search',
+ query: 'rust as',
+ })
+ })
+
+ it('yields an empty bar before any argument has arrived', () => {
+ expect(describeNativeToolCall(search, 'web_search', undefined)).toEqual({
+ variant: 'search',
+ query: '',
+ })
+ })
+
+ it('ignores a non-numeric count', () => {
+ expect(describeNativeToolCall(search, 'web_search', { query: 'q', count: 'five' })).toEqual({
+ variant: 'search',
+ query: 'q',
+ })
+ })
+
+ it('builds an address bar for web fetch', () => {
+ expect(describeNativeToolCall(fetchOrigin, 'web_fetch', { url: 'https://a.dev/x' })).toEqual({
+ variant: 'address',
+ url: 'https://a.dev/x',
+ })
+ })
+
+ it('builds a documents bar for a RAG retrieve', () => {
+ expect(
+ describeNativeToolCall({ kind: 'rag' }, 'retrieve', {
+ query: 'refund policy',
+ top_k: 4,
+ file_ids: ['a', 'b'],
+ })
+ ).toEqual({
+ variant: 'documents',
+ query: 'refund policy',
+ count: 4,
+ fileCount: 2,
+ })
+ })
+
+ it('omits absent RAG modifiers', () => {
+ expect(
+ describeNativeToolCall({ kind: 'rag' }, 'retrieve', { query: 'q' })
+ ).toEqual({ variant: 'documents', query: 'q' })
+ })
+
+ it('has no bar for other RAG tools or for MCP', () => {
+ expect(
+ describeNativeToolCall({ kind: 'rag' }, 'list_attachments', {})
+ ).toBeUndefined()
+ expect(
+ describeNativeToolCall({ kind: 'rag' }, 'get_chunks', { file_id: 'f' })
+ ).toBeUndefined()
+ expect(
+ describeNativeToolCall({ kind: 'mcp', detail: 'fs' }, 'read_file', {})
+ ).toBeUndefined()
+ expect(describeNativeToolCall(undefined, 'x', {})).toBeUndefined()
+ })
+})
+
+describe('parseWebFetchOutput', () => {
+ it('splits the title, url and body', () => {
+ const page = parseWebFetchOutput(
+ 'Title: Async Rust\nURL: https://a.dev/x\n\nbody text here'
+ )
+ expect(page).toEqual({
+ title: 'Async Rust',
+ url: 'https://a.dev/x',
+ content: 'body text here',
+ truncated: false,
+ })
+ })
+
+ it('detects the truncation marker without leaking it into the body', () => {
+ const page = parseWebFetchOutput(
+ 'Title: T\nURL: https://a.dev\n\nbody\n\n[content truncated]'
+ )
+ expect(page?.truncated).toBe(true)
+ expect(page?.content).toBe('body')
+ })
+
+ it('keeps a multi-line body intact', () => {
+ const page = parseWebFetchOutput(
+ 'Title: T\nURL: https://a.dev\n\nline one\n\nline two'
+ )
+ expect(page?.content).toBe('line one\n\nline two')
+ })
+
+ it('treats an unprefixed blob as body-only', () => {
+ expect(parseWebFetchOutput('just content')).toEqual({
+ content: 'just content',
+ truncated: false,
+ })
+ })
+
+ it('unwraps a { content } envelope', () => {
+ expect(parseWebFetchOutput({ content: 'inner' })?.content).toBe('inner')
+ })
+
+ it('omits empty header values', () => {
+ const page = parseWebFetchOutput('Title: \nURL: \n\nbody')
+ expect(page?.title).toBeUndefined()
+ expect(page?.url).toBeUndefined()
+ })
+
+ it('is undefined for a non-text payload', () => {
+ expect(parseWebFetchOutput({ kind: 'web' })).toBeUndefined()
+ expect(parseWebFetchOutput(undefined)).toBeUndefined()
+ })
+})
diff --git a/web-app/src/lib/duration.ts b/web-app/src/lib/duration.ts
new file mode 100644
index 000000000..87feddd87
--- /dev/null
+++ b/web-app/src/lib/duration.ts
@@ -0,0 +1,38 @@
+type TranslateFn = (key: string, options?: Record<string, unknown>) => string
+
+const SECONDS_PER_MINUTE = 60
+const SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE
+
+/**
+ * Elapsed time as at most two units: "45s", "1m 30s", "1h 20m". Abbreviated
+ * units keep the label short enough for an inline header and avoid per-language
+ * plural rules, which the translation layer does not implement.
+ */
+export function formatCompactDuration(
+ totalSeconds: number,
+ t: TranslateFn
+): string {
+ const seconds = Math.max(0, Math.floor(totalSeconds))
+
+ if (seconds < SECONDS_PER_MINUTE) {
+ return t('common:duration.seconds', { count: seconds })
+ }
+
+ if (seconds < SECONDS_PER_HOUR) {
+ const minutes = t('common:duration.minutes', {
+ count: Math.floor(seconds / SECONDS_PER_MINUTE),
+ })
+ const rest = seconds % SECONDS_PER_MINUTE
+ return rest === 0
+ ? minutes
+ : `${minutes} ${t('common:duration.seconds', { count: rest })}`
+ }
+
+ const hours = t('common:duration.hours', {
+ count: Math.floor(seconds / SECONDS_PER_HOUR),
+ })
+ const rest = Math.floor((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE)
+ return rest === 0
+ ? hours
+ : `${hours} ${t('common:duration.minutes', { count: rest })}`
+}
diff --git a/web-app/src/lib/reasoning.ts b/web-app/src/lib/reasoning.ts
index 63ee92623..85619ebe3 100644
--- a/web-app/src/lib/reasoning.ts
+++ b/web-app/src/lib/reasoning.ts
@@ -14,3 +14,71 @@ export function splitReasoningParagraphs(text: string): string[] {
.map((p) => p.replace(/\s+$/, ''))
.filter((p) => p.trim().length > 0)
}
+
+/**
+ * Character budget per step, roughly five lines at the chat column's width.
+ * Exact line count depends on the rendered width, so the view still caps its
+ * own height; this budget only decides when a step is considered finished.
+ */
+export const REASONING_STEP_MAX_CHARS = 400
+
+/** A break this early would emit a stub step, so keep looking. */
+const MIN_STEP_RATIO = 0.4
+
+const SENTENCE_END = /[.!?。!?](?=\s)/g
+const WHITESPACE = /\s/
+
+/**
+ * Offset just past the best break in `window`, or -1 when none is usable.
+ * Preference order: sentence end, then line break, then word boundary.
+ */
+function findBreak(window: string, minChars: number): number {
+ let sentence = -1
+ for (const match of window.matchAll(SENTENCE_END)) {
+ sentence = match.index + 1
+ }
+ if (sentence >= minChars) return sentence
+
+ const newline = window.lastIndexOf('\n')
+ if (newline >= minChars) return newline + 1
+
+ for (let i = window.length - 1; i >= minChars; i--) {
+ if (WHITESPACE.test(window[i])) return i + 1
+ }
+ return -1
+}
+
+/**
+ * Split a reasoning trace into steps that always advance. Blank lines still
+ * take precedence, but any paragraph longer than `maxChars` is subdivided, so a
+ * model that streams one unbroken block still produces completed steps instead
+ * of a single ever-growing one.
+ *
+ * Segmentation is greedy from the start, so a step's boundary depends only on
+ * the text before it: re-segmenting a longer prefix on the next streaming tick
+ * leaves already-settled steps untouched. As with splitReasoningParagraphs, the
+ * last element is the step currently being written.
+ */
+export function segmentReasoningSteps(
+ text: string,
+ maxChars: number = REASONING_STEP_MAX_CHARS
+): string[] {
+ const minChars = Math.floor(maxChars * MIN_STEP_RATIO)
+ const steps: string[] = []
+
+ for (const paragraph of splitReasoningParagraphs(text)) {
+ let rest = paragraph
+ while (rest.length > maxChars) {
+ const window = rest.slice(0, maxChars)
+ const cut = findBreak(window, minChars)
+ const end = cut === -1 ? maxChars : cut
+ const step = rest.slice(0, end).trim()
+ if (step) steps.push(step)
+ rest = rest.slice(end).trimStart()
+ }
+ const tail = rest.trim()
+ if (tail) steps.push(tail)
+ }
+
+ return steps
+}
diff --git a/web-app/src/lib/toolInputSummary.ts b/web-app/src/lib/toolInputSummary.ts
new file mode 100644
index 000000000..3999eec64
--- /dev/null
+++ b/web-app/src/lib/toolInputSummary.ts
@@ -0,0 +1,72 @@
+const ELLIPSIS = '...'
+
+/**
+ * Tool arguments reach the UI either as an object (the SDK parses streamed
+ * argument deltas for us) or as a raw JSON string from providers that pass it
+ * through. Normalize both, leaving unparseable text as-is.
+ */
+export function parseToolInput(input: unknown): unknown {
+ if (typeof input !== 'string') return input
+ try {
+ return JSON.parse(input)
+ } catch {
+ return input
+ }
+}
+
+export function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return (
+ typeof value === 'object' && value !== null && !Array.isArray(value)
+ )
+}
+
+/** Pretty JSON for the raw view and for copying. */
+export function stringifyToolInput(input: unknown): string {
+ if (typeof input === 'string') return input
+ try {
+ return JSON.stringify(input, null, 2) ?? ''
+ } catch {
+ return String(input)
+ }
+}
+
+const collapseWhitespace = (text: string) => text.replace(/\s+/g, ' ').trim()
+
+function previewValue(value: unknown): string {
+ if (typeof value === 'string') return collapseWhitespace(value)
+ if (value === null) return 'null'
+ if (typeof value === 'number' || typeof value === 'boolean') {
+ return String(value)
+ }
+ if (Array.isArray(value)) return `[${value.length}]`
+ if (typeof value === 'object') return '{...}'
+ return ''
+}
+
+function truncate(text: string, maxLength: number): string {
+ if (text.length <= maxLength) return text
+ return text.slice(0, Math.max(0, maxLength - ELLIPSIS.length)) + ELLIPSIS
+}
+
+/**
+ * One-line preview of a tool call's arguments for the collapsed header, so a
+ * call reads as "read_file path: src/app.ts" rather than just "read_file".
+ * Nested values collapse to a shape hint; the expanded card shows them in full.
+ */
+export function summarizeToolInput(input: unknown, maxLength = 72): string {
+ const parsed = parseToolInput(input)
+
+ if (parsed === undefined || parsed === null) return ''
+ if (typeof parsed === 'string') return truncate(collapseWhitespace(parsed), maxLength)
+ if (!isPlainObject(parsed)) return truncate(previewValue(parsed), maxLength)
+
+ const pairs: string[] = []
+ for (const [key, value] of Object.entries(parsed)) {
+ if (value === undefined) continue
+ const preview = previewValue(value)
+ if (preview === '') continue
+ pairs.push(`${key}: ${preview}`)
+ }
+
+ return truncate(pairs.join(', '), maxLength)
+}
diff --git a/web-app/src/lib/toolOrigin.ts b/web-app/src/lib/toolOrigin.ts
new file mode 100644
index 000000000..7ffdf137a
--- /dev/null
+++ b/web-app/src/lib/toolOrigin.ts
@@ -0,0 +1,39 @@
+/**
+ * Where a tool call came from. Jan runs three families of tools -- the native
+ * web tools, the built-in RAG tools, and MCP server tools -- and a collapsed
+ * card is ambiguous without saying which.
+ */
+export type ToolOrigin =
+ | { kind: 'web-search'; detail: string }
+ | { kind: 'web-fetch' }
+ | { kind: 'rag' }
+ | { kind: 'mcp'; detail: string }
+
+export type ToolOriginContext = {
+ /** MCP server owning this tool, when it is an MCP tool. */
+ mcpServer?: string
+ isRagTool: boolean
+ /** Display name of the configured web search provider, e.g. "Exa". */
+ webSearchProviderLabel: string
+}
+
+export const WEB_SEARCH_TOOL = 'web_search'
+export const WEB_FETCH_TOOL = 'web_fetch'
+
+/**
+ * Resolution order mirrors the execution order in the thread route: native web
+ * tools win, then RAG, then MCP. RAG names shadowed by an MCP server are
+ * already dropped from the RAG set upstream, so the two cannot both match.
+ */
+export function resolveToolOrigin(
+ toolName: string,
+ { mcpServer, isRagTool, webSearchProviderLabel }: ToolOriginContext
+): ToolOrigin | undefined {
+ if (toolName === WEB_SEARCH_TOOL) {
+ return { kind: 'web-search', detail: webSearchProviderLabel }
+ }
+ if (toolName === WEB_FETCH_TOOL) return { kind: 'web-fetch' }
+ if (isRagTool) return { kind: 'rag' }
+ if (mcpServer) return { kind: 'mcp', detail: mcpServer }
+ return undefined
+}
diff --git a/web-app/src/lib/toolOutputSummary.ts b/web-app/src/lib/toolOutputSummary.ts
new file mode 100644
index 000000000..b02f1f2bf
--- /dev/null
+++ b/web-app/src/lib/toolOutputSummary.ts
@@ -0,0 +1,91 @@
+import { isPlainObject } from './toolInputSummary'
+
+/**
+ * A short, human description of what a tool returned, so a generic (MCP) result
+ * leads with "3 text blocks, 1 image" or its first line rather than a wall of
+ * JSON. Returns an i18n key plus its interpolation values; the raw payload stays
+ * available behind a toggle.
+ */
+export type ToolOutputSummary = {
+ key: string
+ values?: Record<string, string | number>
+}
+
+const PREVIEW_MAX = 140
+const ELLIPSIS = '...'
+
+const firstLine = (text: string): string => {
+ const line = text
+ .split('\n')
+ .map((l) => l.trim())
+ .find((l) => l.length > 0)
+ if (!line) return ''
+ return line.length > PREVIEW_MAX
+ ? line.slice(0, PREVIEW_MAX - ELLIPSIS.length) + ELLIPSIS
+ : line
+}
+
+type ContentItem = { type?: string; text?: string }
+
+const isContentEnvelope = (
+ value: unknown
+): value is { content: ContentItem[] } =>
+ isPlainObject(value) && Array.isArray(value.content)
+
+export function summarizeToolOutput(
+ output: unknown
+): ToolOutputSummary | undefined {
+ if (output === undefined || output === null) return undefined
+
+ if (typeof output === 'string') {
+ const preview = firstLine(output)
+ return preview
+ ? { key: 'tools:toolCall.summaryText', values: { preview } }
+ : { key: 'tools:toolCall.summaryEmpty' }
+ }
+
+ // The MCP content envelope: a list of typed blocks.
+ if (isContentEnvelope(output)) {
+ const items = output.content
+ const texts = items.filter((item) => item.type === 'text')
+ const others = items.length - texts.length
+
+ if (others > 0) {
+ return {
+ key: 'tools:toolCall.summaryBlocks',
+ values: { text: texts.length, other: others },
+ }
+ }
+ const joined = texts.map((item) => item.text ?? '').join('\n')
+ const preview = firstLine(joined)
+ if (preview) {
+ return texts.length > 1
+ ? {
+ key: 'tools:toolCall.summaryTextBlocks',
+ values: { count: texts.length, preview },
+ }
+ : { key: 'tools:toolCall.summaryText', values: { preview } }
+ }
+ return items.length === 0
+ ? { key: 'tools:toolCall.summaryEmpty' }
+ : { key: 'tools:toolCall.summaryBlocks', values: { text: texts.length, other: 0 } }
+ }
+
+ if (Array.isArray(output)) {
+ return output.length === 0
+ ? { key: 'tools:toolCall.summaryEmpty' }
+ : { key: 'tools:toolCall.summaryItems', values: { count: output.length } }
+ }
+
+ if (isPlainObject(output)) {
+ const keys = Object.keys(output)
+ return keys.length === 0
+ ? { key: 'tools:toolCall.summaryEmpty' }
+ : {
+ key: 'tools:toolCall.summaryFields',
+ values: { count: keys.length, fields: keys.slice(0, 4).join(', ') },
+ }
+ }
+
+ return { key: 'tools:toolCall.summaryText', values: { preview: String(output) } }
+}
diff --git a/web-app/src/lib/toolPresentation.ts b/web-app/src/lib/toolPresentation.ts
new file mode 100644
index 000000000..2ff2e2dd3
--- /dev/null
+++ b/web-app/src/lib/toolPresentation.ts
@@ -0,0 +1,95 @@
+import type { ToolUIPart } from 'ai'
+import type { ToolOrigin } from './toolOrigin'
+
+/** The call is still being written or executed: no result yet. */
+export const isToolRunning = (state: ToolUIPart['state']) =>
+ state === 'input-streaming' || state === 'input-available'
+
+/**
+ * The chrome a native tool call is presented as: web search reads as a search
+ * bar the model types into, web fetch as an address bar.
+ */
+export type ToolCallBar =
+ | { variant: 'search'; query: string; count?: number }
+ | { variant: 'address'; url: string }
+ | { variant: 'documents'; query: string; count?: number; fileCount?: number }
+
+/**
+ * Owned by the RAG extension (extensions/rag-extension/src/tools.ts) and not
+ * exported through @janhq/core, so this must stay in sync with it. Only
+ * `retrieve` gets a bar; the other RAG tools fall back to the generic card.
+ */
+export const RAG_RETRIEVE_TOOL = 'retrieve'
+
+const asString = (value: unknown): string =>
+ typeof value === 'string' ? value : ''
+
+/**
+ * Build the bar for a native tool call from its arguments. Arguments stream in,
+ * so a missing or partial value is normal and renders as an empty/partial bar
+ * rather than being suppressed.
+ */
+export function describeNativeToolCall(
+ origin: ToolOrigin | undefined,
+ toolName: string,
+ input: unknown
+): ToolCallBar | undefined {
+ if (!origin) return undefined
+ const args = (input ?? {}) as Record<string, unknown>
+ const asCount = (value: unknown) =>
+ typeof value === 'number' ? value : undefined
+
+ if (origin.kind === 'web-search') {
+ return { variant: 'search', query: asString(args.query), count: asCount(args.count) }
+ }
+ if (origin.kind === 'web-fetch') {
+ return { variant: 'address', url: asString(args.url) }
+ }
+ if (origin.kind === 'rag' && toolName === RAG_RETRIEVE_TOOL) {
+ return {
+ variant: 'documents',
+ query: asString(args.query),
+ count: asCount(args.top_k),
+ fileCount: Array.isArray(args.file_ids) ? args.file_ids.length : undefined,
+ }
+ }
+ return undefined
+}
+
+export type WebFetchPage = {
+ title?: string
+ url?: string
+ content: string
+ truncated: boolean
+}
+
+const TRUNCATION_MARKER = '\n\n[content truncated]'
+const FETCH_HEADER = /^Title: (.*)\nURL: (.*)\n\n([\s\S]*)$/
+
+/**
+ * web_fetch returns a plain-text blob prefixed with `Title:` / `URL:` lines
+ * (see executeWebTool), not a structured payload. Split it back apart so the
+ * page can be presented as a page instead of a wall of text.
+ */
+export function parseWebFetchOutput(output: unknown): WebFetchPage | undefined {
+ const text =
+ typeof output === 'string'
+ ? output
+ : typeof (output as { content?: unknown })?.content === 'string'
+ ? ((output as { content: string }).content)
+ : undefined
+ if (text === undefined) return undefined
+
+ const truncated = text.endsWith(TRUNCATION_MARKER)
+ const body = truncated ? text.slice(0, -TRUNCATION_MARKER.length) : text
+
+ const match = body.match(FETCH_HEADER)
+ if (!match) return { content: body, truncated }
+
+ return {
+ title: match[1] || undefined,
+ url: match[2] || undefined,
+ content: match[3],
+ truncated,
+ }
+}
diff --git a/web-app/src/lib/webUrl.ts b/web-app/src/lib/webUrl.ts
new file mode 100644
index 000000000..d5dd2f27d
--- /dev/null
+++ b/web-app/src/lib/webUrl.ts
@@ -0,0 +1,11 @@
+/** Display host for a URL, e.g. "https://www.rust-lang.org/x" -> "rust-lang.org". */
+export const hostOf = (url: string): string => {
+ try {
+ return new URL(url).hostname.replace(/^www\./, '')
+ } catch {
+ return url
+ }
+}
+
+export const faviconForUrl = (url: string): string =>
+ `https://www.google.com/s2/favicons?domain=${hostOf(url)}&sz=64`
diff --git a/web-app/src/locales/ca/tools.json b/web-app/src/locales/ca/tools.json
index 42e7698ea..c7808ce44 100644
--- a/web-app/src/locales/ca/tools.json
+++ b/web-app/src/locales/ca/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "Cal aprovar l’eina",
- "description": "L’assistent vol utilitzar",
"needsApproval": "Aquesta eina necessita la teva aprovació abans d’executar-se.",
- "securityNotice": "Eines malicioses o contingut de la conversa podrien enganyar l’assistent perquè faci accions perjudicials. Revisa bé cada sol·licitud abans d’aprovar-la.",
"deny": "Denega",
- "allowOnce": "Permet un cop",
- "alwaysAllow": "Permet en aquest fil",
- "parameters": "Paràmetres de l’eina",
- "permissionScope": "Els permisos concedits només s’apliquen a aquesta conversa."
+ "allowOnce": "Permet un cop"
}
}
diff --git a/web-app/src/locales/cs/tools.json b/web-app/src/locales/cs/tools.json
index b2c12971e..a1fb9aeaa 100644
--- a/web-app/src/locales/cs/tools.json
+++ b/web-app/src/locales/cs/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "Vyžadováno schválení nástroje",
- "description": "Asistent chce použít",
"needsApproval": "Tento nástroj vyžaduje vaše schválení před spuštěním.",
- "securityNotice": "Škodlivé nástroje nebo obsah konverzace by mohly potenciálně oklamat asistenta k pokusu o škodlivé akce. Před schválením pečlivě zkontrolujte každé volání nástroje.",
"deny": "Zamítnout",
- "allowOnce": "Povolit jednou",
- "alwaysAllow": "Povolit ve vlákně",
- "parameters": "Parametry nástroje",
- "permissionScope": "Udělená oprávnění platí pouze pro tuto konverzaci."
+ "allowOnce": "Povolit jednou"
}
}
diff --git a/web-app/src/locales/de-DE/tools.json b/web-app/src/locales/de-DE/tools.json
index d7ec8acd0..476c52098 100644
--- a/web-app/src/locales/de-DE/tools.json
+++ b/web-app/src/locales/de-DE/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "Werkzeuggenehmigung erforderlich",
- "description": "Der Assistent möchte das Werkzeug <strong>{{toolName}}</strong> verwenden.",
"needsApproval": "Dieses Werkzeug benötigt Ihre Genehmigung, bevor es ausgeführt wird.",
- "securityNotice": "Dieses Werkzeug möchte eine Aktion ausführen. Bitte überprüfen und genehmigen oder Ablehnen.",
"deny": "Ablehnen",
- "allowOnce": "Einmal erlauben",
- "alwaysAllow": "Im Thread erlauben",
- "parameters": "Werkzeug-Parameter",
- "permissionScope": "Erteilte Berechtigungen gelten nur für dieses Gespräch."
+ "allowOnce": "Einmal erlauben"
}
}
diff --git a/web-app/src/locales/en/chat.json b/web-app/src/locales/en/chat.json
index b367fab97..e033c00b9 100644
--- a/web-app/src/locales/en/chat.json
+++ b/web-app/src/locales/en/chat.json
@@ -18,5 +18,16 @@
"continue": "Continue generating"
},
"done": "Done",
- "webSources": "{{count}} source(s)"
+ "webSources": "{{count}} source(s)",
+ "reasoning": {
+ "label": "Reasoning...",
+ "thinking": "Thinking",
+ "usingTool": "{{tool}}...",
+ "showFullTimeline": "Show full timeline",
+ "showCurrentStep": "Show current step only",
+ "thoughtForAWhile": "Thought for a few seconds",
+ "thoughtFor": "Thought for {{duration}}",
+ "workedForAWhile": "Worked for a few seconds",
+ "workedFor": "Worked for {{duration}}"
+ }
}
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 8d9bd024b..e7edeb56b 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -536,5 +536,10 @@
"forceQuit": "Force quit",
"forcing": "Force quitting…",
"shuttingDown": "Shutting down…"
+ },
+ "duration": {
+ "seconds": "{{count}}s",
+ "minutes": "{{count}}m",
+ "hours": "{{count}}h"
}
}
diff --git a/web-app/src/locales/en/tools.json b/web-app/src/locales/en/tools.json
index d2e6893b4..53b00d40a 100644
--- a/web-app/src/locales/en/tools.json
+++ b/web-app/src/locales/en/tools.json
@@ -1,13 +1,47 @@
{
"toolApproval": {
- "title": "Tool Approval Required",
- "description": "The assistant wants to use",
"needsApproval": "This tool needs your approval before it runs.",
- "securityNotice": "Malicious tools or conversation content could potentially trick the assistant into attempting harmful actions. Review each tool call carefully before approving.",
"deny": "Deny",
"allowOnce": "Allow Once",
- "alwaysAllow": "Allow in thread",
- "parameters": "Tool Parameters",
- "permissionScope": "Permissions granted apply only to this conversation."
+ "allowInThread": "Allow in thread",
+ "allowServerAlways": "Always allow {{server}}",
+ "allowToolAlways": "Always allow {{tool}}"
+ },
+ "toolCall": {
+ "awaitingApproval": "Awaiting approval: {{tool}}",
+ "running": "Running {{tool}}...",
+ "queued": "{{tool}} queued",
+ "queuedPosition": "{{count}} ahead",
+ "working": "Working...",
+ "failed": "{{tool}} failed",
+ "used": "Used {{tool}}",
+ "parameters": "Parameters",
+ "result": "Result",
+ "error": "Error",
+ "searchPlaceholder": "Search the web",
+ "documentsPlaceholder": "Search your documents",
+ "searchingDocuments": "Searching documents...",
+ "noMatches": "No matching passages",
+ "fileFilter": "in {{count}} file(s)",
+ "addressPlaceholder": "Enter a URL",
+ "searching": "Searching...",
+ "opening": "Opening page...",
+ "noResults": "No results",
+ "resultLimit": "top {{count}}",
+ "contentTruncated": "Content truncated",
+ "originWeb": "Web",
+ "originDocuments": "Documents",
+ "viewRaw": "Raw",
+ "viewTable": "Table",
+ "showMore": "Show more",
+ "showLess": "Show less",
+ "executionFailed": "Tool execution failed",
+ "hideRaw": "Hide raw",
+ "summaryText": "{{preview}}",
+ "summaryTextBlocks": "{{count}} blocks: {{preview}}",
+ "summaryBlocks": "{{text}} text, {{other}} attachment(s)",
+ "summaryItems": "{{count}} item(s)",
+ "summaryFields": "{{count}} field(s): {{fields}}",
+ "summaryEmpty": "Empty result"
}
}
diff --git a/web-app/src/locales/es/tools.json b/web-app/src/locales/es/tools.json
index 40750ec39..83b94f607 100644
--- a/web-app/src/locales/es/tools.json
+++ b/web-app/src/locales/es/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "Aprobación de herramienta requerida",
- "description": "El asistente quiere usar",
"needsApproval": "Esta herramienta necesita tu aprobación antes de ejecutarse.",
- "securityNotice": "Herramientas maliciosas o contenido de conversación podrían engañar al asistente para que intente acciones dañinas. Revisa cada llamada a herramienta cuidadosamente antes de aprobar.",
"deny": "Denegar",
- "allowOnce": "Permitir una vez",
- "alwaysAllow": "Permitir en el hilo",
- "parameters": "Parámetros de la herramienta",
- "permissionScope": "Los permisos otorgados aplican solo a esta conversación."
+ "allowOnce": "Permitir una vez"
}
}
diff --git a/web-app/src/locales/fr/tools.json b/web-app/src/locales/fr/tools.json
index 9d24c941d..eaef22255 100644
--- a/web-app/src/locales/fr/tools.json
+++ b/web-app/src/locales/fr/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "Approbation d'outil requise",
- "description": "L'assistant veut utiliser",
"needsApproval": "Cet outil nécessite votre approbation avant de s'exécuter.",
- "securityNotice": "Des outils malveillants ou du contenu de conversation pourraient potentiellement tromper l'assistant pour qu'il tente des actions nuisibles. Examinez attentivement chaque appel d'outil avant de l'approuver.",
"deny": "Refuser",
- "allowOnce": "Autoriser une fois",
- "alwaysAllow": "Autoriser dans la discussion",
- "parameters": "Paramètres de l'outil",
- "permissionScope": "Les permissions accordées ne s'appliquent qu'à cette conversation."
+ "allowOnce": "Autoriser une fois"
}
}
diff --git a/web-app/src/locales/hi/tools.json b/web-app/src/locales/hi/tools.json
index 4e13af38f..0b3e01d92 100644
--- a/web-app/src/locales/hi/tools.json
+++ b/web-app/src/locales/hi/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "टूल की स्वीकृति आवश्यक है",
- "description": "सहायक निम्नलिखित का उपयोग करने का प्रयास कर रहा है",
"needsApproval": "इस टूल को चलने से पहले आपकी अनुमति की आवश्यकता है।",
- "securityNotice": "दुर्भावनापूर्ण टूल या वार्तालाप सामग्री सहायक को हानिकारक कार्य करने के लिए धोखा दे सकती है। अनुमति देने से पहले प्रत्येक टूल कॉल को सावधानीपूर्वक जांचें।",
"deny": "अस्वीकार करें",
- "allowOnce": "एक बार अनुमति दें",
- "alwaysAllow": "इस थ्रेड में हमेशा अनुमति दें",
- "parameters": "टूल पैरामीटर",
- "permissionScope": "दी गई अनुमतियाँ केवल इस वार्तालाप पर लागू होती हैं।"
+ "allowOnce": "एक बार अनुमति दें"
}
-}
\ No newline at end of file
+}
diff --git a/web-app/src/locales/id/tools.json b/web-app/src/locales/id/tools.json
index 7c87ccf02..2e328be03 100644
--- a/web-app/src/locales/id/tools.json
+++ b/web-app/src/locales/id/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "Persetujuan Alat Diperlukan",
- "securityNotice": "Alat ini ingin melakukan suatu tindakan. Harap tinjau dan setujui.",
"deny": "Tolak",
"allowOnce": "Izinkan Sekali",
- "alwaysAllow": "Izinkan di thread",
- "description": "Asisten ingin menggunakan <strong>{{toolName}}</strong>",
- "needsApproval": "Alat ini memerlukan persetujuan Anda sebelum dijalankan.",
- "parameters": "Parameter Alat",
- "permissionScope": "Izin yang diberikan hanya berlaku untuk percakapan ini."
+ "needsApproval": "Alat ini memerlukan persetujuan Anda sebelum dijalankan."
}
}
diff --git a/web-app/src/locales/it/tools.json b/web-app/src/locales/it/tools.json
index af9d9b849..425146c08 100644
--- a/web-app/src/locales/it/tools.json
+++ b/web-app/src/locales/it/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "Approvazione strumento richiesta",
- "description": "L'assistente vuole utilizzare",
"needsApproval": "Questo strumento richiede la tua approvazione prima di essere eseguito.",
- "securityNotice": "Strumenti dannosi o il contenuto della conversazione potrebbero ingannare l'assistente spingendolo a compiere azioni nocive. Verifica attentamente ogni chiamata prima di approvarla.",
"deny": "Rifiuta",
- "allowOnce": "Consenti una volta",
- "alwaysAllow": "Consenti nella conversazione",
- "parameters": "Parametri dello strumento",
- "permissionScope": "Le autorizzazioni concesse si applicano solo a questa conversazione."
+ "allowOnce": "Consenti una volta"
}
}
diff --git a/web-app/src/locales/ja/tools.json b/web-app/src/locales/ja/tools.json
index 63abc19af..68a1aaa27 100644
--- a/web-app/src/locales/ja/tools.json
+++ b/web-app/src/locales/ja/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "ツールの承認が必要です",
- "description": "アシスタントは以下を使用しようとしています",
"needsApproval": "このツールを実行するには承認が必要です。",
- "securityNotice": "悪意のあるツールや会話の内容は、アシスタントを騙して有害なアクションを試みさせる可能性があります。承認する前に、各ツール呼び出しを注意深く確認してください。",
"deny": "拒否",
- "allowOnce": "一度だけ許可",
- "alwaysAllow": "スレッドで許可",
- "parameters": "ツールパラメータ",
- "permissionScope": "付与された権限は、この会話にのみ適用されます。"
+ "allowOnce": "一度だけ許可"
}
-}
\ No newline at end of file
+}
diff --git a/web-app/src/locales/ko/tools.json b/web-app/src/locales/ko/tools.json
index fd2728d94..da77aa688 100644
--- a/web-app/src/locales/ko/tools.json
+++ b/web-app/src/locales/ko/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "도구 승인 필요",
- "description": "어시스턴트가 다음 도구를 사용하려고 합니다",
"needsApproval": "이 도구를 실행하기 전에 승인이 필요합니다.",
- "securityNotice": "악성 도구 또는 대화 내용으로 인해 어시스턴트가 유해한 작업을 시도하도록 유도될 수 있습니다. 승인하기 전에 각 도구 호출을 주의 깊게 검토하세요.",
"deny": "거부",
- "allowOnce": "한 번 허용",
- "alwaysAllow": "이 대화에서 허용",
- "parameters": "도구 매개변수",
- "permissionScope": "부여된 권한은 이 대화에만 적용됩니다."
+ "allowOnce": "한 번 허용"
}
}
diff --git a/web-app/src/locales/pl/tools.json b/web-app/src/locales/pl/tools.json
index 0b5cc10d1..c2139f2fe 100644
--- a/web-app/src/locales/pl/tools.json
+++ b/web-app/src/locales/pl/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "Wymagane Pozwolenie na Narzędzie",
- "description": "Asystent chce użyć",
"needsApproval": "To narzędzie wymaga Twojej zgody przed uruchomieniem.",
- "securityNotice": "Złośliwe narzędzia lub treści rozmowy mają potencjał nakłonić agenta do szkodliwych działań. Dokładnie przejrzyj każdą prośbę o użycie narzędzia przed wyrażeniem zgody.",
"deny": "Odmów",
- "allowOnce": "Pozwól Raz",
- "alwaysAllow": "Pozwól w wątku",
- "parameters": "Parametry Narzędzia",
- "permissionScope": "Udzielone pozwolenia dotyczą tylko tej rozmowy."
+ "allowOnce": "Pozwól Raz"
}
}
diff --git a/web-app/src/locales/pt-BR/tools.json b/web-app/src/locales/pt-BR/tools.json
index ad4e071d5..1fb7acfbe 100644
--- a/web-app/src/locales/pt-BR/tools.json
+++ b/web-app/src/locales/pt-BR/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "Aprovação de Ferramenta Necessária",
- "description": "O assistente quer usar a ferramenta: <strong>{{toolName}}</strong>",
"needsApproval": "Esta ferramenta precisa da sua aprovação antes de ser executada.",
- "securityNotice": "<strong>Aviso de Segurança:</strong> Ferramentas maliciosas ou conteúdo de conversa podem potencialmente enganar o assistente para tentar ações prejudiciais. Revise cada chamada de ferramenta cuidadosamente antes de aprovar.",
"deny": "Negar",
- "allowOnce": "Permitir Uma Vez",
- "alwaysAllow": "Permitir na conversa",
- "parameters": "Parâmetros da Ferramenta",
- "permissionScope": "Permissões concedidas aplicam-se apenas a esta conversa."
+ "allowOnce": "Permitir Uma Vez"
}
}
diff --git a/web-app/src/locales/ru/tools.json b/web-app/src/locales/ru/tools.json
index 7bde2829e..e6f186621 100644
--- a/web-app/src/locales/ru/tools.json
+++ b/web-app/src/locales/ru/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "Необходимо одобрение инструмента",
- "description": "Ассистент хочет использовать",
"needsApproval": "Этот инструмент требует вашего одобрения перед запуском.",
- "securityNotice": "Вредоносные инструменты или содержимое диалогов могут потенциально обмануть ассистента, заставив его попытаться выполнить опасные действия. Внимательно проверяйте каждый вызов инструмента перед его одобрением.",
"deny": "Запретить",
- "allowOnce": "Разрешить один раз",
- "alwaysAllow": "Разрешить в обсуждении",
- "parameters": "Параметры инструмента",
- "permissionScope": "Предоставленные разрешения применяются только к этому диалогу."
+ "allowOnce": "Разрешить один раз"
}
}
diff --git a/web-app/src/locales/vn/tools.json b/web-app/src/locales/vn/tools.json
index d1342e135..b533cc5b6 100644
--- a/web-app/src/locales/vn/tools.json
+++ b/web-app/src/locales/vn/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "Yêu cầu phê duyệt công cụ",
- "securityNotice": "Công cụ này muốn thực hiện một hành động. Vui lòng xem xét và phê duyệt.",
"deny": "Từ chối",
"allowOnce": "Cho phép một lần",
- "alwaysAllow": "Cho phép trong chuỗi",
- "description": "Trợ lý muốn sử dụng <strong>{{toolName}}</strong>",
- "needsApproval": "Công cụ này cần sự chấp thuận của bạn trước khi chạy.",
- "parameters": "Tham số công cụ",
- "permissionScope": "Quyền được cấp chỉ áp dụng cho cuộc trò chuyện này."
+ "needsApproval": "Công cụ này cần sự chấp thuận của bạn trước khi chạy."
}
}
diff --git a/web-app/src/locales/zh-CN/tools.json b/web-app/src/locales/zh-CN/tools.json
index ca739b8d1..a9af7a571 100644
--- a/web-app/src/locales/zh-CN/tools.json
+++ b/web-app/src/locales/zh-CN/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "需要工具批准",
- "securityNotice": "此工具想要执行一个操作。请审查并批准。",
"deny": "拒绝",
"allowOnce": "允许一次",
- "alwaysAllow": "在线程中允许",
- "description": "助手想要使用 <strong>{{toolName}}</strong>",
- "needsApproval": "此工具需要您的批准才能运行。",
- "parameters": "工具参数",
- "permissionScope": "授予的权限仅适用于此对话。"
+ "needsApproval": "此工具需要您的批准才能运行。"
}
}
diff --git a/web-app/src/locales/zh-TW/tools.json b/web-app/src/locales/zh-TW/tools.json
index 7eed6e639..995d21b31 100644
--- a/web-app/src/locales/zh-TW/tools.json
+++ b/web-app/src/locales/zh-TW/tools.json
@@ -1,13 +1,7 @@
{
"toolApproval": {
- "title": "需要工具核准",
- "securityNotice": "此工具想要執行一個動作。請檢閱並核准。",
"deny": "拒絕",
"allowOnce": "允許一次",
- "alwaysAllow": "在討論串中允許",
- "description": "助理想要使用 <strong>{{toolName}}</strong>",
- "needsApproval": "此工具需要您的核准才能執行。",
- "parameters": "工具參數",
- "permissionScope": "授予的權限僅適用於此對話。"
+ "needsApproval": "此工具需要您的核准才能執行。"
}
}
diff --git a/web-app/src/providers/GlobalEventHandler.tsx b/web-app/src/providers/GlobalEventHandler.tsx
index f20a83015..af790599d 100644
--- a/web-app/src/providers/GlobalEventHandler.tsx
+++ b/web-app/src/providers/GlobalEventHandler.tsx
@@ -3,6 +3,7 @@ import { events } from '@janhq/core'
import { useModelProvider } from '@/hooks/useModelProvider'
import { useServiceHub } from '@/hooks/useServiceHub'
import { useHardware } from '@/hooks/useHardware'
+import { useMcpToolProgress } from '@/hooks/useMcpToolProgress'
import { isPlatformTauri } from '@/lib/platform/utils'
/**
@@ -14,6 +15,8 @@ export function GlobalEventHandler() {
const serviceHub = useServiceHub()
const setHardwareData = useHardware((state) => state.setHardwareData)
+ useMcpToolProgress()
+
// Probe hardware on mount so Hub fit-status renders before the user
// visits Settings → Hardware. Re-detect on visibility return (post-sleep, #6447).
useEffect(() => {
diff --git a/web-app/src/routes/__root.tsx b/web-app/src/routes/__root.tsx
index 85fbc5097..ebc48d00b 100644
--- a/web-app/src/routes/__root.tsx
+++ b/web-app/src/routes/__root.tsx
@@ -17,7 +17,6 @@ import { useJanModelPrompt } from '@/hooks/useJanModelPrompt'
import { PromptJanModel } from '@/containers/PromptJanModel'
import { AnalyticProvider } from '@/providers/AnalyticProvider'
import { useLeftPanel } from '@/hooks/useLeftPanel'
-import ToolApproval from '@/containers/dialogs/ToolApproval'
import { TranslationProvider } from '@/i18n/TranslationContext'
import OutOfContextPromiseModal from '@/containers/dialogs/OutOfContextDialog'
import AttachmentIngestionDialog from '@/containers/dialogs/AttachmentIngestionDialog'
@@ -127,7 +126,6 @@ function RootLayout() {
{IS_LOGS_ROUTE ? <LogsLayout /> : <AppLayout />}
</ExtensionProvider>
{/* <TanStackRouterDevtools position="bottom-right" /> */}
- <ToolApproval />
<AttachmentIngestionDialog />
<ErrorDialog />
<LlamacppBusyOnExitDialog />
diff --git a/web-app/src/routes/__tests__/__root.test.tsx b/web-app/src/routes/__tests__/__root.test.tsx
index dff013218..7ef6a8857 100644
--- a/web-app/src/routes/__tests__/__root.test.tsx
+++ b/web-app/src/routes/__tests__/__root.test.tsx
@@ -73,9 +73,6 @@ vi.mock('@/containers/dialogs/AppUpdater', () => ({
vi.mock('@/containers/dialogs/BackendUpdater', () => ({
default: () => <div data-testid="backend-updater" />,
}))
-vi.mock('@/containers/dialogs/ToolApproval', () => ({
- default: () => <div data-testid="tool-approval" />,
-}))
vi.mock('@/containers/dialogs/OutOfContextDialog', () => ({
default: () => <div data-testid="oocp" />,
}))
@@ -172,7 +169,6 @@ describe('__root route', () => {
it('renders all persistent dialogs', () => {
renderComponent()
- expect(screen.getByTestId('tool-approval')).toBeInTheDocument()
expect(screen.getByTestId('attach-ingest')).toBeInTheDocument()
expect(screen.getByTestId('error-dialog')).toBeInTheDocument()
expect(screen.getByTestId('oocp')).toBeInTheDocument()
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 4c2489914..e1c75cb47 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -75,6 +75,7 @@ import { Button } from '@/components/ui/button'
import { IconAlertCircle, IconRefresh, IconLoader2 } from '@tabler/icons-react'
import { useToolApproval } from '@/hooks/useToolApproval'
import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'
+import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
import { WEB_TOOL_NAMES, executeWebTool } from '@/lib/webSearchTool'
import DropdownModelProvider from '@/containers/DropdownModelProvider'
import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'
@@ -91,6 +92,13 @@ const CHAT_STATUS = {
const TITLE_REFRESH_EVERY_N_ASSISTANT_MESSAGES = 4
+// The MCP server a tool belongs to, so an approval prompt can offer to trust
+// the whole server rather than this one tool.
+function serverForTool(toolName: string): string | undefined {
+ return useAppState.getState().tools.find((tool) => tool.name === toolName)
+ ?.server
+}
+
// Persist the out-of-context error onto the latest user message so the banner
// survives thread switches, mirroring how LlamacppOomListener stamps oom/backend.
function stampContextErrorOnThread(
@@ -466,6 +474,11 @@ function ThreadDetail() {
// since streaming has already ended and isSessionBusy's tools-array read isn't reactive.
useAppState.getState().setThreadBusy(threadId, true)
+ // Tools run one at a time below, so the rest are genuinely queued.
+ useToolCallRuntime
+ .getState()
+ .enqueue(sessionData.tools.map((tc) => tc.toolCallId))
+
;(async () => {
for (const toolCall of sessionData.tools) {
if (signal.aborted) {
@@ -482,7 +495,12 @@ function ThreadDetail() {
: await (toolApprovalPromises.current.get(toolCall.toolCallId) ??
useToolApprovalRequests
.getState()
- .requestApproval(toolCall.toolCallId, toolName, threadId))
+ .requestApproval(
+ toolCall.toolCallId,
+ toolName,
+ threadId,
+ serverForTool(toolName)
+ ))
toolApprovalPromises.current.delete(toolCall.toolCallId)
if (!approved) {
@@ -495,6 +513,10 @@ function ThreadDetail() {
continue
}
+ // Timed from here, not from approval, so a long approval wait is
+ // not reported as the tool being slow.
+ useToolCallRuntime.getState().markRunning(toolCall.toolCallId)
+
let result
if (WEB_TOOL_NAMES.has(toolName)) {
@@ -542,9 +564,13 @@ function ThreadDetail() {
errorText: `Error: ${JSON.stringify(error)}`,
})
}
+ } finally {
+ // Covers every exit from the iteration, including the denied path.
+ useToolCallRuntime.getState().markSettled(toolCall.toolCallId)
}
}
+ useToolCallRuntime.getState().settleRemaining()
sessionData.tools = []
toolApprovalPromises.current.clear()
toolCallAbortController.current = null
@@ -553,6 +579,7 @@ function ThreadDetail() {
if (error.name !== 'AbortError') {
console.error('Tool call error:', error)
}
+ useToolCallRuntime.getState().settleRemaining()
sessionData.tools = []
toolApprovalPromises.current.clear()
toolCallAbortController.current = null
@@ -646,7 +673,12 @@ function ThreadDetail() {
toolCall.toolCallId,
useToolApprovalRequests
.getState()
- .requestApproval(toolCall.toolCallId, toolCall.toolName, threadId)
+ .requestApproval(
+ toolCall.toolCallId,
+ toolCall.toolName,
+ threadId,
+ serverForTool(toolCall.toolName)
+ )
)
}
},
diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
index f2a885af5..c64b64525 100644
--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx
+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
@@ -51,6 +51,7 @@ const h = vi.hoisted(() => {
const appStateState = {
ragToolNames: new Set<string>(),
mcpToolNames: new Set<string>(),
+ tools: [] as Array<{ name: string; server?: string }>,
setOomError: vi.fn(),
setBackendError: vi.fn(),
busyThreads: {} as Record<string, boolean>,
@@ -112,7 +113,6 @@ const h = vi.hoisted(() => {
useToolAvailableMock.getState = () => toolAvailableState
const toolApprovalState: any = {
- showApprovalModal: vi.fn().mockResolvedValue(true),
approveToolForThread: vi.fn(),
clearPendingForThread: vi.fn(),
requestApproval: vi.fn().mockResolvedValue(true),
@@ -412,6 +412,13 @@ vi.mock('@/utils/error', () => ({
// Import component AFTER mocks
// -----------------------------------------------------------------------------
import { Route } from '../$threadId'
+import { getServiceHub } from '@/hooks/useServiceHub'
+import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
+
+// The global setup mock is a shared object, so an overridden factory has to be
+// put back or it leaks into every later test.
+const hub = getServiceHub() as unknown as Record<string, unknown>
+const realMcp = hub.mcp
const renderComponent = () => {
const Component = Route.component as React.ComponentType
@@ -457,7 +464,10 @@ describe('ThreadDetail route', () => {
h.appStateState.oomError = undefined
h.appStateState.ragToolNames = new Set<string>()
h.appStateState.mcpToolNames = new Set<string>()
+ h.appStateState.tools = []
h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)
+ hub.mcp = realMcp
+ useToolCallRuntime.getState().reset()
sessionStorage.clear()
})
@@ -734,7 +744,27 @@ describe('ThreadDetail route', () => {
expect(h.toolApprovalState.requestApproval).toHaveBeenCalledWith(
'tc1',
'fetch',
- 'thread-1'
+ 'thread-1',
+ undefined
+ )
+ })
+
+ // The prompt offers to trust the whole server, so it needs to know which.
+ it('passes the tool server along with the approval request', async () => {
+ h.appStateState.mcpToolNames = new Set(['fetch'])
+ h.appStateState.tools = [{ name: 'fetch', server: 'fetch-server' }]
+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)
+ renderComponent()
+
+ await act(async () => {
+ await (h as any).capturedOnToolCall(toolCall('tc1'))
+ })
+
+ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledWith(
+ 'tc1',
+ 'fetch',
+ 'thread-1',
+ 'fetch-server'
)
})
@@ -785,6 +815,129 @@ describe('ThreadDetail route', () => {
expect(h.toolApprovalState.requestApproval).toHaveBeenCalledTimes(1)
})
+ // A model can request several tools in one turn. They arrive together but
+ // are executed one at a time, which is what the queue display depends on.
+ describe('several tool calls in one turn', () => {
+ const arrive = async (...ids: string[]) => {
+ for (const id of ids) {
+ await act(async () => {
+ await (h as any).capturedOnToolCall(toolCall(id))
+ })
+ }
+ }
+
+ it('executes every call in the turn', async () => {
+ h.appStateState.mcpToolNames = new Set(['fetch'])
+ renderComponent()
+ await arrive('tcA', 'tcB', 'tcC')
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+
+ const ids = h.mockAddToolOutput.mock.calls.map(
+ (c: any[]) => c[0].toolCallId
+ )
+ expect(ids).toEqual(['tcA', 'tcB', 'tcC'])
+ })
+
+ it('runs them one at a time, not concurrently', async () => {
+ h.appStateState.mcpToolNames = new Set(['fetch'])
+ const started: string[] = []
+ let releaseFirst: (() => void) | undefined
+ const callTool = vi.fn(({ arguments: args }: any) => {
+ started.push(args.id)
+ if (started.length === 1) {
+ return new Promise((resolve) => {
+ releaseFirst = () => resolve({ error: '', content: [] })
+ })
+ }
+ return Promise.resolve({ error: '', content: [] })
+ })
+ hub.mcp = () => ({ callTool }) as never
+
+ renderComponent()
+ await act(async () => {
+ await (h as any).capturedOnToolCall({
+ toolCall: {
+ toolCallId: 'tcA',
+ toolName: 'fetch',
+ input: { id: 'tcA' },
+ },
+ })
+ await (h as any).capturedOnToolCall({
+ toolCall: {
+ toolCallId: 'tcB',
+ toolName: 'fetch',
+ input: { id: 'tcB' },
+ },
+ })
+ })
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+
+ // Second call must not have been dispatched while the first is pending.
+ expect(started).toEqual(['tcA'])
+ await act(async () => {
+ releaseFirst?.()
+ })
+ expect(started).toEqual(['tcA', 'tcB'])
+ })
+
+ it('drains the runtime queue and times every call', async () => {
+ h.appStateState.mcpToolNames = new Set(['fetch'])
+ renderComponent()
+ await arrive('tcA', 'tcB')
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+
+ const runtime = useToolCallRuntime.getState()
+ expect(runtime.queue).toEqual([])
+ for (const id of ['tcA', 'tcB']) {
+ expect(runtime.timings[id]?.startedAt).toBeDefined()
+ expect(runtime.timings[id]?.endedAt).toBeDefined()
+ }
+ })
+
+ it('keeps going when one call is denied', async () => {
+ h.appStateState.mcpToolNames = new Set(['fetch'])
+ h.toolApprovalState.requestApproval = vi.fn((id: string) =>
+ Promise.resolve(id !== 'tcA')
+ )
+ renderComponent()
+ await arrive('tcA', 'tcB')
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+
+ const outputs = h.mockAddToolOutput.mock.calls.map((c: any[]) => c[0])
+ expect(outputs[0]).toMatchObject({
+ toolCallId: 'tcA',
+ state: 'output-error',
+ })
+ expect(outputs[1]).toMatchObject({ toolCallId: 'tcB' })
+ expect(outputs[1].state).not.toBe('output-error')
+ })
+
+ // A denied call never runs, so it has no duration -- but leaving it in
+ // the queue would keep its card claiming it is waiting its turn.
+ it('leaves nothing queued after a denied call', async () => {
+ h.appStateState.mcpToolNames = new Set(['fetch'])
+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(false)
+ renderComponent()
+ await arrive('tcA', 'tcB')
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+
+ const runtime = useToolCallRuntime.getState()
+ expect(runtime.queue).toEqual([])
+ expect(runtime.timings['tcA']?.startedAt).toBeUndefined()
+ expect(runtime.timings['tcA']?.endedAt).toBeDefined()
+ })
+ })
+
it('marks the thread busy during onFinish execution and clears it when tools drain', async () => {
h.appStateState.mcpToolNames = new Set(['fetch'])
h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)