story-kit: merge 86_story_show_live_activity_status_instead_of_static_thinking_indicator_in_chat

This commit is contained in:
Dave
2026-02-23 18:38:15 +00:00
parent da8ded460e
commit af1625a132
5 changed files with 54 additions and 4 deletions

View File

@@ -50,7 +50,8 @@ export type WsResponse =
request_id: string; request_id: string;
tool_name: string; tool_name: string;
tool_input: Record<string, unknown>; tool_input: Record<string, unknown>;
}; }
| { type: "tool_activity"; tool_name: string };
export interface ProviderConfig { export interface ProviderConfig {
provider: string; provider: string;
@@ -260,6 +261,7 @@ export class ChatWebSocket {
toolName: string, toolName: string,
toolInput: Record<string, unknown>, toolInput: Record<string, unknown>,
) => void; ) => void;
private onActivity?: (toolName: string) => void;
private connected = false; private connected = false;
private closeTimer?: number; private closeTimer?: number;
private wsPath = DEFAULT_WS_PATH; private wsPath = DEFAULT_WS_PATH;
@@ -302,6 +304,7 @@ export class ChatWebSocket {
data.tool_name, data.tool_name,
data.tool_input, data.tool_input,
); );
if (data.type === "tool_activity") this.onActivity?.(data.tool_name);
} catch (err) { } catch (err) {
this.onError?.(String(err)); this.onError?.(String(err));
} }
@@ -341,6 +344,7 @@ export class ChatWebSocket {
toolName: string, toolName: string,
toolInput: Record<string, unknown>, toolInput: Record<string, unknown>,
) => void; ) => void;
onActivity?: (toolName: string) => void;
}, },
wsPath = DEFAULT_WS_PATH, wsPath = DEFAULT_WS_PATH,
) { ) {
@@ -350,6 +354,7 @@ export class ChatWebSocket {
this.onError = handlers.onError; this.onError = handlers.onError;
this.onPipelineState = handlers.onPipelineState; this.onPipelineState = handlers.onPipelineState;
this.onPermissionRequest = handlers.onPermissionRequest; this.onPermissionRequest = handlers.onPermissionRequest;
this.onActivity = handlers.onActivity;
this.wsPath = wsPath; this.wsPath = wsPath;
this.shouldReconnect = true; this.shouldReconnect = true;

View File

@@ -14,6 +14,23 @@ const { useCallback, useEffect, useRef, useState } = React;
const NARROW_BREAKPOINT = 900; const NARROW_BREAKPOINT = 900;
function formatToolActivity(toolName: string): string {
switch (toolName) {
case "read_file":
return "Reading file...";
case "write_file":
return "Writing file...";
case "list_directory":
return "Listing directory...";
case "search_files":
return "Searching files...";
case "exec_shell":
return "Executing command...";
default:
return `Using ${toolName}...`;
}
}
interface ChatProps { interface ChatProps {
projectPath: string; projectPath: string;
onCloseProject: () => void; onCloseProject: () => void;
@@ -38,6 +55,7 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) {
merge: [], merge: [],
}); });
const [claudeSessionId, setClaudeSessionId] = useState<string | null>(null); const [claudeSessionId, setClaudeSessionId] = useState<string | null>(null);
const [activityStatus, setActivityStatus] = useState<string | null>(null);
const [permissionRequest, setPermissionRequest] = useState<{ const [permissionRequest, setPermissionRequest] = useState<{
requestId: string; requestId: string;
toolName: string; toolName: string;
@@ -159,6 +177,7 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) {
const last = history[history.length - 1]; const last = history[history.length - 1];
if (last?.role === "assistant" && !last.tool_calls) { if (last?.role === "assistant" && !last.tool_calls) {
setLoading(false); setLoading(false);
setActivityStatus(null);
} }
}, },
onSessionId: (sessionId) => { onSessionId: (sessionId) => {
@@ -167,6 +186,7 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) {
onError: (message) => { onError: (message) => {
console.error("WebSocket error:", message); console.error("WebSocket error:", message);
setLoading(false); setLoading(false);
setActivityStatus(null);
}, },
onPipelineState: (state) => { onPipelineState: (state) => {
setPipeline(state); setPipeline(state);
@@ -174,6 +194,9 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) {
onPermissionRequest: (requestId, toolName, toolInput) => { onPermissionRequest: (requestId, toolName, toolInput) => {
setPermissionRequest({ requestId, toolName, toolInput }); setPermissionRequest({ requestId, toolName, toolInput });
}, },
onActivity: (toolName) => {
setActivityStatus(formatToolActivity(toolName));
},
}); });
return () => { return () => {
@@ -248,6 +271,7 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) {
} }
setLoading(false); setLoading(false);
setActivityStatus(null);
} catch (e) { } catch (e) {
console.error("Failed to cancel chat:", e); console.error("Failed to cancel chat:", e);
} }
@@ -276,6 +300,7 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) {
} }
setLoading(true); setLoading(true);
setStreamingContent(""); setStreamingContent("");
setActivityStatus(null);
try { try {
const provider = isClaudeCode const provider = isClaudeCode
@@ -352,6 +377,7 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) {
setMessages([]); setMessages([]);
setStreamingContent(""); setStreamingContent("");
setLoading(false); setLoading(false);
setActivityStatus(null);
setClaudeSessionId(null); setClaudeSessionId(null);
} }
}; };
@@ -644,7 +670,9 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) {
marginTop: "10px", marginTop: "10px",
}} }}
> >
<span className="pulse">Thinking...</span> <span className="pulse">
{activityStatus ?? "Thinking..."}
</span>
</div> </div>
)} )}
<div ref={messagesEndRef} /> <div ref={messagesEndRef} />

