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.

Good for / Not for on the create form; Browser sites in bot settings

Pixel (kwant bot)8f41657eadb0
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 92cd1bed..fd036bde 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -2109,6 +2109,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
preferred_model: agentData.preferred_model,
...(agentData.profile_id !== undefined ? { profile_id: agentData.profile_id } : {}),
...(agentData.profile_failover !== undefined ? { profile_failover: agentData.profile_failover } : {}),
+ ...(agentData.covers?.length ? { covers: agentData.covers } : {}),
+ ...(agentData.avoids?.length ? { avoids: agentData.avoids } : {}),
}),
});
diff --git a/frontend/src/browserSites.ts b/frontend/src/browserSites.ts
new file mode 100644
index 00000000..8d0e6584
--- /dev/null
+++ b/frontend/src/browserSites.ts
@@ -0,0 +1,65 @@
+// Which sites a bot's own browser may open (browser-borrowed/contract.md). The server normalizes
+// entries (lowercase, a pasted URL keeps its host, punycode) and names a bad one in a 400; the UI
+// shows the stored lists it gets back.
+import type { TagLimits } from './tagList';
+
+export type BrowserSites = {
+ browser_allowed_sites: string[];
+ browser_blocked_sites: string[];
+ browser_block_private_network: boolean;
+};
+
+export const SITE_LIMITS: TagLimits = { max: 200, maxChars: 0, split: /[\s,]+/, noun: 'site' };
+
+/** The bot's rules as the server sent them, or null when this server doesn't have them. */
+export function sitesOf(bot: Partial<BrowserSites> | null | undefined): BrowserSites | null {
+ if (!bot || !Array.isArray(bot.browser_allowed_sites) || !Array.isArray(bot.browser_blocked_sites)) return null;
+ return {
+ browser_allowed_sites: bot.browser_allowed_sites,
+ browser_blocked_sites: bot.browser_blocked_sites,
+ browser_block_private_network: !!bot.browser_block_private_network,
+ };
+}
+
+const sameList = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i]);
+
+/**
+ * Only the fields that changed, for PUT /api/kwants/:id: one left out stays as it is. Profile
+ * edits then never depend on the site rules, which a bad entry or a bot's token would refuse.
+ */
+export function changedSites(before: BrowserSites, after: BrowserSites): Partial<BrowserSites> {
+ const out: Partial<BrowserSites> = {};
+ if (!sameList(before.browser_allowed_sites, after.browser_allowed_sites)) out.browser_allowed_sites = after.browser_allowed_sites;
+ if (!sameList(before.browser_blocked_sites, after.browser_blocked_sites)) out.browser_blocked_sites = after.browser_blocked_sites;
+ if (before.browser_block_private_network !== after.browser_block_private_network)
+ out.browser_block_private_network = after.browser_block_private_network;
+ return out;
+}
+
+/** One line for the closed Browser section: "No limits", "Only wikipedia.org · never 2 sites · …". */
+export function sitesSummary(s: BrowserSites): string {
+ const sites = (n: number) => (n === 1 ? '1 site' : `${n} sites`);
+ const parts: string[] = [];
+ const a = s.browser_allowed_sites;
+ if (a.length) parts.push(a.length === 1 ? `Only ${a[0]}` : `Only ${sites(a.length)}`);
+ const b = s.browser_blocked_sites;
+ if (b.length) parts.push(b.length === 1 ? `never ${b[0]}` : `never ${sites(b.length)}`);
+ if (s.browser_block_private_network) parts.push('no local network');
+ if (!parts.length) return 'Any site';
+ const line = parts.join(' · ');
+ return line[0].toUpperCase() + line.slice(1);
+}
+
+export type FieldErrorKey = 'covers' | 'avoids' | 'browser_allowed_sites' | 'browser_blocked_sites';
+
+/**
+ * Splits a 400 that names a field ("browser_allowed_sites: \"a*b.com\" isn't a site: …", "covers:
+ * at most 20 entries") into the field and what to show next to it.
+ */
+export function fieldError(message: string): { field: FieldErrorKey; text: string } | null {
+ // The app capitalizes server messages, so "Browser_allowed_sites: …" counts too.
+ const m = /^(covers|avoids|browser_allowed_sites|browser_blocked_sites):\s*(.+)$/is.exec(message.trim());
+ if (!m) return null;
+ const text = m[2].trim();
+ return { field: m[1].toLowerCase() as FieldErrorKey, text: text[0].toUpperCase() + text.slice(1) };
+}
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsx
index fef1504e..92e1c1f8 100644
--- a/frontend/src/components/NewAgentModal.tsx
+++ b/frontend/src/components/NewAgentModal.tsx
@@ -1,6 +1,6 @@
import React, { useEffect, useRef, useState } from 'react';
import { TagListInput } from './TagListInput';
-import { X, Sparkles, Pencil, ChevronRight, Brain, CalendarClock, UserRound, ListChecks, Trash2, Gauge } from 'lucide-react';
+import { X, Sparkles, Pencil, ChevronRight, Brain, CalendarClock, UserRound, ListChecks, Trash2, Gauge, Globe } from 'lucide-react';
import { ModernAvatar, AVATAR_STYLES } from './ModernAvatar';
import { AGENT_PRESETS, AgentPreset, PRESET_GROUPS, PresetGroup, uniqueAgentName } from '../agentPresets';
import { playSfx } from '../audio/chiptune';
@@ -17,6 +17,7 @@ import type { Channel, Kwant } from './Sidebar';
import { BotApprovalsSetting } from './ApprovalsSetting';
import { FlightSchoolPanel } from './FlightSchoolPanel';
import { useEscapeLayer } from '../escape';
+import { BrowserSites, FieldErrorKey, SITE_LIMITS, changedSites, fieldError, sitesOf, sitesSummary } from '../browserSites';
export type EditTab = 'profile' | 'memory' | 'skills' | 'routines' | 'usage';
const EDIT_TABS: Array<{ id: EditTab; label: string; Icon: typeof Brain }> = [
@@ -42,6 +43,10 @@ export interface AgentFormData {
/** What routing sends it ("Good for") and keeps away from it ("Not for"). */
covers?: string[];
avoids?: string[];
+ /** Which sites its own browser may open; absent on older servers. Sent only when changed. */
+ browser_allowed_sites?: string[];
+ browser_blocked_sites?: string[];
+ browser_block_private_network?: boolean;
}
interface NewAgentModalProps {
@@ -84,7 +89,7 @@ interface NewAgentModalProps {
approvalsOff?: boolean;
}
-type ProfileFields = { name: string; title: string; roleStyle: string; model: string; prompt: string; soul: string; profileId: string | null; failover: boolean; covers: string; avoids: string };
+type ProfileFields = { name: string; title: string; roleStyle: string; model: string; prompt: string; soul: string; profileId: string | null; failover: boolean; covers: string; avoids: string; sites: string };
export const NewAgentModal: React.FC<NewAgentModalProps> = ({
isOpen,
@@ -124,6 +129,12 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
const [failover, setFailover] = useState(true);
const [covers, setCovers] = useState<string[]>([]);
const [avoids, setAvoids] = useState<string[]>([]);
+ // The site rules as the bot has them (null: this server has none), and as edited here.
+ const [sitesBase, setSitesBase] = useState<BrowserSites | null>(null);
+ const [sites, setSites] = useState<BrowserSites | null>(null);
+ const [sitesOpen, setSitesOpen] = useState(false);
+ // A 400 that names one list ("browser_allowed_sites: …"), shown next to that list.
+ const [fieldErrors, setFieldErrors] = useState<Partial<Record<FieldErrorKey, string>>>({});
// Follows the prop until the person changes this bot's approvals here.
const [toolsRunFree, setToolsRunFree] = useState(approvalsOff);
useEffect(() => setToolsRunFree(approvalsOff), [approvalsOff, isOpen]);
@@ -138,7 +149,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
// The profile as it opened (or as a preset filled it in): Escape keeps the editor open while it differs.
const [base, setBase] = useState<ProfileFields | null>(null);
- const current: ProfileFields = { name, title, roleStyle, model, prompt, soul, profileId, failover, covers: covers.join('\n'), avoids: avoids.join('\n') };
+ const current: ProfileFields = { name, title, roleStyle, model, prompt, soul, profileId, failover, covers: covers.join('\n'), avoids: avoids.join('\n'), sites: JSON.stringify(sites) };
const unsaved = !!base && (Object.keys(base) as (keyof ProfileFields)[]).some((k) => base[k] !== current[k]);
const rootRef = useRef<HTMLDivElement>(null);
useEscapeLayer(rootRef, isOpen, onClose, {
@@ -164,6 +175,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
failover: initial?.profile_failover ?? true,
covers: (initial?.covers ?? []).join('\n'),
avoids: (initial?.avoids ?? []).join('\n'),
+ sites: JSON.stringify(sitesOf(initial)),
});
setName(initial?.name ?? '');
setTitle(initial?.title ?? '');
@@ -180,6 +192,10 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
setFailover(initial?.profile_failover ?? true);
setCovers(initial?.covers ?? []);
setAvoids(initial?.avoids ?? []);
+ setSitesBase(sitesOf(initial));
+ setSites(sitesOf(initial));
+ setSitesOpen(false);
+ setFieldErrors({});
let cancelled = false;
// If a list can't load, the picker stays hidden and nothing is saved: saving an empty
// list would switch every server off for this kwant.
@@ -223,6 +239,16 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
if (!isOpen) return null;
+ const fieldInputId = (field: FieldErrorKey) => `agent-${field.replace(/_/g, '-')}`;
+ const listProps = (field: FieldErrorKey, set: (next: string[]) => void) => ({
+ inputId: fieldInputId(field),
+ serverError: fieldErrors[field] ?? null,
+ onChange: (next: string[]) => {
+ set(next);
+ if (fieldErrors[field]) setFieldErrors(({ [field]: _gone, ...rest }) => rest);
+ },
+ });
+
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) return;
@@ -233,6 +259,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
setSubmitting(true);
setError(null);
+ setFieldErrors({});
playSfx('click');
const err = await onSubmit({
@@ -248,13 +275,23 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
profile_id:
profiles.length === 0 ? undefined : engine && engineProfiles.some((p) => p.id === profileId) ? profileId : null,
profile_failover: failover,
- // Only once loaded (edit): older servers leave them out, and a new bot has none yet.
- ...(isEdit && initial?.covers ? { covers, avoids } : {}),
+ // Editing: only once loaded, since older servers leave them out. Creating: always.
+ ...(!isEdit || initial?.covers ? { covers, avoids } : {}),
+ ...(isEdit && sitesBase && sites ? changedSites(sitesBase, sites) : {}),
});
setSubmitting(false);
if (err) {
- setError(err);
+ const named = fieldError(err);
+ if (!named) {
+ setError(err);
+ return;
+ }
+ // Nothing was saved: show why next to the list, and take focus there.
+ setFieldErrors({ [named.field]: named.text });
+ setError('Nothing was saved. Fix the entry marked above, then save again.');
+ if (named.field.startsWith('browser_')) setSitesOpen(true);
+ setTimeout(() => document.getElementById(fieldInputId(named.field))?.focus(), 0);
return;
}
onClose();
@@ -514,6 +551,60 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
<KwantToolsPicker model={model} selected={mcpIds} onChange={setMcpIds} onManageServers={onManageServers} approvalsOff={toolsRunFree} />
)}
+ {isEdit && sites && (
+ <details
+ className="group rounded-lg border border-zinc-800 bg-zinc-950/40"
+ open={sitesOpen}
+ onToggle={(e) => setSitesOpen((e.currentTarget as HTMLDetailsElement).open)}
+ data-browser-sites
+ >
+ <summary className="flex items-center gap-2 px-3 py-2 min-h-[40px] cursor-pointer select-none list-none [&::-webkit-details-marker]:hidden rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500">
+ <Globe size={13} className="flex-shrink-0 text-zinc-500" aria-hidden="true" />
+ <span className="text-xs font-medium text-zinc-400">Browser sites</span>
+ <span className="min-w-0 flex-1 truncate text-[11px] text-zinc-500" data-sites-summary>
+ · {sitesSummary(sites)}
+ </span>
+ <ChevronRight size={13} className="flex-shrink-0 text-zinc-500 transition-transform motion-reduce:transition-none group-open:rotate-90" aria-hidden="true" />
+ </summary>
+ <div className="space-y-3 px-3 pb-3 pt-1">
+ <p className="text-[11px] text-zinc-500 leading-snug">
+ Which sites this bot's own browser may open. <span className="font-mono text-zinc-400">example.com</span> includes
+ its subdomains; <span className="font-mono text-zinc-400">*.example.com</span> only the subdomains. Your own
+ browsing isn't limited.
+ </p>
+ <TagListInput
+ label="Allowed sites"
+ hint={sites.browser_allowed_sites.length ? 'only these' : 'empty: any site'}
+ placeholder="e.g. wikipedia.org — Enter to add"
+ value={sites.browser_allowed_sites}
+ limits={SITE_LIMITS}
+ {...listProps('browser_allowed_sites', (next) => setSites({ ...sites, browser_allowed_sites: next }))}
+ />
+ <TagListInput
+ label="Blocked sites"
+ hint="never these, even if allowed"
+ placeholder="e.g. facebook.com — Enter to add"
+ value={sites.browser_blocked_sites}
+ limits={SITE_LIMITS}
+ tone="bad"
+ {...listProps('browser_blocked_sites', (next) => setSites({ ...sites, browser_blocked_sites: next }))}
+ />
+ <label className="flex items-start gap-2 text-[11px] text-zinc-400">
+ <input
+ type="checkbox"
+ checked={sites.browser_block_private_network}
+ onChange={(e) => setSites({ ...sites, browser_block_private_network: e.target.checked })}
+ className="mt-0.5 accent-sky-500"
+ />
+ <span>
+ Block local and private network addresses
+ <span className="block text-zinc-500">localhost, 192.168.x.x, 10.x.x.x and names that point to them, such as your router</span>
+ </span>
+ </label>
+ </div>
+ </details>
+ )}
+
<div>
<label className="block text-xs font-medium text-zinc-400 mb-1">Persona & Instructions</label>
<textarea
@@ -538,23 +629,28 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
/>
</div>
- {isEdit && initial?.covers && (
+ {(!isEdit || initial?.covers) && (
<div className="space-y-3">
<TagListInput
label="Good for"
hint="what to send this bot"
placeholder="e.g. taxes, invoices — Enter to add"
value={covers}
- onChange={setCovers}
+ {...listProps('covers', setCovers)}
/>
<TagListInput
label="Not for"
hint="what never to send it"
placeholder="e.g. legal advice — Enter to add"
value={avoids}
- onChange={setAvoids}
+ {...listProps('avoids', setAvoids)}
tone="bad"
/>
+ {!isEdit && (
+ <p className="text-[11px] text-zinc-500 leading-snug">
+ Channels use these to pick who answers. Optional; you can change them later in the bot's settings.
+ </p>
+ )}
</div>
)}
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 7f4286a4..5aa3392c 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -36,6 +36,10 @@ export interface Kwant {
/** "Good for" / "Not for" phrases routing reads; absent on older servers. */
covers?: string[];
avoids?: string[];
+ /** Which sites its own browser may open (browser-borrowed/contract.md); absent on older servers. */
+ browser_allowed_sites?: string[];
+ browser_blocked_sites?: string[];
+ browser_block_private_network?: boolean;
}
export interface Channel {
diff --git a/frontend/src/components/TagListInput.tsx b/frontend/src/components/TagListInput.tsx
index ab9db138..700032d1 100644
--- a/frontend/src/components/TagListInput.tsx
+++ b/frontend/src/components/TagListInput.tsx
@@ -1,6 +1,6 @@
import React, { useId, useState } from 'react';
import { X } from 'lucide-react';
-import { MAX_TAGS, addTags } from '../tagList';
+import { PHRASE_LIMITS, TagLimits, addTags } from '../tagList';
/** A list of short phrases: type and press Enter (or a comma) to add one, × or Backspace to remove. */
export const TagListInput: React.FC<{
@@ -10,18 +10,31 @@ export const TagListInput: React.FC<{
value: string[];
onChange: (next: string[]) => void;
tone?: 'good' | 'bad';
-}> = ({ label, hint, placeholder, value, onChange, tone = 'good' }) => {
- const id = useId();
+ /** Defaults to the "Good for" / "Not for" rules. */
+ limits?: TagLimits;
+ /** What the server said about this list, shown like a typing error. */
+ serverError?: string | null;
+ /** For focusing the field from outside (a server error that names it). */
+ inputId?: string;
+}> = ({ label, hint, placeholder, value, onChange, tone = 'good', limits = PHRASE_LIMITS, serverError, inputId }) => {
+ const ownId = useId();
+ const id = inputId ?? ownId;
const [draft, setDraft] = useState('');
- const [error, setError] = useState<string | null>(null);
+ const [typedError, setError] = useState<string | null>(null);
+ const error = typedError ?? serverError ?? null;
const chip = tone === 'good' ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-100' : 'border-amber-500/30 bg-amber-500/10 text-amber-100';
+ const splits = (s: string) => new RegExp(limits.split.source).test(s);
+ const plain = limits !== PHRASE_LIMITS; // site names: no capitals or spell check
- const commit = () => {
- if (!draft.trim()) return;
- const r = addTags(value, draft);
+ const add = (typed: string) => {
+ const r = addTags(value, typed, limits);
setError(r.error);
if (r.list.length !== value.length) onChange(r.list);
- if (!r.error) setDraft('');
+ return r;
+ };
+ const commit = () => {
+ if (!draft.trim()) return;
+ if (!add(draft).error) setDraft('');
};
return (
@@ -29,7 +42,11 @@ export const TagListInput: React.FC<{
<label htmlFor={id} className="block text-xs font-medium text-zinc-400 mb-1">
{label} <span className="text-zinc-600 font-normal">· {hint}</span>
</label>
- <div className="flex flex-wrap items-center gap-1.5 w-full bg-zinc-950 border border-zinc-800 rounded-lg px-2 py-1.5 focus-within:border-sky-500 transition-colors">
+ <div
+ className={`flex flex-wrap items-center gap-1.5 w-full bg-zinc-950 border rounded-lg px-2 py-1.5 focus-within:border-sky-500 transition-colors ${
+ error ? 'border-rose-500/60' : 'border-zinc-800'
+ }`}
+ >
{value.map((t) => (
<span key={t} className={`inline-flex items-center gap-1 max-w-full rounded-md border pl-2 pr-0.5 text-[11px] ${chip}`}>
<span className="truncate">{t}</span>
@@ -49,12 +66,18 @@ export const TagListInput: React.FC<{
value={draft}
onChange={(e) => {
setError(null);
- if (e.target.value.includes(',')) {
- const r = addTags(value, e.target.value);
- setError(r.error);
- onChange(r.list);
+ if (splits(e.target.value) && e.target.value.trim()) {
+ add(e.target.value);
setDraft('');
- } else setDraft(e.target.value);
+ } else setDraft(e.target.value.trimStart() === '' ? '' : e.target.value);
+ }}
+ onPaste={(e) => {
+ // A text field drops line breaks from a pasted list; split it here instead.
+ const text = e.clipboardData.getData('text');
+ if (!/[\n,]/.test(text)) return;
+ e.preventDefault();
+ setError(null);
+ if (!add(draft + text).error) setDraft('');
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
@@ -64,8 +87,11 @@ export const TagListInput: React.FC<{
}}
onBlur={commit}
placeholder={value.length ? '' : placeholder}
+ aria-invalid={error ? true : undefined}
aria-describedby={error ? `${id}-err` : undefined}
- disabled={value.length >= MAX_TAGS && !draft}
+ disabled={value.length >= limits.max && !draft}
+ autoCapitalize={plain ? 'off' : undefined}
+ spellCheck={plain ? false : undefined}
className="flex-1 min-w-[8rem] bg-transparent py-0.5 text-xs text-zinc-100 placeholder-zinc-600 focus:outline-none"
/>
</div>
diff --git a/frontend/src/tagList.ts b/frontend/src/tagList.ts
index 6d0ae28f..60ac436e 100644
--- a/frontend/src/tagList.ts
+++ b/frontend/src/tagList.ts
@@ -4,20 +4,32 @@
export const MAX_TAGS = 20;
export const MAX_TAG_CHARS = 60;
+export type TagLimits = {
+ max: number;
+ /** Longest entry; 0 leaves the length to the server. */
+ maxChars: number;
+ /** What separates entries in typed or pasted text. */
+ split: RegExp;
+ /** The words for one entry in the messages ("one" for phrases, "site" for sites). */
+ noun?: string;
+};
+
+export const PHRASE_LIMITS: TagLimits = { max: MAX_TAGS, maxChars: MAX_TAG_CHARS, split: /[,\n]/ };
+
/** Adds what was typed (commas split it) to `list`, keeping the server's rules. */
-export function addTags(list: string[], typed: string): { list: string[]; error: string | null } {
+export function addTags(list: string[], typed: string, limits: TagLimits = PHRASE_LIMITS): { list: string[]; error: string | null } {
const out = [...list];
let error: string | null = null;
- for (const raw of typed.split(',')) {
+ for (const raw of typed.split(limits.split)) {
const t = raw.trim().replace(/\s+/g, ' ');
if (!t) continue;
- if (t.length > MAX_TAG_CHARS) {
- error = `Keep each one under ${MAX_TAG_CHARS} characters.`;
+ if (limits.maxChars && t.length > limits.maxChars) {
+ error = `Keep each one under ${limits.maxChars} characters.`;
continue;
}
if (out.some((x) => x.toLowerCase() === t.toLowerCase())) continue;
- if (out.length >= MAX_TAGS) {
- error = `Up to ${MAX_TAGS}. Remove one to add another.`;
+ if (out.length >= limits.max) {
+ error = `Up to ${limits.max}. Remove ${limits.noun ? `a ${limits.noun}` : 'one'} to add another.`;
break;
}
out.push(t);
diff --git a/frontend/tests/createSites064.test.mjs b/frontend/tests/createSites064.test.mjs
new file mode 100644
index 00000000..a4a0d693
--- /dev/null
+++ b/frontend/tests/createSites064.test.mjs
@@ -0,0 +1,370 @@
+// 0.6.4 follow-ups on the bot editor: "Good for" / "Not for" on the create form (POST /api/kwants
+// takes covers / avoids, router-concierge/contract.md §5), and a Browser sites section in bot
+// settings for the sites a bot's own browser may open (browser-borrowed/contract.md). These render
+// the whole space app in a DOM, so what's checked is the body that reaches the server.
+import assert from 'node:assert/strict';
+import test, { afterEach } from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_default', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+class FakeEvents {
+ addEventListener() {}
+ removeEventListener() {}
+ close() {}
+}
+g.EventSource = g.window.EventSource = FakeEvents;
+g.window.HTMLElement.prototype.scrollIntoView ??= () => {};
+
+const bot = (id, name, extra = {}) => ({ id, name, title: 'Role', persona_prompt: '', avatar_sprite: 'mouse', driver_type: 'claude', preferred_model: '', covers: [], avoids: [], ...extra });
+const sites = (allowed = [], blocked = [], priv = false) => ({ browser_allowed_sites: allowed, browser_blocked_sites: blocked, browser_block_private_network: priv });
+let kwants;
+const space = { id: 'spc_default', name: 'Default', icon: '💼', color: '#f59e0b', sort: 0, is_default: true, archived_at: null,
+ created_at: '', general_channel_id: 'ch1', counts: { bots: 2, ready_accounts: 1, unread: 0 } };
+
+// Every write the app sent, and what the next write to a path answers (default: 200 with the bot).
+let writes;
+let answer;
+const json = (b, status = 200) => new Response(JSON.stringify(b), { status, headers: { 'Content-Type': 'application/json' } });
+g.fetch = g.window.fetch = async (url, init = {}) => {
+ const path = String(url).split('?')[0];
+ const method = init.method ?? 'GET';
+ if (method !== 'GET') {
+ const body = init.body ? JSON.parse(init.body) : null;
+ writes.push({ method, path, body });
+ const a = answer[`${method} ${path}`];
+ if (a) return json(a.body, a.status);
+ if (method === 'POST' && path === '/api/kwants') return json({ ...bot('k_new', body.name), ...body, id: 'k_new' });
+ if (method === 'PUT' && path.startsWith('/api/kwants/') && !path.endsWith('/mcp-servers')) {
+ const id = path.split('/')[3];
+ return json({ ...kwants.find((k) => k.id === id), ...body });
+ }
+ return json({});
+ }
+ const routes = {
+ '/api/kwants': kwants,
+ '/api/channels': [{ id: 'ch1', name: 'general', kwant_ids: kwants.map((k) => k.id), created_at: '' }],
+ '/api/teams': [],
+ '/api/engines': [{ id: 'claude', kind: 'cli', enabled: true, status: 'ready', ready: true }],
+ '/api/automation-discovery': { setting: 'off', daily_cap: 3, blocked_by: [], last_scan_at: null, suggestions: [], stats: {} },
+ };
+ return json(path in routes ? routes[path] : []);
+};
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { SpaceApp } from './src/App';
+ export * from './src/browserSites';
+ export { addTags } from './src/tagList';
+`);
+const { React } = m;
+const noop = () => {};
+const settle = async () => {
+ for (let i = 0; i < 30; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const click = async (el) => {
+ assert.ok(el, 'the element to click is there');
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+const key = async (k, el = document.activeElement ?? document.body) => {
+ el.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true }));
+ await settle();
+};
+const type = async (el, text) => {
+ el.focus();
+ const proto = el.tagName === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
+ Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, text);
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+};
+/** Types a tag and presses Enter, the way a person adds one. */
+const addTag = async (input, text) => {
+ await type(input, text);
+ await key('Enter', input);
+};
+const paste = async (input, text) => {
+ input.focus();
+ const e = new Event('paste', { bubbles: true, cancelable: true });
+ e.clipboardData = { getData: () => text };
+ input.dispatchEvent(e);
+ await settle();
+};
+
+const mounted = new Set();
+afterEach(() => {
+ for (const unmount of mounted) unmount();
+ document.body.replaceChildren();
+});
+const mountSpace = async (over = {}) => {
+ writes = [];
+ answer = {};
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ root.render(React.createElement(m.SpaceApp, {
+ space, spaces: [space], initialTarget: null, onSwitchSpace: noop, onCreateSpace: noop, onOpenArchived: noop,
+ onSpacesChanged: noop, onSpaceArchived: noop, onChatChange: noop, ...over,
+ }));
+ await settle();
+ const unmount = () => {
+ if (!mounted.delete(unmount)) return;
+ root.unmount();
+ host.remove();
+ };
+ mounted.add(unmount);
+ return { unmount };
+};
+const q = (sel) => document.querySelector(sel);
+const button = (label) => [...document.querySelectorAll('button')].find((b) => b.getAttribute('aria-label') === label || b.textContent.trim() === label);
+const editor = () => q('[role="dialog"][aria-labelledby="agent-modal-title"]');
+const inputFor = (label) => {
+ const l = [...editor().querySelectorAll('label')].find((x) => x.textContent.trim().startsWith(label));
+ assert.ok(l, `a field labelled ${label}`);
+ return document.getElementById(l.htmlFor);
+};
+const errorOf = (input) => document.getElementById(input.getAttribute('aria-describedby') ?? '')?.textContent ?? null;
+const submit = async () => {
+ editor().querySelector('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+};
+const openCreate = async () => {
+ await mountSpace();
+ await click(button('New bot') ?? button('New bot in Default'));
+ assert.ok(editor(), 'the create form is open');
+ await type(q('#agent-name'), 'Foodie');
+};
+const openEdit = async (name = 'Ada') => {
+ await mountSpace({ initialView: { kind: 'settings', scope: 'space', tab: 'bots' } });
+ await click(button(`Edit ${name}`));
+ assert.ok(editor(), 'the bot editor is open');
+};
+const sitesSection = () => editor().querySelector('[data-browser-sites]');
+const postBody = () => writes.find((w) => w.method === 'POST' && w.path === '/api/kwants')?.body;
+const putBody = (id = 'k1') => writes.find((w) => w.method === 'PUT' && w.path === `/api/kwants/${id}`)?.body;
+
+const reset = () => {
+ kwants = [bot('k1', 'Ada', sites(['wikipedia.org'], [], false)), bot('k2', 'Lin')];
+};
+
+// ---------------------------------------------------------------------------
+// Helpers
+
+test('sitesOf reads the three fields, and is null when the server has none', () => {
+ reset();
+ assert.equal(m.sitesOf({ name: 'Old' }), null);
+ assert.deepEqual(m.sitesOf(kwants[0]), sites(['wikipedia.org']));
+ assert.deepEqual(m.sitesOf({ browser_allowed_sites: [], browser_blocked_sites: [] }), sites(), 'a missing toggle reads as off');
+});
+
+test('changedSites sends only what changed, so a profile edit leaves the rules alone', () => {
+ const before = sites(['a.com'], ['b.com'], false);
+ assert.deepEqual(m.changedSites(before, sites(['a.com'], ['b.com'], false)), {});
+ assert.deepEqual(m.changedSites(before, sites(['a.com', 'c.com'], ['b.com'], false)), { browser_allowed_sites: ['a.com', 'c.com'] });
+ assert.deepEqual(m.changedSites(before, sites(['a.com'], [], true)), { browser_blocked_sites: [], browser_block_private_network: true });
+});
+
+test('sitesSummary says what the closed section holds', () => {
+ assert.equal(m.sitesSummary(sites()), 'Any site');
+ assert.equal(m.sitesSummary(sites(['wikipedia.org'])), 'Only wikipedia.org');
+ assert.equal(m.sitesSummary(sites(['a.com', 'b.com', 'c.com'], ['evil.com'], true)), 'Only 3 sites · never evil.com · no local network');
+ assert.equal(m.sitesSummary(sites([], ['x.com', 'y.com'])), 'Never 2 sites');
+ assert.equal(m.sitesSummary(sites([], [], true)), 'No local network');
+});
+
+test('fieldError finds the list a 400 names; other errors stay whole', () => {
+ assert.deepEqual(m.fieldError('browser_allowed_sites: "a*b.com" isn\'t a site: use a domain such as example.com or *.example.com'), {
+ field: 'browser_allowed_sites',
+ text: '"a*b.com" isn\'t a site: use a domain such as example.com or *.example.com',
+ });
+ assert.deepEqual(m.fieldError('covers: at most 20 entries'), { field: 'covers', text: 'At most 20 entries' });
+ assert.deepEqual(m.fieldError('Browser_blocked_sites: "*" isn\'t a site'), { field: 'browser_blocked_sites', text: '"*" isn\'t a site' }, 'as the app capitalizes it');
+ assert.deepEqual(m.fieldError('avoids: each entry is at most 60 characters'), { field: 'avoids', text: 'Each entry is at most 60 characters' });
+ assert.equal(m.fieldError('only the person sets which sites a bot\'s browser may open'), null);
+ assert.equal(m.fieldError('Another bot is already named "Ada".'), null);
+});
+
+test('site lists split on spaces, commas and lines, keep up to 200, and leave the length to the server', () => {
+ const r = m.addTags([], 'wikipedia.org, en.wikipedia.org\n*.example.com WIKIPEDIA.org', m.SITE_LIMITS);
+ assert.deepEqual(r.list, ['wikipedia.org', 'en.wikipedia.org', '*.example.com']);
+ assert.equal(r.error, null);
+ const long = `${'a'.repeat(70)}.com`;
+ assert.deepEqual(m.addTags([], long, m.SITE_LIMITS).list, [long]);
+ const full = Array.from({ length: 200 }, (_, i) => `s${i}.com`);
+ assert.equal(m.addTags(full, 'one-more.com', m.SITE_LIMITS).error, 'Up to 200. Remove a site to add another.');
+ assert.equal(m.addTags([], 'a'.repeat(61)).error, 'Keep each one under 60 characters.', 'Good for keeps its 60-character rule');
+});
+
+// ---------------------------------------------------------------------------
+// Good for / Not for on create
+
+test('create: Good for and Not for are on the form and reach POST /api/kwants', async () => {
+ reset();
+ await openCreate();
+ await addTag(inputFor('Good for'), 'restaurants');
+ await addTag(inputFor('Good for'), 'street food');
+ await addTag(inputFor('Not for'), 'legal advice');
+ assert.ok(button('Remove street food') && button('Remove legal advice'), 'the phrases show as chips');
+ assert.ok(!sitesSection(), 'the Browser sites section is only in bot settings');
+ await submit();
+ const body = postBody();
+ assert.ok(body, 'the bot was created');
+ assert.deepEqual(body.covers, ['restaurants', 'street food']);
+ assert.deepEqual(body.avoids, ['legal advice']);
+ assert.ok(!('browser_allowed_sites' in body), 'no site rules on create');
+ assert.ok(!editor(), 'the form closed');
+});
+
+test('create: with no phrases the request has no covers / avoids, as before', async () => {
+ reset();
+ await openCreate();
+ await submit();
+ const body = postBody();
+ assert.ok(body);
+ assert.ok(!('covers' in body) && !('avoids' in body));
+});
+
+test('create: a 400 naming covers shows next to Good for, takes focus there, and keeps the form open', async () => {
+ reset();
+ await openCreate();
+ await addTag(inputFor('Good for'), 'food');
+ answer['POST /api/kwants'] = { status: 400, body: { error: 'covers: at most 20 entries' } };
+ await submit();
+ const good = inputFor('Good for');
+ assert.ok(editor(), 'the form stays open');
+ assert.equal(errorOf(good), 'At most 20 entries');
+ assert.equal(good.getAttribute('aria-invalid'), 'true');
+ assert.ok(document.activeElement === good, 'focus is on Good for');
+ assert.match(editor().textContent, /Nothing was saved\. Fix the entry marked above/);
+ await click(button('Remove food'));
+ assert.equal(errorOf(inputFor('Good for')), null, 'changing the list clears the server message');
+});
+
+test('create: typing a phrase and pressing Escape keeps the form open (it counts as unsaved)', async () => {
+ reset();
+ await mountSpace();
+ await click(button('New bot') ?? button('New bot in Default'));
+ await addTag(inputFor('Good for'), 'taxes');
+ inputFor('Good for').blur();
+ await key('Escape', editor());
+ assert.ok(editor(), 'a Good for phrase keeps it open');
+});
+
+// ---------------------------------------------------------------------------
+// Browser sites in bot settings
+
+test('edit: Browser sites is closed with a summary, opens to two lists and the private-network toggle', async () => {
+ reset();
+ await openEdit();
+ const s = sitesSection();
+ assert.ok(s, 'the section is there');
+ assert.equal(s.open, false, 'closed by default');
+ assert.match(s.querySelector('summary').textContent, /Browser sites.*Only wikipedia\.org/);
+ s.open = true;
+ s.dispatchEvent(new Event('toggle'));
+ await settle();
+ assert.ok(button('Remove wikipedia.org'), 'the stored allowed site is a chip');
+ assert.ok(inputFor('Blocked sites'));
+ const toggle = [...s.querySelectorAll('input[type="checkbox"]')].find((c) => c.closest('label').textContent.includes('Block local and private network'));
+ assert.ok(toggle && !toggle.checked, 'the toggle shows the stored value');
+});
+
+test('edit: a bot from a server without site rules has no Browser sites section', async () => {
+ reset();
+ kwants[1] = { ...kwants[1] };
+ await openEdit('Lin');
+ assert.ok(!sitesSection());
+});
+
+test('edit: a profile-only change sends no browser_* fields', async () => {
+ reset();
+ await openEdit();
+ await type(q('#agent-name'), 'Ada2');
+ await submit();
+ const body = putBody();
+ assert.ok(body, 'saved');
+ assert.equal(body.name, 'Ada2');
+ for (const k of ['browser_allowed_sites', 'browser_blocked_sites', 'browser_block_private_network']) assert.ok(!(k in body), `${k} left out`);
+});
+
+test('edit: added sites, a removed one and the toggle are sent; untouched lists are left out', async () => {
+ reset();
+ await openEdit();
+ const s = sitesSection();
+ s.open = true;
+ s.dispatchEvent(new Event('toggle'));
+ await settle();
+ await paste(inputFor('Allowed sites'), 'en.wikipedia.org\nhttps://docs.rs/serde');
+ await click(button('Remove wikipedia.org'));
+ const toggle = [...s.querySelectorAll('input[type="checkbox"]')].find((c) => c.closest('label').textContent.includes('Block local'));
+ await click(toggle);
+ assert.match(s.querySelector('summary').textContent, /Only 2 sites · no local network/, 'the summary follows the edit');
+ await submit();
+ const body = putBody();
+ assert.deepEqual(body.browser_allowed_sites, ['en.wikipedia.org', 'https://docs.rs/serde'], 'sent as typed; the server keeps the host');
+ assert.equal(body.browser_block_private_network, true);
+ assert.ok(!('browser_blocked_sites' in body), 'the untouched blocked list is left out');
+});
+
+test('edit: a 400 naming a bad site opens the section, shows the message under that list and focuses it', async () => {
+ reset();
+ await openEdit();
+ const s = sitesSection();
+ s.open = true;
+ s.dispatchEvent(new Event('toggle'));
+ await settle();
+ await addTag(inputFor('Blocked sites'), 'a*b.com');
+ s.open = false;
+ s.dispatchEvent(new Event('toggle'));
+ await settle();
+ answer['PUT /api/kwants/k1'] = {
+ status: 400,
+ body: { error: 'browser_blocked_sites: "a*b.com" isn\'t a site: use a domain such as example.com or *.example.com' },
+ };
+ await submit();
+ assert.ok(editor(), 'the editor stays open');
+ assert.equal(sitesSection().open, true, 'the section opened to show it');
+ const blocked = inputFor('Blocked sites');
+ assert.equal(errorOf(blocked), '"a*b.com" isn\'t a site: use a domain such as example.com or *.example.com');
+ assert.equal(errorOf(inputFor('Allowed sites')), null, 'only the named list');
+ assert.ok(document.activeElement === blocked, 'focus is on Blocked sites');
+ assert.match(editor().textContent, /Nothing was saved/);
+ await click(button('Remove a*b.com'));
+ assert.equal(errorOf(inputFor('Blocked sites')), null);
+});
+
+test('edit: the 403 for a bot\'s token shows as the form error', async () => {
+ reset();
+ await openEdit();
+ const s = sitesSection();
+ s.open = true;
+ s.dispatchEvent(new Event('toggle'));
+ await settle();
+ await addTag(inputFor('Allowed sites'), 'example.com');
+ answer['PUT /api/kwants/k1'] = { status: 403, body: { error: 'only the person sets which sites a bot\'s browser may open' } };
+ await submit();
+ assert.ok(editor());
+ assert.match(editor().textContent, /Only the person sets which sites a bot's browser may open/);
+ assert.ok(!sitesSection().querySelector('[role="alert"]'), 'not pinned on a list: it is about who may set them');
+});
+
+test('edit: a changed site list keeps the editor open on Escape', async () => {
+ reset();
+ await openEdit();
+ await key('Escape', editor());
+ assert.ok(!editor(), 'untouched, Escape closes it');
+ await click(button('Edit Ada'));
+ const s = sitesSection();
+ s.open = true;
+ s.dispatchEvent(new Event('toggle'));
+ await settle();
+ await click(button('Remove wikipedia.org'));
+ await key('Escape', editor());
+ assert.ok(editor(), 'a removed site keeps it open');
+});