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 a person-facing "New channel" action

Pixel (kwant bot)61508d92e6a6
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 2d74b56e..df2a7a60 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -33,6 +33,8 @@ import { AlertTriangle, Bot, Check, HelpCircle, Inbox, KeyRound, ListChecks, Loa
import { ChatApproval, OpenChat, approvalFromEvent, lateAnswerText, approvalsForChat, approvalsFromAway, syncApprovals, upsertApproval, withoutApproval } from './approvals';
import type { AgentFormData } from './components/NewAgentModal';
import { NewTeamModal } from './components/NewTeamModal';
+import { NewChannelModal } from './components/NewChannelModal';
+import type { NewChannelBody } from './channels';
import { ManageTeamModal } from './components/ManageTeamModal';
import { playSfx } from './audio/chiptune';
import { Toasts, Toast } from './components/Toasts';
@@ -512,6 +514,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// Team that a newly created bot should join (set by a team's "Add member")
const [newAgentTeam, setNewAgentTeam] = useState<Team | null>(null);
const [isNewTeamOpen, setIsNewTeamOpen] = useState(false);
+ const [isNewChannelOpen, setIsNewChannelOpen] = useState(false);
const [editingTeam, setEditingTeam] = useState<Team | null>(null);
const [editingKwant, setEditingKwant] = useState<Kwant | null>(null);
const [deletingKwant, setDeletingKwant] = useState<Kwant | null>(null);
@@ -1905,6 +1908,31 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
};
+ /** Creates a channel and opens it; resolves to what went wrong, or null. */
+ const handleCreateChannel = async (body: NewChannelBody): Promise<string | null> => {
+ try {
+ const res = await fetch('/api/channels', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ if (!res.ok) {
+ const data = await res.json().catch(() => null);
+ return typeof data?.error === 'string' ? data.error : `Could not create the channel (HTTP ${res.status}).`;
+ }
+ const created: Channel = await res.json();
+ setChannels((prev) => (prev.some((c) => c.id === created.id) ? prev : [...prev, created]));
+ messagesCacheRef.current[created.id] = [];
+ setIsNewChannelOpen(false);
+ handleSelectChannel(created);
+ playSfx('fanfare');
+ onSpacesChanged();
+ return null;
+ } catch {
+ return 'Could not reach the server.';
+ }
+ };
+
const handleCreateTeam = async (teamData: {
name: string;
description?: string;
@@ -2565,6 +2593,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setIsNewTeamOpen(true);
playSfx('click');
}}
+ onCreateChannel={() => {
+ setIsNewChannelOpen(true);
+ playSfx('click');
+ }}
awayCount={awayCount}
awayActive={showAway}
looseActive={showLoose}
@@ -2855,6 +2887,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
)}
</Suspense>
+ <NewChannelModal
+ isOpen={isNewChannelOpen}
+ onClose={() => setIsNewChannelOpen(false)}
+ kwants={kwants}
+ channels={channels}
+ onCreate={handleCreateChannel}
+ />
+
{/* New Team Modal */}
<NewTeamModal
isOpen={isNewTeamOpen}
diff --git a/frontend/src/channels.ts b/frontend/src/channels.ts
new file mode 100644
index 00000000..2e3f3d47
--- /dev/null
+++ b/frontend/src/channels.ts
@@ -0,0 +1,75 @@
+// Channels people make themselves: the name rules, what "New channel" sends, and when Laya picks
+// who answers. No imports, so the node tests can load it on its own.
+
+const unique = (ids: string[]) => ids.filter((id, i) => ids.indexOf(id) === i);
+
+type ChannelLike = { name: string; lead_kwant_id?: string | null; member_kwants?: string[] | string | null; routing_mode?: string | null };
+
+/** What a typed name becomes: no leading #, lower case, spaces and other characters as dashes. */
+export function channelSlug(typed: string): string {
+ return typed
+ .trim()
+ .replace(/^#+/, '')
+ .toLowerCase()
+ .replace(/[^a-z0-9_-]+/g, '-')
+ .replace(/-{2,}/g, '-')
+ .replace(/^-|-$/g, '');
+}
+
+/** Why `slug` can't be a new channel here, or null when it can. */
+export function channelNameError(slug: string, existing: { name: string }[]): string | null {
+ if (!slug) return 'Give the channel a name.';
+ if (slug.length > 80) return 'Use 80 characters or fewer.';
+ if (slug.startsWith('team-')) return 'Names starting with "team-" are kept for team chats.';
+ if (existing.some((c) => c.name.toLowerCase() === slug)) return `#${slug} already exists in this space.`;
+ return null;
+}
+
+export interface NewChannelBody {
+ name: string;
+ description?: string;
+ lead_kwant_id: string;
+ member_kwants: string[];
+ routing_mode: 'auto';
+}
+
+/** The `POST /api/channels` body: the first bot picked leads, and the lead is always a member. */
+export function newChannelBody(name: string, description: string, members: string[]): NewChannelBody {
+ const ids = unique(members);
+ const body: NewChannelBody = { name, lead_kwant_id: ids[0] ?? '', member_kwants: ids, routing_mode: 'auto' };
+ const d = description.trim();
+ if (d) body.description = d;
+ return body;
+}
+
+/** A channel's member list: the server sends it as a JSON string, older code as an array. */
+function memberList(raw: ChannelLike['member_kwants']): string[] {
+ if (Array.isArray(raw)) return raw;
+ if (typeof raw !== 'string') return [];
+ try {
+ const v = JSON.parse(raw);
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
+ } catch {
+ return [];
+ }
+}
+
+/** The channel's bots: its members, plus its lead where an older row leaves it out. */
+export function channelBotIds(c: ChannelLike): string[] {
+ const ids = memberList(c.member_kwants);
+ return unique(c.lead_kwant_id ? [c.lead_kwant_id, ...ids] : ids);
+}
+
+/** Whether Laya picks who answers in `c`: #general once the space has 2+ bots, any other channel
+ * on auto routing with 2+ bots of its own. */
+export function layaRoutes(c: ChannelLike, botsInSpace: number): boolean {
+ if (c.name === 'general') return botsInSpace >= 2;
+ return (c.routing_mode ?? 'auto') === 'auto' && channelBotIds(c).length >= 2;
+}
+
+/** The line under the bot picker, for `picked` bots. */
+export function routingHint(picked: number): string {
+ if (picked === 0) return 'Pick at least one bot.';
+ if (picked === 1) return 'With one bot, it answers every message. Add another and Laya picks who answers.';
+ return 'Laya picks which of these bots answers each message.';
+}
diff --git a/frontend/src/components/NewChannelModal.tsx b/frontend/src/components/NewChannelModal.tsx
new file mode 100644
index 00000000..727588bf
--- /dev/null
+++ b/frontend/src/components/NewChannelModal.tsx
@@ -0,0 +1,222 @@
+import React, { useEffect, useId, useRef, useState } from 'react';
+import { AlertCircle, Hash, X } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import type { Channel, Kwant } from './Sidebar';
+import { playSfx } from '../audio/chiptune';
+import { channelNameError, channelSlug, newChannelBody, routingHint } from '../channels';
+
+export interface NewChannelModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ kwants: Kwant[];
+ channels: Channel[];
+ /** Creates the channel; resolves to an error message, or null once it exists. */
+ onCreate: (body: ReturnType<typeof newChannelBody>) => Promise<string | null>;
+}
+
+const input =
+ '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';
+
+export const NewChannelModal: React.FC<NewChannelModalProps> = ({ isOpen, onClose, kwants, channels, onCreate }) => {
+ const [name, setName] = useState('');
+ const [description, setDescription] = useState('');
+ const [members, setMembers] = useState<string[]>([]);
+ const [touched, setTouched] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const nameRef = useRef<HTMLInputElement>(null);
+ const titleId = useId();
+ const nameId = useId();
+ const hintId = useId();
+
+ useEffect(() => {
+ if (!isOpen) return;
+ setName('');
+ setDescription('');
+ // Every bot to start with, so Laya has someone to choose from
+ setMembers(kwants.map((k) => k.id));
+ setTouched(false);
+ setError(null);
+ setSubmitting(false);
+ requestAnimationFrame(() => nameRef.current?.focus());
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isOpen]);
+
+ useEffect(() => {
+ if (!isOpen) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape' && !submitting) onClose();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [isOpen, submitting, onClose]);
+
+ if (!isOpen) return null;
+
+ const slug = channelSlug(name);
+ const nameError = channelNameError(slug, channels);
+ const showNameError = touched && !!nameError;
+
+ const toggle = (id: string) =>
+ setMembers((prev) => (prev.includes(id) ? prev.filter((m) => m !== id) : [...prev, id]));
+
+ const submit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ setTouched(true);
+ if (nameError || members.length === 0 || submitting) return;
+ setSubmitting(true);
+ setError(null);
+ const failed = await onCreate(newChannelBody(slug, description, members));
+ setSubmitting(false);
+ if (failed) setError(failed);
+ };
+
+ return (
+ <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4" onMouseDown={(e) => e.target === e.currentTarget && !submitting && onClose()}>
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={titleId}
+ className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-md w-full max-h-[calc(100dvh-2rem)] overflow-y-auto p-5 sm: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">
+ <Hash size={15} />
+ </div>
+ <h3 id={titleId} className="text-sm font-semibold text-zinc-100">
+ New channel
+ </h3>
+ </div>
+ <button
+ type="button"
+ aria-label="Close"
+ onClick={() => {
+ playSfx('click');
+ onClose();
+ }}
+ className="p-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <X size={17} />
+ </button>
+ </div>
+
+ {error && (
+ <div role="alert" className="p-2.5 rounded-lg bg-rose-500/10 border border-rose-500/20 flex items-center gap-2 text-rose-400 text-xs">
+ <AlertCircle size={15} className="flex-shrink-0" />
+ <span>{error}</span>
+ </div>
+ )}
+
+ {kwants.length === 0 ? (
+ <p className="text-xs text-zinc-400">Add a bot to this space first. A channel needs at least one bot to answer.</p>
+ ) : (
+ <form onSubmit={submit} className="space-y-4" noValidate>
+ <div>
+ <label htmlFor={nameId} className="block text-xs font-medium text-zinc-400 mb-1">
+ Name
+ </label>
+ <div className="relative">
+ <Hash size={13} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500" aria-hidden />
+ <input
+ id={nameId}
+ ref={nameRef}
+ type="text"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ onBlur={() => name && setTouched(true)}
+ placeholder="e.g. launch-plan"
+ autoComplete="off"
+ aria-invalid={showNameError}
+ aria-describedby={showNameError ? `${nameId}-err` : undefined}
+ className={`${input} pl-8 ${showNameError ? 'border-rose-500/60' : ''}`}
+ />
+ </div>
+ {showNameError ? (
+ <p id={`${nameId}-err`} className="text-[11px] text-rose-400 mt-1">
+ {nameError}
+ </p>
+ ) : (
+ slug &&
+ slug !== name.trim() && (
+ <p className="text-[11px] text-zinc-500 mt-1">
+ Saved as <span className="font-mono text-sky-400">#{slug}</span>
+ </p>
+ )
+ )}
+ </div>
+
+ <div>
+ <label className="block text-xs font-medium text-zinc-400 mb-1">
+ What it's for <span className="text-zinc-600 font-normal">(optional)</span>
+ <input
+ type="text"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder="e.g. Planning the spring launch"
+ className={`${input} mt-1 font-normal`}
+ />
+ </label>
+ </div>
+
+ <fieldset aria-describedby={hintId}>
+ <div className="flex items-center justify-between mb-1.5">
+ <legend className="text-xs font-medium text-zinc-400">Bots in this channel</legend>
+ <span className="text-[11px] font-mono text-zinc-500">{members.length} picked</span>
+ </div>
+ <div className="space-y-1 max-h-52 overflow-y-auto pr-1">
+ {kwants.map((k) => {
+ const on = members.includes(k.id);
+ return (
+ <label
+ key={k.id}
+ className={`flex items-center gap-2.5 p-2 rounded-lg border text-xs cursor-pointer transition-all focus-within:outline focus-within:outline-2 focus-within:outline-sky-500 ${
+ on ? 'border-sky-500/40 bg-sky-500/10 text-zinc-100' : 'border-zinc-800 bg-zinc-950/60 text-zinc-400 hover:border-zinc-700'
+ }`}
+ >
+ <input
+ type="checkbox"
+ checked={on}
+ onChange={() => toggle(k.id)}
+ className="rounded border-zinc-700 bg-zinc-900 text-sky-500 focus:ring-0 focus:ring-offset-0"
+ />
+ <ModernAvatar role={k.avatar_sprite} name={k.name} size={24} />
+ <span className="truncate">
+ <span className="font-semibold text-zinc-200">{k.name}</span>
+ <span className="text-[10px] text-zinc-400 ml-1.5">{k.title}</span>
+ </span>
+ </label>
+ );
+ })}
+ </div>
+ <p id={hintId} className={`text-[11px] mt-1.5 ${members.length === 0 && touched ? 'text-rose-400' : 'text-zinc-500'}`}>
+ {routingHint(members.length)}
+ </p>
+ </fieldset>
+
+ <div className="flex items-center justify-end gap-2.5 pt-2 border-t border-zinc-800">
+ <button
+ type="button"
+ onClick={() => {
+ playSfx('click');
+ onClose();
+ }}
+ className="px-3.5 py-2 rounded-lg text-xs font-medium text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={submitting || members.length === 0}
+ className="px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5"
+ >
+ <Hash size={14} />
+ <span>{submitting ? 'Creating…' : 'Create channel'}</span>
+ </button>
+ </div>
+ </form>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index c6b57307..174a4025 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -12,6 +12,7 @@ import { isMac } from './LayaStatus';
import { ApprovalsOffBadge } from './ApprovalsSetting';
import { approvalsOff, spaceOffLine } from '../approvalMode';
import { teamChannelOf } from '../teamChannel';
+import { layaRoutes } from '../channels';
import { InstallAppButton } from './InstallAppButton';
export interface Kwant {
@@ -90,6 +91,8 @@ export interface SidebarProps {
/** Opens the new-bot form; with a team, the new bot joins it. */
onSummonKwant: (team?: Team) => void;
onCreateTeam: () => void;
+ /** Opens the new-channel form. */
+ onCreateChannel?: () => void;
/** "While you were away": unseen count for the badge, whether it's open, and how to open it. */
awayCount?: number;
awayActive?: boolean;
@@ -149,6 +152,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
onEditKwant,
onSummonKwant,
onCreateTeam,
+ onCreateChannel,
awayCount = 0,
awayActive = false,
looseActive = false,
@@ -320,8 +324,19 @@ export const Sidebar: React.FC<SidebarProps> = ({
{/* Channels Section */}
{showChats && (
<div>
- <div className="px-2 py-1 text-[11px] font-semibold text-zinc-500 uppercase tracking-wider">
- Channels
+ <div className="px-2 py-1 flex items-center justify-between text-[11px] font-semibold text-zinc-500 uppercase tracking-wider">
+ <span>Channels</span>
+ {onCreateChannel && kwants.length > 0 && (
+ <button
+ type="button"
+ onClick={onCreateChannel}
+ className="flex items-center gap-1 text-[10px] font-medium text-sky-400 hover:text-sky-300 hover:bg-sky-500/10 px-1.5 py-0.5 rounded border border-sky-500/20 transition-all normal-case tracking-normal focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ title={`New channel in ${space.name}`}
+ >
+ <Plus size={11} />
+ <span>New channel</span>
+ </button>
+ )}
</div>
<div className="mt-1 space-y-0.5">
{displayChannels.map((c) => {
@@ -338,7 +353,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
>
<Hash size={15} className={active ? 'text-sky-400' : 'text-zinc-500'} />
<span className="truncate flex-1">{c.name}</span>
- {c.name === 'general' && (
+ {layaRoutes(c, kwants.length) && (
<span className="shrink-0 text-[10px] px-1.5 py-px rounded-full border border-violet-500/30 bg-violet-500/10 text-violet-200" title="Laya picks who answers here">
Laya
</span>
diff --git a/frontend/tests/newChannel.test.mjs b/frontend/tests/newChannel.test.mjs
new file mode 100644
index 00000000..030ea7f9
--- /dev/null
+++ b/frontend/tests/newChannel.test.mjs
@@ -0,0 +1,62 @@
+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 } });
+ return import(`data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`);
+};
+
+const c = await load('../src/channels.ts');
+
+test('a typed name becomes a channel handle', () => {
+ assert.equal(c.channelSlug(' #Launch Plan 2027! '), 'launch-plan-2027');
+ assert.equal(c.channelSlug('###'), '');
+ assert.equal(c.channelSlug('ops_team'), 'ops_team');
+});
+
+test('names that would clash or look like a team chat are refused with a reason', () => {
+ const existing = [{ name: 'general' }, { name: 'launch' }];
+ assert.equal(c.channelNameError('', existing), 'Give the channel a name.');
+ assert.match(c.channelNameError('launch', existing), /#launch already exists/);
+ assert.match(c.channelNameError('team-ops', existing), /kept for team chats/);
+ assert.equal(c.channelNameError('marketing', existing), null);
+});
+
+test('the request: first bot picked leads, the lead is a member, Laya routing on', () => {
+ assert.deepEqual(c.newChannelBody('launch', ' ', ['b', 'a', 'b']), {
+ name: 'launch',
+ lead_kwant_id: 'b',
+ member_kwants: ['b', 'a'],
+ routing_mode: 'auto',
+ });
+ assert.equal(c.newChannelBody('launch', ' For the launch ', ['a']).description, 'For the launch');
+});
+
+test('the Laya pill follows the routing rule, not the channel name', () => {
+ const two = { name: 'launch', lead_kwant_id: 'a', member_kwants: '["a","b"]', routing_mode: 'auto' };
+ assert.equal(c.layaRoutes(two, 3), true, 'members arrive as a JSON string');
+ assert.equal(c.layaRoutes({ ...two, member_kwants: ['b'] }, 3), true, 'an older row that leaves the lead out still counts it');
+ assert.equal(c.layaRoutes({ ...two, member_kwants: '["a"]' }, 3), false, 'one bot: nobody to choose between');
+ assert.equal(c.layaRoutes({ ...two, routing_mode: 'lead' }, 3), false);
+ assert.equal(c.layaRoutes({ name: 'general', lead_kwant_id: 'a', member_kwants: '[]', routing_mode: 'auto' }, 2), true);
+ assert.equal(c.layaRoutes({ name: 'general', lead_kwant_id: 'a', member_kwants: '[]', routing_mode: 'auto' }, 1), false);
+});
+
+test('the picker explains what one bot versus several means', () => {
+ assert.match(c.routingHint(0), /at least one/);
+ assert.match(c.routingHint(1), /Add another and Laya picks/);
+ assert.match(c.routingHint(3), /Laya picks/);
+});
+
+test('the sidebar offers New channel and the app creates it through /api/channels', async () => {
+ const sidebar = await readFile(new URL('../src/components/Sidebar.tsx', import.meta.url), 'utf8');
+ const app = await readFile(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ assert.match(sidebar, /New channel/);
+ assert.match(sidebar, /layaRoutes\(c, kwants\.length\)/);
+ assert.doesNotMatch(sidebar, /c\.name === 'general' && \(/, 'the pill is no longer #general only');
+ assert.match(app, /<NewChannelModal/);
+ assert.match(app, /fetch\('\/api\/channels', \{\s*method: 'POST'/);
+});