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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
import React, { useState, useEffect, useRef } from 'react';
import { X, Users, Trash2, Check, AlertTriangle, ShieldCheck, Folder, GitBranch, FolderSearch } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { Team, Kwant, memberIdsOf } from './Sidebar';
import { FolderBrowserModal } from './FolderBrowserModal';
import { playSfx } from '../audio/chiptune';
import { InstructionsField } from './Instructions';
import { MAX_INSTRUCTIONS } from '../continuity';
import { teamNameToSave } from '../teamChannel';
import { TeamRepoDevLine } from './TeamRepoDevLine';
import { useEscapeLayer } from '../escape';
import { SuggestMembersButton } from './ReadyTeamsEntry';
/** The workspace tab a team opens on: its own folder or repo, else (A8, no workspace yet) Git Repo for "Pick a repo",
* Local Folder for "Pick a folder", or Default. */
export function seededWorkspaceType(
team: Pick<Team, 'workspace_path' | 'repo_url'>,
focusWorkspace: boolean | 'folder',
): 'local' | 'repo' | 'default' {
if (team.workspace_path) return 'local';
if (team.repo_url) return 'repo';
return focusWorkspace === 'folder' ? 'local' : focusWorkspace ? 'repo' : 'default';
}
interface ManageTeamModalProps {
isOpen: boolean;
team: Team | null;
kwants: Kwant[];
onClose: () => void;
onUpdateTeam: (
id: string,
data: {
name: string;
description?: string;
workspace_path?: string;
repo_url?: string;
lead_kwant_id: string;
member_kwants: string[];
instructions?: string;
}
) => Promise<void>;
onDeleteTeam: (id: string) => Promise<void>;
/** A8 ("Pick a repo"): open with the Team Workspace group in view and its input focused.
* 'folder' (an isolation notice's Change folder): the same, but a team with no workspace yet
* lands on Local Path, not Git Repo. */
focusWorkspace?: boolean | 'folder';
}
/**
* Why a delete didn't happen, shown right below the Delete button. On a phone the modal is scrolled
* down to that button, so a note at the top would be out of sight; this one scrolls itself into view.
*/
export const DeleteNote: React.FC<{ text: string | null }> = ({ text }) => {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (text) ref.current?.scrollIntoView?.({ block: 'nearest', behavior: 'smooth' });
}, [text]);
if (!text) return null;
return (
<div ref={ref} role="alert" data-testid="team-delete-note" className="p-2.5 bg-rose-500/10 border border-rose-500/20 rounded-xl text-xs text-rose-300 flex items-center gap-2">
<AlertTriangle size={14} className="flex-shrink-0 text-rose-400" aria-hidden="true" />
<span>{text}</span>
</div>
);
};
export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({
isOpen,
team,
kwants,
onClose,
onUpdateTeam,
onDeleteTeam,
focusWorkspace = false,
}) => {
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [instructions, setInstructions] = useState('');
const [workspaceType, setWorkspaceType] = useState<'local' | 'repo' | 'default'>('default');
const [workspacePath, setWorkspacePath] = useState('');
const [repoUrl, setRepoUrl] = useState('');
const [isBrowsing, setIsBrowsing] = useState(false);
const [isFolderBrowserOpen, setIsFolderBrowserOpen] = useState(false);
const [leadKwantId, setLeadKwantId] = useState('');
const [memberIds, setMemberIds] = useState<string[]>([]);
const [isDeleting, setIsDeleting] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const [isSaving, setIsSaving] = useState(false);
// D1: hidden (not unmounted) while the suggestion sheet is open.
const [sheetOpen, setSheetOpen] = useState(false);
const [error, setError] = useState<string | null>(null);
const [deleteError, setDeleteError] = useState<string | null>(null);
const handleBrowseFolder = async () => {
playSfx('click');
setIsBrowsing(true);
try {
const res = await fetch('/api/system/select-folder', { method: 'POST' });
if (res.ok) {
const data = await res.json();
if (data.path) {
setWorkspacePath(data.path);
playSfx('coin');
return;
} else if (data.canceled) {
return;
}
}
setIsFolderBrowserOpen(true);
} catch {
setIsFolderBrowserOpen(true);
} finally {
setIsBrowsing(false);
}
};
// Escape closes Manage team when nothing differs from the saved team, and keeps it open otherwise.
const saved = team
? {
name: team.name,
description: team.description || '',
instructions: team.instructions || '',
workspace: team.workspace_path ? `local:${team.workspace_path}` : team.repo_url ? `repo:${team.repo_url}` : 'default',
lead: team.lead_kwant_id || (kwants[0]?.id ?? ''),
members: [...memberIdsOf(team)].sort().join(','),
}
: null;
const edited = {
name,
description,
instructions,
workspace: workspaceType === 'local' ? `local:${workspacePath}` : workspaceType === 'repo' ? `repo:${repoUrl}` : 'default',
lead: leadKwantId,
members: [...memberIds].sort().join(','),
};
const unsaved = !!saved && (Object.keys(saved) as (keyof typeof saved)[]).some((k) => saved[k] !== edited[k]);
const rootRef = useRef<HTMLDivElement>(null);
useEscapeLayer(rootRef, isOpen && !!team && !sheetOpen, onClose, {
modal: true,
unsaved,
fallback: () => [...document.querySelectorAll<HTMLElement>('[data-composer]')].find((el) => !el.closest('[inert]')),
});
useEffect(() => {
if (team) {
setName(team.name);
setDescription(team.description || '');
setInstructions(team.instructions || '');
setLeadKwantId(team.lead_kwant_id || (kwants[0]?.id ?? ''));
setWorkspaceType(seededWorkspaceType(team, focusWorkspace));
setWorkspacePath(team.workspace_path || '');
setRepoUrl(team.workspace_path ? '' : team.repo_url || '');
const parsedMembers: string[] = Array.isArray(team.member_kwants)
? team.member_kwants
: typeof team.member_kwants === 'string'
? JSON.parse(team.member_kwants || '[]')
: [];
setMemberIds(parsedMembers);
setConfirmDelete(false);
setError(null);
setDeleteError(null);
}
}, [team, kwants, isOpen, focusWorkspace]);
// A8/21f: bring Team Workspace into view and focus the seeded tab's input, once per opening. This waits for the
// render where the seeded tab is showing (its input is in the DOM), instead of a frame that could fire before the
// seed's state change rendered. Switching tabs by hand afterwards doesn't pull focus back.
const wsRef = useRef<HTMLDivElement>(null);
const wsFocusedFor = useRef<string | null>(null);
useEffect(() => {
if (!isOpen || !team || !focusWorkspace) {
wsFocusedFor.current = null;
return;
}
if (wsFocusedFor.current === team.id || workspaceType !== seededWorkspaceType(team, focusWorkspace)) return;
const input = wsRef.current?.querySelector<HTMLInputElement>('input[data-ws-input]');
if (!input) return;
wsFocusedFor.current = team.id;
wsRef.current?.scrollIntoView?.({ block: 'center' });
input.focus({ preventScroll: true });
}, [isOpen, team, focusWorkspace, workspaceType]);
if (!isOpen || !team) return null;
const savedMembers = memberIdsOf(team);
const removedNames = savedMembers
.filter((id) => !memberIds.includes(id))
.map((id) => kwants.find((k) => k.id === id)?.name)
.filter((n): n is string => !!n);
const handleToggleMember = (kwantId: string) => {
playSfx('click');
if (memberIds.includes(kwantId)) {
if (memberIds.length <= 1) {
setError('A team needs at least one bot.');
return;
}
setError(null);
const next = memberIds.filter((id) => id !== kwantId);
setMemberIds(next);
if (leadKwantId === kwantId && next.length > 0) {
setLeadKwantId(next[0]);
}
} else {
setError(null);
setMemberIds([...memberIds, kwantId]);
}
};
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
const cleanName = teamNameToSave(name, team.name);
if (!cleanName) {
setError('Please provide a valid team name.');
return;
}
if (memberIds.length === 0) {
setError('Pick at least one bot for this team.');
return;
}
if (instructions.length > MAX_INSTRUCTIONS) {
setError(`Team instructions can be at most ${MAX_INSTRUCTIONS} characters.`);
return;
}
try {
setIsSaving(true);
setError(null);
await onUpdateTeam(team.id, {
name: cleanName,
description: description.trim() || undefined,
workspace_path: workspaceType === 'local' && workspacePath.trim() ? workspacePath.trim() : undefined,
repo_url: workspaceType === 'repo' && repoUrl.trim() ? repoUrl.trim() : undefined,
lead_kwant_id: leadKwantId || memberIds[0],
member_kwants: memberIds,
instructions: instructions.trim(),
});
playSfx('fanfare');
setIsSaving(false);
onClose();
} catch (err) {
setIsSaving(false);
setError(err instanceof Error && err.message ? err.message : 'Couldn’t save the team. Try again.');
}
};
const handleDelete = async () => {
if (!confirmDelete) {
setConfirmDelete(true);
playSfx('click');
return;
}
try {
setIsDeleting(true);
setDeleteError(null);
playSfx('click');
await onDeleteTeam(team.id);
setIsDeleting(false);
onClose();
} catch (err) {
setIsDeleting(false);
setDeleteError(err instanceof Error && err.message ? err.message : 'Couldn’t delete the team.');
}
};
return (
<div className={`kw-dialog fixed inset-0 z-50 bg-black/75 backdrop-blur-sm ${sheetOpen ? 'hidden' : 'flex'} items-center justify-center p-4 select-none animate-in fade-in duration-150`} hidden={sheetOpen}>
<div ref={rootRef} tabIndex={-1} role="dialog" aria-modal="true" aria-labelledby="manage-team-title" className="kw-dialog-panel outline-none bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full max-h-[94vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-5">
{/* Header */}
<div className="flex items-center justify-between border-b border-zinc-800 pb-3">
<div className="flex items-center gap-2.5">
<div className="w-8 h-8 rounded-lg bg-sky-500/10 border border-sky-500/20 flex items-center justify-center text-sky-400">
<Users size={16} />
</div>
<div>
<h3 id="manage-team-title" className="text-sm font-semibold text-zinc-100">Manage Team: @{team.name}</h3>
<p className="text-[11px] text-zinc-400">Members, lead and instructions</p>
</div>
</div>
<button
type="button"
aria-label="Close"
onClick={() => {
playSfx('click');
onClose();
}}
className="p-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"
>
<X size={17} />
</button>
</div>
{error && (
<div role="alert" className="p-2.5 bg-rose-500/10 border border-rose-500/20 rounded-xl text-xs text-rose-300 flex items-center gap-2">
<AlertTriangle size={14} className="flex-shrink-0 text-rose-400" />
<span>{error}</span>
</div>
)}
<form onSubmit={handleSave} className="space-y-4">
{/* Team Name */}
<div>
<label className="block text-xs font-medium text-zinc-400 mb-1">Team Handle</label>
<div className="relative flex items-center">
<span className="absolute left-3 text-zinc-500 text-xs font-mono">@</span>
<input
type="text"
required
value={name}
onChange={(e) => setName(e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, '-'))}
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg pl-7 pr-3 py-2 text-xs text-zinc-100 font-mono focus:border-sky-500 focus:outline-none transition-colors"
/>
</div>
</div>
{/* Description */}
<div>
<label className="block text-xs font-medium text-zinc-400 mb-1">Mission / Purpose</label>
<input
type="text"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="e.g. Systems architecture, performance & reliability"
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors"
/>
</div>
<InstructionsField
value={instructions}
onChange={setInstructions}
label="Team instructions"
hint="Pinned for every bot in this team, before each turn. Leave empty to unpin."
rows={4}
/>
{/* Team Workspace */}
<div ref={wsRef} data-team-workspace>
<label className="block text-xs font-medium text-zinc-400 mb-1.5">
Team Workspace
</label>
<div className="grid grid-cols-3 gap-1.5 p-1 bg-zinc-950 rounded-lg border border-zinc-800 text-xs mb-2">
<button
type="button"
onClick={() => {
playSfx('click');
setWorkspaceType('local');
}}
className={`flex items-center justify-center gap-1.5 py-1.5 rounded-md font-medium transition-all ${
workspaceType === 'local'
? 'bg-zinc-800 text-sky-400 border border-sky-500/30 shadow-sm'
: 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900'
}`}
>
<Folder size={13} />
<span>Local Folder</span>
</button>
<button
type="button"
onClick={() => {
playSfx('click');
setWorkspaceType('repo');
}}
className={`flex items-center justify-center gap-1.5 py-1.5 rounded-md font-medium transition-all ${
workspaceType === 'repo'
? 'bg-zinc-800 text-sky-400 border border-sky-500/30 shadow-sm'
: 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900'
}`}
>
<GitBranch size={13} />
<span>Git Repo</span>
</button>
<button
type="button"
onClick={() => {
playSfx('click');
setWorkspaceType('default');
}}
className={`flex items-center justify-center gap-1.5 py-1.5 rounded-md font-medium transition-all ${
workspaceType === 'default'
? 'bg-zinc-800 text-sky-400 border border-sky-500/30 shadow-sm'
: 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900'
}`}
>
<span>Default</span>
</button>
</div>
{workspaceType === 'local' && (
<div className="space-y-2">
<div className="flex flex-wrap sm:flex-nowrap gap-2 items-center">
<input
type="text"
data-ws-input
value={workspacePath}
onChange={(e) => setWorkspacePath(e.target.value)}
placeholder="e.g. ~/projects/my-app or /path/to/folder"
className="flex-1 min-w-0 basis-full sm:basis-auto bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors font-mono"
/>
<button
type="button"
onClick={handleBrowseFolder}
disabled={isBrowsing}
className="flex items-center gap-1.5 px-3 py-2 bg-zinc-800 hover:bg-zinc-700 active:bg-zinc-600 text-zinc-200 border border-zinc-700 rounded-lg text-xs font-medium transition-colors shadow-sm cursor-pointer whitespace-nowrap disabled:opacity-50"
title="Open native folder chooser"
>
<Folder size={14} className="text-amber-400" />
<span>{isBrowsing ? 'Selecting...' : 'Browse...'}</span>
</button>
<button
type="button"
onClick={() => {
playSfx('click');
setIsFolderBrowserOpen(true);
}}
className="p-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 border border-zinc-700 rounded-lg transition-colors cursor-pointer"
title="Explore local directories in-app"
>
<FolderSearch size={14} className="text-sky-400" />
</button>
</div>
{/* Quick Directory Chips */}
<div className="flex flex-wrap items-center gap-1.5 text-[11px]">
<span className="text-zinc-500">Quick:</span>
<button
type="button"
onClick={() => {
playSfx('click');
setWorkspacePath('~/dev/my-app');
}}
className="px-2 py-0.5 rounded bg-zinc-950 border border-zinc-800 text-zinc-400 hover:text-zinc-200 hover:border-zinc-700 font-mono transition-colors"
>
~/dev/my-app
</button>
<button
type="button"
onClick={() => {
playSfx('click');
setWorkspacePath('~');
}}
className="px-2 py-0.5 rounded bg-zinc-950 border border-zinc-800 text-zinc-400 hover:text-zinc-200 hover:border-zinc-700 font-mono transition-colors"
>
~
</button>
<button
type="button"
onClick={() => {
playSfx('click');
setWorkspacePath('~/dev');
}}
className="px-2 py-0.5 rounded bg-zinc-950 border border-zinc-800 text-zinc-400 hover:text-zinc-200 hover:border-zinc-700 font-mono transition-colors"
>
~/dev
</button>
</div>
<p className="text-[11px] text-zinc-500">
Team members will execute commands and tools directly in this directory.
</p>
</div>
)}
{workspaceType === 'repo' && (
<div>
<input
type="text"
data-ws-input
aria-label="Repo URL"
value={repoUrl}
onChange={(e) => setRepoUrl(e.target.value)}
placeholder="https://github.com/owner/repository.git"
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors font-mono"
/>
<TeamRepoDevLine url={repoUrl} teamId={team?.id ?? null} />
<p className="text-[11px] text-zinc-500 mt-1">
Bots clone it into the team’s folder on first run.
</p>
</div>
)}
{team && (team.workspace_path || team.repo_url) && (
<SuggestMembersButton
team={{ id: team.id, name: team.name }}
workspace_path={team.workspace_path || undefined}
repo_url={team.repo_url || undefined}
onHide={() => setSheetOpen(true)}
onShow={() => setSheetOpen(false)}
onDone={() => {
setSheetOpen(false);
onClose();
}}
/>
)}
{workspaceType === 'default' && (
<p className="text-[11px] text-zinc-500">
Uses the default shared workspace directory.
</p>
)}
</div>
{/* Lead Kwant Selector */}
<div>
<label className="block text-xs font-medium text-zinc-400 mb-1">Team Lead</label>
<select
value={leadKwantId}
onChange={(e) => setLeadKwantId(e.target.value)}
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none transition-colors"
>
{kwants
.filter((k) => memberIds.includes(k.id))
.map((k) => (
<option key={k.id} value={k.id}>
{k.name} — {k.title}
</option>
))}
</select>
</div>
{/* Members Roster Checklist: each row is a toggle button (Tab to it, Space or Enter) */}
<div>
<div className="flex items-center justify-between mb-1.5">
<p id="team-roster-label" className="block text-xs font-medium text-zinc-400">
Team Roster ({memberIds.length}/{kwants.length} Assigned)
</p>
<span className="text-[11px] text-zinc-500">Select a bot to add or remove it</span>
</div>
<div role="group" aria-labelledby="team-roster-label" className="space-y-1.5 max-h-48 overflow-y-auto p-1 bg-zinc-950/60 border border-zinc-800/80 rounded-xl">
{kwants.map((k) => {
const isMember = memberIds.includes(k.id);
const isLead = leadKwantId === k.id;
return (
<button
type="button"
key={k.id}
aria-pressed={isMember}
data-roster-row={k.id}
onClick={() => handleToggleMember(k.id)}
className={`w-full text-left flex items-center justify-between p-2 rounded-lg cursor-pointer transition-all border focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-400 ${
isMember
? 'bg-zinc-800/70 border-sky-500/30 text-zinc-100'
: 'bg-zinc-900/30 border-zinc-800/40 text-zinc-400 hover:bg-zinc-800/30 hover:text-zinc-200'
}`}
>
<span className="flex items-center gap-2.5 min-w-0">
<ModernAvatar role={k.avatar_sprite} name={k.name} size={28} />
<span className="block min-w-0">
<span className="flex items-center gap-1.5">
<span className="text-xs font-medium text-zinc-200 truncate">{k.name}</span>
{isLead && (
<span className="text-[9px] font-semibold uppercase px-1 py-0.2 rounded bg-sky-500/20 text-sky-300 border border-sky-500/30 flex items-center gap-0.5">
<ShieldCheck size={9} aria-hidden="true" />
Lead
</span>
)}
</span>
<span className="block text-[10px] text-zinc-400 truncate">{k.title}</span>
</span>
</span>
<span
aria-hidden="true"
className={`w-5 h-5 shrink-0 rounded flex items-center justify-center border transition-all ${
isMember
? 'bg-sky-600 text-white border-sky-400'
: 'border-zinc-700 bg-zinc-900 text-transparent'
}`}
>
<Check size={13} strokeWidth={2.5} />
</span>
</button>
);
})}
</div>
</div>
{/* Unticked members only leave on Save; say who, so Save is the confirm */}
{removedNames.length > 0 && (
<p data-team-removals className="text-[11px] text-amber-200/90">
Saving removes {removedNames.join(', ')} from @{team.name}. {removedNames.length === 1 ? 'The bot stays' : 'They stay'} in this space and {removedNames.length === 1 ? 'keeps its' : 'keep their'} chats.
</p>
)}
{/* Action Buttons & Danger Zone */}
<div className="pt-2 border-t border-zinc-800 flex items-center justify-between gap-3">
<button
type="button"
onClick={handleDelete}
disabled={isDeleting}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-all ${
confirmDelete
? 'bg-rose-600 text-white border-rose-500 animate-pulse motion-reduce:animate-none'
: 'text-rose-400 hover:text-rose-300 bg-rose-500/10 hover:bg-rose-500/20 border-rose-500/20'
}`}
>
<Trash2 size={13} />
<span>{confirmDelete ? 'Confirm Delete?' : 'Delete Team'}</span>
</button>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => {
playSfx('click');
onClose();
}}
className="px-3 py-1.5 rounded-lg text-xs font-medium text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={isSaving}
className="kw-btn-primary kw-focus gap-1.5 px-4 py-1.5 rounded-lg text-xs"
>
<Check size={14} />
<span>{isSaving ? 'Saving...' : 'Save Changes'}</span>
</button>
</div>
</div>
<DeleteNote text={deleteError} />
</form>
</div>
<FolderBrowserModal
isOpen={isFolderBrowserOpen}
initialPath={workspacePath}
onClose={() => setIsFolderBrowserOpen(false)}
onSelectPath={(p) => {
setWorkspacePath(p);
playSfx('coin');
}}
/>
</div>
);
};