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.

UI: delete bot, team hire card, built-in approval card, import tool list, honest routing line

Lin (kwant bot)51c9799c834c
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index ac9c1017..d3658a0d 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -73,6 +73,7 @@ import { claudeNeedsSignIn } from './claudeLogin';
// Kwant and Tools editors are their own chunks. They stay mounted (rendering nothing while closed),
// so both load right after start-up and opening them never waits.
+const DeleteBotDialog = lazy(() => import('./components/DeleteBotDialog').then((m) => ({ default: m.DeleteBotDialog })));
const NewAgentModal = lazy(() => import('./components/NewAgentModal').then((m) => ({ default: m.NewAgentModal })));
const McpServersModal = lazy(() => import('./components/McpServersModal').then((m) => ({ default: m.McpServersModal })));
const ChannelInstructionsModal = lazy(() =>
@@ -448,6 +449,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const [isNewTeamOpen, setIsNewTeamOpen] = useState(false);
const [editingTeam, setEditingTeam] = useState<Team | null>(null);
const [editingKwant, setEditingKwant] = useState<Kwant | null>(null);
+ const [deletingKwant, setDeletingKwant] = useState<Kwant | null>(null);
const [editingTab, setEditingTab] = useState<EditTab>('profile');
// Skills waiting for review, for the counts on the bot's header and Skills tab.
const [pendingSkills, setPendingSkills] = useState<Skill[]>([]);
@@ -801,6 +803,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
candidateCount: typeof event.data?.candidate_count === 'number' ? event.data.candidate_count : prev?.candidateCount ?? null,
fallback: !!event.data?.fallback,
matchedTerms: Array.isArray(event.data?.matched_terms) ? event.data.matched_terms : undefined,
+ basis: typeof event.data?.basis === 'string' ? event.data.basis : undefined,
}));
if (name && (ctx || targetId) && (ctx || targetId) in liveRef.current) markLive(ctx || targetId, name);
playSfx('blip');
@@ -2128,6 +2131,33 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
busyKwants[t.kwant_id] = `${t.state === 'queued' ? 'Waiting to work on' : awaitingTurns.has(t.turn_id) ? 'Asked you a question in' : 'Working on'} ${describeContext(t.context_id, t.kwant_id)}`;
}
+ // Delete is off while the bot runs anywhere, the open chat included.
+ const workingKwants = new Set(Object.values(turns).map((t) => t.kwant_id));
+
+ /** Drops a deleted bot from the lists; leaves its chat if it was open. */
+ const handleKwantDeleted = async (id: string) => {
+ const gone = kwants.find((k) => k.id === id);
+ setDeletingKwant(null);
+ setEditingKwant(null);
+ setKwants((prev) => prev.filter((k) => k.id !== id));
+ if (!isChannel && selectedId === id) {
+ setOpenThreadId(null);
+ if (channels.length > 0) {
+ setSelectedId(channels[0].id);
+ setIsChannel(true);
+ }
+ }
+ try {
+ const [cRes, tRes] = await Promise.all([fetch('/api/channels'), fetch('/api/teams')]);
+ if (cRes.ok) setChannels(await cRes.json());
+ if (tRes.ok) setTeams(await tRes.json());
+ } catch {
+ /* the next refresh picks it up */
+ }
+ playSfx('click');
+ pushToast(gone ? `Deleted ${gone.name}.` : 'Bot deleted.');
+ };
+
const viewingHistory = !!historyWindow && historyWindow.ctx === openCtx;
const errorBar = messagesError ? (
<div role="alert" className="px-3 sm:px-6 py-2 border-b border-rose-500/20 bg-rose-500/5 flex items-center gap-2 text-xs text-rose-300">
@@ -2562,7 +2592,17 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
pendingSkills={editingKwant ? pendingSkillCounts[editingKwant.id] ?? 0 : 0}
onClose={() => setEditingKwant(null)}
onSubmit={(data) => (editingKwant ? handleUpdateAgent(editingKwant, data) : undefined)}
+ onRequestDelete={editingKwant ? () => setDeletingKwant(editingKwant) : undefined}
/>
+
+ {deletingKwant && (
+ <DeleteBotDialog
+ kwant={deletingKwant}
+ busy={workingKwants.has(deletingKwant.id) ? busyKwants[deletingKwant.id] ?? 'Working' : null}
+ onClose={() => setDeletingKwant(null)}
+ onDeleted={handleKwantDeleted}
+ />
+ )}
</Suspense>
{/* New Team Modal */}
diff --git a/frontend/src/botActions.ts b/frontend/src/botActions.ts
index 26612da8..ee4bcf5a 100644
--- a/frontend/src/botActions.ts
+++ b/frontend/src/botActions.ts
@@ -117,8 +117,11 @@ export function botGone(m: Pick<BotActionMeta, 'status' | 'action' | 'target_kin
}
/** An accepted hire whose bot has since been deleted. */
-export function hiredBotGone(h: Pick<HireMeta, 'status' | 'hired_kwant_id'>, botIds: ReadonlySet<string> | null): boolean {
- return !!botIds && (h.status === 'accepted' || h.status === 'auto_accepted') && !!h.hired_kwant_id && !botIds.has(h.hired_kwant_id);
+export function hiredBotGone(h: Pick<HireMeta, 'status' | 'hired_kwant_id'> & Partial<Pick<HireMeta, 'hired_kwant_ids'>>, botIds: ReadonlySet<string> | null): boolean {
+ if (!botIds || (h.status !== 'accepted' && h.status !== 'auto_accepted')) return false;
+ // A team hire is gone once every bot it made is.
+ const ids = h.hired_kwant_ids?.length ? h.hired_kwant_ids : h.hired_kwant_id ? [h.hired_kwant_id] : [];
+ return ids.length > 0 && ids.every((id) => !botIds.has(id));
}
/** The state line in plain words. Never "Done" once the change was undone or declined, or its bot is gone. */
@@ -243,6 +246,20 @@ export interface HireMeta {
note: string | null;
created_at: string | null;
resolved_at: string | null;
+ /** Every bot the proposal hires, the first being the top-level one; one entry for a single hire. */
+ members: HireMember[];
+ /** The team the proposal creates for them, when it makes a new one. */
+ new_team: { name: string } | null;
+ /** The bots made on accept, in `members` order; empty until then. */
+ hired_kwant_ids: string[];
+}
+
+export interface HireMember {
+ name: string;
+ role: string;
+ model: string | null;
+ tools: Array<{ id: string; name: string | null }>;
+ instructions: string;
}
/** A proposal from the API or `hire_updated`; `card` is its meta. */
@@ -263,6 +280,22 @@ function parseEvidence(raw: unknown): HireEvidence | null {
return null;
}
+function parseTools(raw: unknown): Array<{ id: string; name: string | null }> {
+ return Array.isArray(raw)
+ ? raw.flatMap((t) => (t && typeof t === 'object' && str((t as Record<string, unknown>).id) ? [{ id: (t as Record<string, string>).id, name: str((t as Record<string, unknown>).name) }] : []))
+ : [];
+}
+
+function parseMembers(raw: unknown): HireMember[] {
+ if (!Array.isArray(raw)) return [];
+ return raw.flatMap((x) => {
+ if (!x || typeof x !== 'object') return [];
+ const o = x as Record<string, unknown>;
+ const name = str(o.name);
+ return name ? [{ name, role: str(o.role) ?? '', model: str(o.model), tools: parseTools(o.tools), instructions: str(o.instructions) ?? '' }] : [];
+ });
+}
+
export function parseHireMeta(raw: unknown): HireMeta | null {
const m = parseMetaObject(raw);
if (!m || m.kind !== 'hire_proposal') return null;
@@ -280,9 +313,7 @@ export function parseHireMeta(raw: unknown): HireMeta | null {
role: str(m.role) ?? '',
instructions: str(m.instructions) ?? '',
model: str(m.model),
- tools: Array.isArray(m.tools)
- ? m.tools.flatMap((t) => (t && typeof t === 'object' && str((t as Record<string, unknown>).id) ? [{ id: (t as Record<string, string>).id, name: str((t as Record<string, unknown>).name) }] : []))
- : [],
+ tools: parseTools(m.tools),
team: team && str(team.id) ? { id: team.id as string, name: str(team.name) ?? 'a team' } : null,
reason: str(m.reason) ?? '',
evidence: parseEvidence(m.evidence),
@@ -297,9 +328,19 @@ export function parseHireMeta(raw: unknown): HireMeta | null {
note: str(m.note),
created_at: str(m.created_at),
resolved_at: str(m.resolved_at),
+ members: (() => {
+ const listed = parseMembers(m.members);
+ const top: HireMember = { name, role: str(m.role) ?? '', model: str(m.model), tools: parseTools(m.tools), instructions: str(m.instructions) ?? '' };
+ return listed.length ? listed : [top];
+ })(),
+ new_team: m.new_team && typeof m.new_team === 'object' && str((m.new_team as Record<string, unknown>).name) ? { name: (m.new_team as Record<string, string>).name } : null,
+ hired_kwant_ids: strs(m.hired_kwant_ids),
};
}
+/** Whether the proposal hires several bots at once (a team), rather than one. */
+export const isTeamHire = (h: Pick<HireMeta, 'members'>) => h.members.length > 1;
+
const HIRE_RANK: Record<HireStatus, number> = { pending: 0, accepted: 1, auto_accepted: 1, denied: 2, undone: 2 };
export function hireView(meta: HireMeta, live?: HireMeta | null): HireMeta {
@@ -337,17 +378,28 @@ export function evidenceText(e: HireEvidence | null, requestedByPerson: boolean)
/** "auto" or empty means the app picks; anything else is shown as is. */
export const modelText = (model: string | null) => (!model || model === 'auto' ? 'Picked automatically' : model);
-export function hireStateText(h: Pick<HireMeta, 'status' | 'name' | 'team' | 'proposer_name'>, gone = false): { label: string; tone: 'ok' | 'wait' | 'off' } {
- if (gone) return { label: `Hired ${h.name}. It’s since been deleted.`, tone: 'off' };
+/** "Ana, Ben and Cy". */
+export const andList = (xs: string[]) => (xs.length > 1 ? `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}` : xs[0] ?? '');
+
+export function hireStateText(
+ h: Pick<HireMeta, 'status' | 'name' | 'team' | 'proposer_name'> & Partial<Pick<HireMeta, 'members' | 'new_team'>>,
+ gone = false,
+): { label: string; tone: 'ok' | 'wait' | 'off' } {
+ const names = h.members && h.members.length > 1 ? h.members.map((m) => m.name) : [h.name];
+ const many = names.length > 1;
+ const who = andList(names);
+ const team = h.new_team?.name ?? h.team?.name;
+ const joined = team ? `joined ${team}` : many ? 'are ready' : 'is ready';
+ if (gone) return { label: many ? `Hired ${who}. They’ve since been deleted.` : `Hired ${h.name}. It’s since been deleted.`, tone: 'off' };
switch (h.status) {
case 'accepted':
- return { label: `Hired. ${h.name} ${h.team ? `joined ${h.team.name}` : 'is ready'}.`, tone: 'ok' };
+ return { label: `Hired. ${who} ${joined}.`, tone: 'ok' };
case 'auto_accepted':
- return { label: `Hired at once, because you chose Always accept. ${h.name} ${h.team ? `joined ${h.team.name}` : 'is ready'}.`, tone: 'ok' };
+ return { label: `Hired at once, because you chose Always accept. ${who} ${joined}.`, tone: 'ok' };
case 'denied':
- return { label: `Not hired. Bots here won’t suggest this kind of bot again unless you ask.`, tone: 'off' };
+ return { label: many ? 'Not hired. Bots here won’t suggest this team again unless you ask.' : `Not hired. Bots here won’t suggest this kind of bot again unless you ask.`, tone: 'off' };
case 'undone':
- return { label: `Hire undone. ${h.name} was removed.`, tone: 'off' };
+ return { label: many ? `Hire undone. ${who} were removed.` : `Hire undone. ${h.name} was removed.`, tone: 'off' };
default:
return { label: `Waiting for you. ${h.proposer_name || 'The bot'} carries on with your request meanwhile.`, tone: 'wait' };
}
diff --git a/frontend/src/botDelete.ts b/frontend/src/botDelete.ts
new file mode 100644
index 00000000..e1552b78
--- /dev/null
+++ b/frontend/src/botDelete.ts
@@ -0,0 +1,73 @@
+// Deleting a bot: what it takes with it, and the call. The person starts it from the bot's
+// settings; a bot can only propose it (bot_delete action card).
+
+/** What deleting a bot removes, from GET /api/kwants/:id/usage; null when the server can't say. */
+export interface BotUsage {
+ conversations: number;
+ memories: number;
+ skills: number;
+ routines: number;
+ running: boolean;
+}
+
+const n = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0);
+
+export function parseUsage(raw: unknown): BotUsage | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const o = raw as Record<string, unknown>;
+ return { conversations: n(o.conversations), memories: n(o.memories), skills: n(o.skills), routines: n(o.routines), running: o.running === true };
+}
+
+const count = (k: number, one: string, many: string) => `${k} ${k === 1 ? one : many}`;
+
+/** The lines the confirm dialog lists: counts when known, else the kinds of thing. */
+export function lossLines(usage: BotUsage | null): string[] {
+ if (!usage) return ['Its conversations and threads', 'Its memory', 'Its skills', 'Its routines'];
+ return [
+ count(usage.conversations, 'conversation', 'conversations'),
+ count(usage.memories, 'memory', 'memories'),
+ count(usage.skills, 'skill', 'skills'),
+ count(usage.routines, 'routine', 'routines'),
+ ];
+}
+
+/** Why Delete is off right now, or null when it can be pressed. `busy` is the sidebar's activity line. */
+export function deleteBlockedReason(name: string, busy: string | null | undefined, usage: BotUsage | null): string | null {
+ if (busy || usage?.running) return `${name} is working right now. Stop it or wait until it finishes, then delete it.`;
+ return null;
+}
+
+const enc = encodeURIComponent;
+
+export const botDeleteApi = {
+ /** null when the server has no usage endpoint or the call fails; the dialog then words it generally. */
+ usage: async (id: string): Promise<BotUsage | null> => {
+ try {
+ const res = await fetch(`/api/kwants/${enc(id)}/usage`);
+ return res.ok ? parseUsage(await res.json()) : null;
+ } catch {
+ return null;
+ }
+ },
+ /** Resolves to an error sentence, or null once it's deleted (or already gone). */
+ remove: async (id: string, name: string): Promise<string | null> => {
+ let res: Response;
+ try {
+ res = await fetch(`/api/kwants/${enc(id)}`, { method: 'DELETE' });
+ } catch {
+ return 'Couldn’t reach the server. Check your connection and try again.';
+ }
+ if (res.ok || res.status === 404) return null;
+ let msg = '';
+ try {
+ const body = await res.json();
+ msg = typeof body?.message === 'string' ? body.message : typeof body?.error === 'string' && body.error.includes(' ') ? body.error : '';
+ } catch {
+ /* not JSON */
+ }
+ if (msg) return msg;
+ if (res.status === 409) return `${name} is working right now. Stop it or wait until it finishes, then delete it.`;
+ if (res.status === 405) return 'This server can’t delete bots yet. Update the app and try again.';
+ return `Couldn’t delete ${name} (HTTP ${res.status}).`;
+ },
+};
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 56a961ce..b912550e 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -32,6 +32,7 @@ import { FileTiles, UploadChip } from './Attachments';
import { ranOnLabel } from '../engines';
import { parseRoutingMeta, ranOnAccount, routingLine } from '../spaces';
import { SetupNeededCard, parseSetupMeta } from './SetupNeededCard';
+import { routeReasonText } from '../routeReason';
export interface ChatMessage {
id: string;
@@ -90,6 +91,8 @@ export interface RoutingState {
candidateCount?: number | null;
fallback?: boolean;
matchedTerms?: string[];
+ /** How the bot was picked: by role, the team lead as fallback, keywords, or the only choice. */
+ basis?: string;
}
export interface ChatViewProps {
@@ -192,6 +195,7 @@ export const renderFormattedText = (text: string): React.ReactNode => {
const LayaRoutingCard: React.FC<{ routing: RoutingState; spaceName?: string }> = ({ routing, spaceName }) => {
const deciding = routing.phase === 'deciding';
const isDiscuss = routing.mode === 'discuss';
+ const why = routeReasonText(routing);
const pool = routing.candidateCount ?? (routing.candidates.length || null);
const where = spaceName ? ` in ${spaceName}` : '';
@@ -228,7 +232,7 @@ const LayaRoutingCard: React.FC<{ routing: RoutingState; spaceName?: string }> =
<span className="font-semibold text-violet-200">{routing.kwantName}</span>
{routing.kwantTitle && <span className="text-zinc-400 text-xs">({routing.kwantTitle})</span>}
</div>
- {routing.reason && <span className="text-xs text-zinc-400">{routing.reason}</span>}
+ {why && <span className="text-xs text-zinc-400">{why}</span>}
{routing.fallback && <span className="text-xs text-amber-300/90">Picked by keywords (Laya is offline)</span>}
</div>
)}
diff --git a/frontend/src/components/DeleteBotDialog.tsx b/frontend/src/components/DeleteBotDialog.tsx
new file mode 100644
index 00000000..f2206912
--- /dev/null
+++ b/frontend/src/components/DeleteBotDialog.tsx
@@ -0,0 +1,163 @@
+import React, { useEffect, useRef, useState } from 'react';
+import { AlertTriangle, Download, Loader2, Trash2 } from 'lucide-react';
+import { BotUsage, botDeleteApi, deleteBlockedReason, lossLines } from '../botDelete';
+import { downloadExport, trapFocusTarget } from '../imports';
+
+interface DeleteBotDialogProps {
+ kwant: { id: string; name: string };
+ /** The sidebar's "Working on …" line when the bot is busy. */
+ busy?: string | null;
+ onClose: () => void;
+ /** Called once the server has deleted it. */
+ onDeleted: (id: string) => void;
+}
+
+const FOCUSABLE = 'button:not([disabled]), a[href]';
+
+/** Confirms deleting a bot: names what goes with it, and offers Export first. */
+export const DeleteBotDialog: React.FC<DeleteBotDialogProps> = ({ kwant, busy, onClose, onDeleted }) => {
+ const [usage, setUsage] = useState<BotUsage | null>(null);
+ const [loaded, setLoaded] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+ const [exporting, setExporting] = useState(false);
+ const [exported, setExported] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const boxRef = useRef<HTMLDivElement>(null);
+ const cancelRef = useRef<HTMLButtonElement>(null);
+
+ useEffect(() => {
+ let live = true;
+ botDeleteApi.usage(kwant.id).then((u) => {
+ if (!live) return;
+ setUsage(u);
+ setLoaded(true);
+ });
+ return () => {
+ live = false;
+ };
+ }, [kwant.id]);
+
+ // Start on Cancel: the safe choice.
+ useEffect(() => cancelRef.current?.focus(), []);
+
+ const blocked = deleteBlockedReason(kwant.name, busy, usage);
+
+ const onKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ if (!deleting) onClose();
+ return;
+ }
+ if (e.key !== 'Tab' || !boxRef.current) return;
+ const items = Array.from(boxRef.current.querySelectorAll<HTMLElement>(FOCUSABLE));
+ const to = trapFocusTarget(items.length, items.indexOf(document.activeElement as HTMLElement), e.shiftKey);
+ if (to !== null) {
+ e.preventDefault();
+ items[to]?.focus();
+ }
+ };
+
+ const doExport = async () => {
+ setExporting(true);
+ setError(null);
+ try {
+ const file = await downloadExport(kwant.id);
+ setExported(file);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Couldn’t export the bot.');
+ }
+ setExporting(false);
+ };
+
+ const doDelete = async () => {
+ if (blocked || deleting) return;
+ setDeleting(true);
+ setError(null);
+ const err = await botDeleteApi.remove(kwant.id, kwant.name);
+ setDeleting(false);
+ if (err) {
+ setError(err);
+ return;
+ }
+ onDeleted(kwant.id);
+ };
+
+ const btn =
+ 'inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3.5 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2';
+
+ return (
+ <div className="fixed inset-0 z-[60] bg-black/70 backdrop-blur-sm flex items-center justify-center p-4" onKeyDown={onKeyDown}>
+ <div
+ ref={boxRef}
+ role="alertdialog"
+ aria-modal="true"
+ aria-labelledby="delete-bot-title"
+ aria-describedby="delete-bot-desc"
+ className="bg-zinc-900 border border-rose-500/30 rounded-2xl max-w-md w-full max-h-[92vh] overflow-y-auto p-4 sm:p-5 text-zinc-100 shadow-2xl space-y-4"
+ >
+ <div className="flex items-start gap-2.5">
+ <div className="w-8 h-8 shrink-0 rounded-lg bg-rose-500/10 border border-rose-500/25 flex items-center justify-center text-rose-300">
+ <Trash2 size={15} aria-hidden="true" />
+ </div>
+ <div className="min-w-0">
+ <h3 id="delete-bot-title" className="text-sm font-semibold break-words">
+ Delete {kwant.name}?
+ </h3>
+ <p id="delete-bot-desc" className="text-xs text-zinc-400">
+ This removes the bot and everything below for good. It can’t be undone.
+ </p>
+ </div>
+ </div>
+
+ <ul aria-label="What gets deleted" aria-busy={!loaded} className="list-disc pl-5 text-xs text-zinc-200 space-y-0.5">
+ {lossLines(usage).map((l) => (
+ <li key={l}>{l}</li>
+ ))}
+ </ul>
+ <p className="text-[11px] text-zinc-500">Teams it’s in lose it as a member. Other bots and their chats stay.</p>
+
+ <div className="rounded-xl border border-zinc-800 bg-zinc-950/70 p-3 space-y-2">
+ <p className="text-xs text-zinc-300">Want a copy first? Export saves its instructions, memory, skills and routines to a file you can import later.</p>
+ <button type="button" onClick={doExport} disabled={exporting || deleting} className={`${btn} text-zinc-100 border border-zinc-700 hover:bg-zinc-800 focus-visible:outline-zinc-400`}>
+ {exporting ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Download size={13} aria-hidden="true" />}
+ {exporting ? 'Exporting…' : `Export ${kwant.name}`}
+ </button>
+ {exported && (
+ <p role="status" className="text-[11px] text-emerald-300 break-words">
+ Saved {exported}.
+ </p>
+ )}
+ </div>
+
+ {blocked && (
+ <p role="status" className="flex items-start gap-1.5 text-xs text-amber-200">
+ <AlertTriangle size={13} className="mt-px shrink-0" aria-hidden="true" />
+ <span>{blocked}</span>
+ </p>
+ )}
+ {error && (
+ <p role="alert" className="flex items-start gap-1.5 rounded-lg border border-rose-500/30 bg-rose-500/10 px-2.5 py-1.5 text-xs text-rose-200 break-words">
+ <AlertTriangle size={13} className="mt-px shrink-0" aria-hidden="true" />
+ <span>{error}</span>
+ </p>
+ )}
+
+ <div className="flex flex-wrap items-center justify-end gap-2 pt-1">
+ <button ref={cancelRef} type="button" onClick={onClose} disabled={deleting} className={`${btn} text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 focus-visible:outline-zinc-400`}>
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={doDelete}
+ disabled={!!blocked || deleting}
+ title={blocked ?? undefined}
+ className={`${btn} text-white bg-rose-600 hover:bg-rose-500 focus-visible:outline-rose-400`}
+ >
+ {deleting ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Trash2 size={13} aria-hidden="true" />}
+ {deleting ? 'Deleting…' : `Delete ${kwant.name}`}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/HireCard.tsx b/frontend/src/components/HireCard.tsx
index c4bc3645..b4eaa05c 100644
--- a/frontend/src/components/HireCard.tsx
+++ b/frontend/src/components/HireCard.tsx
@@ -1,7 +1,7 @@
import React, { useId, useState } from 'react';
import { AlertTriangle, CheckCircle2, ChevronDown, ChevronRight, Loader2, MinusCircle, Undo2, UserPlus } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
-import { HireMeta, evidenceText, hireStateText, hireView, hiredBotGone, modelText } from '../botActions';
+import { HireMeta, evidenceText, hireStateText, hireView, hiredBotGone, isTeamHire, modelText } from '../botActions';
export type HireDecision = 'deny' | 'accept_once' | 'always_accept' | 'undo';
@@ -55,6 +55,8 @@ export const HireCard: React.FC<HireCardProps> = ({ meta, messageId, kwantName,
const evidence = evidenceText(view.evidence, view.requested_by_person);
const border = pending ? 'border-violet-500/40' : done ? 'border-zinc-800' : 'border-emerald-500/25';
const can = (c: string) => pending && view.choices.includes(c);
+ const team = isTeamHire(view);
+ const toolText = (tools: HireMeta['tools']) => (tools.length ? tools.map((t) => t.name || 'Unknown tool').join(', ') : 'None');
return (
<section data-message-id={messageId} aria-labelledby={headingId} className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl ${flash ? 'kw-flash' : ''}`}>
@@ -65,18 +67,34 @@ export const HireCard: React.FC<HireCardProps> = ({ meta, messageId, kwantName,
<UserPlus size={12} className="text-violet-300" aria-hidden="true" />
<span>
<span className="text-zinc-200">{proposer}</span>
- {view.status === 'auto_accepted' ? ' hired a new bot' : pending ? ' proposes hiring a new bot' : ' proposed hiring a new bot'}
+ {team
+ ? view.status === 'auto_accepted'
+ ? ` hired a team of ${view.members.length}`
+ : pending
+ ? ` proposes hiring a team of ${view.members.length}`
+ : ` proposed hiring a team of ${view.members.length}`
+ : view.status === 'auto_accepted'
+ ? ' hired a new bot'
+ : pending
+ ? ' proposes hiring a new bot'
+ : ' proposed hiring a new bot'}
</span>
</span>
- <div className="flex items-center gap-2.5 min-w-0">
- <ModernAvatar role={view.role || view.name} name={view.name} size={28} kwantId={view.hired_kwant_id ?? undefined} />
- <div className="min-w-0">
- <h3 id={headingId} className={`text-sm font-semibold break-words leading-snug ${done ? 'text-zinc-400' : 'text-zinc-100'}`}>
- {view.name}
- </h3>
- {view.role && <p className="text-xs text-zinc-400 break-words">{view.role}</p>}
+ {team ? (
+ <h3 id={headingId} className={`text-sm font-semibold break-words leading-snug ${done ? 'text-zinc-400' : 'text-zinc-100'}`}>
+ {view.new_team?.name ?? view.team?.name ?? `${view.members.length} new bots`}
+ </h3>
+ ) : (
+ <div className="flex items-center gap-2.5 min-w-0">
+ <ModernAvatar role={view.role || view.name} name={view.name} size={28} kwantId={view.hired_kwant_id ?? undefined} />
+ <div className="min-w-0">
+ <h3 id={headingId} className={`text-sm font-semibold break-words leading-snug ${done ? 'text-zinc-400' : 'text-zinc-100'}`}>
+ {view.name}
+ </h3>
+ {view.role && <p className="text-xs text-zinc-400 break-words">{view.role}</p>}
+ </div>
</div>
- </div>
+ )}
{view.reason && (
<p className="text-sm text-zinc-300 break-words leading-relaxed">
<span className="text-zinc-500">Why: </span>
@@ -91,16 +109,41 @@ export const HireCard: React.FC<HireCardProps> = ({ meta, messageId, kwantName,
)}
</div>
- <dl className="mx-4 mb-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-xl border border-zinc-800 bg-zinc-950/70 px-3 py-2 text-xs">
- <dt className="text-zinc-500">Team</dt>
- <dd className="min-w-0 break-words text-zinc-200">{view.team ? view.team.name : 'No team'}</dd>
- <dt className="text-zinc-500">Model</dt>
- <dd className="min-w-0 break-words text-zinc-200">{modelText(view.model)}</dd>
- <dt className="text-zinc-500">Tools</dt>
- <dd className="min-w-0 break-words text-zinc-200">{view.tools.length ? view.tools.map((t) => t.name || 'Unknown tool').join(', ') : 'None'}</dd>
- </dl>
+ {team ? (
+ <>
+ <ul aria-label="Proposed members" className="mx-4 mb-2 divide-y divide-zinc-800 rounded-xl border border-zinc-800 bg-zinc-950/70 text-xs">
+ {view.members.map((m, i) => (
+ <li key={`${m.name}-${i}`} className="flex items-start gap-2.5 px-3 py-2 min-w-0">
+ <ModernAvatar role={m.role || m.name} name={m.name} size={24} kwantId={view.hired_kwant_ids[i]} />
+ <div className="min-w-0 flex-1">
+ <p className={`font-medium break-words ${done ? 'text-zinc-400' : 'text-zinc-100'}`}>{m.name}</p>
+ {m.role && <p className="text-zinc-400 break-words">{m.role}</p>}
+ <p className="text-[11px] text-zinc-500 break-words">
+ {modelText(m.model)} · Tools: {toolText(m.tools)}
+ </p>
+ </div>
+ </li>
+ ))}
+ </ul>
+ <dl className="mx-4 mb-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 px-1 text-xs">
+ <dt className="text-zinc-500">Team</dt>
+ <dd className="min-w-0 break-words text-zinc-200">
+ {view.new_team ? `New team: ${view.new_team.name}` : view.team ? view.team.name : 'No team'}
+ </dd>
+ </dl>
+ </>
+ ) : (
+ <dl className="mx-4 mb-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-xl border border-zinc-800 bg-zinc-950/70 px-3 py-2 text-xs">
+ <dt className="text-zinc-500">Team</dt>
+ <dd className="min-w-0 break-words text-zinc-200">{view.team ? view.team.name : 'No team'}</dd>
+ <dt className="text-zinc-500">Model</dt>
+ <dd className="min-w-0 break-words text-zinc-200">{modelText(view.model)}</dd>
+ <dt className="text-zinc-500">Tools</dt>
+ <dd className="min-w-0 break-words text-zinc-200">{toolText(view.tools)}</dd>
+ </dl>
+ )}
- {view.instructions && (
+ {(team ? view.members.some((m) => m.instructions) : view.instructions) && (
<div className="mx-4 mb-2">
<button
type="button"
@@ -110,14 +153,14 @@ export const HireCard: React.FC<HireCardProps> = ({ meta, messageId, kwantName,
className="inline-flex items-center gap-1 min-h-[32px] text-xs text-zinc-300 hover:text-zinc-100 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"
>
{showInstructions ? <ChevronDown size={13} aria-hidden="true" /> : <ChevronRight size={13} aria-hidden="true" />}
- {showInstructions ? 'Hide its instructions' : 'Show its instructions'}
+ {team ? (showInstructions ? 'Hide their instructions' : 'Show their instructions') : showInstructions ? 'Hide its instructions' : 'Show its instructions'}
</button>
{showInstructions && (
<p
id={instructionsId}
className="mt-1 max-h-64 overflow-y-auto rounded-xl border border-zinc-800 bg-zinc-950/70 px-3 py-2 text-xs text-zinc-300 whitespace-pre-wrap break-words leading-relaxed"
>
- {view.instructions}
+ {team ? view.members.filter((m) => m.instructions).map((m) => `${m.name}\n${m.instructions}`).join('\n\n') : view.instructions}
</p>
)}
</div>
@@ -148,7 +191,7 @@ export const HireCard: React.FC<HireCardProps> = ({ meta, messageId, kwantName,
className={`${btn} bg-violet-500 text-white hover:bg-violet-400 focus-visible:outline-violet-400`}
>
{busy === 'accept_once' && spin}
- {busy === 'accept_once' ? 'Hiring…' : 'Accept once'}
+ {busy === 'accept_once' ? 'Hiring…' : team ? `Approve all ${view.members.length}` : 'Accept once'}
</button>
)}
{can('always_accept') && (
@@ -159,7 +202,7 @@ export const HireCard: React.FC<HireCardProps> = ({ meta, messageId, kwantName,
)}
{can('deny') && (
<button type="button" onClick={() => decide('deny')} disabled={busy !== null} className={quiet}>
- {busy === 'deny' ? 'Saying no…' : 'Deny'}
+ {busy === 'deny' ? 'Saying no…' : team ? 'Decline' : 'Deny'}
</button>
)}
</div>
diff --git a/frontend/src/components/ImportDialog.tsx b/frontend/src/components/ImportDialog.tsx
index bdc83c71..4551c469 100644
--- a/frontend/src/components/ImportDialog.tsx
+++ b/frontend/src/components/ImportDialog.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useRef, useState } from 'react';
+import React, { useEffect, useId, useRef, useState } from 'react';
import { AlertTriangle, ArrowLeft, Check, ChevronRight, ClipboardCopy, FileUp, Info, Loader2, Undo2, Upload, X } from 'lucide-react';
import {
Applied,
@@ -15,6 +15,8 @@ import {
previewRows,
sourceName,
textTooLong,
+ ToolNote,
+ toolNote,
trapFocusTarget,
} from '../imports';
@@ -181,12 +183,56 @@ export const UploadStep: React.FC<{ file: File | null; onFile: (f: File | null)
);
};
+/** How many app names a tool notice shows before "Show all". */
+const APPS_SHOWN = 5;
+
+/** The "It used tools (…)" notice as a short list of app names, with the rest behind "Show all". */
+const ToolNoteItem: React.FC<{ note: ToolNote }> = ({ note }) => {
+ const [open, setOpen] = useState(false);
+ const listId = useId();
+ const n = note.apps.length;
+ const shown = open ? note.apps : note.apps.slice(0, APPS_SHOWN);
+ const hidden = n - shown.length;
+ return (
+ <li>
+ <span>
+ {open
+ ? `It used tools from ${n === 1 ? note.apps[0].name : `${n} apps, listed below`}. `
+ : `It used tools from ${n === 1 ? '' : `${n} apps: `}${shown.map((a) => a.name).join(', ')}${hidden > 0 ? ` and ${hidden} more` : ''}. `}
+ {note.tail}
+ </span>{' '}
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ aria-controls={listId}
+ className="underline underline-offset-2 text-amber-200 hover:text-amber-100 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"
+ >
+ {open ? 'Show less' : hidden > 0 ? 'Show all' : 'Show tool names'}
+ </button>
+ {open && (
+ <ul id={listId} className="mt-1 space-y-0.5 pl-1 list-none">
+ {note.apps.map((a) => (
+ <li key={a.name} className="break-words">
+ <span className="text-amber-100">{a.name}</span>
+ {a.tools.length > 1 || a.tools[0] !== a.name ? <span className="text-zinc-400">: {a.tools.join(', ')}</span> : null}
+ </li>
+ ))}
+ </ul>
+ )}
+ </li>
+ );
+};
+
const Notes: React.FC<{ items: string[]; tone: 'warn' | 'drop' | 'problem'; label: string }> = ({ items, tone, label }) =>
items.length === 0 ? null : (
<div>
<p className={`text-[11px] font-medium ${tone === 'problem' ? 'text-rose-300' : tone === 'warn' ? 'text-amber-300' : 'text-zinc-400'}`}>{label}</p>
- <ul className={`list-disc pl-5 text-[11px] ${tone === 'problem' ? 'text-rose-200/90' : tone === 'warn' ? 'text-amber-100/80' : 'text-zinc-500'}`}>
- {items.map((m, i) => <li key={i}>{m}</li>)}
+ <ul className={`list-disc pl-5 text-[11px] break-words ${tone === 'problem' ? 'text-rose-200/90' : tone === 'warn' ? 'text-amber-100/80' : 'text-zinc-500'}`}>
+ {items.map((m, i) => {
+ const tools = tone === 'warn' ? toolNote(m) : null;
+ return tools ? <ToolNoteItem key={i} note={tools} /> : <li key={i}>{m}</li>;
+ })}
</ul>
</div>
);
diff --git a/frontend/src/components/ModernApprovalCard.tsx b/frontend/src/components/ModernApprovalCard.tsx
index 2834136d..d6ae19e1 100644
--- a/frontend/src/components/ModernApprovalCard.tsx
+++ b/frontend/src/components/ModernApprovalCard.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { ShieldAlert, Check, CheckCheck, X, Plug } from 'lucide-react';
+import { ShieldAlert, Check, CheckCheck, X, Plug, FileText, Terminal } from 'lucide-react';
import { playSfx } from '../audio/chiptune';
import { formatArgs, humanizeToolName, parseMcpToolName } from '../mcp';
@@ -38,6 +38,42 @@ export const localShellView = (approval: PendingApproval) => {
};
};
+const BUILTIN_SHELL = ['Bash'];
+const BUILTIN_FILE = ['Write', 'Edit', 'MultiEdit', 'NotebookEdit'];
+const s = (v: unknown) => (typeof v === 'string' && v ? v : null);
+
+/**
+ * A Claude CLI built-in tool (Bash, Write, Edit, ...) the bot asks to use: the command or file in
+ * plain words, or null for other tools. Reads `details.arguments` (or `details.input`, the CLI's
+ * own name for it) and works without `source` when the tool name is a known built-in.
+ */
+export const builtinView = (approval: PendingApproval) => {
+ const d = approval.details ?? {};
+ const tool = s(d.tool) ?? approval.tool_name;
+ const known = BUILTIN_SHELL.includes(tool) || BUILTIN_FILE.includes(tool);
+ if (d.source !== 'claude_builtin' && !known) return null;
+ const raw = d.arguments ?? d.input;
+ const args = (raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}) as Record<string, unknown>;
+ const base = { tool, kwant: s(d.kwant_name), cwd: s(d.cwd), outsideFolder: d.outside_folder === true };
+ if (BUILTIN_SHELL.includes(tool)) {
+ return { ...base, kind: 'shell' as const, command: s(args.command) ?? '', description: s(args.description), path: null, change: null };
+ }
+ if (BUILTIN_FILE.includes(tool)) {
+ const path = s(args.file_path) ?? s(args.notebook_path) ?? s(args.path);
+ const edits = Array.isArray(args.edits) ? args.edits.length : 0;
+ const change =
+ tool === 'Write'
+ ? `Write ${typeof args.content === 'string' ? `${args.content.split('\n').length} lines` : 'the file'}`
+ : tool === 'MultiEdit'
+ ? `${edits} ${edits === 1 ? 'edit' : 'edits'}`
+ : tool === 'NotebookEdit'
+ ? 'Change a notebook cell'
+ : 'Replace text';
+ return { ...base, kind: 'file' as const, command: null, description: null, path, change };
+ }
+ return { ...base, kind: 'other' as const, command: null, description: null, path: null, change: null, args: formatArgs(args) };
+};
+
export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
approval,
onResolve,
@@ -48,6 +84,8 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
};
const mcp = mcpView(approval);
const shell = localShellView(approval);
+ const builtin = shell || mcp ? null : builtinView(approval);
+ const who = builtin?.kwant ? <span className="font-medium text-zinc-100">{builtin.kwant}</span> : 'A bot';
return (
<div className="my-3 border border-amber-500/30 bg-amber-950/20 rounded-xl p-4 text-zinc-100 max-w-2xl shadow-lg backdrop-blur-sm">
@@ -68,6 +106,57 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
</p>
)}
</div>
+ ) : builtin?.kind === 'shell' ? (
+ <div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs space-y-2 mb-3">
+ <p className="flex items-center gap-1.5 text-zinc-300">
+ <Terminal size={13} className="shrink-0 text-sky-400" aria-hidden="true" />
+ <span>{who} wants to run a command.</span>
+ </p>
+ {builtin.description && <p className="text-zinc-400 break-words">{builtin.description}</p>}
+ <pre className="font-mono text-[11px] text-zinc-100 bg-zinc-950/70 border border-zinc-800 rounded-md p-2 whitespace-pre-wrap break-all max-h-64 overflow-y-auto">
+ {builtin.command || '(empty command)'}
+ </pre>
+ {builtin.cwd && (
+ <p className="text-[11px] text-zinc-400 break-all">
+ <span className="text-zinc-500">In folder:</span> <span className="font-mono text-zinc-300">{builtin.cwd}</span>
+ </p>
+ )}
+ </div>
+ ) : builtin?.kind === 'file' ? (
+ <div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs space-y-2 mb-3">
+ <p className="flex items-center gap-1.5 text-zinc-300">
+ <FileText size={13} className="shrink-0 text-sky-400" aria-hidden="true" />
+ <span>
+ {who} wants to {builtin.tool === 'Write' ? 'write a file' : 'change a file'}
+ {builtin.outsideFolder ? ' outside its own folder' : ''}.
+ </span>
+ </p>
+ <p className="font-mono text-[11px] text-zinc-100 bg-zinc-950/70 border border-zinc-800 rounded-md p-2 break-all">
+ {builtin.path || '(no file given)'}
+ </p>
+ <p className="text-[11px] text-zinc-400 break-words">
+ {builtin.change}
+ {builtin.cwd && (
+ <>
+ {' · '}
+ <span className="text-zinc-500">Its folder:</span> <span className="font-mono text-zinc-300 break-all">{builtin.cwd}</span>
+ </>
+ )}
+ </p>
+ </div>
+ ) : builtin ? (
+ <div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs space-y-2 mb-3">
+ <p className="text-zinc-300">
+ {who} wants to use <span className="font-medium text-sky-200">{builtin.tool}</span>.
+ </p>
+ {'args' in builtin && builtin.args ? (
+ <pre className="font-mono text-[11px] text-zinc-300 bg-zinc-950/70 border border-zinc-800 rounded-md p-2 whitespace-pre-wrap break-all max-h-48 overflow-y-auto">
+ {builtin.args}
+ </pre>
+ ) : (
+ <p className="text-[11px] text-zinc-500">No arguments.</p>
+ )}
+ </div>
) : mcp ? (
<div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs space-y-2 mb-3">
<p className="text-zinc-300">
@@ -104,16 +193,18 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
<div className="flex flex-wrap items-center justify-end gap-2">
<button
+ type="button"
onClick={() => handleDecision('deny')}
- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800 hover:bg-zinc-700 transition-colors"
+ className="flex items-center gap-1.5 px-3 py-1.5 min-h-[40px] sm:min-h-0 rounded-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 text-xs font-medium text-zinc-300 bg-zinc-800 hover:bg-zinc-700 transition-colors"
>
<X size={14} />
<span>Deny</span>
</button>
<button
+ type="button"
onClick={() => handleDecision('allow_once')}
- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-emerald-600 hover:bg-emerald-500 transition-colors shadow-sm"
+ className="flex items-center gap-1.5 px-3 py-1.5 min-h-[40px] sm:min-h-0 rounded-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 text-xs font-medium text-white bg-emerald-600 hover:bg-emerald-500 transition-colors shadow-sm"
>
<Check size={14} />
<span>Allow Once</span>
@@ -122,12 +213,13 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
{/* Local shell approvals are never remembered, so only offer a one-off answer. */}
{!shell && (
<button
+ type="button"
onClick={() => handleDecision('always_allow')}
- title={mcp ? 'Allow this tool for this bot until the app restarts' : undefined}
- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm"
+ title={mcp || builtin ? 'Allow this tool for this bot until the app restarts' : undefined}
+ className="flex items-center gap-1.5 px-3 py-1.5 min-h-[40px] sm:min-h-0 rounded-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm"
>
<CheckCheck size={14} />
- <span>Always Allow</span>
+ <span>{builtin ? 'Always this session' : 'Always Allow'}</span>
</button>
)}
</div>
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsx
index 3bca16ba..e61b3dca 100644
--- a/frontend/src/components/NewAgentModal.tsx
+++ b/frontend/src/components/NewAgentModal.tsx
@@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react';
-import { X, Sparkles, Pencil, ChevronRight, Brain, CalendarClock, UserRound, ListChecks } from 'lucide-react';
+import { X, Sparkles, Pencil, ChevronRight, Brain, CalendarClock, UserRound, ListChecks, Trash2 } from 'lucide-react';
import { ModernAvatar, AVATAR_STYLES } from './ModernAvatar';
import { AGENT_PRESETS, AgentPreset, PRESET_GROUPS, PresetGroup, uniqueAgentName } from '../agentPresets';
import { playSfx } from '../audio/chiptune';
@@ -67,6 +67,8 @@ interface NewAgentModalProps {
initialTab?: EditTab;
/** Skills waiting for review, shown as a count on the Skills tab. */
pendingSkills?: number;
+ /** Editing only: opens the Delete bot confirm. */
+ onRequestDelete?: () => void;
}
export const NewAgentModal: React.FC<NewAgentModalProps> = ({
@@ -87,6 +89,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
channels = [],
initialTab = 'profile',
pendingSkills = 0,
+ onRequestDelete,
}) => {
const [tab, setTab] = useState<EditTab>('profile');
const [name, setName] = useState('');
@@ -460,7 +463,20 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
{error && <p className="text-[11px] text-rose-400">{error}</p>}
- <div className="flex items-center justify-end gap-2.5 pt-2 border-t border-zinc-800">
+ <div className="flex flex-wrap items-center justify-end gap-2.5 pt-2 border-t border-zinc-800">
+ {isEdit && onRequestDelete && (
+ <button
+ type="button"
+ onClick={() => {
+ playSfx('click');
+ onRequestDelete();
+ }}
+ className="mr-auto inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-rose-300 hover:text-rose-200 hover:bg-rose-500/10 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-rose-400"
+ >
+ <Trash2 size={13} aria-hidden="true" />
+ Delete bot
+ </button>
+ )}
<button
type="button"
onClick={() => {
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 07322365..e90a23bf 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -423,8 +423,9 @@ export const Sidebar: React.FC<SidebarProps> = ({
e.stopPropagation();
onEditKwant(k);
}}
- className="opacity-0 group-hover/member:opacity-100 p-0.5 rounded text-zinc-500 hover:text-sky-300 hover:bg-sky-500/10 transition-all"
- title={`Edit ${k.name}`}
+ className="opacity-0 group-hover/member:opacity-100 max-sm:opacity-100 focus-visible:opacity-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 p-0.5 rounded text-zinc-500 hover:text-sky-300 hover:bg-sky-500/10 transition-all"
+ title={`Edit or delete ${k.name}`}
+ aria-label={`Edit or delete ${k.name}`}
>
<Pencil size={11} />
</button>
@@ -442,7 +443,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
e.stopPropagation();
onUpdateTeamMembers(t, memberIds.filter((id) => id !== k.id));
}}
- className="opacity-0 group-hover/member:opacity-100 p-0.5 rounded text-zinc-500 hover:text-rose-300 hover:bg-rose-500/10 transition-all"
+ className="opacity-0 group-hover/member:opacity-100 max-sm:opacity-100 focus-visible:opacity-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 p-0.5 rounded text-zinc-500 hover:text-rose-300 hover:bg-rose-500/10 transition-all"
title={`Remove ${k.name} from @${t.name}`}
>
<X size={11} />
@@ -582,8 +583,9 @@ export const Sidebar: React.FC<SidebarProps> = ({
e.stopPropagation();
onEditKwant(k);
}}
- className="ml-auto opacity-0 group-hover/fleet:opacity-100 p-0.5 rounded text-zinc-500 hover:text-sky-300 hover:bg-sky-500/10 transition-all"
- title={`Edit ${k.name}`}
+ className="ml-auto opacity-0 group-hover/fleet:opacity-100 max-sm:opacity-100 focus-visible:opacity-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 p-0.5 rounded text-zinc-500 hover:text-sky-300 hover:bg-sky-500/10 transition-all"
+ title={`Edit or delete ${k.name}`}
+ aria-label={`Edit or delete ${k.name}`}
>
<Pencil size={11} />
</button>
diff --git a/frontend/src/imports.ts b/frontend/src/imports.ts
index e75c5b04..25f67201 100644
--- a/frontend/src/imports.ts
+++ b/frontend/src/imports.ts
@@ -326,3 +326,55 @@ export function trapFocusTarget(count: number, index: number, shift: boolean): n
if (!shift && index === count - 1) return 0;
return null;
}
+
+/** The server's "It used tools (a, b, c). Imported bots start with no tools; …" notice, split up. */
+const TOOL_NOTE = /^It used tools \((.*)\)\.\s*(.*)$/s;
+
+/** "mcp__gmail__send_email", "gmail.send", "Gmail: send" → "gmail"; a plain name stays whole. */
+function appOf(hint: string): string | null {
+ const t = hint.trim();
+ const mcp = /^mcp__(.+?)__/.exec(t);
+ if (mcp) return mcp[1];
+ const sep = /^([^\s.:/]+)\s*(?:\.|:|\/|__)\s*\S/.exec(t);
+ return sep ? sep[1] : null;
+}
+
+const appLabel = (name: string) => {
+ // claude.ai connectors arrive as "claude_ai_Notion".
+ const words = name.replace(/^claude[_.]ai[_-]+/i, '').replace(/[_-]+/g, ' ').trim();
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : name;
+};
+
+export interface ToolNote {
+ /** Apps (or tools that name no app) in first-seen order, each with the tools it listed. */
+ apps: Array<{ name: string; tools: string[] }>;
+ /** The rest of the sentence: "Imported bots start with no tools; connect the ones it needs." */
+ tail: string;
+}
+
+/**
+ * The tool notice grouped by app, so 40 tool names read as a few app names; null for any other
+ * notice. snake_case names group on their first word only when another hint shares it.
+ */
+export function toolNote(message: string): ToolNote | null {
+ const m = TOOL_NOTE.exec(message);
+ if (!m) return null;
+ const hints = m[1].split(/,\s*/).map((h) => h.trim()).filter(Boolean);
+ if (hints.length === 0) return null;
+ const first = (h: string) => (/^[a-z0-9]+_[a-z0-9_]+$/i.test(h) ? h.split('_')[0].toLowerCase() : null);
+ const counts = new Map<string, number>();
+ for (const h of hints) {
+ const f = first(h);
+ if (f) counts.set(f, (counts.get(f) ?? 0) + 1);
+ }
+ const groups = new Map<string, { name: string; tools: string[] }>();
+ for (const h of hints) {
+ const f = first(h);
+ const app = appOf(h) ?? (f && (counts.get(f) ?? 0) > 1 ? f : h);
+ const key = app.toLowerCase();
+ const g = groups.get(key) ?? { name: appLabel(app), tools: [] };
+ if (!g.tools.includes(h)) g.tools.push(h);
+ groups.set(key, g);
+ }
+ return { apps: [...groups.values()], tail: m[2].trim() };
+}
diff --git a/frontend/src/routeReason.ts b/frontend/src/routeReason.ts
new file mode 100644
index 00000000..d5143cae
--- /dev/null
+++ b/frontend/src/routeReason.ts
@@ -0,0 +1,28 @@
+// The line under "Sending your question to X" on Laya's routing card: why that bot, in words that
+// match how it was actually picked.
+
+export type RouteBasis = 'skills' | 'lead' | 'keywords' | 'only';
+
+export interface RouteReasonInput {
+ kwantName?: string;
+ reason?: string;
+ basis?: string;
+ fallback?: boolean;
+ matchedTerms?: string[];
+}
+
+export function routeReasonText(r: RouteReasonInput): string | null {
+ const name = r.kwantName || 'the team lead';
+ const terms = (r.matchedTerms ?? []).filter(Boolean).slice(0, 4);
+ switch (r.basis) {
+ case 'lead':
+ return `No one’s role matched this, so it went to the team lead, ${name}.`;
+ case 'only':
+ return `${name} is the only bot here that can answer.`;
+ case 'keywords':
+ return terms.length ? `Picked by matching words: ${terms.join(', ')}.` : 'Picked by matching words in your message.';
+ default:
+ // Older servers phrase every pick, even the lead fallback, as "Laya picked …".
+ return r.reason || null;
+ }
+}
diff --git a/frontend/src/spaces.ts b/frontend/src/spaces.ts
index 666480e2..937696e0 100644
--- a/frontend/src/spaces.ts
+++ b/frontend/src/spaces.ts
@@ -249,6 +249,8 @@ export interface RoutingMeta {
candidate_count?: number | null;
fallback?: boolean;
matched_terms?: string[];
+ /** 'lead' when no role matched and the team lead took it; see routeReason.ts. */
+ basis?: string;
}
export function parseRoutingMeta(meta: string | null | undefined): RoutingMeta | null {
@@ -267,6 +269,8 @@ export function routingLine(r: RoutingMeta, spaceName: string): string {
const pool = n ? `from ${n} ${n === 1 ? 'bot' : 'bots'} in ${spaceName}` : `in ${spaceName}`;
const matched = r.matched_terms?.length ? ` · matched ${r.matched_terms.map((t) => `'${t}'`).join(', ')}` : '';
if (r.fallback) return `Picked by keywords (Laya is offline) · ${r.kwant_name} ${pool}${matched}`;
+ if (r.basis === 'lead') return `No one’s role matched, so the team lead ${r.kwant_name} took it ${pool}`;
+ if (r.basis === 'only') return `${r.kwant_name} is the only bot that can answer ${pool}`;
return `Laya picked ${r.kwant_name} ${pool}${matched}`;
}
diff --git a/frontend/tests/botCapabilities.test.mjs b/frontend/tests/botCapabilities.test.mjs
new file mode 100644
index 00000000..28d7e46e
--- /dev/null
+++ b/frontend/tests/botCapabilities.test.mjs
@@ -0,0 +1,170 @@
+// Oleks's Mac findings (2026-10-19): Delete bot, team hires on one card, readable approval cards
+// for Claude CLI built-in tools, a short tool list in Import, and an honest routing line.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
+
+const m = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { ModernApprovalCard } from './src/components/ModernApprovalCard';
+ import { HireCard } from './src/components/HireCard';
+ import { DeleteBotDialog } from './src/components/DeleteBotDialog';
+ import { PreviewView } from './src/components/ImportDialog';
+ export { builtinView } from './src/components/ModernApprovalCard';
+ export { parseHireMeta, hireStateText, hiredBotGone, isTeamHire } from './src/botActions';
+ export { lossLines, parseUsage, deleteBlockedReason } from './src/botDelete';
+ export { toolNote } from './src/imports';
+ export { routeReasonText } from './src/routeReason';
+ export { routingLine } from './src/spaces';
+ const r = (C, p) => renderToStaticMarkup(React.createElement(C, p));
+ export const approval = (a) => r(ModernApprovalCard, { approval: a, onResolve: () => {} });
+ export const hire = (p) => r(HireCard, p);
+ export const del = (p) => r(DeleteBotDialog, { onClose: () => {}, onDeleted: () => {}, ...p });
+ export const preview = (p) => r(PreviewView, { skip: new Set(), onToggle: () => {}, ...p });
+`);
+
+const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/’/g, "'").replace(/&#x27;|&#39;/g, "'").replace(/&quot;/g, '"').replace(/&amp;/g, '&').replace(/\s+/g, ' ').trim();
+const buttons = (html) => [...html.matchAll(/<button[^>]*>([\s\S]*?)<\/button>/g)].map((x) => text(x[1]));
+
+// ---------------------------------------------------------------- built-in tool approvals
+
+const bash = { id: 'b1', tool_name: 'Bash', details: { source: 'claude_builtin', tool: 'Bash', kwant_name: 'Frontend', cwd: '/Users/oleks/trader', arguments: { command: 'go test ./internal/strategy/', description: 'Run the strategy tests' } } };
+
+test('a Bash approval shows who, the command and the folder, with the three choices, and no raw JSON', () => {
+ const html = m.approval(bash);
+ const t = text(html);
+ assert.match(t, /Frontend wants to run a command\./);
+ assert.match(t, /Run the strategy tests/);
+ assert.match(html, /<pre[^>]*>go test \.\/internal\/strategy\/<\/pre>/);
+ assert.match(t, /In folder: \/Users\/oleks\/trader/);
+ assert.deepEqual(buttons(html), ['Deny', 'Allow Once', 'Always this session']);
+ assert.doesNotMatch(html, /&quot;source&quot;|claude_builtin|kwant_name/);
+});
+
+test('a Write outside its folder names the file, the size and its own folder', () => {
+ const html = m.approval({ id: 'w1', tool_name: 'Write', details: { source: 'claude_builtin', tool: 'Write', kwant_name: 'Frontend', cwd: '/Users/oleks/bots/frontend', outside_folder: true, arguments: { file_path: '/Users/oleks/trader/internal/strategy/smacross.go', content: 'package strategy\n\nfunc x() {}\n' } } });
+ const t = text(html);
+ assert.match(t, /Frontend wants to write a file outside its own folder\./);
+ assert.match(t, /\/Users\/oleks\/trader\/internal\/strategy\/smacross\.go/);
+ assert.match(t, /Write 4 lines/);
+ assert.match(t, /Its folder: \/Users\/oleks\/bots\/frontend/);
+ assert.doesNotMatch(t, /package strategy/, 'file contents are not dumped on the card');
+});
+
+test('built-ins are recognised by tool name alone, with the CLI input field', () => {
+ const v = m.builtinView({ id: 'e', tool_name: 'Edit', details: { input: { file_path: '/a.go', old_string: 'a', new_string: 'b' } } });
+ assert.equal(v.kind, 'file');
+ assert.equal(v.path, '/a.go');
+ assert.equal(v.change, 'Replace text');
+ assert.equal(m.builtinView({ id: 'x', tool_name: 'write_file', details: {} }), null, 'unknown tools keep the old card');
+ assert.equal(m.builtinView({ id: 'x', tool_name: 'Bash', details: null }).command, '');
+});
+
+// ---------------------------------------------------------------- team hires
+
+const hireMeta = (over = {}) => ({
+ kind: 'hire_proposal', hire_id: 'h1', kwant_id: 'k1', proposer_name: 'Backend', name: 'Frontend', role: 'Frontend Engineer',
+ instructions: 'Own the UI.', model: 'auto', tools: [], team: null, reason: 'You asked for a professional engineering team.',
+ evidence: null, requested_by_person: true, status: 'pending', auto: false, choices: ['deny', 'accept_once', 'always_accept'],
+ hired_kwant_id: null, action_id: null, can_undo: false, policy: 'ask', note: null, created_at: '2026-10-19T10:00:00Z', resolved_at: null,
+ members: [
+ { name: 'Frontend', role: 'Frontend Engineer', model: 'auto', tools: [], instructions: 'Own the UI.' },
+ { name: 'QA', role: 'QA / Test Engineer', model: 'claude-sonnet-5-5', tools: [{ id: 's', name: 'Browser' }], instructions: 'Test it.' },
+ { name: 'Lead', role: 'Tech Lead', model: null, tools: [], instructions: '' },
+ ],
+ new_team: { name: 'Engineering' },
+ ...over,
+});
+const hireProps = (meta) => ({ meta: m.parseHireMeta(meta), messageId: 'm1', kwantName: 'Backend', kwantId: 'k1', onDecide: async () => {} });
+
+test('a team proposal lists every member with role and model, and asks once', () => {
+ const html = m.hire(hireProps(hireMeta()));
+ const t = text(html);
+ assert.match(t, /Backend proposes hiring a team of 3/);
+ assert.match(t, /Engineering/);
+ for (const s of ['Frontend Frontend Engineer Picked automatically', 'QA QA \/ Test Engineer claude-sonnet-5-5 · Tools: Browser', 'Lead Tech Lead Picked automatically']) assert.match(t, new RegExp(s));
+ assert.match(t, /New team: Engineering/);
+ assert.deepEqual(buttons(html), ['Show their instructions', 'Approve all 3', 'Always accept', 'Decline']);
+});
+
+test('a single hire still reads as before; old metas without members parse as one', () => {
+ const one = m.parseHireMeta(hireMeta({ members: undefined, new_team: undefined }));
+ assert.equal(one.members.length, 1);
+ assert.equal(m.isTeamHire(one), false);
+ const t = text(m.hire(hireProps(hireMeta({ members: undefined, new_team: undefined }))));
+ assert.match(t, /proposes hiring a new bot/);
+ assert.match(t, /Accept once/);
+});
+
+test('team state lines name everyone; gone only when every hired bot is gone', () => {
+ const h = m.parseHireMeta(hireMeta({ status: 'accepted', hired_kwant_ids: ['a', 'b', 'c'] }));
+ assert.equal(m.hireStateText(h).label, 'Hired. Frontend, QA and Lead joined Engineering.');
+ assert.equal(m.hiredBotGone(h, new Set(['b'])), false);
+ assert.equal(m.hiredBotGone(h, new Set()), true);
+});
+
+// ---------------------------------------------------------------- delete bot
+
+test('the delete confirm names what goes, offers Export, and starts safe', () => {
+ const html = m.del({ kwant: { id: 'k1', name: 'Frontend' } });
+ const t = text(html);
+ assert.match(html, /role="alertdialog"/);
+ assert.match(t, /Delete Frontend\?/);
+ assert.match(t, /can't be undone/);
+ for (const s of ['conversations', 'memory', 'skills', 'routines']) assert.match(t, new RegExp(s));
+ assert.deepEqual(buttons(html), ['Export Frontend', 'Cancel', 'Delete Frontend']);
+});
+
+test('Delete is off with a reason while the bot works', () => {
+ const html = m.del({ kwant: { id: 'k1', name: 'Frontend' }, busy: 'Working on #general' });
+ assert.match(text(html), /Frontend is working right now\. Stop it or wait until it finishes, then delete it\./);
+ assert.match(html, /<button[^>]*disabled=""[^>]*>[\s\S]*?Delete Frontend<\/button>/);
+ assert.equal(m.deleteBlockedReason('X', null, m.parseUsage({ running: true })), 'X is working right now. Stop it or wait until it finishes, then delete it.');
+ assert.equal(m.deleteBlockedReason('X', null, null), null);
+});
+
+test('loss lines use counts when the server gives them', () => {
+ assert.deepEqual(m.lossLines(m.parseUsage({ conversations: 12, memories: 1, skills: 0, routines: 2 })), ['12 conversations', '1 memory', '0 skills', '2 routines']);
+ assert.equal(m.parseUsage(null), null);
+ assert.equal(m.lossLines(null).length, 4);
+});
+
+// ---------------------------------------------------------------- import tool list
+
+const LONG = 'It used tools (mcp__agents__coordinate_bots, mcp__agents__memory_update, mcp__agents__session_search, mcp__browser__agent_browser_open, mcp__browser__agent_browser_click, mcp__claude_ai_Notion__notion-search, mcp__claude_ai_Gmail__send, mcp__composio__COMPOSIO_SEARCH_TOOLS, mcp__claude_ai_Canva__create-design, WebSearch, Bash). Imported bots start with no tools; connect the ones it needs.';
+
+test('a long tool notice groups by app', () => {
+ const n = m.toolNote(LONG);
+ assert.deepEqual(n.apps.map((a) => a.name), ['Agents', 'Browser', 'Notion', 'Gmail', 'Composio', 'Canva', 'WebSearch', 'Bash']);
+ assert.deepEqual(n.apps[0].tools.length, 3);
+ assert.equal(n.tail, 'Imported bots start with no tools; connect the ones it needs.');
+ assert.equal(m.toolNote('Routine X: paused.'), null);
+});
+
+test('the preview shows five app names and "Show all", not every tool', () => {
+ const p = {
+ bundle: { format: 'kwant.bundle/1', source: { kind: 'openmausbot' }, bots: [{ ref: 'b1', name: 'Personal assistant', persona_prompt: 'Helps.' }] },
+ warnings: [{ bot: 'b1', message: LONG }], dropped: [], problems: [], renames: [], can_apply: true,
+ };
+ const html = m.preview({ preview: p });
+ const t = text(html);
+ assert.match(t, /It used tools from 8 apps: Agents, Browser, Notion, Gmail, Composio and 3 more\./);
+ assert.match(html, /aria-expanded="false"[^>]*>Show all</);
+ assert.doesNotMatch(t, /coordinate_bots/);
+});
+
+test('a one-app tool note reads as a sentence', () => {
+ assert.match(text(m.preview({ preview: { bundle: { format: 'kwant.bundle/1', source: { kind: 'openmausbot' }, bots: [{ ref: 'b1', name: 'A', persona_prompt: '' }] }, warnings: [{ bot: 'b1', message: 'It used tools (mcp__claude_ai_Notion__notion-search). Connect it.' }], dropped: [], problems: [], renames: [], can_apply: true } })), /It used tools from Notion\. Connect it\./);
+});
+
+// ---------------------------------------------------------------- routing
+
+test('the routing line says when the team lead took it because no role matched', () => {
+ assert.equal(m.routeReasonText({ kwantName: 'Ada', basis: 'lead', reason: 'Laya picked Ada (Tech Lead) as the best fit for this question' }), 'No one’s role matched this, so it went to the team lead, Ada.');
+ assert.equal(m.routeReasonText({ kwantName: 'Lin', reason: 'Laya picked Lin (Backend) as the best fit' }), 'Laya picked Lin (Backend) as the best fit');
+ assert.equal(m.routeReasonText({ basis: 'keywords', matchedTerms: ['strategy', 'go'] }), 'Picked by matching words: strategy, go.');
+ assert.match(m.routingLine({ kwant_name: 'Ada', basis: 'lead', candidate_count: 4 }, 'Work'), /^No one’s role matched, so the team lead Ada took it from 4 bots in Work$/);
+});