Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

feat: complete team autonomous discussion streaming with stop controls

Oleksandr Ivanchenkoc0cab7df7ff0
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index d2ab43be..84554471 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,7 +1,7 @@
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect, useRef } from 'react';
import { AppHeader } from './components/AppHeader';
import { Sidebar, Kwant, Channel, Team } from './components/Sidebar';
-import { ChatView, ChatMessage } from './components/ChatView';
+import { ChatView, ChatMessage, DiscussionState } from './components/ChatView';
import { PendingApproval } from './components/ModernApprovalCard';
import { SettingsModal } from './components/SettingsModal';
import { NewAgentModal } from './components/NewAgentModal';
@@ -19,6 +19,8 @@ export const App: React.FC = () => {
const [streamingText, setStreamingText] = useState('');
const [streamingThinking, setStreamingThinking] = useState('');
const [isStreaming, setIsStreaming] = useState(false);
+ const [discussionState, setDiscussionState] = useState<DiscussionState>({ inProgress: false });
+ const discussionInProgressRef = useRef(false);
const [pendingApproval, setPendingApproval] = useState<PendingApproval | null>(null);
const [tokensUsed, setTokensUsed] = useState(0);
@@ -113,12 +115,59 @@ export const App: React.FC = () => {
});
playSfx('alert');
break;
+ case 'discussion_started':
+ case 'DiscussionStarted':
+ discussionInProgressRef.current = true;
+ setDiscussionState({
+ inProgress: true,
+ teamName: event.data?.team_name,
+ totalTurns: event.data?.total_turns,
+ currentSpeaker: event.data?.speakers?.[0],
+ currentTurn: 1,
+ });
+ setIsStreaming(true);
+ playSfx('alert');
+ break;
+ case 'discussion_turn_started':
+ case 'DiscussionTurnStarted':
+ discussionInProgressRef.current = true;
+ setDiscussionState((prev) => ({
+ ...prev,
+ inProgress: true,
+ currentSpeaker: event.data?.speaker_name,
+ currentTurn: event.data?.turn_index,
+ totalTurns: event.data?.total_turns ?? prev.totalTurns,
+ }));
+ setIsStreaming(true);
+ setStreamingText('');
+ setStreamingThinking('');
+ if (selectedId) {
+ fetch(`/api/channels/${selectedId}/messages`)
+ .then((r) => r.json())
+ .then((msgs) => setMessages(msgs))
+ .catch(() => {});
+ }
+ break;
+ case 'discussion_completed':
+ case 'DiscussionCompleted':
+ discussionInProgressRef.current = false;
+ setDiscussionState({ inProgress: false });
+ setIsStreaming(false);
+ setStreamingText('');
+ setStreamingThinking('');
+ playSfx('coin');
+ if (selectedId) {
+ fetch(`/api/channels/${selectedId}/messages`)
+ .then((r) => r.json())
+ .then((msgs) => setMessages(msgs))
+ .catch(() => {});
+ }
+ break;
case 'TurnComplete':
playSfx('coin');
- setIsStreaming(false);
setStreamingText('');
setStreamingThinking('');
- setTokensUsed((prev) => prev + (event.data.tokens || 0));
+ setTokensUsed((prev) => prev + (event.data?.tokens || 0));
// Refresh messages
if (selectedId) {
fetch(`/api/channels/${selectedId}/messages`)
@@ -126,8 +175,13 @@ export const App: React.FC = () => {
.then((msgs) => setMessages(msgs))
.catch(() => {});
}
+ if (!discussionInProgressRef.current) {
+ setIsStreaming(false);
+ }
break;
case 'Error':
+ discussionInProgressRef.current = false;
+ setDiscussionState({ inProgress: false });
setIsStreaming(false);
setStreamingText('');
break;
@@ -142,7 +196,36 @@ export const App: React.FC = () => {
};
}, [selectedId]);
+ const handleCancelDiscussion = async () => {
+ try {
+ await fetch('/api/chat/cancel', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ channel_id: isChannel ? selectedId : null,
+ kwant_id: !isChannel ? selectedId : null,
+ team_id: selectedTeamId || null,
+ }),
+ });
+ } catch (err) {
+ console.error('Failed cancelling chat/discussion:', err);
+ }
+ discussionInProgressRef.current = false;
+ setDiscussionState({ inProgress: false });
+ setIsStreaming(false);
+ setStreamingText('');
+ setStreamingThinking('');
+ if (selectedId) {
+ fetch(`/api/channels/${selectedId}/messages`)
+ .then((r) => r.json())
+ .then((msgs) => setMessages(msgs))
+ .catch(() => {});
+ }
+ };
+
const handleSendMessage = async (text: string) => {
+ discussionInProgressRef.current = false;
+ setDiscussionState({ inProgress: false });
setIsStreaming(true);
setStreamingText('');
setStreamingThinking('');
@@ -384,6 +467,8 @@ export const App: React.FC = () => {
onResolveApproval={handleResolveApproval}
kwants={kwants}
teams={teams}
+ discussionState={discussionState}
+ onCancelDiscussion={handleCancelDiscussion}
/>
</div>
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index c89c5e06..2f15f4fa 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -1,5 +1,5 @@
import React, { useState, useRef, useEffect } from 'react';
-import { ArrowUp, Sparkles, ChevronDown, ChevronRight, Copy, Check, Cpu } from 'lucide-react';
+import { ArrowUp, Sparkles, ChevronDown, ChevronRight, Copy, Check, Cpu, Users, Square } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';
import { MentionPopover, MentionItem } from './MentionPopover';
@@ -15,6 +15,14 @@ export interface ChatMessage {
tokens_used?: number;
}
+export interface DiscussionState {
+ inProgress: boolean;
+ teamName?: string;
+ currentSpeaker?: string;
+ currentTurn?: number;
+ totalTurns?: number;
+}
+
export interface ChatViewProps {
title: string;
subtitle: string;
@@ -27,6 +35,8 @@ export interface ChatViewProps {
onResolveApproval: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
kwants?: Array<{ id: string; name: string; title: string; avatar_sprite: string }>;
teams?: Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>;
+ discussionState?: DiscussionState;
+ onCancelDiscussion?: () => void;
}
export const renderFormattedText = (text: string): React.ReactNode => {
@@ -59,6 +69,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
onResolveApproval,
kwants: kwantsProp,
teams: teamsProp,
+ discussionState,
+ onCancelDiscussion,
}) => {
const [inputVal, setInputVal] = useState('');
const [openThoughts, setOpenThoughts] = useState<Record<string, boolean>>({});
@@ -256,6 +268,17 @@ export const ChatView: React.FC<ChatViewProps> = ({
</div>
<div className="flex items-center gap-2">
+ {isStreaming && !discussionState?.inProgress && onCancelDiscussion && (
+ <button
+ type="button"
+ onClick={onCancelDiscussion}
+ className="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium text-red-300 bg-red-500/10 hover:bg-red-500/20 border border-red-500/30 transition-colors shadow-sm cursor-pointer"
+ title="Stop generation"
+ >
+ <Square size={10} fill="currentColor" />
+ <span>Stop</span>
+ </button>
+ )}
<div className="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium text-sky-400 bg-sky-500/10 border border-sky-500/20 shadow-sm">
<Cpu size={13} />
<span>Laya Auto-Fleet</span>
@@ -263,6 +286,30 @@ export const ChatView: React.FC<ChatViewProps> = ({
</div>
</div>
+ {/* Discussion In-Flight Banner */}
+ {discussionState?.inProgress && (
+ <div className="px-6 pt-3 select-none flex-shrink-0">
+ <div className="flex items-center justify-between px-4 py-2 bg-sky-950/40 border border-sky-800/40 rounded-xl mb-3 text-xs">
+ <div className="flex items-center gap-2 text-sky-200">
+ <Users size={14} className="text-sky-400 animate-pulse" />
+ <span>
+ Team Discussion: <strong>{discussionState.currentSpeaker || 'Team member'}</strong> speaking (Turn {discussionState.currentTurn || 1} of {discussionState.totalTurns || 1})
+ </span>
+ </div>
+ {onCancelDiscussion && (
+ <button
+ type="button"
+ onClick={onCancelDiscussion}
+ className="flex items-center gap-1 px-2.5 py-1 bg-red-500/20 hover:bg-red-500/30 text-red-300 rounded border border-red-500/30 transition-colors cursor-pointer"
+ >
+ <Square size={11} fill="currentColor" />
+ <span>Stop Discussion</span>
+ </button>
+ )}
+ </div>
+ </div>
+ )}
+
{/* Messages Stream */}
<div ref={scrollRef} className="flex-1 overflow-y-auto p-6 space-y-6">
{messages.map((msg) => {
@@ -348,13 +395,21 @@ export const ChatView: React.FC<ChatViewProps> = ({
{/* Live Streaming Assistant Message */}
{isStreaming && (
<div className="flex items-start gap-3.5 max-w-4xl">
- <ModernAvatar role={title} name={title} size={34} />
+ <ModernAvatar
+ role={discussionState?.inProgress && discussionState.currentSpeaker ? discussionState.currentSpeaker : title}
+ name={discussionState?.inProgress && discussionState.currentSpeaker ? discussionState.currentSpeaker : title}
+ size={34}
+ />
<div className="flex flex-col items-start min-w-0 max-w-2xl">
<div className="flex items-center gap-2 mb-1 text-[11px] text-zinc-400 font-medium">
- <span className="text-zinc-200">{title}</span>
+ <span className="text-zinc-200">
+ {discussionState?.inProgress && discussionState.currentSpeaker
+ ? discussionState.currentSpeaker
+ : title}
+ </span>
<span className="inline-flex items-center gap-1 text-sky-400 text-[10px]">
<span className="w-1.5 h-1.5 rounded-full bg-sky-400 animate-ping" />
- Generating...
+ {discussionState?.inProgress ? 'Speaking...' : 'Generating...'}
</span>
</div>
@@ -440,17 +495,28 @@ export const ChatView: React.FC<ChatViewProps> = ({
className="flex-1 bg-transparent px-3 py-1.5 text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none resize-none max-h-40 leading-relaxed font-sans"
/>
- <button
- type="submit"
- disabled={!inputVal.trim() || isStreaming}
- className={`w-8 h-8 rounded-xl flex items-center justify-center transition-all flex-shrink-0 ${
- inputVal.trim() && !isStreaming
- ? 'bg-sky-500 text-white hover:bg-sky-400 shadow-sm'
- : 'bg-zinc-800 text-zinc-500 cursor-not-allowed'
- }`}
- >
- <ArrowUp size={16} strokeWidth={2.4} />
- </button>
+ {isStreaming ? (
+ <button
+ type="button"
+ onClick={onCancelDiscussion}
+ className="w-8 h-8 rounded-xl flex items-center justify-center transition-all flex-shrink-0 bg-red-500/20 hover:bg-red-500/30 text-red-400 border border-red-500/30 shadow-sm cursor-pointer"
+ title={discussionState?.inProgress ? 'Stop Discussion' : 'Stop generation'}
+ >
+ <Square size={12} fill="currentColor" />
+ </button>
+ ) : (
+ <button
+ type="submit"
+ disabled={!inputVal.trim()}
+ className={`w-8 h-8 rounded-xl flex items-center justify-center transition-all flex-shrink-0 ${
+ inputVal.trim()
+ ? 'bg-sky-500 text-white hover:bg-sky-400 shadow-sm'
+ : 'bg-zinc-800 text-zinc-500 cursor-not-allowed'
+ }`}
+ >
+ <ArrowUp size={16} strokeWidth={2.4} />
+ </button>
+ )}
</form>
</div>
</div>
diff --git a/src/server/routes.rs b/src/server/routes.rs
index bfb51d7c..a8afa390 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -138,6 +138,7 @@ pub async fn cancel_chat(
val.get("session_id")
.or_else(|| val.get("channel_id"))
.or_else(|| val.get("team_id"))
+ .or_else(|| val.get("kwant_id"))
.and_then(|s| s.as_str())
.map(|s| s.to_string())
} else {
@@ -150,6 +151,10 @@ pub async fn cancel_chat(
if let Some(session_id) = maybe_session_id {
if let Some(token) = tokens.remove(&session_id) {
token.cancel();
+ } else {
+ for (_, token) in tokens.drain() {
+ token.cancel();
+ }
}
} else {
for (_, token) in tokens.drain() {
@@ -404,6 +409,9 @@ pub async fn send_chat(
if let Some(cid) = &payload.channel_id {
tokens.insert(cid.clone(), cancel_token.clone());
}
+ if let Some(kid) = &payload.kwant_id {
+ tokens.insert(kid.clone(), cancel_token.clone());
+ }
if let Some(ref team) = target_team {
tokens.insert(team.id.clone(), cancel_token.clone());
tokens.insert(team.name.clone(), cancel_token.clone());
@@ -608,11 +616,9 @@ pub async fn send_chat(
}
}
- if !cancel_token_clone.is_cancelled() {
- let _ = event_broadcast.send(RuntimeEvent::DiscussionCompleted {
- total_turns: turns,
- });
- }
+ let _ = event_broadcast.send(RuntimeEvent::DiscussionCompleted {
+ total_turns: turns,
+ });
let mut tokens = active_cancellations.lock().await;
tokens.remove(&session_id_clone);