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.

frontend: skills review in the agent's settings (batch 2 / B)

Pixel (kwant bot)e450527e5441
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 3b78cf71..1b6971d3 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -4,7 +4,7 @@ import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar
import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState } from './components/ChatView';
import { ThreadBar, ThreadHeader } from './components/ThreadBar';
import { DelegationCard } from './components/DelegationCard';
-import { Loader2 } from 'lucide-react';
+import { ListChecks, Loader2 } from 'lucide-react';
import { PendingApproval } from './components/ModernApprovalCard';
import type { AgentFormData } from './components/NewAgentModal';
import { NewTeamModal } from './components/NewTeamModal';
@@ -44,6 +44,8 @@ import {
shouldShowOsNotification,
} from './continuity';
import type { PinnedItem } from './components/Instructions';
+import type { EditTab } from './components/NewAgentModal';
+import { Skill, applySkillEvent, pendingByKwant, skillsApi } from './skills';
// 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.
@@ -131,14 +133,21 @@ export const App: React.FC = () => {
const toastIdRef = useRef(0);
const dismissToast = useCallback((id: number) => setToasts((prev) => prev.filter((t) => t.id !== id)), []);
// Set each render once the select handlers exist; the SSE handler and notification clicks go through it.
+ // Opens an agent's settings on the Skills tab (set once the agents are known).
+ const openSkillsRef = useRef<(kwantId: string) => void>(() => undefined);
const openTargetRef = useRef<(t: { channel_id: string | null; kwant_id: string | null }) => boolean>(() => false);
const showNotification = (n: NotifyEvent) => {
const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };
// Failed routines and finished or slow delegations show in the app; the OS notification is for a hidden tab.
if (!document.hidden && (TOAST_KINDS as string[]).includes(n.kind)) {
- if (n.kind !== 'routine_failed' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
+ if (n.kind !== 'routine_failed' && n.kind !== 'skill_proposed' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
const id = ++toastIdRef.current;
- const action = n.kind === 'routine_failed' ? undefined : { label: 'Open', onClick: () => openTargetRef.current(target) };
+ const action =
+ n.kind === 'routine_failed'
+ ? undefined
+ : n.kind === 'skill_proposed'
+ ? { label: 'Review', onClick: () => openSkillsRef.current(n.kwant_id) }
+ : { label: 'Open', onClick: () => openTargetRef.current(target) };
setToasts((prev) => [...prev.slice(-2), { id, title: n.title, detail: n.body, action }]);
if (n.kind !== 'routine_failed') playSfx('alert');
return;
@@ -148,7 +157,8 @@ export const App: React.FC = () => {
const note = new Notification(n.title, { body: n.body, tag: `kwnt-${n.kind}-${n.channel_id ?? n.kwant_id}` });
note.onclick = () => {
window.focus();
- openTargetRef.current(target);
+ if (n.kind === 'skill_proposed') openSkillsRef.current(n.kwant_id);
+ else openTargetRef.current(target);
note.close();
};
} catch {
@@ -227,6 +237,7 @@ export const App: React.FC = () => {
/** Running turns after a (re)connect; chats whose reply ended meanwhile stop spinning. */
const hydrateFromServer = async () => {
+ skillsApi.list({ status: 'pending' }).then(setPendingSkills, () => undefined);
try {
const { turns: list } = await threadsApi.turns();
const map = hydrateTurns(list);
@@ -254,6 +265,9 @@ export const App: React.FC = () => {
const [isNewTeamOpen, setIsNewTeamOpen] = useState(false);
const [editingTeam, setEditingTeam] = useState<Team | null>(null);
const [editingKwant, setEditingKwant] = useState<Kwant | null>(null);
+ const [editingTab, setEditingTab] = useState<EditTab>('profile');
+ // Skills waiting for review, for the counts on the agent's header and Skills tab.
+ const [pendingSkills, setPendingSkills] = useState<Skill[]>([]);
// Virtual Machine & Live Browser state
const [isVmPaneOpen, setIsVmPaneOpen] = useState(false);
@@ -484,6 +498,14 @@ export const App: React.FC = () => {
refreshProfiles();
break;
}
+ case 'skill_updated':
+ case 'SkillUpdated': {
+ const sk = event.data?.skill;
+ if (!sk?.id) break;
+ emitContinuity({ type: 'skill_updated', data: sk });
+ setPendingSkills((prev) => applySkillEvent(prev, sk).filter((x) => x.status === 'pending'));
+ break;
+ }
case 'memory_changed':
case 'MemoryChanged':
emitContinuity({ type: 'memory_changed', data: event.data });
@@ -954,6 +976,15 @@ export const App: React.FC = () => {
return true;
};
openTargetRef.current = openTarget;
+ const openAgentSettings = (kwant: Kwant, tab: EditTab = 'profile') => {
+ setEditingTab(tab);
+ setEditingKwant(kwant);
+ playSfx('click');
+ };
+ openSkillsRef.current = (kwantId: string) => {
+ const k = kwants.find((x) => x.id === kwantId);
+ if (k) openAgentSettings(k, 'skills');
+ };
const pushToast = (title: string, detail?: string) => {
const id = ++toastIdRef.current;
@@ -1547,6 +1578,19 @@ export const App: React.FC = () => {
{elsewhere.length > 1 && <span className="shrink-0 text-sky-300/80">+{elsewhere.length - 1} more</span>}
</button>
) : null;
+ const pendingSkillCounts = pendingByKwant(pendingSkills);
+ const pendingHere = currentKwant ? pendingSkillCounts[currentKwant.id] ?? 0 : 0;
+ const skillsBadge =
+ currentKwant && pendingHere > 0 ? (
+ <button
+ type="button"
+ onClick={() => openAgentSettings(currentKwant, 'skills')}
+ className="inline-flex items-center gap-1 shrink-0 px-2 py-0.5 rounded-full border border-amber-500/30 bg-amber-500/10 text-[11px] text-amber-200 hover:bg-amber-500/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400"
+ >
+ <ListChecks size={11} aria-hidden="true" />
+ {pendingHere === 1 ? '1 skill to review' : `${pendingHere} skills to review`}
+ </button>
+ ) : null;
// Sidebar: agents busy somewhere other than the open chat.
const busyKwants: Record<string, string> = {};
for (const t of Object.values(turns)) {
@@ -1642,8 +1686,7 @@ export const App: React.FC = () => {
playSfx('click');
}}
onEditKwant={(kwant) => {
- setEditingKwant(kwant);
- playSfx('click');
+ openAgentSettings(kwant);
}}
onSummonKwant={(team) => {
setNewAgentTeam(team ?? null);
@@ -1688,8 +1731,7 @@ export const App: React.FC = () => {
onEditKwant={
currentKwant
? () => {
- setEditingKwant(currentKwant);
- playSfx('click');
+ openAgentSettings(currentKwant);
}
: undefined
}
@@ -1716,7 +1758,14 @@ export const App: React.FC = () => {
highlightMessageId={highlightMessageId}
onHighlightDone={() => setHighlightMessageId(null)}
subHeader={subHeader}
- titleExtra={workingBadge}
+ titleExtra={
+ workingBadge || skillsBadge ? (
+ <>
+ {workingBadge}
+ {skillsBadge}
+ </>
+ ) : null
+ }
queued={queuedHere}
renderDelegation={renderDelegation}
contextKey={openCtx}
@@ -1749,6 +1798,8 @@ export const App: React.FC = () => {
profiles={profiles}
onManageProfiles={() => setIsProfilesOpen(true)}
onManageServers={() => setIsMcpOpen(true)}
+ initialTab={editingTab}
+ pendingSkills={editingKwant ? pendingSkillCounts[editingKwant.id] ?? 0 : 0}
onClose={() => setEditingKwant(null)}
onSubmit={(data) => (editingKwant ? handleUpdateAgent(editingKwant, data) : undefined)}
/>
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsx
index 88d12cc5..dab742a0 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 } from 'lucide-react';
+import { X, Sparkles, Pencil, ChevronRight, Brain, CalendarClock, UserRound, ListChecks } from 'lucide-react';
import { ModernAvatar, AVATAR_STYLES } from './ModernAvatar';
import { AGENT_PRESETS, AgentPreset, PRESET_GROUPS, PresetGroup, uniqueAgentName } from '../agentPresets';
import { playSfx } from '../audio/chiptune';
@@ -8,12 +8,14 @@ import { McpServer, defaultKwantServerIds } from '../mcp';
import { ENGINES, Profile, engineOfModel, profileStatus, profilesForEngine } from '../profiles';
import { MemoryPanel } from './MemoryPanel';
import { RoutinesPanel } from './RoutinesPanel';
+import { SkillsPanel } from './SkillsPanel';
import type { Channel, Kwant } from './Sidebar';
-type EditTab = 'profile' | 'memory' | 'routines';
+export type EditTab = 'profile' | 'memory' | 'skills' | 'routines';
const EDIT_TABS: Array<{ id: EditTab; label: string; Icon: typeof Brain }> = [
{ id: 'profile', label: 'Profile', Icon: UserRound },
{ id: 'memory', label: 'Memory', Icon: Brain },
+ { id: 'skills', label: 'Skills', Icon: ListChecks },
{ id: 'routines', label: 'Routines', Icon: CalendarClock },
];
@@ -61,6 +63,10 @@ interface NewAgentModalProps {
/** For the Routines tab when editing. */
kwants?: Kwant[];
channels?: Channel[];
+ /** Tab to open on (editing only), e.g. 'skills' from a "skill proposed" notification. */
+ initialTab?: EditTab;
+ /** Skills waiting for review, shown as a count on the Skills tab. */
+ pendingSkills?: number;
}
export const NewAgentModal: React.FC<NewAgentModalProps> = ({
@@ -76,6 +82,8 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
onSubmit,
kwants = [],
channels = [],
+ initialTab = 'profile',
+ pendingSkills = 0,
}) => {
const [tab, setTab] = useState<EditTab>('profile');
const [name, setName] = useState('');
@@ -105,7 +113,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
setSoul(initial?.soul ?? '');
setSubmitting(false);
setError(null);
- setTab('profile');
+ setTab(initialTab);
setPresetId(null);
setMcpIds(undefined);
setProfileId(initial?.profile_id ?? null);
@@ -231,6 +239,11 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
}`}
>
<Icon size={12} aria-hidden="true" /> {label}
+ {id === 'skills' && pendingSkills > 0 && (
+ <span className="ml-0.5 px-1 min-w-[1rem] rounded-full bg-amber-500/25 text-amber-200 text-[10px]" aria-label={`${pendingSkills} to review`}>
+ {pendingSkills}
+ </span>
+ )}
</button>
))}
</div>
@@ -241,6 +254,11 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
<MemoryPanel kwantId={kwantId} kwantName={initial?.name ?? 'This kwant'} />
</div>
)}
+ {isEdit && kwantId && tab === 'skills' && (
+ <div role="tabpanel" id="agent-panel-skills" aria-labelledby="agent-tab-skills">
+ <SkillsPanel kwantId={kwantId} kwantName={initial?.name ?? 'This kwant'} />
+ </div>
+ )}
{isEdit && kwantId && tab === 'routines' && (
<div role="tabpanel" id="agent-panel-routines" aria-labelledby="agent-tab-routines">
<RoutinesPanel kwantId={kwantId} kwants={kwants} channels={channels} />
diff --git a/frontend/src/components/SkillsPanel.tsx b/frontend/src/components/SkillsPanel.tsx
new file mode 100644
index 00000000..96d06668
--- /dev/null
+++ b/frontend/src/components/SkillsPanel.tsx
@@ -0,0 +1,535 @@
+import React, { useCallback, useEffect, useState } from 'react';
+import { Bot, Check, ChevronDown, ChevronRight, Globe2, Loader2, Pencil, Plus, RefreshCw, Trash2, User, X } from 'lucide-react';
+import { formatWhen, onContinuity } from '../continuity';
+import { playSfx } from '../audio/chiptune';
+import {
+ SKILL_LIMITS,
+ Skill,
+ SkillDiff,
+ SkillDraft,
+ applySkillEvent,
+ groupSkills,
+ skillDraftError,
+ skillsApi,
+ slugifySkillName,
+} from '../skills';
+
+const smallBtn =
+ 'inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium border transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
+const quietBtn = `${smallBtn} border-zinc-700/70 bg-zinc-800/70 text-zinc-200 hover:bg-zinc-700`;
+const goBtn = `${smallBtn} border-emerald-500/40 bg-emerald-600/80 text-white hover:bg-emerald-500`;
+const dangerBtn = `${smallBtn} border-rose-500/30 bg-rose-500/10 text-rose-300 hover:bg-rose-500/20`;
+const inputClass =
+ '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';
+
+const errText = (e: unknown) => (e instanceof Error ? e.message : 'That failed.');
+
+/** Name, description and steps; used to write a new skill and to edit one (before approving). */
+const SkillForm: React.FC<{
+ idPrefix: string;
+ initial: SkillDraft;
+ submitLabel: string;
+ onSubmit: (d: SkillDraft) => Promise<string | void>;
+ onCancel: () => void;
+}> = ({ idPrefix, initial, submitLabel, onSubmit, onCancel }) => {
+ const [d, setD] = useState<SkillDraft>(initial);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const problem = skillDraftError(d);
+
+ const submit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (problem) {
+ setError(problem);
+ return;
+ }
+ setBusy(true);
+ const err = await onSubmit({ name: d.name.trim(), description: d.description.trim(), body: d.body });
+ setBusy(false);
+ if (err) setError(err);
+ };
+
+ return (
+ <form onSubmit={submit} className="space-y-2" aria-label={submitLabel}>
+ <div>
+ <label htmlFor={`${idPrefix}-name`} className="block text-[11px] font-medium text-zinc-400 mb-1">
+ Name
+ </label>
+ <input
+ id={`${idPrefix}-name`}
+ value={d.name}
+ maxLength={SKILL_LIMITS.name}
+ onChange={(e) => setD({ ...d, name: e.target.value })}
+ onBlur={() => setD((x) => ({ ...x, name: slugifySkillName(x.name) }))}
+ placeholder="weekly-report"
+ className={`${inputClass} font-mono`}
+ autoComplete="off"
+ />
+ </div>
+ <div>
+ <label htmlFor={`${idPrefix}-desc`} className="block text-[11px] font-medium text-zinc-400 mb-1">
+ When to use it
+ </label>
+ <input
+ id={`${idPrefix}-desc`}
+ value={d.description}
+ maxLength={SKILL_LIMITS.description}
+ onChange={(e) => setD({ ...d, description: e.target.value })}
+ placeholder="Building the Friday status report from the repo and tickets"
+ className={inputClass}
+ />
+ </div>
+ <div>
+ <label htmlFor={`${idPrefix}-body`} className="block text-[11px] font-medium text-zinc-400 mb-1">
+ Steps (Markdown)
+ </label>
+ <textarea
+ id={`${idPrefix}-body`}
+ value={d.body}
+ rows={7}
+ onChange={(e) => setD({ ...d, body: e.target.value })}
+ className={`${inputClass} font-mono resize-y`}
+ />
+ <span className={`block text-right text-[10px] font-mono ${d.body.length > SKILL_LIMITS.body ? 'text-rose-400' : 'text-zinc-500'}`}>
+ {d.body.length}/{SKILL_LIMITS.body}
+ </span>
+ </div>
+ {error && (
+ <p className="text-[11px] text-rose-400" role="alert">
+ {error}
+ </p>
+ )}
+ <div className="flex items-center justify-end gap-2">
+ <button type="button" onClick={onCancel} className={quietBtn}>
+ Cancel
+ </button>
+ <button type="submit" disabled={busy} className={goBtn}>
+ {busy ? <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Check size={11} aria-hidden="true" />}
+ {submitLabel}
+ </button>
+ </div>
+ </form>
+ );
+};
+
+/** What approving changes: the whole text for a new skill, line changes for a revision. */
+const SkillChanges: React.FC<{ skill: Skill }> = ({ skill }) => {
+ const [diff, setDiff] = useState<SkillDiff | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const load = useCallback(() => {
+ setError(null);
+ skillsApi.diff(skill.id).then(setDiff, (e) => setError(errText(e)));
+ }, [skill.id]);
+ useEffect(() => {
+ if (skill.replaces_id) load();
+ }, [skill.replaces_id, skill.updated_at, load]);
+
+ if (!skill.replaces_id) {
+ return (
+ <pre className="max-h-64 overflow-auto rounded-lg bg-zinc-950 border border-zinc-800 p-2.5 text-[11px] leading-relaxed text-zinc-300 whitespace-pre-wrap break-words font-mono">
+ {skill.body}
+ </pre>
+ );
+ }
+ if (error) {
+ return (
+ <div className="flex items-center justify-between gap-2 text-[11px] text-rose-300" role="alert">
+ <span>Couldn't load the changes: {error}</span>
+ <button type="button" onClick={load} className={quietBtn}>
+ <RefreshCw size={11} aria-hidden="true" /> Retry
+ </button>
+ </div>
+ );
+ }
+ if (!diff) {
+ return (
+ <p className="flex items-center gap-2 text-[11px] text-zinc-400" role="status">
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading changes…
+ </p>
+ );
+ }
+ const added = diff.lines.filter((l) => l.op === 'add').length;
+ const removed = diff.lines.filter((l) => l.op === 'del').length;
+ return (
+ <div className="space-y-1">
+ <p className="text-[10px] text-zinc-500">
+ <span className="text-emerald-300">+{added}</span> <span className="text-rose-300">−{removed}</span> lines
+ {diff.description_changed && diff.base && <> · description was “{diff.base.description}”</>}
+ </p>
+ <div
+ className="max-h-64 overflow-auto rounded-lg bg-zinc-950 border border-zinc-800 py-1.5 text-[11px] leading-relaxed font-mono"
+ role="region"
+ aria-label={`Changes to ${skill.name}`}
+ tabIndex={0}
+ >
+ {diff.lines.map((l, i) => (
+ <div
+ key={i}
+ className={`px-2.5 whitespace-pre-wrap break-words ${
+ l.op === 'add' ? 'bg-emerald-500/10 text-emerald-200' : l.op === 'del' ? 'bg-rose-500/10 text-rose-200 line-through decoration-rose-400/40' : 'text-zinc-400'
+ }`}
+ >
+ <span className="select-none inline-block w-3 text-zinc-500" aria-hidden="true">
+ {l.op === 'add' ? '+' : l.op === 'del' ? '−' : ' '}
+ </span>
+ <span className="sr-only">{l.op === 'add' ? 'Added: ' : l.op === 'del' ? 'Removed: ' : ''}</span>
+ {l.text || ' '}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+};
+
+const Badge: React.FC<{ tone: string; children: React.ReactNode }> = ({ tone, children }) => (
+ <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium border ${tone}`}>{children}</span>
+);
+
+const SkillMeta: React.FC<{ skill: Skill; replaces?: Skill }> = ({ skill, replaces }) => (
+ <div className="flex flex-wrap items-center gap-1.5 text-[10px] text-zinc-500">
+ {skill.source === 'agent' ? (
+ <Badge tone="bg-violet-500/10 text-violet-300 border-violet-500/20">
+ <Bot size={10} aria-hidden="true" /> Proposed
+ </Badge>
+ ) : (
+ <Badge tone="bg-sky-500/10 text-sky-300 border-sky-500/20">
+ <User size={10} aria-hidden="true" /> You
+ </Badge>
+ )}
+ {skill.kwant_id === null && (
+ <Badge tone="bg-zinc-800 text-zinc-300 border-zinc-700">
+ <Globe2 size={10} aria-hidden="true" /> Every agent
+ </Badge>
+ )}
+ {skill.replaces_id && <Badge tone="bg-amber-500/10 text-amber-300 border-amber-500/20">Update to {replaces?.name ?? 'an enabled skill'}</Badge>}
+ <span>{formatWhen(skill.status === 'pending' ? skill.created_at : skill.updated_at)}</span>
+ </div>
+);
+
+const PendingSkill: React.FC<{ skill: Skill; replaces?: Skill }> = ({ skill, replaces }) => {
+ const [mode, setMode] = useState<'view' | 'edit'>('view');
+ const [open, setOpen] = useState(true);
+ const [busy, setBusy] = useState<'approve' | 'reject' | null>(null);
+ const [confirmReject, setConfirmReject] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const approve = async (edits?: SkillDraft) => {
+ setBusy('approve');
+ setError(null);
+ try {
+ await skillsApi.approve(skill.id, edits);
+ playSfx('coin');
+ } catch (e) {
+ setBusy(null);
+ return errText(e);
+ }
+ };
+ const reject = async () => {
+ if (!confirmReject) {
+ setConfirmReject(true);
+ return;
+ }
+ setBusy('reject');
+ setError(null);
+ try {
+ await skillsApi.reject(skill.id);
+ } catch (e) {
+ setError(errText(e));
+ setBusy(null);
+ setConfirmReject(false);
+ }
+ };
+
+ return (
+ <li className="p-3 rounded-lg border border-amber-500/25 bg-amber-500/[0.04] space-y-2">
+ <div className="flex items-start gap-2">
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ aria-controls={`skill-${skill.id}-detail`}
+ className="mt-0.5 text-zinc-500 hover:text-zinc-200 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ aria-label={open ? `Hide ${skill.name}` : `Show ${skill.name}`}
+ >
+ {open ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
+ </button>
+ <div className="min-w-0 flex-1 space-y-1">
+ <h5 className="text-xs font-semibold font-mono text-zinc-100 break-all">{skill.name}</h5>
+ {skill.description && <p className="text-[11px] text-zinc-400 break-words">{skill.description}</p>}
+ <SkillMeta skill={skill} replaces={replaces} />
+ </div>
+ </div>
+ <div id={`skill-${skill.id}-detail`} hidden={!open} className="space-y-2">
+ {mode === 'edit' ? (
+ <SkillForm
+ idPrefix={`skill-${skill.id}`}
+ initial={{ name: skill.name, description: skill.description, body: skill.body }}
+ submitLabel="Save & approve"
+ onSubmit={(d) => approve(d)}
+ onCancel={() => setMode('view')}
+ />
+ ) : (
+ <>
+ <SkillChanges skill={skill} />
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" onClick={() => approve().then((e) => e && setError(e))} disabled={!!busy} className={goBtn}>
+ {busy === 'approve' ? <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Check size={11} aria-hidden="true" />}
+ Approve
+ </button>
+ <button type="button" onClick={() => setMode('edit')} disabled={!!busy} className={quietBtn}>
+ <Pencil size={11} aria-hidden="true" /> Edit, then approve
+ </button>
+ <button type="button" onClick={reject} onBlur={() => setConfirmReject(false)} disabled={!!busy} className={dangerBtn}>
+ {busy === 'reject' ? <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <X size={11} aria-hidden="true" />}
+ {confirmReject ? 'Reject it?' : 'Reject'}
+ </button>
+ </div>
+ </>
+ )}
+ {error && (
+ <p className="text-[11px] text-rose-400" role="alert">
+ {error}
+ </p>
+ )}
+ </div>
+ </li>
+ );
+};
+
+const ActiveSkill: React.FC<{ skill: Skill }> = ({ skill }) => {
+ const [editing, setEditing] = useState(false);
+ const [open, setOpen] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const enabled = skill.status === 'enabled';
+
+ const run = async (fn: () => Promise<unknown>) => {
+ setBusy(true);
+ setError(null);
+ try {
+ await fn();
+ } catch (e) {
+ setError(errText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+ const remove = () => {
+ if (!confirmDelete) {
+ setConfirmDelete(true);
+ return;
+ }
+ setConfirmDelete(false);
+ run(() => skillsApi.remove(skill.id));
+ };
+
+ return (
+ <li className={`p-2.5 rounded-lg border border-zinc-800 bg-zinc-950/60 space-y-1.5 ${enabled ? '' : 'opacity-70'}`}>
+ <div className="flex items-start gap-2">
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ className="min-w-0 flex-1 text-left rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <span className="flex items-center gap-1.5 text-xs font-mono font-semibold text-zinc-100 break-all">
+ {open ? <ChevronDown size={12} className="shrink-0 text-zinc-500" aria-hidden="true" /> : <ChevronRight size={12} className="shrink-0 text-zinc-500" aria-hidden="true" />}
+ {skill.name}
+ {skill.kwant_id === null && <Globe2 size={11} className="shrink-0 text-zinc-500" aria-label="Every agent" />}
+ </span>
+ {skill.description && <span className="block mt-0.5 pl-[18px] text-[11px] text-zinc-400 break-words">{skill.description}</span>}
+ </button>
+ <button
+ type="button"
+ role="switch"
+ aria-checked={enabled}
+ aria-label={`${skill.name}: ${enabled ? 'on' : 'off'}`}
+ disabled={busy}
+ onClick={() => run(() => skillsApi.patch(skill.id, { enabled: !enabled }))}
+ className={`relative shrink-0 mt-0.5 w-8 h-[18px] rounded-full border transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
+ enabled ? 'bg-emerald-500/70 border-emerald-400/60' : 'bg-zinc-800 border-zinc-700'
+ }`}
+ >
+ <span className={`absolute top-[2px] w-3 h-3 rounded-full bg-white transition-all ${enabled ? 'left-[16px]' : 'left-[2px]'}`} aria-hidden="true" />
+ </button>
+ </div>
+ {open && !editing && (
+ <div className="pl-[18px] space-y-1.5">
+ <pre className="max-h-56 overflow-auto rounded-lg bg-zinc-950 border border-zinc-800 p-2.5 text-[11px] leading-relaxed text-zinc-300 whitespace-pre-wrap break-words font-mono">
+ {skill.body}
+ </pre>
+ <div className="flex items-center gap-2">
+ <SkillMeta skill={skill} />
+ <span className="ml-auto flex items-center gap-1">
+ <button type="button" onClick={() => setEditing(true)} className={quietBtn}>
+ <Pencil size={11} aria-hidden="true" /> Edit
+ </button>
+ <button type="button" onClick={remove} onBlur={() => setConfirmDelete(false)} disabled={busy} className={dangerBtn}>
+ <Trash2 size={11} aria-hidden="true" /> {confirmDelete ? 'Delete it?' : 'Delete'}
+ </button>
+ </span>
+ </div>
+ </div>
+ )}
+ {editing && (
+ <SkillForm
+ idPrefix={`skill-${skill.id}`}
+ initial={{ name: skill.name, description: skill.description, body: skill.body }}
+ submitLabel="Save"
+ onSubmit={async (d) => {
+ try {
+ await skillsApi.patch(skill.id, d);
+ setEditing(false);
+ } catch (e) {
+ return errText(e);
+ }
+ }}
+ onCancel={() => setEditing(false)}
+ />
+ )}
+ {error && (
+ <p className="text-[11px] text-rose-400" role="alert">
+ {error}
+ </p>
+ )}
+ </li>
+ );
+};
+
+/**
+ * An agent's skills (its own plus shared ones): proposals to review, the ones in use with an
+ * on/off switch, and the rejected/replaced ones for the record. Live through `skill_updated`.
+ */
+export const SkillsPanel: React.FC<{ kwantId: string; kwantName: string }> = ({ kwantId, kwantName }) => {
+ const [skills, setSkills] = useState<Skill[] | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [writing, setWriting] = useState(false);
+ const [showHistory, setShowHistory] = useState(false);
+
+ const reload = useCallback(async () => {
+ try {
+ setSkills(await skillsApi.list({ kwant_id: kwantId }));
+ setLoadError(null);
+ } catch (e) {
+ setLoadError(errText(e));
+ }
+ }, [kwantId]);
+
+ useEffect(() => {
+ setSkills(null);
+ reload();
+ return onContinuity('skill_updated', (ev) => setSkills((prev) => (prev ? applySkillEvent(prev, ev, kwantId) : prev)));
+ }, [kwantId, reload]);
+
+ const groups = skills ? groupSkills(skills) : null;
+ const byId = (id: string | null) => (id ? skills?.find((s) => s.id === id) : undefined);
+
+ return (
+ <div className="space-y-3">
+ <p className="text-[11px] text-zinc-500 leading-relaxed">
+ Written steps {kwantName} follows when a request fits one. {kwantName} can propose new ones; nothing is used until you approve it. Skills
+ are instructions only and never give an agent new tools.
+ </p>
+
+ {writing ? (
+ <div className="p-3 rounded-lg border border-zinc-800 bg-zinc-950/60">
+ <SkillForm
+ idPrefix="skill-new"
+ initial={{ name: '', description: '', body: '' }}
+ submitLabel="Add skill"
+ onSubmit={async (d) => {
+ try {
+ await skillsApi.create({ ...d, kwant_id: kwantId });
+ playSfx('coin');
+ setWriting(false);
+ } catch (e) {
+ return errText(e);
+ }
+ }}
+ onCancel={() => setWriting(false)}
+ />
+ </div>
+ ) : (
+ <button type="button" onClick={() => setWriting(true)} className={quietBtn}>
+ <Plus size={11} aria-hidden="true" /> Write a skill
+ </button>
+ )}
+
+ {loadError && (
+ <div className="flex items-center justify-between gap-2 bg-rose-500/10 border border-rose-500/20 text-rose-300 px-3 py-2 rounded-lg text-xs" role="alert">
+ <span>Couldn't load skills: {loadError}</span>
+ <button type="button" onClick={reload} className={quietBtn}>
+ <RefreshCw size={12} aria-hidden="true" /> Retry
+ </button>
+ </div>
+ )}
+ {!skills && !loadError && (
+ <p className="flex items-center gap-2 text-xs text-zinc-400" role="status">
+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading skills…
+ </p>
+ )}
+
+ {groups && (
+ <>
+ {groups.pending.length > 0 && (
+ <section aria-labelledby="skills-pending" className="space-y-1.5">
+ <h4 id="skills-pending" className="flex items-center gap-1.5 text-xs font-medium text-amber-200">
+ To review
+ <span className="px-1.5 rounded-full bg-amber-500/20 text-amber-200 text-[10px]">{groups.pending.length}</span>
+ </h4>
+ <ul className="space-y-2">
+ {groups.pending.map((s) => (
+ <PendingSkill key={s.id} skill={s} replaces={byId(s.replaces_id)} />
+ ))}
+ </ul>
+ </section>
+ )}
+
+ <section aria-labelledby="skills-active" className="space-y-1.5">
+ <h4 id="skills-active" className="text-xs font-medium text-zinc-300">
+ In use
+ </h4>
+ {groups.active.length === 0 ? (
+ <p className="text-xs text-zinc-500 border border-dashed border-zinc-800 rounded-lg p-4 text-center">
+ No skills yet. When {kwantName} works out a procedure worth repeating, ask it to propose a skill, or write one yourself.
+ </p>
+ ) : (
+ <ul className="space-y-1.5">
+ {groups.active.map((s) => (
+ <ActiveSkill key={s.id} skill={s} />
+ ))}
+ </ul>
+ )}
+ </section>
+
+ {groups.history.length > 0 && (
+ <section className="space-y-1.5">
+ <button
+ type="button"
+ onClick={() => setShowHistory((v) => !v)}
+ aria-expanded={showHistory}
+ className="flex items-center gap-1 text-[11px] text-zinc-500 hover:text-zinc-300 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ {showHistory ? <ChevronDown size={12} aria-hidden="true" /> : <ChevronRight size={12} aria-hidden="true" />}
+ Rejected and replaced ({groups.history.length})
+ </button>
+ {showHistory && (
+ <ul className="space-y-1">
+ {groups.history.map((s) => (
+ <li key={s.id} className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg border border-zinc-800/70 text-[11px] text-zinc-500">
+ <span className="font-mono text-zinc-400 break-all">{s.name}</span>
+ <span>{s.status === 'rejected' ? 'rejected' : 'replaced'}</span>
+ <span className="ml-auto shrink-0">{formatWhen(s.reviewed_at ?? s.updated_at)}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ )}
+ </>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.ts
index c315eb6b..2fa9e9f4 100644
--- a/frontend/src/continuity.ts
+++ b/frontend/src/continuity.ts
@@ -1,6 +1,8 @@
// Agent continuity: pinned instructions, chat search, kwant memory, routines and notifications.
// Shapes follow /home/maus/shared/ship-software-safely/agent-continuity/contract.md ("Lin's implementation notes").
+import type { DeletedSkill, Skill } from './skills';
+
export const MAX_INSTRUCTIONS = 4000;
export const MAX_MEMORY = 500;
export const MAX_MEMORIES = 100;
@@ -79,17 +81,26 @@ export interface RoutineInput {
enabled: boolean;
}
-export type NotifyKind = 'turn_finished' | 'approval_needed' | 'routine_failed' | 'delegation_finished' | 'delegation_stalled';
+export type NotifyKind =
+ | 'turn_finished'
+ | 'approval_needed'
+ | 'routine_failed'
+ | 'delegation_finished'
+ | 'delegation_stalled'
+ | 'skill_proposed'
+ | 'question_asked';
export const NOTIFY_KINDS: Array<{ id: NotifyKind; label: string }> = [
{ id: 'turn_finished', label: 'A kwant finished replying' },
{ id: 'approval_needed', label: 'A kwant needs your approval' },
{ id: 'routine_failed', label: 'A routine failed' },
{ id: 'delegation_finished', label: 'A delegated task finished' },
{ id: 'delegation_stalled', label: 'A delegated task is taking long' },
+ { id: 'skill_proposed', label: 'A kwant proposed a skill to review' },
+ { id: 'question_asked', label: 'A kwant has a question for you' },
];
/** Kinds also shown as an in-app toast while kwnt is visible (the others only matter in the background). */
-export const TOAST_KINDS: NotifyKind[] = ['routine_failed', 'delegation_finished', 'delegation_stalled'];
+export const TOAST_KINDS: NotifyKind[] = ['routine_failed', 'delegation_finished', 'delegation_stalled', 'skill_proposed', 'question_asked'];
export interface NotifyEvent {
kind: NotifyKind;
@@ -365,7 +376,8 @@ export function notificationPermission(): NotificationPermission | 'unsupported'
export type ContinuityEvent =
| { type: 'memory_changed'; data: { kwant_id: string } }
- | { type: 'routine_run'; data: { routine_id: string; run_id: string; status: RunStatus } };
+ | { type: 'routine_run'; data: { routine_id: string; run_id: string; status: RunStatus } }
+ | { type: 'skill_updated'; data: Skill | DeletedSkill };
const bus = typeof EventTarget !== 'undefined' ? new EventTarget() : null;
diff --git a/frontend/src/skills.ts b/frontend/src/skills.ts
new file mode 100644
index 00000000..0c89fddd
--- /dev/null
+++ b/frontend/src/skills.ts
@@ -0,0 +1,136 @@
+// Skills: short written procedures an agent proposes and a person reviews (batch 2 / B).
+import { request } from './threads';
+
+export type SkillStatus = 'pending' | 'enabled' | 'disabled' | 'rejected' | 'superseded';
+
+export interface Skill {
+ id: string;
+ /** null = shared by every agent. */
+ kwant_id: string | null;
+ name: string;
+ description: string;
+ body: string;
+ status: SkillStatus;
+ source: 'agent' | 'user';
+ proposed_by: string | null;
+ /** A proposed revision: the enabled skill it replaces once approved. */
+ replaces_id: string | null;
+ created_at: string;
+ updated_at: string;
+ reviewed_at: string | null;
+}
+
+/** `skill_updated` after a delete. */
+export interface DeletedSkill {
+ id: string;
+ kwant_id: string | null;
+ deleted: true;
+}
+
+export interface DiffLine {
+ op: 'same' | 'add' | 'del';
+ text: string;
+}
+
+export interface SkillDiff {
+ skill: Skill;
+ base: Skill | null;
+ description_changed: boolean;
+ lines: DiffLine[];
+ unified: string;
+}
+
+export interface SkillDraft {
+ name: string;
+ description: string;
+ body: string;
+}
+
+export const SKILL_LIMITS = { name: 48, description: 200, body: 8000 } as const;
+const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+
+/** First problem with a draft (same rules as the server), or null when it can be saved. */
+export function skillDraftError(d: SkillDraft): string | null {
+ const name = d.name.trim();
+ if (!name) return 'Give it a name.';
+ if (name.length > SKILL_LIMITS.name) return `Names are at most ${SKILL_LIMITS.name} characters.`;
+ if (!NAME_RE.test(name)) return 'Use lowercase letters, digits and dashes, e.g. weekly-report.';
+ if (d.description.trim().length > SKILL_LIMITS.description) return `Descriptions are at most ${SKILL_LIMITS.description} characters.`;
+ if (!d.body.trim()) return 'Write the steps.';
+ if (d.body.length > SKILL_LIMITS.body) return `The steps are at most ${SKILL_LIMITS.body} characters.`;
+ return null;
+}
+
+/** Turns free text into a valid-looking name ("Weekly Report!" -> "weekly-report"). */
+export function slugifySkillName(s: string): string {
+ return s
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, SKILL_LIMITS.name)
+ .replace(/-+$/, '');
+}
+
+/** Whether a skill applies to this agent: its own, or shared. */
+export const skillAppliesTo = (s: Pick<Skill, 'kwant_id'>, kwantId: string) => s.kwant_id === null || s.kwant_id === kwantId;
+
+/**
+ * Applies a `skill_updated` payload to a list (newest first). Skills of other agents are ignored
+ * when `kwantId` is given; a deleted one is dropped. Returns the same list when nothing changed.
+ */
+export function applySkillEvent(list: Skill[], ev: Skill | DeletedSkill, kwantId?: string): Skill[] {
+ const i = list.findIndex((s) => s.id === ev.id);
+ if ('deleted' in ev && ev.deleted) return i < 0 ? list : list.filter((s) => s.id !== ev.id);
+ const skill = ev as Skill;
+ if (kwantId !== undefined && !skillAppliesTo(skill, kwantId)) return i < 0 ? list : list.filter((s) => s.id !== ev.id);
+ if (i < 0) return [skill, ...list];
+ const next = list.slice();
+ next[i] = skill;
+ return next;
+}
+
+export interface SkillGroups {
+ pending: Skill[];
+ /** Enabled first, then disabled; each by name. */
+ active: Skill[];
+ /** Rejected and replaced, kept for the record. */
+ history: Skill[];
+}
+
+export function groupSkills(list: Skill[]): SkillGroups {
+ const byName = (a: Skill, b: Skill) => a.name.localeCompare(b.name);
+ return {
+ pending: list.filter((s) => s.status === 'pending'),
+ active: [
+ ...list.filter((s) => s.status === 'enabled').sort(byName),
+ ...list.filter((s) => s.status === 'disabled').sort(byName),
+ ],
+ history: list.filter((s) => s.status === 'rejected' || s.status === 'superseded'),
+ };
+}
+
+/** Pending skills per agent (shared ones count for nobody: they show in every agent's list). */
+export function pendingByKwant(list: Skill[]): Record<string, number> {
+ const out: Record<string, number> = {};
+ for (const s of list) if (s.status === 'pending' && s.kwant_id) out[s.kwant_id] = (out[s.kwant_id] ?? 0) + 1;
+ return out;
+}
+
+const enc = encodeURIComponent;
+
+export const skillsApi = {
+ list: (q: { kwant_id?: string; status?: SkillStatus } = {}) => {
+ const p = new URLSearchParams();
+ if (q.kwant_id) p.set('kwant_id', q.kwant_id);
+ if (q.status) p.set('status', q.status);
+ const qs = p.toString();
+ return request<Skill[]>('GET', `/api/skills${qs ? `?${qs}` : ''}`);
+ },
+ create: (d: SkillDraft & { kwant_id?: string | null }) => request<Skill>('POST', '/api/skills', d),
+ diff: (id: string) => request<SkillDiff>('GET', `/api/skills/${enc(id)}/diff`),
+ approve: (id: string, edits?: Partial<SkillDraft>) => request<Skill>('POST', `/api/skills/${enc(id)}/approve`, edits ?? {}),
+ reject: (id: string) => request<Skill>('POST', `/api/skills/${enc(id)}/reject`),
+ patch: (id: string, body: Partial<SkillDraft> & { enabled?: boolean; kwant_id?: string | null }) =>
+ request<Skill>('PATCH', `/api/skills/${enc(id)}`, body),
+ remove: (id: string) => request<void>('DELETE', `/api/skills/${enc(id)}`),
+};
diff --git a/frontend/src/threads.ts b/frontend/src/threads.ts
index 42bcb404..b2bbfd5f 100644
--- a/frontend/src/threads.ts
+++ b/frontend/src/threads.ts
@@ -316,7 +316,7 @@ export const messageContextId = (m: { thread_id?: string | null; channel_id?: st
// ---------------------------------------------------------------------------
// API
-async function request<T>(method: string, url: string, body?: unknown): Promise<T> {
+export async function request<T>(method: string, url: string, body?: unknown): Promise<T> {
const res = await fetch(url, {
method,
headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
@@ -332,6 +332,7 @@ async function request<T>(method: string, url: string, body?: unknown): Promise<
}
throw new Error(message);
}
+ if (res.status === 204) return undefined as T;
return res.json();
}
diff --git a/frontend/tests/bundle.mjs b/frontend/tests/bundle.mjs
new file mode 100644
index 00000000..65969646
--- /dev/null
+++ b/frontend/tests/bundle.mjs
@@ -0,0 +1,19 @@
+// Bundles a TypeScript module (with its imports) for the node test runner.
+import { build } from 'esbuild';
+import { fileURLToPath } from 'node:url';
+
+const root = fileURLToPath(new URL('..', import.meta.url));
+
+export async function loadBundled(contents) {
+ const out = await build({
+ stdin: { contents, resolveDir: root, loader: 'tsx' },
+ bundle: true,
+ write: false,
+ format: 'esm',
+ platform: 'node',
+ jsx: 'automatic',
+ logLevel: 'silent',
+ define: { 'process.env.NODE_ENV': '"production"' },
+ });
+ return import(`data:text/javascript;base64,${Buffer.from(out.outputFiles[0].text).toString('base64')}`);
+}
diff --git a/frontend/tests/skills.test.mjs b/frontend/tests/skills.test.mjs
new file mode 100644
index 00000000..c8c078e8
--- /dev/null
+++ b/frontend/tests/skills.test.mjs
@@ -0,0 +1,85 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const s = await loadBundled(`export * from './src/skills';`);
+
+const skill = (over = {}) => ({
+ id: 'a', kwant_id: 'cto', name: 'weekly-report', description: 'Friday report', body: '1. Pull\n2. Write',
+ status: 'pending', source: 'agent', proposed_by: 'cto', replaces_id: null,
+ created_at: '2026-10-17T10:00:00Z', updated_at: '2026-10-17T10:00:00Z', reviewed_at: null, ...over,
+});
+
+test('drafts follow the server rules', () => {
+ const ok = { name: 'weekly-report', description: 'x', body: 'steps' };
+ assert.equal(s.skillDraftError(ok), null);
+ assert.match(s.skillDraftError({ ...ok, name: '' }), /name/);
+ assert.match(s.skillDraftError({ ...ok, name: 'Weekly Report' }), /lowercase/);
+ assert.match(s.skillDraftError({ ...ok, name: '-x' }), /lowercase/);
+ assert.match(s.skillDraftError({ ...ok, name: 'a'.repeat(49) }), /48/);
+ assert.match(s.skillDraftError({ ...ok, description: 'd'.repeat(201) }), /200/);
+ assert.match(s.skillDraftError({ ...ok, body: ' ' }), /steps/);
+ assert.match(s.skillDraftError({ ...ok, body: 'b'.repeat(8001) }), /8000/);
+});
+
+test('names are slugified on blur', () => {
+ assert.equal(s.slugifySkillName(' Weekly Report! v2 '), 'weekly-report-v2');
+ assert.equal(s.slugifySkillName('---'), '');
+ assert.equal(s.slugifySkillName('a'.repeat(47) + ' b').length <= 48, true);
+ assert.equal(s.slugifySkillName('a'.repeat(47) + ' b').endsWith('-'), false);
+});
+
+test('skill_updated upserts, filters by agent and handles deletes', () => {
+ let list = [];
+ list = s.applySkillEvent(list, skill(), 'cto');
+ assert.equal(list.length, 1);
+ list = s.applySkillEvent(list, skill({ id: 'b', kwant_id: null, status: 'enabled' }), 'cto');
+ assert.deepEqual(list.map((x) => x.id), ['b', 'a'], 'shared skills count, newest first');
+ const same = s.applySkillEvent(list, skill({ id: 'c', kwant_id: 'other' }), 'cto');
+ assert.equal(same, list, 'another agent’s skill leaves the list alone');
+ list = s.applySkillEvent(list, skill({ status: 'enabled' }), 'cto');
+ assert.equal(list.find((x) => x.id === 'a').status, 'enabled', 'updated in place');
+ list = s.applySkillEvent(list, { id: 'a', kwant_id: 'cto', deleted: true }, 'cto');
+ assert.deepEqual(list.map((x) => x.id), ['b']);
+ assert.equal(s.applySkillEvent(list, { id: 'zz', kwant_id: null, deleted: true }), list);
+ // Moved to another agent: it leaves this list
+ list = s.applySkillEvent(list, skill({ id: 'b', kwant_id: 'other' }), 'cto');
+ assert.equal(list.length, 0);
+});
+
+test('groups: pending, then in use (enabled before disabled), then history', () => {
+ const g = s.groupSkills([
+ skill({ id: '1', status: 'pending' }),
+ skill({ id: '2', status: 'disabled', name: 'a-off' }),
+ skill({ id: '3', status: 'enabled', name: 'z-on' }),
+ skill({ id: '4', status: 'enabled', name: 'b-on' }),
+ skill({ id: '5', status: 'rejected' }),
+ skill({ id: '6', status: 'superseded' }),
+ ]);
+ assert.deepEqual(g.pending.map((x) => x.id), ['1']);
+ assert.deepEqual(g.active.map((x) => x.id), ['4', '3', '2']);
+ assert.deepEqual(g.history.map((x) => x.id), ['5', '6']);
+});
+
+test('pending counts per agent', () => {
+ const c = s.pendingByKwant([skill(), skill({ id: 'b' }), skill({ id: 'c', kwant_id: 'ellis' }), skill({ id: 'd', status: 'enabled' }), skill({ id: 'e', kwant_id: null })]);
+ assert.deepEqual(c, { cto: 2, ellis: 1 });
+});
+
+test('the API sends the documented requests', async () => {
+ const calls = [];
+ globalThis.fetch = async (url, init = {}) => {
+ calls.push([init.method, url, init.body ?? null]);
+ return init.method === 'DELETE' ? new Response(null, { status: 204 }) : new Response('{}', { status: 200 });
+ };
+ await s.skillsApi.list({ kwant_id: 'cto', status: 'pending' });
+ await s.skillsApi.approve('id/1', { body: 'x' });
+ await s.skillsApi.patch('id1', { enabled: false });
+ assert.equal(await s.skillsApi.remove('id1'), undefined, '204 has no body');
+ assert.deepEqual(calls, [
+ ['GET', '/api/skills?kwant_id=cto&status=pending', null],
+ ['POST', '/api/skills/id%2F1/approve', '{"body":"x"}'],
+ ['PATCH', '/api/skills/id1', '{"enabled":false}'],
+ ['DELETE', '/api/skills/id1', null],
+ ]);
+});