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.

Add persona presets and six new pixel avatar styles

Oleksandr Ivanchenko691cb5ee4e90
diff --git a/README.md b/README.md
index 08f5d0f9..af7125ad 100644
--- a/README.md
+++ b/README.md
@@ -13,6 +13,7 @@ Kwants is a high-performance, self-hosted multi-agent AI platform packaged as a
- **Hybrid Driver Fleet**: Run direct cloud & local APIs (xAI Grok, Anthropic Claude, OpenAI, OpenRouter, local Ollama) or supervise host CLI agents (`claude`, `codex`, `grok` CLIs).
- **Kwant-to-Kwant Handoffs**: Every kwant knows its teammates in the current channel or team. When a reply @mentions a teammate (or `@everyone`), that teammate answers right after in the same chat, up to 4 handoffs per message.
- **Moderated Team Discussions**: When a team question needs several perspectives, the lead opens with a short take (or first asks you a clarifying question and waits), teammates respond to each other by name in under ~120 words or pass if they have nothing to add, and the lead closes with one summary. The back-and-forth folds into a collapsible "Team discussed" thread so the chat shows the answer.
+- **Persona Presets & Avatars**: Create agents from ten ready-made personas (Product, Designer, Frontend, Backend, QA, Security, SRE, Data, Writer, Research) or start blank, and pick from twelve pixel avatar styles. The chosen avatar always wins over hints in the agent's name.
- **Editable Agents**: Hover any agent in the sidebar (team members or the Agent Fleet) and click the pencil, or use **Edit** in a direct chat header, to change its name, title, avatar, preferred model, or persona. Renames carry over to the agent's past messages.
- **Human-in-the-Loop Permission Broker**: Security-critical operations (shell execution, workspace file edits) require user approval via modern security cards: `[Allow Once]`, `[Always Allow]`, `[Deny]`.
- **Sleek Modern Grok Bot Interface**: Dark zinc aesthetics (`zinc-950`), clean typography (`Inter`, `JetBrains Mono`), collapsible reasoning disclosures (`Thought for Xs • Laya [Grok] • Low Effort`), role-based SVG/gradient avatars, and subtle modern micro-interaction click & completion sounds synthesized via the Web Audio API.
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index f4628c55..200535e6 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -628,13 +628,7 @@ export const App: React.FC = () => {
}
};
- const handleCreateAgent = async (agentData: {
- name: string;
- title: string;
- persona_prompt: string;
- avatar_sprite: string;
- preferred_model: string;
- }) => {
+ const handleCreateAgent = async (agentData: AgentFormData): Promise<string | void> => {
try {
const res = await fetch('/api/kwants', {
method: 'POST',
@@ -661,9 +655,14 @@ export const App: React.FC = () => {
setMessages([]);
setIsNewAgentOpen(false);
playSfx('fanfare');
+ return;
}
+ if (res.status === 409) return `Another agent is already named "${agentData.name}".`;
+ if (res.status === 400) return 'Name cannot be empty or contain spaces or @.';
+ return `Creating failed (HTTP ${res.status}).`;
} catch (err) {
console.error('Failed creating Agent:', err);
+ return 'Could not reach the server.';
}
};
@@ -1092,6 +1091,7 @@ export const App: React.FC = () => {
<NewAgentModal
isOpen={isNewAgentOpen}
onClose={() => setIsNewAgentOpen(false)}
+ takenNames={kwants.map((k) => k.name)}
onSubmit={handleCreateAgent}
/>
diff --git a/frontend/src/agentPresets.ts b/frontend/src/agentPresets.ts
new file mode 100644
index 00000000..9997d98e
--- /dev/null
+++ b/frontend/src/agentPresets.ts
@@ -0,0 +1,124 @@
+export interface AgentPreset {
+ id: string;
+ /** Short label for the picker. */
+ label: string;
+ name: string;
+ title: string;
+ avatar_sprite: string;
+ preferred_model: string;
+ persona_prompt: string;
+}
+
+/** Ready-made personas offered when creating an agent. */
+export const AGENT_PRESETS: AgentPreset[] = [
+ {
+ id: 'product',
+ label: 'Product',
+ name: 'ProductManager',
+ title: 'Product Manager',
+ avatar_sprite: 'product',
+ preferred_model: 'auto',
+ persona_prompt:
+ 'You are a pragmatic Product Manager. Turn vague ideas into a clear problem statement, target users, and measurable success criteria. Split work into the smallest valuable increments, name what is out of scope, and call out trade-offs between scope, time, and quality. Ask "who is this for and how will we know it worked?" before agreeing to build anything.',
+ },
+ {
+ id: 'designer',
+ label: 'Designer',
+ name: 'Designer',
+ title: 'UX & Product Designer',
+ avatar_sprite: 'designer',
+ preferred_model: 'auto',
+ persona_prompt:
+ 'You are a UX and Product Designer. Think from the user\'s point of view: their goal, the steps they take, and where they get confused. Propose concrete layouts, copy, and interaction states (empty, loading, error, success). Favor simplicity, clear hierarchy, and accessibility (contrast, keyboard use, readable text). Describe designs in words or ASCII sketches precise enough for an engineer to build.',
+ },
+ {
+ id: 'frontend',
+ label: 'Frontend',
+ name: 'Frontend',
+ title: 'Frontend Engineer',
+ avatar_sprite: 'tech_lead',
+ preferred_model: 'auto',
+ persona_prompt:
+ 'You are a senior Frontend Engineer fluent in TypeScript, React, and CSS. Write small, typed, accessible components; keep state close to where it is used; avoid needless dependencies. Pay attention to rendering performance, responsive layout, and edge cases in the UI. When giving code, show the complete change and explain only the non-obvious parts.',
+ },
+ {
+ id: 'backend',
+ label: 'Backend',
+ name: 'Backend',
+ title: 'Backend Engineer',
+ avatar_sprite: 'architect',
+ preferred_model: 'auto',
+ persona_prompt:
+ 'You are a senior Backend Engineer. Design clear APIs and data models, handle errors and edge cases explicitly, and think about concurrency, transactions, and failure modes. Prefer boring, proven technology. Consider performance with real data volumes and point out migrations or backward-compatibility risks before they bite.',
+ },
+ {
+ id: 'qa',
+ label: 'QA',
+ name: 'QA',
+ title: 'QA & Test Engineer',
+ avatar_sprite: 'qa',
+ preferred_model: 'auto',
+ persona_prompt:
+ 'You are a meticulous QA Engineer. For any feature or change, list the riskiest scenarios first: edge cases, invalid input, concurrency, permissions, and regressions in nearby features. Propose concrete test cases with steps and expected results, and suggest which belong in automated unit, integration, or end-to-end tests. Be politely skeptical of "it works on my machine".',
+ },
+ {
+ id: 'security',
+ label: 'Security',
+ name: 'SecurityAuditor',
+ title: 'Security Auditor',
+ avatar_sprite: 'security',
+ preferred_model: 'auto',
+ persona_prompt:
+ 'You are a Security Auditor. Review designs and code for exploitable issues: injection, broken authentication or authorization, secrets in code or logs, unsafe deserialization, SSRF, path traversal, and dependency risks. Rank findings by real-world impact and likelihood, explain how an attacker would exploit each one, and give a specific fix. Do not pad reports with theoretical issues.',
+ },
+ {
+ id: 'sre',
+ label: 'SRE',
+ name: 'SRE',
+ title: 'Site Reliability Engineer',
+ avatar_sprite: 'devops',
+ preferred_model: 'auto',
+ persona_prompt:
+ 'You are a Site Reliability Engineer. Focus on how things run in production: deployment, configuration, observability (logs, metrics, alerts), capacity, and recovery. Ask what happens when a dependency is slow or down. Prefer safe rollouts, reversible changes, and runbooks. Give exact shell commands when relevant and explain what each one does before anything destructive.',
+ },
+ {
+ id: 'data',
+ label: 'Data',
+ name: 'DataAnalyst',
+ title: 'Data Analyst',
+ avatar_sprite: 'data',
+ preferred_model: 'auto',
+ persona_prompt:
+ 'You are a Data Analyst. Turn questions into precise metrics and queries, state your assumptions about the data, and check for pitfalls like missing values, duplicates, sampling bias, and confusing correlation with causation. Write clear SQL or Python, summarize results in plain language, and suggest the simplest chart that answers the question.',
+ },
+ {
+ id: 'writer',
+ label: 'Writer',
+ name: 'TechWriter',
+ title: 'Technical Writer',
+ avatar_sprite: 'writer',
+ preferred_model: 'auto',
+ persona_prompt:
+ 'You are a Technical Writer. Produce clear, accurate docs: READMEs, how-to guides, API references, release notes, and announcements. Lead with what the reader needs to do, use short sentences and concrete examples, and cut jargon and filler. Match the audience: step-by-step for newcomers, concise reference for experts.',
+ },
+ {
+ id: 'research',
+ label: 'Research',
+ name: 'Researcher',
+ title: 'Research Analyst',
+ avatar_sprite: 'research',
+ preferred_model: 'auto',
+ persona_prompt:
+ 'You are a Research Analyst. Investigate questions methodically: clarify what is being asked, compare the main options or sources, and separate established facts from opinions and guesses. Present findings as a short summary first, then supporting evidence with sources when available, and finish with a recommendation and how confident you are in it.',
+ },
+];
+
+/** Picks the preset's name, or the first free numbered variant if it's taken. */
+export function uniqueAgentName(base: string, taken: string[]): string {
+ const lower = new Set(taken.map((n) => n.toLowerCase()));
+ if (!lower.has(base.toLowerCase())) return base;
+ for (let i = 2; ; i++) {
+ const candidate = `${base}${i}`;
+ if (!lower.has(candidate.toLowerCase())) return candidate;
+ }
+}
diff --git a/frontend/src/components/ModernAvatar.tsx b/frontend/src/components/ModernAvatar.tsx
index cb74a92b..556af12c 100644
--- a/frontend/src/components/ModernAvatar.tsx
+++ b/frontend/src/components/ModernAvatar.tsx
@@ -8,7 +8,9 @@ interface ModernAvatarProps {
className?: string;
}
-type Accessory = 'antenna' | 'spikes' | 'ears' | 'horns' | 'sprout' | 'crown' | 'visor' | 'none';
+type Accessory =
+ | 'antenna' | 'spikes' | 'ears' | 'horns' | 'sprout' | 'crown' | 'visor'
+ | 'beret' | 'glasses' | 'goggles' | 'tie' | 'quill' | 'bulb' | 'none';
interface Creature {
body: string;
@@ -32,6 +34,45 @@ const PALETTES: Record<string, Omit<Creature, 'accessory'>> = {
violet: { body: '#a98bff', shade: '#6d4fd6', light: '#e1d6ff', accent: '#ffd23f' },
orange: { body: '#ff9f43', shade: '#c4621c', light: '#ffd9a8', accent: '#5ce1ff' },
blue: { body: '#6d9bff', shade: '#3c5fcf', light: '#cddcff', accent: '#ff7eb6' },
+ coral: { body: '#ff8a7a', shade: '#cf5446', light: '#ffd6cf', accent: '#6d4fd6' },
+ teal: { body: '#2fd4b5', shade: '#17917c', light: '#b5f5e8', accent: '#ffd23f' },
+ red: { body: '#ff6b6b', shade: '#c43c4c', light: '#ffc9c9', accent: '#5ce1ff' },
+ gold: { body: '#f7c948', shade: '#c28a14', light: '#fff1b8', accent: '#e5484d' },
+ lilac: { body: '#d49cff', shade: '#9a5fd1', light: '#f1ddff', accent: '#f5f2ff' },
+ mint: { body: '#9be564', shade: '#5e9e33', light: '#e2ffc7', accent: '#ffe066' },
+};
+
+/** Avatar styles an agent can pick; `avatar_sprite` stores the id. */
+export const AVATAR_STYLES: Array<{ id: string; label: string }> = [
+ { id: 'architect', label: 'Architecture' },
+ { id: 'tech_lead', label: 'Tech Lead' },
+ { id: 'devops', label: 'DevOps' },
+ { id: 'security', label: 'Security' },
+ { id: 'fast', label: 'Speed' },
+ { id: 'designer', label: 'Design' },
+ { id: 'data', label: 'Data' },
+ { id: 'qa', label: 'QA' },
+ { id: 'product', label: 'Product' },
+ { id: 'writer', label: 'Writing' },
+ { id: 'research', label: 'Research' },
+ { id: 'default', label: 'Droid' },
+];
+
+const ROLE_CREATURES: Record<string, [keyof typeof PALETTES, Accessory]> = {
+ brand: ['yellow', 'antenna'],
+ laya: ['violet', 'crown'],
+ user: ['blue', 'ears'],
+ architect: ['violet', 'horns'],
+ tech_lead: ['cyan', 'visor'],
+ devops: ['green', 'spikes'],
+ security: ['orange', 'ears'],
+ fast: ['pink', 'sprout'],
+ designer: ['coral', 'beret'],
+ data: ['teal', 'glasses'],
+ qa: ['red', 'goggles'],
+ product: ['gold', 'tie'],
+ writer: ['lilac', 'quill'],
+ research: ['mint', 'bulb'],
};
const hash = (s: string) => {
@@ -41,7 +82,9 @@ const hash = (s: string) => {
};
function pickCreature(role: string, name: string): Creature {
- if (role === 'brand') return { ...PALETTES.yellow, accessory: 'antenna' };
+ // An explicitly chosen style wins over hints in the name
+ const chosen = ROLE_CREATURES[role];
+ if (chosen) return { ...PALETTES[chosen[0]], accessory: chosen[1] };
const norm = `${role} ${name}`.toLowerCase();
const rules: Array<[string[], keyof typeof PALETTES, Accessory]> = [
[['laya'], 'violet', 'crown'],
@@ -51,6 +94,12 @@ function pickCreature(role: string, name: string): Creature {
[['devops', 'terminal', 'knight', 'shell', 'infra'], 'green', 'spikes'],
[['security', 'shield', 'guard'], 'orange', 'ears'],
[['fast', 'grok', 'zap', 'speed'], 'pink', 'sprout'],
+ [['design', 'ux'], 'coral', 'beret'],
+ [['data', 'analyst'], 'teal', 'glasses'],
+ [['qa', 'test'], 'red', 'goggles'],
+ [['product', 'manager'], 'gold', 'tie'],
+ [['writer', 'docs'], 'lilac', 'quill'],
+ [['research', 'scientist'], 'mint', 'bulb'],
];
for (const [keys, palette, accessory] of rules) {
if (keys.some((k) => norm.includes(k))) return { ...PALETTES[palette], accessory };
@@ -101,6 +150,39 @@ function renderAccessory(c: Creature) {
case 'visor':
// Headphones
return [px(9, 5, 8, 1, c.accent), px(8, 6, 1, 3, c.accent), px(17, 6, 1, 3, c.accent), px(6, 10, 2, 3, c.accent), px(18, 10, 2, 3, c.accent)];
+ case 'beret':
+ return [px(9, 5, 8, 2, c.accent), px(8, 6, 1, 1, c.accent), px(13, 4, 1, 1, c.accent), px(10, 5, 2, 1, '#9a7cff')];
+ case 'quill':
+ return [
+ px(18, 2, 2, 1, '#f5f2ff'), px(17, 3, 3, 1, '#f5f2ff'), px(16, 4, 3, 1, '#f5f2ff'), px(16, 5, 2, 1, '#f5f2ff'),
+ px(19, 2, 1, 1, '#c9c2e8'), px(18, 3, 1, 1, '#8f86b8'), px(17, 4, 1, 1, '#8f86b8'), px(16, 5, 1, 1, '#8f86b8'),
+ px(16, 6, 1, 1, INK),
+ ];
+ case 'bulb':
+ return [
+ px(12, 2, 2, 1, c.accent), px(11, 3, 4, 2, c.accent), px(12, 3, 1, 1, '#ffffff'),
+ px(12, 5, 2, 1, '#8a8aa8'), px(12, 6, 2, 1, INK),
+ ];
+ default:
+ return [];
+ }
+}
+
+// Accessories worn in front of the body (on the face or chest)
+function renderOverlay(c: Creature) {
+ switch (c.accessory) {
+ case 'glasses':
+ return [
+ px(9, 9, 4, 1, c.accent), px(13, 9, 4, 1, c.accent), px(9, 10, 1, 2, c.accent), px(16, 10, 1, 2, c.accent),
+ px(12, 10, 2, 1, c.accent), px(7, 10, 2, 1, c.shade), px(17, 10, 2, 1, c.shade),
+ ];
+ case 'goggles':
+ return [
+ px(7, 8, 12, 1, INK), px(9, 7, 3, 2, c.accent), px(14, 7, 3, 2, c.accent),
+ px(9, 7, 1, 1, '#ffffff'), px(14, 7, 1, 1, '#ffffff'),
+ ];
+ case 'tie':
+ return [px(12, 16, 2, 1, c.accent), px(12, 17, 2, 1, c.accent), px(12, 18, 2, 1, '#a8323a')];
default:
return [];
}
@@ -138,6 +220,7 @@ function renderCreature(c: Creature) {
// Feet
px(9, 18, 2, 1, INK, 'f1'),
px(15, 18, 2, 1, INK, 'f2'),
+ ...renderOverlay(c),
];
}
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsx
index 4565ebad..ceec4254 100644
--- a/frontend/src/components/NewAgentModal.tsx
+++ b/frontend/src/components/NewAgentModal.tsx
@@ -1,6 +1,7 @@
import React, { useEffect, useState } from 'react';
import { X, Sparkles, Pencil } from 'lucide-react';
-import { ModernAvatar } from './ModernAvatar';
+import { ModernAvatar, AVATAR_STYLES } from './ModernAvatar';
+import { AGENT_PRESETS, AgentPreset, uniqueAgentName } from '../agentPresets';
import { playSfx } from '../audio/chiptune';
export interface AgentFormData {
@@ -24,6 +25,8 @@ interface NewAgentModalProps {
onClose: () => void;
/** When set, the modal edits this agent instead of creating a new one. */
initial?: AgentFormData | null;
+ /** Names already in use, so presets pick a free one. */
+ takenNames?: string[];
/** Resolves to an error message when saving failed. */
onSubmit: (data: AgentFormData) => Promise<string | void> | void;
}
@@ -32,6 +35,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
isOpen,
onClose,
initial,
+ takenNames = [],
onSubmit,
}) => {
const [name, setName] = useState('');
@@ -41,6 +45,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
const [prompt, setPrompt] = useState('');
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const [presetId, setPresetId] = useState<string | null>(null);
const isEdit = !!initial;
useEffect(() => {
@@ -52,8 +57,20 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
setPrompt(initial?.persona_prompt ?? '');
setSubmitting(false);
setError(null);
+ setPresetId(null);
}, [isOpen, initial]);
+ const applyPreset = (preset: AgentPreset | null) => {
+ playSfx('click');
+ setPresetId(preset?.id ?? null);
+ setError(null);
+ setName(preset ? uniqueAgentName(preset.name, takenNames) : '');
+ setTitle(preset?.title ?? '');
+ setRoleStyle(preset?.avatar_sprite ?? 'architect');
+ setModel(preset?.preferred_model ?? 'auto');
+ setPrompt(preset?.persona_prompt ?? '');
+ };
+
if (!isOpen) return null;
const handleSubmit = async (e: React.FormEvent) => {
@@ -90,7 +107,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
return (
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 select-none">
- <div className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-md w-full p-6 text-zinc-100 shadow-2xl space-y-5">
+ <div className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full max-h-[92vh] overflow-y-auto p-6 text-zinc-100 shadow-2xl space-y-5">
<div className="flex items-center justify-between border-b border-zinc-800 pb-3">
<div className="flex items-center gap-2">
<div className="w-7 h-7 rounded-lg bg-sky-500/10 border border-sky-500/20 flex items-center justify-center text-sky-400">
@@ -112,6 +129,37 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
</div>
<form onSubmit={handleSubmit} className="space-y-4">
+ {!isEdit && (
+ <div>
+ <label className="block text-xs font-medium text-zinc-400 mb-1">Start from a persona</label>
+ <div className="grid grid-cols-3 gap-1.5">
+ {[null, ...AGENT_PRESETS].map((preset) => {
+ const active = (preset?.id ?? null) === presetId;
+ return (
+ <button
+ key={preset?.id ?? 'blank'}
+ type="button"
+ onClick={() => applyPreset(preset)}
+ title={preset ? `${preset.title}: ${preset.persona_prompt}` : 'Start with empty fields'}
+ className={`flex items-center gap-1.5 px-2 py-1.5 rounded-lg border text-left text-[11px] transition-all ${
+ active
+ ? 'border-sky-500/60 bg-sky-500/10 text-sky-200'
+ : 'border-zinc-800 bg-zinc-950/60 text-zinc-400 hover:border-zinc-700 hover:text-zinc-200'
+ }`}
+ >
+ {preset ? (
+ <ModernAvatar role={preset.avatar_sprite} size={18} />
+ ) : (
+ <Sparkles size={13} className="mx-0.5 text-zinc-500" />
+ )}
+ <span className="truncate font-medium">{preset ? preset.label : 'Blank'}</span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
<div>
<label className="block text-xs font-medium text-zinc-400 mb-1">Agent Name</label>
<input
@@ -137,28 +185,21 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
<div>
<label className="block text-xs font-medium text-zinc-400 mb-1">Avatar & Role Specialty</label>
- <div className="grid grid-cols-2 gap-2">
- {[
- { id: 'architect', label: 'Architecture' },
- { id: 'tech_lead', label: 'Tech Lead / Code' },
- { id: 'devops', label: 'DevOps & Shell' },
- { id: 'security', label: 'Security & Audit' },
- { id: 'fast', label: 'Speed & Logic' },
- { id: 'default', label: 'General / Droid' },
- ].map((item) => {
+ <div className="grid grid-cols-4 gap-1.5">
+ {AVATAR_STYLES.map((item) => {
const active = roleStyle === item.id;
return (
<button
key={item.id}
type="button"
onClick={() => setRoleStyle(item.id)}
- className={`flex items-center gap-2.5 p-2 rounded-xl border text-left text-xs transition-all ${
+ className={`flex flex-col items-center gap-1 py-2 rounded-xl border text-[11px] transition-all ${
active
? 'border-sky-500/60 bg-sky-500/10 text-sky-200 shadow-sm'
: 'border-zinc-800 bg-zinc-950/60 text-zinc-400 hover:border-zinc-700 hover:text-zinc-200'
}`}
>
- <ModernAvatar role={item.id} size={24} />
+ <ModernAvatar role={item.id} size={32} />
<span className="truncate font-medium">{item.label}</span>
</button>
);
@@ -184,7 +225,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
<div>
<label className="block text-xs font-medium text-zinc-400 mb-1">Persona & System Prompt</label>
<textarea
- rows={isEdit ? 6 : 3}
+ rows={isEdit || presetId ? 6 : 3}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="Define instructions, personality, tone, and domain expertise..."
diff --git a/frontend/tests/agentPresets.test.mjs b/frontend/tests/agentPresets.test.mjs
new file mode 100644
index 00000000..03409644
--- /dev/null
+++ b/frontend/tests/agentPresets.test.mjs
@@ -0,0 +1,32 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import test from 'node:test';
+import ts from 'typescript';
+
+const load = async (path) => {
+ const source = await readFile(new URL(path, import.meta.url), 'utf8');
+ const { outputText } = ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.ESNext, jsx: ts.JsxEmit.ReactJSX },
+ });
+ return outputText;
+};
+
+const presets = await import(`data:text/javascript;base64,${Buffer.from(await load('../src/agentPresets.ts')).toString('base64')}`);
+const { AGENT_PRESETS, uniqueAgentName } = presets;
+
+test('picks a free name when the preset name is taken', () => {
+ assert.equal(uniqueAgentName('QA', ['Architect']), 'QA');
+ assert.equal(uniqueAgentName('QA', ['qa', 'QA2']), 'QA3');
+});
+
+test('presets have mentionable names, distinct ids and real avatar styles', async () => {
+ const avatarSource = await load('../src/components/ModernAvatar.tsx');
+ const styleIds = Array.from(avatarSource.matchAll(/\{ id: '([a-z_]+)', label:/g), (m) => m[1]);
+ assert.ok(styleIds.length >= 12);
+ assert.equal(new Set(AGENT_PRESETS.map((p) => p.id)).size, AGENT_PRESETS.length);
+ for (const p of AGENT_PRESETS) {
+ assert.match(p.name, /^[^\s@]+$/, p.name);
+ assert.ok(styleIds.includes(p.avatar_sprite), `${p.id} uses unknown avatar ${p.avatar_sprite}`);
+ assert.ok(p.persona_prompt.length > 100, `${p.id} persona is too thin`);
+ }
+});
diff --git a/src/server/routes.rs b/src/server/routes.rs
index b8bb9783..2b6ada6a 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -48,10 +48,24 @@ pub async fn list_kwants(State(state): State<AppState>) -> Result<Json<Vec<Kwant
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
+/// Trims the name and rejects names that can't be @mentioned or clash with another kwant.
+async fn validate_kwant_name(state: &AppState, name: &mut String, own_id: Option<&str>) -> Result<(), StatusCode> {
+ *name = name.trim().to_string();
+ if name.is_empty() || name.contains(char::is_whitespace) || name.contains('@') {
+ return Err(StatusCode::BAD_REQUEST);
+ }
+ let kwants = state.db.list_kwants().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ if kwants.iter().any(|k| Some(k.id.as_str()) != own_id && k.name.eq_ignore_ascii_case(name)) {
+ return Err(StatusCode::CONFLICT);
+ }
+ Ok(())
+}
+
pub async fn create_kwant(
State(state): State<AppState>,
- Json(payload): Json<NewKwant>,
+ Json(mut payload): Json<NewKwant>,
) -> Result<Json<Kwant>, StatusCode> {
+ validate_kwant_name(&state, &mut payload.name, None).await?;
state
.db
.create_kwant(&payload)
@@ -65,14 +79,7 @@ pub async fn update_kwant(
Path(id): Path<String>,
Json(mut payload): Json<UpdateKwant>,
) -> Result<Json<Kwant>, StatusCode> {
- payload.name = payload.name.trim().to_string();
- if payload.name.is_empty() || payload.name.contains(char::is_whitespace) || payload.name.contains('@') {
- return Err(StatusCode::BAD_REQUEST);
- }
- let kwants = state.db.list_kwants().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
- if kwants.iter().any(|k| k.id != id && k.name.eq_ignore_ascii_case(&payload.name)) {
- return Err(StatusCode::CONFLICT);
- }
+ validate_kwant_name(&state, &mut payload.name, Some(&id)).await?;
match state.db.update_kwant(&id, &payload).await {
Ok(Some(kwant)) => Ok(Json(kwant)),
Ok(None) => Err(StatusCode::NOT_FOUND),
diff --git a/tests/server_test.rs b/tests/server_test.rs
index 87f4be84..71671da1 100644
--- a/tests/server_test.rs
+++ b/tests/server_test.rs
@@ -722,3 +722,45 @@ async fn test_channel_sandbox_target_resolution() {
+
+#[tokio::test]
+async fn test_kwant_name_validation() {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };
+ let tools = ToolRunner::new(tmp.path().join("workspace"));
+ let state = AppState::new(config.clone(), db, tools, PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
+ let app = create_router(state);
+
+ let send = |method: &str, uri: &str, name: &str| {
+ let body = json!({
+ "name": name, "title": "t", "persona_prompt": "p",
+ "avatar_sprite": "designer", "driver_type": "api", "preferred_model": "auto"
+ });
+ Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap()
+ };
+
+ // Seeded "Architect" exists, so a case-insensitive duplicate is rejected
+ let resp = app.clone().oneshot(send("POST", "/api/kwants", "architect")).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::CONFLICT);
+ let resp = app.clone().oneshot(send("POST", "/api/kwants", "Ux Designer")).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ let resp = app.clone().oneshot(send("POST", "/api/kwants", " Designer ")).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let created: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(created["name"], "Designer");
+ let id = created["id"].as_str().unwrap();
+
+ // Keeping its own name is fine; taking another kwant's isn't
+ let resp = app.clone().oneshot(send("PUT", &format!("/api/kwants/{id}"), "Designer")).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let resp = app.clone().oneshot(send("PUT", &format!("/api/kwants/{id}"), "TechLead")).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::CONFLICT);
+}