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.

Moderate team discussions: clarify first, short replies, one summary

Oleksandr Ivanchenkof7945b3b41f6
diff --git a/README.md b/README.md
index c826e8ce..37c73965 100644
--- a/README.md
+++ b/README.md
@@ -12,6 +12,7 @@ Kwants is a high-performance, self-hosted multi-agent AI platform packaged as a
- **Sub-50ms Intelligent Routing with Laya**: By default, task-based model selection queries [convaiinnovations/laya](https://huggingface.co/convaiinnovations/laya) over its `/v1/systemone` API in ~33ms, with seamless offline heuristic fallback and dynamic effort-level selection.
- **Hybrid Driver Fleet**: Run direct cloud & local APIs (xAI Grok, Anthropic Claude, OpenAI, OpenRouter, local Ollama) or supervise host CLI agents (`claude`, `codex`, `grok` CLIs).
- **Kwant-to-Kwant Handoffs**: Every kwant knows its teammates in the current channel or team. When a reply @mentions a teammate (or `@everyone`), that teammate answers right after in the same chat, up to 4 handoffs per message.
+- **Moderated Team Discussions**: When a team question needs several perspectives, the lead opens with a short take (or first asks you a clarifying question and waits), teammates respond to each other by name in under ~120 words or pass if they have nothing to add, and the lead closes with one summary. The back-and-forth folds into a collapsible "Team discussed" thread so the chat shows the answer.
- **Human-in-the-Loop Permission Broker**: Security-critical operations (shell execution, workspace file edits) require user approval via modern security cards: `[Allow Once]`, `[Always Allow]`, `[Deny]`.
- **Sleek Modern Grok Bot Interface**: Dark zinc aesthetics (`zinc-950`), clean typography (`Inter`, `JetBrains Mono`), collapsible reasoning disclosures (`Thought for Xs • Laya [Grok] • Low Effort`), role-based SVG/gradient avatars, and subtle modern micro-interaction click & completion sounds synthesized via the Web Audio API.
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 27e789af..f1b430fb 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -247,6 +247,7 @@ export const App: React.FC = () => {
inProgress: true,
currentSpeaker: spkName,
askedBy: event.data?.asked_by,
+ phase: event.data?.phase,
currentTurn: event.data?.turn_index,
totalTurns: event.data?.total_turns ?? prev.totalTurns,
}));
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index a2867e6f..b182ab98 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -6,6 +6,7 @@ import { MentionPopover, MentionItem } from './MentionPopover';
import { MarkdownRenderer } from './MarkdownRenderer';
import { VirtualMachinePane, TerminalLogEntry } from './VirtualMachinePane';
import { playSfx } from '../audio/chiptune';
+import { groupDiscussionThreads, stripDiscussionMarkers } from '../discussionThreads';
export interface ChatMessage {
id: string;
@@ -27,8 +28,10 @@ export interface DiscussionState {
totalTurns?: number;
/** 'handoff' when kwants pulled each other in with @mentions. */
kind?: string;
- /** Who handed the current speaker the turn (handoffs only). */
+ /** Who handed the current speaker the turn. */
askedBy?: string;
+ /** Team discussion phase of the current turn: 'open', 'reply' or 'summary'. */
+ phase?: string;
}
export interface RoutingCandidate {
@@ -405,6 +408,97 @@ export const ChatView: React.FC<ChatViewProps> = ({
}
};
+ const renderMessage = (msg: ChatMessage) => {
+ const isUser = msg.sender_role === 'user';
+ const isThoughtOpen = !!openThoughts[msg.id];
+ const displayName = isUser ? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);
+
+ return (
+ <div
+ key={msg.id}
+ className={`flex items-start gap-3.5 w-full max-w-5xl ${isUser ? 'ml-auto flex-row-reverse justify-start' : ''}`}
+ >
+ <ModernAvatar
+ role={isUser ? 'user' : title}
+ name={displayName}
+ size={34}
+ />
+
+ <div className={`flex flex-col min-w-0 ${isUser ? 'max-w-2xl items-end' : 'flex-1 max-w-4xl items-start'}`}>
+ {/* Header info */}
+ <div className="flex items-center gap-2 mb-1.5 text-[11px] text-zinc-400 font-medium">
+ <span className="text-zinc-200">{displayName}</span>
+ {msg.tokens_used ? (
+ <span className="text-zinc-500 font-mono text-[10px]">({msg.tokens_used} tokens)</span>
+ ) : null}
+ </div>
+
+ {/* Collapsible Reasoning Disclosure */}
+ {msg.reasoning_content && (
+ <div className="mb-2 max-w-full">
+ <button
+ type="button"
+ onClick={() => toggleThought(msg.id)}
+ className="flex items-center gap-2 px-3 py-1.5 rounded-xl text-xs font-mono text-zinc-400 hover:text-zinc-200 bg-zinc-900/80 hover:bg-zinc-900 border border-zinc-800 hover:border-zinc-700/80 transition-all cursor-pointer shadow-sm group"
+ >
+ <Sparkles size={13} className="text-violet-400 group-hover:rotate-12 transition-transform flex-shrink-0" />
+ <span className="truncate max-w-xs sm:max-w-md">
+ {msg.reasoning_content.split('\n')[0].replace(/^🔮\s*/, '')}
+ </span>
+ {isThoughtOpen ? <ChevronDown size={13} className="text-zinc-500 flex-shrink-0" /> : <ChevronRight size={13} className="text-zinc-500 flex-shrink-0" />}
+ </button>
+
+ {isThoughtOpen && (
+ <div className="mt-1.5 p-3.5 rounded-xl bg-zinc-950/90 border border-zinc-800 text-xs font-mono text-zinc-300 whitespace-pre-wrap leading-relaxed shadow-inner max-h-80 overflow-y-auto">
+ {msg.reasoning_content}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Message Body Bubble */}
+ <div
+ className={`p-4 sm:p-5 rounded-2xl text-sm leading-relaxed shadow-sm w-full ${
+ isUser
+ ? 'bg-zinc-800 text-zinc-100 rounded-tr-sm border border-zinc-700/60 max-w-2xl'
+ : 'bg-zinc-900/60 text-zinc-200 rounded-tl-sm border border-zinc-800/80'
+ }`}
+ >
+ {isUser ? (
+ <div className="whitespace-pre-wrap break-words">{renderFormattedText(msg.text)}</div>
+ ) : (
+ <MarkdownRenderer content={msg.text} />
+ )}
+ </div>
+
+ {/* Copy action */}
+ {!isUser && (
+ <div className="mt-1.5 flex items-center gap-2 text-zinc-500 text-xs">
+ <button
+ type="button"
+ onClick={() => handleCopy(msg.text, msg.id)}
+ className="px-2 py-1 rounded-md hover:bg-zinc-900 hover:text-zinc-300 transition-colors flex items-center gap-1.5 text-[11px] cursor-pointer"
+ title="Copy response"
+ >
+ {copiedId === msg.id ? (
+ <>
+ <Check size={12} className="text-emerald-400" />
+ <span className="text-emerald-400 font-medium">Copied</span>
+ </>
+ ) : (
+ <>
+ <Copy size={12} />
+ <span>Copy markdown</span>
+ </>
+ )}
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ };
+
return (
<div className="flex-1 flex flex-col h-full bg-zinc-950 overflow-hidden">
{/* Channel / Agent Header */}
@@ -512,9 +606,19 @@ export const ChatView: React.FC<ChatViewProps> = ({
{discussionState.askedBy ? <> (asked by {discussionState.askedBy})</> : null}
{' '}• {discussionState.currentTurn || 1} of {discussionState.totalTurns || 1}
</>
+ ) : discussionState.phase === 'summary' ? (
+ <>
+ <strong>{discussionState.currentSpeaker || 'The lead'}</strong> is summarizing the team's answer
+ </>
) : (
<>
- Team Discussion: <strong>{discussionState.currentSpeaker || 'Team member'}</strong> speaking (Turn {discussionState.currentTurn || 1} of {discussionState.totalTurns || 1})
+ Team discussion: <strong>{discussionState.currentSpeaker || 'Team member'}</strong>
+ {discussionState.phase === 'open'
+ ? ' is opening'
+ : discussionState.askedBy
+ ? <> is answering {discussionState.askedBy}</>
+ : ' is responding'}
+ {' '}• turn {discussionState.currentTurn || 1} of {discussionState.totalTurns || 1}
</>
)}
</span>
@@ -538,93 +642,32 @@ export const ChatView: React.FC<ChatViewProps> = ({
<div className="flex-1 flex flex-col h-full overflow-hidden min-w-0">
{/* Messages Stream */}
<div ref={scrollRef} className="flex-1 overflow-y-auto p-6 space-y-6">
- {messages.map((msg) => {
- const isUser = msg.sender_role === 'user';
- const isThoughtOpen = !!openThoughts[msg.id];
- const displayName = isUser ? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);
-
+ {groupDiscussionThreads(messages).map((item) => {
+ if (item.kind === 'message') return renderMessage(item.message);
+ const threadKey = `thread:${item.id}`;
+ const isThreadOpen = !!openThoughts[threadKey];
return (
- <div
- key={msg.id}
- className={`flex items-start gap-3.5 w-full max-w-5xl ${isUser ? 'ml-auto flex-row-reverse justify-start' : ''}`}
- >
- <ModernAvatar
- role={isUser ? 'user' : title}
- name={displayName}
- size={34}
- />
-
- <div className={`flex flex-col min-w-0 ${isUser ? 'max-w-2xl items-end' : 'flex-1 max-w-4xl items-start'}`}>
- {/* Header info */}
- <div className="flex items-center gap-2 mb-1.5 text-[11px] text-zinc-400 font-medium">
- <span className="text-zinc-200">{displayName}</span>
- {msg.tokens_used ? (
- <span className="text-zinc-500 font-mono text-[10px]">({msg.tokens_used} tokens)</span>
- ) : null}
- </div>
-
- {/* Collapsible Reasoning Disclosure */}
- {msg.reasoning_content && (
- <div className="mb-2 max-w-full">
- <button
- type="button"
- onClick={() => toggleThought(msg.id)}
- className="flex items-center gap-2 px-3 py-1.5 rounded-xl text-xs font-mono text-zinc-400 hover:text-zinc-200 bg-zinc-900/80 hover:bg-zinc-900 border border-zinc-800 hover:border-zinc-700/80 transition-all cursor-pointer shadow-sm group"
- >
- <Sparkles size={13} className="text-violet-400 group-hover:rotate-12 transition-transform flex-shrink-0" />
- <span className="truncate max-w-xs sm:max-w-md">
- {msg.reasoning_content.split('\n')[0].replace(/^🔮\s*/, '')}
- </span>
- {isThoughtOpen ? <ChevronDown size={13} className="text-zinc-500 flex-shrink-0" /> : <ChevronRight size={13} className="text-zinc-500 flex-shrink-0" />}
- </button>
-
- {isThoughtOpen && (
- <div className="mt-1.5 p-3.5 rounded-xl bg-zinc-950/90 border border-zinc-800 text-xs font-mono text-zinc-300 whitespace-pre-wrap leading-relaxed shadow-inner max-h-80 overflow-y-auto">
- {msg.reasoning_content}
- </div>
- )}
- </div>
- )}
-
- {/* Message Body Bubble */}
- <div
- className={`p-4 sm:p-5 rounded-2xl text-sm leading-relaxed shadow-sm w-full ${
- isUser
- ? 'bg-zinc-800 text-zinc-100 rounded-tr-sm border border-zinc-700/60 max-w-2xl'
- : 'bg-zinc-900/60 text-zinc-200 rounded-tl-sm border border-zinc-800/80'
- }`}
- >
- {isUser ? (
- <div className="whitespace-pre-wrap break-words">{renderFormattedText(msg.text)}</div>
- ) : (
- <MarkdownRenderer content={msg.text} />
- )}
+ <div key={threadKey} className="w-full max-w-5xl">
+ <button
+ type="button"
+ onClick={() => toggleThought(threadKey)}
+ className="ml-[48px] flex items-center gap-2.5 px-3 py-1.5 rounded-xl text-xs text-zinc-400 hover:text-zinc-200 bg-zinc-900/60 hover:bg-zinc-900 border border-zinc-800 hover:border-zinc-700/80 transition-all cursor-pointer"
+ >
+ {isThreadOpen ? <ChevronDown size={13} className="text-zinc-500" /> : <ChevronRight size={13} className="text-zinc-500" />}
+ <span className="flex -space-x-1.5">
+ {item.speakers.map((name) => (
+ <ModernAvatar key={name} role={name} name={name} size={18} />
+ ))}
+ </span>
+ <span>
+ Team discussed • {item.turns.length} {item.turns.length === 1 ? 'turn' : 'turns'} • {item.speakers.join(', ')}
+ </span>
+ </button>
+ {isThreadOpen && (
+ <div className="mt-4 ml-[30px] pl-4 border-l border-zinc-800 space-y-6">
+ {item.turns.map(renderMessage)}
</div>
-
- {/* Copy action */}
- {!isUser && (
- <div className="mt-1.5 flex items-center gap-2 text-zinc-500 text-xs">
- <button
- type="button"
- onClick={() => handleCopy(msg.text, msg.id)}
- className="px-2 py-1 rounded-md hover:bg-zinc-900 hover:text-zinc-300 transition-colors flex items-center gap-1.5 text-[11px] cursor-pointer"
- title="Copy response"
- >
- {copiedId === msg.id ? (
- <>
- <Check size={12} className="text-emerald-400" />
- <span className="text-emerald-400 font-medium">Copied</span>
- </>
- ) : (
- <>
- <Copy size={12} />
- <span>Copy markdown</span>
- </>
- )}
- </button>
- </div>
- )}
- </div>
+ )}
</div>
);
})}
@@ -671,7 +714,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
<div className="p-4 sm:p-5 rounded-2xl rounded-tl-sm bg-zinc-900/60 text-zinc-200 border border-zinc-800/80 text-sm leading-relaxed shadow-sm w-full">
- <MarkdownRenderer content={streamingText} isStreaming={true} />
+ <MarkdownRenderer content={stripDiscussionMarkers(streamingText)} isStreaming={true} />
</div>
</div>
</div>
diff --git a/frontend/src/discussionThreads.ts b/frontend/src/discussionThreads.ts
new file mode 100644
index 00000000..35d71751
--- /dev/null
+++ b/frontend/src/discussionThreads.ts
@@ -0,0 +1,47 @@
+// Folds the back-and-forth of a finished team discussion into one collapsible thread, so the chat
+// shows the team's summary instead of every intermediate turn. Labels come from src/server/discussion.rs.
+
+export const TURN_LABEL = 'Team Discussion';
+export const SUMMARY_LABEL = 'Team Summary';
+
+interface LabeledMessage {
+ id: string;
+ sender_id: string;
+ reasoning_content?: string | null;
+}
+
+export type ChatItem<M> =
+ | { kind: 'message'; message: M }
+ | { kind: 'thread'; id: string; turns: M[]; speakers: string[] };
+
+const isTurn = (m: LabeledMessage) => !!m.reasoning_content?.startsWith(TURN_LABEL);
+const isSummary = (m: LabeledMessage) => !!m.reasoning_content?.startsWith(SUMMARY_LABEL);
+
+/** Groups runs of discussion turns that end in a team summary; turns still in progress stay inline. */
+export function groupDiscussionThreads<M extends LabeledMessage>(messages: M[]): ChatItem<M>[] {
+ const items: ChatItem<M>[] = [];
+ let i = 0;
+ while (i < messages.length) {
+ if (!isTurn(messages[i])) {
+ items.push({ kind: 'message', message: messages[i] });
+ i += 1;
+ continue;
+ }
+ let j = i;
+ while (j < messages.length && isTurn(messages[j])) j += 1;
+ const turns = messages.slice(i, j);
+ if (j < messages.length && isSummary(messages[j])) {
+ const speakers = Array.from(new Set(turns.map((t) => t.sender_id)));
+ items.push({ kind: 'thread', id: turns[0].id, turns, speakers });
+ } else {
+ turns.forEach((message) => items.push({ kind: 'message', message }));
+ }
+ i = j;
+ }
+ return items;
+}
+
+/** Hides the reply markers kwants use to pass or to ask the user first. */
+export function stripDiscussionMarkers(text: string): string {
+ return text.replace(/\[(PASS|ASK_USER)\]/gi, '').trimStart();
+}
diff --git a/frontend/tests/discussionThreads.test.mjs b/frontend/tests/discussionThreads.test.mjs
new file mode 100644
index 00000000..cae69e4b
--- /dev/null
+++ b/frontend/tests/discussionThreads.test.mjs
@@ -0,0 +1,42 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import test from 'node:test';
+import ts from 'typescript';
+
+const source = await readFile(new URL('../src/discussionThreads.ts', import.meta.url), 'utf8');
+const { outputText } = ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.ESNext },
+});
+const { groupDiscussionThreads, stripDiscussionMarkers } = await import(
+ `data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`
+);
+
+const msg = (id, sender_id, reasoning_content = null) => ({ id, sender_id, reasoning_content });
+
+test('folds discussion turns that end in a team summary into one thread', () => {
+ const items = groupDiscussionThreads([
+ msg('u1', 'You'),
+ msg('t1', 'TechLead', 'Team Discussion • Turn 1 • @core'),
+ msg('t2', 'Architect', 'Team Discussion • Turn 2 • @core'),
+ msg('t3', 'TechLead', 'Team Discussion • Turn 3 • @core'),
+ msg('s1', 'TechLead', 'Team Summary • @core • with TechLead, Architect'),
+ ]);
+ assert.deepEqual(
+ items.map((i) => (i.kind === 'thread' ? `thread:${i.turns.length}:${i.speakers.join(',')}` : i.message.id)),
+ ['u1', 'thread:3:TechLead,Architect', 's1'],
+ );
+});
+
+test('keeps in-progress or summary-less turns inline', () => {
+ const items = groupDiscussionThreads([
+ msg('t1', 'TechLead', 'Team Discussion • Turn 1 of 2 • @core'),
+ msg('t2', 'Architect', 'Team Discussion • Turn 2 of 2 • @core'),
+ msg('u2', 'You'),
+ ]);
+ assert.deepEqual(items.map((i) => i.kind), ['message', 'message', 'message']);
+});
+
+test('hides pass and ask-user markers while streaming', () => {
+ assert.equal(stripDiscussionMarkers('[ASK_USER] Who is it for?'), 'Who is it for?');
+ assert.equal(stripDiscussionMarkers('[PASS]'), '');
+});
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 52bfdf77..4d4c341e 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -256,10 +256,13 @@ impl Database {
pub async fn list_messages(&self, channel_or_kwant_id: &str, limit: i64) -> Result<Vec<Message>, DbError> {
let rows = sqlx::query_as::<_, Message>(
r#"
- SELECT * FROM messages
- WHERE channel_id = ? OR direct_kwant_id = ?
- ORDER BY created_at ASC
- LIMIT ?
+ SELECT * FROM (
+ SELECT *, rowid AS _seq FROM messages
+ WHERE channel_id = ? OR direct_kwant_id = ?
+ ORDER BY created_at DESC, rowid DESC
+ LIMIT ?
+ )
+ ORDER BY created_at ASC, _seq ASC
"#,
)
.bind(channel_or_kwant_id)
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index a51dfd91..bac5ae04 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -45,6 +45,9 @@ pub enum RuntimeEvent {
/// Kwant that handed this speaker the turn with an @mention (handoffs only).
#[serde(default, skip_serializing_if = "Option::is_none")]
asked_by: Option<String>,
+ /// "open", "reply" or "summary" for team discussions; None for handoffs.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ phase: Option<String>,
},
#[serde(rename = "discussion_completed", alias = "DiscussionCompleted")]
DiscussionCompleted {
diff --git a/src/server/discussion.rs b/src/server/discussion.rs
new file mode 100644
index 00000000..76ba719a
--- /dev/null
+++ b/src/server/discussion.rs
@@ -0,0 +1,121 @@
+//! Prompts and reply conventions for moderated team discussions: the lead opens (or asks the user
+//! first), teammates react to each other briefly or pass, and the lead closes with one summary.
+
+/// A teammate with nothing new to add replies with this instead of posting.
+pub const PASS: &str = "[PASS]";
+/// The opening speaker starts its reply with this to pause the discussion for the user's input.
+pub const ASK_USER: &str = "[ASK_USER]";
+
+/// Prefix of `reasoning_content` on intermediate discussion turns; the UI folds these into a thread.
+pub const TURN_LABEL: &str = "Team Discussion";
+/// Prefix of `reasoning_content` on the closing summary.
+pub const SUMMARY_LABEL: &str = "Team Summary";
+
+/// Turns allowed per discussion, not counting the closing summary.
+pub const MAX_TURNS: usize = 5;
+/// How often one kwant may speak in a discussion (a reply when a teammate @mentions them back).
+pub const MAX_TURNS_PER_KWANT: usize = 2;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Reply {
+ Speak(String),
+ Pass,
+ AskUser(String),
+}
+
+pub fn parse_reply(text: &str) -> Reply {
+ let trimmed = text.trim();
+ if trimmed.is_empty() || trimmed.to_ascii_uppercase().starts_with(PASS) {
+ return Reply::Pass;
+ }
+ if trimmed.contains(ASK_USER) {
+ let question = trimmed.replace(ASK_USER, "").trim().to_string();
+ return if question.is_empty() { Reply::Pass } else { Reply::AskUser(question) };
+ }
+ Reply::Speak(trimmed.replace(PASS, "").trim().to_string())
+}
+
+pub fn turn_label(turn: usize, team: &str) -> String {
+ format!("{} • Turn {} • @{}", TURN_LABEL, turn, team)
+}
+
+pub fn summary_label(team: &str, contributors: &[String]) -> String {
+ format!("{} • @{} • with {}", SUMMARY_LABEL, team, contributors.join(", "))
+}
+
+pub fn question_label(speaker: &str, team: &str) -> String {
+ format!("{} needs your input before the team continues • @{}", speaker, team)
+}
+
+pub fn opening_prompt(user_prompt: &str, team: &str, responders: &[String]) -> String {
+ let next = if responders.is_empty() {
+ "You'll then wrap up with a short summary.".to_string()
+ } else {
+ format!(
+ "{} will react to your points next (they get the turn automatically, so don't @mention them), then you'll wrap up with a short summary.",
+ responders.join(" and ")
+ )
+ };
+ format!(
+ "You're opening a team discussion in @{team} about the user's latest message. {next}\n\n\
+ User's message:\n{user_prompt}\n\n\
+ How to open:\n\
+ - If you truly can't make progress without information only the user has, reply with {ask} followed by at most 2 short questions; the team then waits for the user's answer. Prefer stating a reasonable assumption in one line and moving on.\n\
+ - Otherwise give your take from your role: concrete and numbered, so teammates can react to specific points.\n\
+ - Under 150 words. No preamble, don't introduce yourself, don't write the final answer yet.",
+ ask = ASK_USER,
+ )
+}
+
+pub fn reply_prompt(user_prompt: &str, team: &str, previous_speaker: &str, asked_by: Option<&str>) -> String {
+ let cue = match asked_by {
+ Some(from) => format!("{from} asked you directly; answer them first."),
+ None => format!("{previous_speaker} just spoke."),
+ };
+ format!(
+ "Team discussion in @{team} about the user's message (see the conversation above). {cue}\n\n\
+ User's message:\n{user_prompt}\n\n\
+ Your turn:\n\
+ - React to what teammates said, naming them without @: agree, challenge, or refine specific points. Don't restart from scratch or repeat them.\n\
+ - Add only what your expertise brings that's still missing.\n\
+ - Under 120 words. No preamble.\n\
+ - Only if one teammate's input is truly needed, @mention that one teammate with a specific question.\n\
+ - If you have nothing meaningful to add, reply with exactly {pass} and nothing else.",
+ pass = PASS,
+ )
+}
+
+pub fn summary_prompt(user_prompt: &str, contributors: &[String]) -> String {
+ format!(
+ "Wrap up the team discussion above (contributors: {}). Write the team's single final answer to the user's message:\n{user_prompt}\n\n\
+ - Lead with the answer or recommendation; merge the best points and resolve disagreements, crediting teammates by name where it helps.\n\
+ - Bullets, under 200 words.\n\
+ - End with \"Open questions:\" only if decisions remain for the user.\n\
+ - No @mentions and no commentary about the discussion itself.",
+ contributors.join(", "),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_pass_ask_and_speak() {
+ assert_eq!(parse_reply(" [PASS] "), Reply::Pass);
+ assert_eq!(parse_reply("[pass] nothing to add"), Reply::Pass);
+ assert_eq!(parse_reply(""), Reply::Pass);
+ assert_eq!(
+ parse_reply("[ASK_USER] Who is the audience?"),
+ Reply::AskUser("Who is the audience?".into())
+ );
+ assert_eq!(parse_reply("I agree with TechLead."), Reply::Speak("I agree with TechLead.".into()));
+ }
+
+ #[test]
+ fn labels_share_prefixes_the_ui_groups_on() {
+ assert!(turn_label(2, "core").starts_with(TURN_LABEL));
+ assert!(summary_label("core", &["A".into(), "B".into()]).starts_with(SUMMARY_LABEL));
+ assert!(!question_label("A", "core").starts_with(TURN_LABEL));
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 78ce7ada..3ee01728 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -1,3 +1,4 @@
+pub mod discussion;
pub mod routes;
pub mod sse;
pub mod browser_stream;
diff --git a/src/server/routes.rs b/src/server/routes.rs
index a34fb4a9..e0c53d47 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1,3 +1,4 @@
+use super::discussion;
use super::AppState;
use crate::broker::ApprovalDecision;
use crate::db::models::*;
@@ -276,7 +277,7 @@ fn execute_single_turn(
let prompt = payload.prompt.clone();
tokio::spawn(async move {
- if let Some(reply) = run_kwant_turn(&scope, &target_kwant, prompt.clone()).await {
+ if let Some(reply) = run_kwant_turn(&scope, &target_kwant, prompt.clone(), TurnOpts::default()).await {
run_handoffs(&scope, &[target_kwant.id.clone()], &[(target_kwant.clone(), reply)], &prompt).await;
}
@@ -354,10 +355,11 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(
total_turns: total(queue.len(), done + 1),
prompt: prompt.clone(),
asked_by: Some(from.clone()),
+ phase: None,
});
done += 1;
spoken.push(kwant.id.clone());
- match run_kwant_turn(scope, &kwant, prompt).await {
+ match run_kwant_turn(scope, &kwant, prompt, TurnOpts::default()).await {
Some(reply) => enqueue(&mut queue, &spoken, &kwant, &reply),
None if scope.cancel_token.is_cancelled() => break,
None => {}
@@ -367,9 +369,139 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(
let _ = events.send(RuntimeEvent::DiscussionCompleted { total_turns: done + 1 });
}
+/// Runs a moderated team discussion: the lead opens (or pauses to ask the user), teammates react to
+/// each other briefly or pass, @mentioned teammates join in, and the lead closes with one summary.
+async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, user_prompt: &str) {
+ use std::collections::{HashMap, VecDeque};
+
+ let events = scope.state.event_sender.clone();
+ let Some(lead) = planned.first().cloned() else {
+ return;
+ };
+ let responders: Vec<String> = planned.iter().skip(1).map(|k| k.name.clone()).collect();
+ let mut queue: VecDeque<(Kwant, Option<String>)> = planned.iter().cloned().map(|k| (k, None)).collect();
+
+ let mut plan = vec![format!("{}: opens with a proposal", lead.name)];
+ plan.extend(responders.iter().map(|n| format!("{}: reacts and adds what's missing", n)));
+ plan.push(format!("{}: summary for you", lead.name));
+ let _ = events.send(RuntimeEvent::DiscussionStarted {
+ team_id: team.id.clone(),
+ team_name: team.name.clone(),
+ total_turns: queue.len() + 1,
+ speakers: planned.iter().map(|k| k.id.clone()).collect(),
+ plan,
+ kind: "discussion".into(),
+ });
+
+ let names: Vec<&str> = scope.teammates.iter().map(|k| k.name.as_str()).collect();
+ let mut spoke: HashMap<String, usize> = HashMap::new();
+ let mut contributors: Vec<String> = Vec::new();
+ let mut previous: Option<Kwant> = None;
+ let mut turn = 0;
+ let mut waiting_for_user = false;
+
+ while let Some((kwant, asked_by)) = queue.pop_front() {
+ if scope.cancel_token.is_cancelled() || turn >= discussion::MAX_TURNS {
+ break;
+ }
+ if previous.as_ref().is_some_and(|p| p.id == kwant.id) {
+ continue;
+ }
+ turn += 1;
+ let opening = turn == 1;
+ let prompt = if opening {
+ discussion::opening_prompt(user_prompt, &team.name, &responders)
+ } else {
+ let prev = previous.as_ref().map(|p| p.name.as_str()).unwrap_or(&lead.name);
+ discussion::reply_prompt(user_prompt, &team.name, prev, asked_by.as_deref())
+ };
+ let _ = events.send(RuntimeEvent::DiscussionTurnStarted {
+ speaker_id: kwant.id.clone(),
+ speaker_name: kwant.name.clone(),
+ turn_index: turn,
+ total_turns: turn + queue.len().min(discussion::MAX_TURNS - turn) + 1,
+ prompt: prompt.clone(),
+ asked_by: asked_by.clone(),
+ phase: Some(if opening { "open" } else { "reply" }.into()),
+ });
+ let opts = TurnOpts {
+ label: Some(discussion::turn_label(turn, &team.name)),
+ // Only the opening turn may navigate the bot browser for a URL in the user's message
+ nav_prompt: Some(if opening { user_prompt.to_string() } else { String::new() }),
+ discussion: Some(opening.then(|| discussion::question_label(&kwant.name, &team.name))),
+ };
+ let Some(raw) = run_kwant_turn(scope, &kwant, prompt, opts).await else {
+ if scope.cancel_token.is_cancelled() {
+ break;
+ }
+ continue;
+ };
+ match discussion::parse_reply(&raw) {
+ discussion::Reply::Pass => {
+ let _ = events.send(RuntimeEvent::ThinkingDelta(format!("{} has nothing to add", kwant.name)));
+ }
+ discussion::Reply::AskUser(_) if opening => {
+ waiting_for_user = true;
+ break;
+ }
+ discussion::Reply::AskUser(text) | discussion::Reply::Speak(text) => {
+ *spoke.entry(kwant.id.clone()).or_default() += 1;
+ if !contributors.contains(&kwant.name) {
+ contributors.push(kwant.name.clone());
+ }
+ for i in crate::router::handoff_targets(&text, &names) {
+ let k = &scope.teammates[i];
+ let turns_taken = spoke.get(&k.id).copied().unwrap_or(0);
+ if k.id != kwant.id
+ && turns_taken < discussion::MAX_TURNS_PER_KWANT
+ && !queue.iter().any(|(q, _)| q.id == k.id)
+ {
+ queue.push_back((k.clone(), Some(kwant.name.clone())));
+ }
+ }
+ previous = Some(kwant.clone());
+ }
+ }
+ }
+
+ if !waiting_for_user && !scope.cancel_token.is_cancelled() && contributors.len() >= 2 {
+ turn += 1;
+ let prompt = discussion::summary_prompt(user_prompt, &contributors);
+ let _ = events.send(RuntimeEvent::DiscussionTurnStarted {
+ speaker_id: lead.id.clone(),
+ speaker_name: lead.name.clone(),
+ turn_index: turn,
+ total_turns: turn,
+ prompt: prompt.clone(),
+ asked_by: None,
+ phase: Some("summary".into()),
+ });
+ let opts = TurnOpts {
+ label: Some(discussion::summary_label(&team.name, &contributors)),
+ nav_prompt: Some(String::new()),
+ discussion: None,
+ };
+ run_kwant_turn(scope, &lead, prompt, opts).await;
+ }
+
+ let _ = events.send(RuntimeEvent::DiscussionCompleted { total_turns: turn });
+}
+
+/// Per-turn tweaks for turns that kwnt drives itself (team discussions).
+#[derive(Default)]
+struct TurnOpts {
+ /// Saved as the message's `reasoning_content` instead of the driver's reasoning.
+ label: Option<String>,
+ /// Text checked for a URL to open in the bot browser; defaults to the prompt.
+ nav_prompt: Option<String>,
+ /// Discussion reply handling: `[PASS]` replies aren't saved; `Some(label)` lets an `[ASK_USER]`
+ /// reply be saved as a question for the user under that label.
+ discussion: Option<Option<String>>,
+}
+
/// Runs one kwant turn: picks model/effort, syncs the bot browser, streams the reply and saves it.
-/// Returns the reply text, or `None` if the turn was cancelled or failed.
-async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String) -> Option<String> {
+/// Returns the raw reply text, or `None` if the turn was cancelled or failed.
+async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String, opts: TurnOpts) -> Option<String> {
let state = &scope.state;
let event_broadcast = state.event_sender.clone();
let db = state.db.clone();
@@ -433,7 +565,8 @@ async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String)
};
let mut final_prompt = prompt.clone();
- let target_url_opt = detect_url_with_context(&prompt, active_browser_url.as_deref());
+ let nav_prompt = opts.nav_prompt.as_deref().unwrap_or(&prompt);
+ let target_url_opt = detect_url_with_context(nav_prompt, active_browser_url.as_deref());
if let Some(target_url) = target_url_opt {
let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta(format!(
@@ -579,17 +712,30 @@ async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String)
}
}
- let asst_msg = NewMessage {
- channel_id: channel_id.clone(),
- direct_kwant_id: kwant_id.clone(),
- sender_role: "kwant".into(),
- sender_id: target_kwant.name.clone(),
- text: output.text.clone(),
- reasoning_content: output.reasoning,
- tool_calls: None,
- tokens_used: output.tokens_used as i64,
+ let saved = match &opts.discussion {
+ None => Some((output.text.clone(), opts.label.clone().or(output.reasoning))),
+ Some(question_label) => match discussion::parse_reply(&output.text) {
+ discussion::Reply::Pass => None,
+ discussion::Reply::AskUser(q) => match question_label {
+ Some(label) => Some((q, Some(label.clone()))),
+ None => Some((q, opts.label.clone())),
+ },
+ discussion::Reply::Speak(t) => Some((t, opts.label.clone())),
+ },
};
- let _ = db.insert_message(&asst_msg).await;
+ if let Some((text, reasoning_content)) = saved {
+ let asst_msg = NewMessage {
+ channel_id: channel_id.clone(),
+ direct_kwant_id: kwant_id.clone(),
+ sender_role: "kwant".into(),
+ sender_id: target_kwant.name.clone(),
+ text,
+ reasoning_content,
+ tool_calls: None,
+ tokens_used: output.tokens_used as i64,
+ };
+ let _ = db.insert_message(&asst_msg).await;
+ }
return Some(output.text);
}
None
@@ -864,248 +1010,40 @@ pub async fn send_chat(
turns, team.name
)));
- let event_broadcast = state.event_sender.clone();
- let db = state.db.clone();
- let router = state.router.clone();
- let channel_id = payload.channel_id.clone();
- let kwant_id = payload.kwant_id.clone();
- let prompt = payload.prompt.clone();
- let active_cancellations = state.active_cancellations.clone();
- let all_kwants_clone = all_kwants.clone();
- let members_clone = members.clone();
+ let planned: Vec<Kwant> = speakers
+ .iter()
+ .filter_map(|sid| all_kwants.iter().find(|k| &k.id == sid).cloned())
+ .collect();
+ let scope = TurnScope {
+ state: state.clone(),
+ channel_id: payload.channel_id.clone(),
+ kwant_id: payload.kwant_id.clone(),
+ team_keys: Some((team.id.clone(), team.name.clone())),
+ team_context: Some(crate::drivers::TeamContext {
+ id: team.id.clone(),
+ name: team.name.clone(),
+ description: team.description.clone(),
+ workspace_path: team.workspace_path.clone(),
+ repo_url: team.repo_url.clone(),
+ }),
+ workspace_dir: workspace_dir.clone(),
+ teammates: members.clone(),
+ cancel_token: cancel_token.clone(),
+ };
let team_clone = team.clone();
- let speakers_clone = speakers.clone();
- let plan_clone = plan.clone();
- let cancel_token_clone = cancel_token.clone();
+ let prompt = payload.prompt.clone();
let session_id_clone = session_id.clone();
- let workspace_dir_clone = workspace_dir.clone();
- let state_clone = state.clone();
+ let active_cancellations = state.active_cancellations.clone();
tokio::spawn(async move {
- let context_id = channel_id
- .as_deref()
- .or(kwant_id.as_deref())
- .unwrap_or(&team_clone.id)
- .to_string();
-
- let _ = event_broadcast.send(RuntimeEvent::DiscussionStarted {
- team_id: team_clone.id.clone(),
- team_name: team_clone.name.clone(),
- total_turns: turns,
- speakers: speakers_clone.clone(),
- plan: plan_clone.clone(),
- kind: "discussion".into(),
- });
-
- let mut cumulative_transcript: Vec<(String, String)> = Vec::new();
- let mut replies: Vec<(Kwant, String)> = Vec::new();
-
- for (turn_idx, speaker_id) in speakers_clone.iter().enumerate() {
- if cancel_token_clone.is_cancelled() {
- break;
- }
-
- let speaker = match all_kwants_clone.iter().find(|k| &k.id == speaker_id) {
- Some(k) => k.clone(),
- None => {
- tracing::warn!("Speaker Kwant ID {} not found", speaker_id);
- continue;
- }
- };
-
- let mut speaker_prompt = if cumulative_transcript.is_empty() {
- prompt.clone()
- } else {
- let turns_formatted = cumulative_transcript
- .iter()
- .enumerate()
- .map(|(idx, (name, text))| format!("### Turn {} ({})\n{}", idx + 1, name, text))
- .collect::<Vec<_>>()
- .join("\n\n");
- format!(
- "Original user query: {}\n\nDiscussion so far:\n{}\n\nPlease provide your analysis, critique, or synthesis according to the discussion plan.",
- prompt, turns_formatted
- )
- };
-
- if turn_idx == 0 {
- if let Some(target_url) = detect_url_in_prompt(&prompt) {
- let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta(format!(
- "🌐 Navigating bot browser to {}...",
- target_url
- )));
- if let Some(ctrl) = get_or_create_browser_controller(&state_clone, &team_clone.id).await {
- if let Ok(nav) = ctrl.navigate(&target_url).await {
- let page_text = ctrl.extract_content().await.unwrap_or_default();
- let preview = truncate_chars(&page_text, 3000);
- let _ = event_broadcast.send(RuntimeEvent::BrowserNavigated {
- team_id: team_clone.id.clone(),
- url: nav.url.clone(),
- title: nav.title.clone(),
- status_code: nav.status_code,
- });
- if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {
- let _ = event_broadcast.send(RuntimeEvent::BrowserScreenshot {
- team_id: team_clone.id.clone(),
- url: nav.url.clone(),
- image_base64: b64,
- timestamp: chrono::Utc::now().to_rfc3339(),
- });
- }
- speaker_prompt = if let Some(kind) = crate::sandbox::detect_bot_wall(&nav.url, &nav.title, &page_text) {
- format!(
- "{}\n\n[Sandbox Browser State: Tried to open {}. {}]",
- speaker_prompt, target_url, bot_wall_notice(kind, &nav.url)
- )
- } else {
- format!(
- "{}\n\n[Sandbox Browser State: The right-panel bot browser is now on {}. Title: \"{}\".\nPage Content Preview:\n{}\n\nUse this page content in your discussion analysis; only describe what it actually shows. NEVER attempt to open a desktop browser window.]",
- speaker_prompt, nav.url, nav.title, preview
- )
- };
- }
- }
- }
- }
-
- let _ = event_broadcast.send(RuntimeEvent::DiscussionTurnStarted {
- speaker_id: speaker.id.clone(),
- speaker_name: speaker.name.clone(),
- turn_index: turn_idx + 1,
- total_turns: turns,
- prompt: speaker_prompt.clone(),
- asked_by: None,
- });
-
- let available_models = crate::drivers::detect_available_models(&db).await;
- let route = router
- .route_prompt_with_models(&speaker_prompt, "chat", &available_models)
- .await
- .unwrap_or_else(|_| crate::router::RouteDecision {
- selected_model: speaker.preferred_model.clone(),
- effort_level: "medium".into(),
- confidence: 0.8,
- provider_endpoint: None,
- is_fallback: true,
- reasoning: "Fallback routing".into(),
- });
- let route = crate::router::apply_preferred_model(route, &speaker.preferred_model);
-
- let target_model = route.selected_model;
- let effort_level = route.effort_level;
-
- let configured_key = get_configured_key(&db, &target_model).await;
- let endpoint = get_configured_endpoint(&db, &target_model).await;
-
- let driver = resolve_driver_for_model(&target_model, configured_key, endpoint);
- let turn_input = TurnInput {
- browser_api_url: Some(format!("http://127.0.0.1:{}/api/sandbox/{}", state_clone.config.port, team_clone.id)),
- thread_id: context_id.clone(),
- kwant: speaker.clone(),
- prompt: speaker_prompt,
- history: Vec::new(),
- model_override: Some(target_model.clone()),
- effort_level: Some(effort_level),
- team_context: Some(crate::drivers::TeamContext {
- id: team_clone.id.clone(),
- name: team_clone.name.clone(),
- description: team_clone.description.clone(),
- workspace_path: team_clone.workspace_path.clone(),
- repo_url: team_clone.repo_url.clone(),
- }),
- workspace_dir: workspace_dir_clone.clone(),
- sandbox_id: Some(team_clone.id.clone()),
- teammates: members_clone
- .iter()
- .filter(|k| k.id != speaker.id)
- .map(|k| crate::drivers::Teammate { name: k.name.clone(), title: k.title.clone() })
- .collect(),
- };
-
- let (driver_tx, mut driver_rx) = mpsc::channel(32);
- let driver_task = tokio::spawn(async move {
- driver.stream_turn(turn_input, driver_tx).await
- });
-
- let mut turn_cancelled = false;
- loop {
- tokio::select! {
- _ = cancel_token_clone.cancelled() => {
- turn_cancelled = true;
- driver_task.abort();
- break;
- }
- event_opt = driver_rx.recv() => {
- match event_opt {
- Some(event) => {
- let _ = event_broadcast.send(event);
- }
- None => break,
- }
- }
- }
- }
-
- if turn_cancelled {
- let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta(
- "⏹️ Discussion stopped by user".into(),
- ));
- break;
- }
-
- if let Ok(Ok(output)) = driver_task.await {
- let asst_msg = NewMessage {
- channel_id: channel_id.clone(),
- direct_kwant_id: Some(speaker.id.clone()),
- sender_role: "kwant".into(),
- sender_id: speaker.name.clone(),
- text: output.text.clone(),
- reasoning_content: Some(format!(
- "Team Discussion • Turn {} of {} • @{}",
- turn_idx + 1,
- turns,
- team_clone.name
- )),
- tool_calls: None,
- tokens_used: output.tokens_used as i64,
- };
- let _ = db.insert_message(&asst_msg).await;
- replies.push((speaker.clone(), output.text.clone()));
- cumulative_transcript.push((speaker.name.clone(), output.text));
- }
- }
-
- let _ = event_broadcast.send(RuntimeEvent::DiscussionCompleted {
- total_turns: turns,
- });
-
- // Teammates outside the planned speakers that the discussion @mentioned get their turn too
- if !cancel_token_clone.is_cancelled() {
- let scope = TurnScope {
- state: state_clone.clone(),
- channel_id: channel_id.clone(),
- kwant_id: kwant_id.clone(),
- team_keys: Some((team_clone.id.clone(), team_clone.name.clone())),
- team_context: Some(crate::drivers::TeamContext {
- id: team_clone.id.clone(),
- name: team_clone.name.clone(),
- description: team_clone.description.clone(),
- workspace_path: team_clone.workspace_path.clone(),
- repo_url: team_clone.repo_url.clone(),
- }),
- workspace_dir: workspace_dir_clone.clone(),
- teammates: members_clone.clone(),
- cancel_token: cancel_token_clone.clone(),
- };
- run_handoffs(&scope, &speakers_clone, &replies, &prompt).await;
- }
+ run_discussion(&scope, &team_clone, planned, &prompt).await;
let mut tokens = active_cancellations.lock().await;
tokens.remove(&session_id_clone);
- if let Some(cid) = &channel_id {
+ if let Some(cid) = &scope.channel_id {
tokens.remove(cid);
}
- if let Some(kid) = &kwant_id {
+ if let Some(kid) = &scope.kwant_id {
tokens.remove(kid);
}
tokens.remove(&team_clone.id);
diff --git a/tests/db_test.rs b/tests/db_test.rs
index b81bddda..2948ecd9 100644
--- a/tests/db_test.rs
+++ b/tests/db_test.rs
@@ -59,6 +59,13 @@ async fn test_db_init_and_crud() {
assert_eq!(msgs.len(), 1);
assert_eq!(msgs[0].text, "Hello tavern!");
+ // A limit keeps the latest messages, still in chronological order
+ for text in ["second", "third"] {
+ db.insert_message(&NewMessage { text: text.into(), ..new_msg.clone() }).await.unwrap();
+ }
+ let latest: Vec<String> = db.list_messages(&chan.id, 2).await.unwrap().into_iter().map(|m| m.text).collect();
+ assert_eq!(latest, vec!["second", "third"]);
+
// Approvals
let new_app = NewApproval {
turn_id: "turn-123".into(),