View File

@@ -75,6 +75,10 @@ enum WsResponse {
tool_name: String, tool_name: String,
tool_input: serde_json::Value, tool_input: serde_json::Value,
}, },
/// The agent started assembling a tool call; shows live status in the UI.
ToolActivity {
tool_name: String,
},
} }
impl From<WatcherEvent> for WsResponse { impl From<WatcherEvent> for WsResponse {
@@ -168,6 +172,7 @@ pub async fn ws_handler(ws: WebSocket, ctx: Data<&Arc<AppContext>>) -> impl poem
Ok(WsRequest::Chat { messages, config }) => { Ok(WsRequest::Chat { messages, config }) => {
let tx_updates = tx.clone(); let tx_updates = tx.clone();
let tx_tokens = tx.clone(); let tx_tokens = tx.clone();
let tx_activity = tx.clone();
let ctx_clone = ctx.clone(); let ctx_clone = ctx.clone();
let perm_tx = perm_req_tx.clone(); let perm_tx = perm_req_tx.clone();
@@ -188,6 +193,11 @@ pub async fn ws_handler(ws: WebSocket, ctx: Data<&Arc<AppContext>>) -> impl poem
content: token.to_string(), content: token.to_string(),
}); });
}, },
move |tool_name: &str| {
let _ = tx_activity.send(WsResponse::ToolActivity {
tool_name: tool_name.to_string(),
});
},
Some(perm_tx), Some(perm_tx),
); );
tokio::pin!(chat_fut); tokio::pin!(chat_fut);

View File

@@ -176,13 +176,15 @@ pub fn set_anthropic_api_key(store: &dyn StoreOps, api_key: String) -> Result<()
set_anthropic_api_key_impl(store, &api_key) set_anthropic_api_key_impl(store, &api_key)
} }
pub async fn chat<F, U>( #[allow(clippy::too_many_arguments)]
pub async fn chat<F, U, A>(
messages: Vec<Message>, messages: Vec<Message>,
config: ProviderConfig, config: ProviderConfig,
state: &SessionState, state: &SessionState,
store: &dyn StoreOps, store: &dyn StoreOps,
mut on_update: F, mut on_update: F,
mut on_token: U, mut on_token: U,
mut on_activity: A,
permission_tx: Option< permission_tx: Option<
tokio::sync::mpsc::UnboundedSender< tokio::sync::mpsc::UnboundedSender<
crate::llm::providers::claude_code::PermissionReqMsg, crate::llm::providers::claude_code::PermissionReqMsg,
@@ -192,6 +194,7 @@ pub async fn chat<F, U>(
where where
F: FnMut(&[Message]) + Send, F: FnMut(&[Message]) + Send,
U: FnMut(&str) + Send, U: FnMut(&str) + Send,
A: FnMut(&str) + Send,
{ {
use crate::llm::providers::anthropic::AnthropicProvider; use crate::llm::providers::anthropic::AnthropicProvider;
use crate::llm::providers::ollama::OllamaProvider; use crate::llm::providers::ollama::OllamaProvider;
@@ -322,6 +325,7 @@ where
tools, tools,
&mut cancel_rx, &mut cancel_rx,
|token| on_token(token), |token| on_token(token),
|tool_name| on_activity(tool_name),
) )
.await .await
.map_err(|e| format!("Anthropic Error: {e}"))? .map_err(|e| format!("Anthropic Error: {e}"))?

View File

@@ -156,16 +156,18 @@ impl AnthropicProvider {
.join("\n\n") .join("\n\n")
} }
pub async fn chat_stream<F>( pub async fn chat_stream<F, A>(
&self, &self,
model: &str, model: &str,
messages: &[Message], messages: &[Message],
tools: &[ToolDefinition], tools: &[ToolDefinition],
cancel_rx: &mut Receiver<bool>, cancel_rx: &mut Receiver<bool>,
mut on_token: F, mut on_token: F,
mut on_activity: A,
) -> Result<CompletionResponse, String> ) -> Result<CompletionResponse, String>
where where
F: FnMut(&str), F: FnMut(&str),
A: FnMut(&str),
{ {
let anthropic_messages = Self::convert_messages(messages); let anthropic_messages = Self::convert_messages(messages);
let anthropic_tools = Self::convert_tools(tools); let anthropic_tools = Self::convert_tools(tools);
@@ -257,6 +259,7 @@ impl AnthropicProvider {
{ {
let id = content_block["id"].as_str().unwrap_or("").to_string(); let id = content_block["id"].as_str().unwrap_or("").to_string();
let name = content_block["name"].as_str().unwrap_or("").to_string(); let name = content_block["name"].as_str().unwrap_or("").to_string();
on_activity(&name);
current_tool_use = Some((id, name, String::new())); current_tool_use = Some((id, name, String::new()));
} }
} }