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(frontend): add interactive @ mention autocomplete popover to composer

Oleksandr Ivanchenko5bd6f990254f
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 1a9976ff..c89c5e06 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -2,6 +2,7 @@ import React, { useState, useRef, useEffect } from 'react';
import { ArrowUp, Sparkles, ChevronDown, ChevronRight, Copy, Check, Cpu } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';
+import { MentionPopover, MentionItem } from './MentionPopover';
import { playSfx } from '../audio/chiptune';
export interface ChatMessage {
@@ -14,7 +15,7 @@ export interface ChatMessage {
tokens_used?: number;
}
-interface ChatViewProps {
+export interface ChatViewProps {
title: string;
subtitle: string;
messages: ChatMessage[];
@@ -24,8 +25,28 @@ interface ChatViewProps {
isStreaming: boolean;
onSendMessage: (text: string) => void;
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[] }>;
}
+export const renderFormattedText = (text: string): React.ReactNode => {
+ if (!text) return null;
+ const parts = text.split(/(@[a-zA-Z0-9_-]+)/g);
+ return parts.map((part, index) => {
+ if (part.startsWith('@') && /^@[a-zA-Z0-9_-]+$/.test(part)) {
+ return (
+ <span
+ key={index}
+ className="inline-flex items-center px-1.5 py-0.5 rounded text-sky-400 bg-sky-500/10 font-medium font-mono text-[11px] border border-sky-500/20"
+ >
+ {part}
+ </span>
+ );
+ }
+ return part;
+ });
+};
+
export const ChatView: React.FC<ChatViewProps> = ({
title,
subtitle,
@@ -36,6 +57,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
isStreaming,
onSendMessage,
onResolveApproval,
+ kwants: kwantsProp,
+ teams: teamsProp,
}) => {
const [inputVal, setInputVal] = useState('');
const [openThoughts, setOpenThoughts] = useState<Record<string, boolean>>({});
@@ -43,6 +66,113 @@ export const ChatView: React.FC<ChatViewProps> = ({
const scrollRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
+ // Fallback to fetch kwants and teams if not provided as props
+ const [internalKwants, setInternalKwants] = useState<Array<{ id: string; name: string; title: string; avatar_sprite: string }>>([]);
+ const [internalTeams, setInternalTeams] = useState<Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>>([]);
+
+ useEffect(() => {
+ if (!kwantsProp) {
+ fetch('/api/kwants')
+ .then((r) => (r.ok ? r.json() : []))
+ .then((data) => setInternalKwants(data))
+ .catch(() => {});
+ }
+ }, [kwantsProp]);
+
+ useEffect(() => {
+ if (!teamsProp) {
+ fetch('/api/teams')
+ .then((r) => (r.ok ? r.json() : []))
+ .then((data) => setInternalTeams(data))
+ .catch(() => {});
+ }
+ }, [teamsProp]);
+
+ const activeKwants = kwantsProp || internalKwants;
+ const activeTeams = teamsProp || internalTeams;
+
+ const mentionItems: MentionItem[] = [
+ ...activeKwants.map((k) => ({
+ type: 'kwant' as const,
+ id: k.id,
+ name: k.name,
+ title: k.title,
+ avatar_sprite: k.avatar_sprite,
+ })),
+ ...activeTeams.map((t) => ({
+ type: 'team' as const,
+ id: t.id,
+ name: t.name,
+ title: t.description || 'Team',
+ memberCount: t.member_kwants?.length || 0,
+ })),
+ ];
+
+ const [mentionQuery, setMentionQuery] = useState<string | null>(null);
+ const [mentionStartIndex, setMentionStartIndex] = useState<number>(-1);
+ const [selectedIndex, setSelectedIndex] = useState(0);
+
+ const checkMention = (text: string, cursorPos: number | null) => {
+ if (cursorPos === null || cursorPos === undefined) {
+ setMentionQuery(null);
+ setMentionStartIndex(-1);
+ return;
+ }
+ const textBeforeCursor = text.slice(0, cursorPos);
+ const match = textBeforeCursor.match(/(?:^|\s)@([a-zA-Z0-9_-]*)$/);
+ if (match) {
+ const query = match[1];
+ const atIndex = textBeforeCursor.lastIndexOf('@');
+ setMentionQuery(query);
+ setMentionStartIndex(atIndex);
+ } else {
+ setMentionQuery(null);
+ setMentionStartIndex(-1);
+ }
+ };
+
+ const matchingItems = mentionQuery !== null
+ ? mentionItems.filter((item) => {
+ const q = mentionQuery.toLowerCase();
+ return (
+ item.name.toLowerCase().includes(q) ||
+ (item.title && item.title.toLowerCase().includes(q))
+ );
+ })
+ : [];
+
+ const isMentionOpen = mentionQuery !== null && matchingItems.length > 0;
+ const safeSelectedIndex = Math.min(
+ selectedIndex,
+ Math.max(0, matchingItems.length - 1)
+ );
+
+ useEffect(() => {
+ setSelectedIndex(0);
+ }, [mentionQuery]);
+
+ const handleSelectMention = (item: MentionItem) => {
+ if (mentionStartIndex < 0) return;
+ const cursorPos = textareaRef.current?.selectionStart ?? inputVal.length;
+ const textBefore = inputVal.slice(0, mentionStartIndex);
+ const textAfter = inputVal.slice(cursorPos);
+ const mentionText = `@${item.name} `;
+ const newVal = `${textBefore}${mentionText}${textAfter}`;
+ setInputVal(newVal);
+ setMentionQuery(null);
+ setMentionStartIndex(-1);
+
+ const nextCursor = mentionStartIndex + mentionText.length;
+ setTimeout(() => {
+ if (textareaRef.current) {
+ textareaRef.current.focus();
+ textareaRef.current.setSelectionRange(nextCursor, nextCursor);
+ textareaRef.current.style.height = 'auto';
+ textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 160)}px`;
+ }
+ }, 0);
+ };
+
// Auto-scroll on new tokens
useEffect(() => {
if (scrollRef.current) {
@@ -67,12 +197,39 @@ export const ChatView: React.FC<ChatViewProps> = ({
playSfx('click');
onSendMessage(inputVal.trim());
setInputVal('');
+ setMentionQuery(null);
+ setMentionStartIndex(-1);
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
}
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (isMentionOpen) {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ setSelectedIndex((prev) => (prev + 1) % matchingItems.length);
+ return;
+ }
+ if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ setSelectedIndex((prev) => (prev - 1 + matchingItems.length) % matchingItems.length);
+ return;
+ }
+ if (e.key === 'Enter' || e.key === 'Tab') {
+ e.preventDefault();
+ if (matchingItems[safeSelectedIndex]) {
+ handleSelectMention(matchingItems[safeSelectedIndex]);
+ }
+ return;
+ }
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ setMentionQuery(null);
+ return;
+ }
+ }
+
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit();
@@ -161,7 +318,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
: 'bg-zinc-900/90 text-zinc-200 rounded-tl-sm border border-zinc-800/90 shadow-sm'
}`}
>
- {msg.text}
+ {renderFormattedText(msg.text)}
</div>
{/* Copy action */}
@@ -209,7 +366,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
<div className="p-4 rounded-2xl rounded-tl-sm bg-zinc-900 text-zinc-200 border border-zinc-800 text-sm leading-relaxed whitespace-pre-wrap break-words shadow-sm">
- {streamingText}
+ {renderFormattedText(streamingText)}
<span className="inline-block w-1.5 h-4 bg-sky-400 ml-1 cursor-blink align-middle" />
</div>
</div>
@@ -249,19 +406,37 @@ export const ChatView: React.FC<ChatViewProps> = ({
<div className="p-4 border-t border-zinc-800/80 bg-zinc-900/30">
<form
onSubmit={handleSubmit}
- className="max-w-4xl mx-auto flex items-end gap-2 bg-zinc-900 border border-zinc-800 focus-within:border-zinc-700 rounded-2xl p-2 shadow-sm transition-all"
+ className="relative max-w-4xl mx-auto flex items-end gap-2 bg-zinc-900 border border-zinc-800 focus-within:border-zinc-700 rounded-2xl p-2 shadow-sm transition-all"
>
+ {isMentionOpen && (
+ <MentionPopover
+ items={matchingItems}
+ selectedIndex={safeSelectedIndex}
+ onSelect={handleSelectMention}
+ />
+ )}
+
<textarea
ref={textareaRef}
rows={1}
value={inputVal}
onChange={(e) => {
- setInputVal(e.target.value);
+ const val = e.target.value;
+ setInputVal(val);
e.target.style.height = 'auto';
e.target.style.height = `${Math.min(e.target.scrollHeight, 160)}px`;
+ checkMention(val, e.target.selectionStart);
}}
onKeyDown={handleKeyDown}
- placeholder={`Message ${title}... (Enter to send, Shift+Enter for newline)`}
+ onClick={(e) => {
+ checkMention(inputVal, (e.target as HTMLTextAreaElement).selectionStart);
+ }}
+ onKeyUp={(e) => {
+ if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) {
+ checkMention(inputVal, (e.target as HTMLTextAreaElement).selectionStart);
+ }
+ }}
+ placeholder={`Message ${title}... (Enter to send, Shift+Enter for newline, @ to mention)`}
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"
/>
diff --git a/frontend/src/components/MentionPopover.tsx b/frontend/src/components/MentionPopover.tsx
new file mode 100644
index 00000000..2a666294
--- /dev/null
+++ b/frontend/src/components/MentionPopover.tsx
@@ -0,0 +1,114 @@
+import React, { useEffect, useRef } from 'react';
+import { Users } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+
+export interface MentionItem {
+ type: 'kwant' | 'team';
+ id: string;
+ name: string;
+ title?: string;
+ avatar_sprite?: string;
+ memberCount?: number;
+}
+
+export interface MentionPopoverProps {
+ items: MentionItem[];
+ selectedIndex: number;
+ onSelect: (item: MentionItem) => void;
+ position?: { top: number; left: number };
+}
+
+export const MentionPopover: React.FC<MentionPopoverProps> = ({
+ items,
+ selectedIndex,
+ onSelect,
+ position,
+}) => {
+ const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);
+
+ useEffect(() => {
+ if (itemRefs.current[selectedIndex]) {
+ itemRefs.current[selectedIndex]?.scrollIntoView({
+ block: 'nearest',
+ });
+ }
+ }, [selectedIndex]);
+
+ if (items.length === 0) {
+ return null;
+ }
+
+ return (
+ <div
+ className="absolute bottom-full left-0 mb-2 bg-zinc-900 border border-zinc-800 rounded-xl shadow-2xl p-1.5 min-w-[240px] max-w-sm max-h-64 overflow-y-auto z-50 backdrop-blur-md"
+ style={
+ position
+ ? { top: `${position.top}px`, left: `${position.left}px`, bottom: 'auto' }
+ : undefined
+ }
+ >
+ <div className="space-y-0.5">
+ {items.map((item, index) => {
+ const isSelected = index === selectedIndex;
+ const showSectionHeader =
+ index === 0 || items[index - 1].type !== item.type;
+
+ return (
+ <React.Fragment key={`${item.type}-${item.id}`}>
+ {showSectionHeader && (
+ <div className="text-[10px] font-semibold text-zinc-500 uppercase tracking-wider px-2.5 py-1 select-none">
+ {item.type === 'kwant' ? 'Kwants' : 'Teams'}
+ </div>
+ )}
+ <button
+ type="button"
+ ref={(el) => (itemRefs.current[index] = el)}
+ onClick={() => onSelect(item)}
+ onMouseDown={(e) => {
+ // Prevent input blur before click event fires
+ e.preventDefault();
+ }}
+ className={`w-full flex items-center justify-between gap-3 px-2.5 py-1.5 rounded-lg text-left transition-colors text-xs ${
+ isSelected
+ ? 'bg-zinc-800 text-zinc-100'
+ : 'text-zinc-300 hover:bg-zinc-800/60 hover:text-zinc-100'
+ }`}
+ >
+ <div className="flex items-center gap-2.5 min-w-0">
+ {item.type === 'kwant' ? (
+ <ModernAvatar
+ role={item.title || item.name}
+ name={item.name}
+ size={24}
+ />
+ ) : (
+ <div className="w-6 h-6 rounded-lg bg-sky-500/10 border border-sky-500/20 text-sky-400 flex items-center justify-center flex-shrink-0">
+ <Users size={13} />
+ </div>
+ )}
+
+ <div className="min-w-0 truncate">
+ <div className="font-medium truncate text-zinc-100">
+ @{item.name}
+ </div>
+ {item.title && (
+ <div className="text-[10px] text-zinc-400 truncate">
+ {item.title}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {item.type === 'team' && item.memberCount !== undefined && (
+ <span className="flex-shrink-0 text-[10px] font-mono px-1.5 py-0.5 rounded-full bg-zinc-800/80 text-zinc-400 border border-zinc-700/50">
+ {item.memberCount} {item.memberCount === 1 ? 'member' : 'members'}
+ </span>
+ )}
+ </button>
+ </React.Fragment>
+ );
+ })}
+ </div>
+ </div>
+ );
+};