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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Spaces S3: space rail, per-space settings and "kwant bots" wording
Lin (kwant bot)199a8c978598
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex c7ba5667..22747c2d 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -1,12 +1,13 @@import React, { Suspense, lazy, useState, useEffect, useRef, useCallback } from 'react';-import { AppHeader } from './components/AppHeader';import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar';+import { SpaceSettings, SpaceSettingsTab } from './components/SpaceSettings';+import { SpaceTile } from './components/Spaces';import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState } from './components/ChatView';import { ThreadBar, ThreadHeader } from './components/ThreadBar';import { DelegationCard } from './components/DelegationCard';import { QuestionCard } from './components/QuestionCard';import { AwayPage } from './components/AwayView';-import { HelpCircle, ListChecks, Loader2 } from 'lucide-react';+import { Bot, Check, HelpCircle, Inbox, KeyRound, ListChecks, Loader2, MessageSquare, Settings } from 'lucide-react';import { PendingApproval } from './components/ModernApprovalCard';import type { AgentFormData } from './components/NewAgentModal';import { NewTeamModal } from './components/NewTeamModal';@@ -58,20 +59,77 @@ import {questionsApi,turnsAwaitingAnswer,} from './questions';-import { AwayItem, affectsAway, awayApi, awayTarget } from './away';+import { AwayItem, affectsAway, awayApi, awayTarget, badgeText } from './away';+import { Space, eventsUrl, spaceColor } from './spaces';// Kwant and Tools editors are their own chunks. They stay mounted (rendering nothing while closed),// so both load right after start-up and opening them never waits.const NewAgentModal = lazy(() => import('./components/NewAgentModal').then((m) => ({ default: m.NewAgentModal })));const McpServersModal = lazy(() => import('./components/McpServersModal').then((m) => ({ default: m.McpServersModal })));-const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) => ({ default: m.SettingsModal })));const ChannelInstructionsModal = lazy(() =>import('./components/ChannelInstructionsModal').then((m) => ({ default: m.ChannelInstructionsModal })),);const SearchModal = lazy(() => import('./components/SearchModal').then((m) => ({ default: m.SearchModal })));const RoutinesModal = lazy(() => import('./components/RoutinesModal').then((m) => ({ default: m.RoutinesModal })));-export const App: React.FC = () => {+/** Where to land when a space opens: a channel or a bot's direct chat. */+export interface SpaceTarget {+ channelId?: string;+ botId?: string;+}++export interface SpaceAppProps {+ space: Space;+ spaces: Space[];+ initialTarget: SpaceTarget | null;+ onSwitchSpace: (id: string, to?: SpaceTarget | null) => void;+ onCreateSpace: () => void;+ onOpenArchived: () => void;+ onOpenAppSettings: () => void;+ /** Re-reads the space list (counts, #general appearing, a rename). */+ onSpacesChanged: () => void;+ onSpaceArchived: (space: Space) => void;+ /** The open chat changed, for the address bar and reopening it later. */+ onChatChange: (target: SpaceTarget) => void;+ onTokensUsed: (n: number) => void;+}++const PHONE_QUERY = '(max-width: 767px)';++/** Below 768px the space is one column: a list or a chat, with a tab bar. */+function useIsPhone(): boolean {+ const [phone, setPhone] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.(PHONE_QUERY).matches);+ useEffect(() => {+ const mq = window.matchMedia?.(PHONE_QUERY);+ if (!mq) return;+ const on = () => setPhone(mq.matches);+ mq.addEventListener('change', on);+ return () => mq.removeEventListener('change', on);+ }, []);+ return phone;+}++type PhoneTab = 'chats' | 'bots' | 'inbox' | 'space';++/** One space: its bots, teams, channels and chats. Remounted for every space, so nothing carries over. */+export const SpaceApp: React.FC<SpaceAppProps> = ({+ space,+ spaces,+ initialTarget,+ onSwitchSpace,+ onCreateSpace,+ onOpenArchived,+ onOpenAppSettings,+ onSpacesChanged,+ onSpaceArchived,+ onChatChange,+ onTokensUsed,+}) => {+ const isPhone = useIsPhone();+ // Phones: the list (one tab of it) or the open chat.+ const [phoneView, setPhoneView] = useState<'list' | 'chat'>(() => (initialTarget?.channelId || initialTarget?.botId ? 'chat' : 'list'));+ const [phoneTab, setPhoneTab] = useState<PhoneTab>('chats');+ const [loaded, setLoaded] = useState(false);const [kwants, setKwants] = useState<Kwant[]>([]);const [channels, setChannels] = useState<Channel[]>([]);const [teams, setTeams] = useState<Team[]>([]);@@ -80,7 +138,7 @@ export const App: React.FC = () => {const [selectedTeamId, setSelectedTeamId] = useState<string | null>(null);const [messages, setMessages] = useState<ChatMessage[]>([]);const [messagesError, setMessagesError] = useState<string | null>(null);- // The open thread of the selected agent; null for its direct chat (and for channels).+ // The open thread of the selected bot; null for its direct chat (and for channels).const [openThreadId, setOpenThreadId] = useState<string | null>(null);const openCtx = openThreadId || selectedId;const openCtxRef = useRef(openCtx);@@ -132,19 +190,25 @@ export const App: React.FC = () => {const [pendingApproval, setPendingApproval] = useState<PendingApproval | null>(null);const [tokensUsed, setTokensUsed] = useState(0);- // Modals state- const [isSettingsOpen, setIsSettingsOpen] = useState(false);- // Bumped when Settings closes, so open kwant forms read engine status again.+ // Space settings: open on one tab, or closed.+ const [spaceSettingsTab, setSpaceSettingsTab] = useState<SpaceSettingsTab | null>(null);+ // Bumped when Space settings closes, so open bot forms read account status again.const [settingsClosedCount, setSettingsClosedCount] = useState(0);- // Set when Settings opens from a "Sign in with Claude" hint, to focus that button.+ // Set when Accounts opens from a "Sign in with Claude" hint, to focus that button.const [claudeSignInFocus, setClaudeSignInFocus] = useState(0);- const openSettings = () => {+ const openSpaceSettings = (tab: SpaceSettingsTab = 'general') => {setClaudeSignInFocus(0);- setIsSettingsOpen(true);+ setSpaceSettingsTab(tab);+ playSfx('click');};+ const openSettings = () => openSpaceSettings('accounts');const openClaudeSignIn = () => {setClaudeSignInFocus(Date.now());- setIsSettingsOpen(true);+ setSpaceSettingsTab('accounts');+ };+ const closeSpaceSettings = () => {+ setSpaceSettingsTab(null);+ setSettingsClosedCount((n) => n + 1);};const [isMcpOpen, setIsMcpOpen] = useState(false);const [isSearchOpen, setIsSearchOpen] = useState(false);@@ -170,12 +234,14 @@ 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).+ // Opens a bot's settings on the Skills tab (set once the bots are known).const openSkillsRef = useRef<(kwantId: string) => void>(() => undefined);- // Opens the chat of an agent's newest open question; false when it has none.+ // Opens the chat of a bot's newest open question; false when it has none.const openQuestionRef = useRef<(kwantId: string) => boolean>(() => false);const openTargetRef = useRef<(t: { channel_id: string | null; kwant_id: string | null }) => boolean>(() => false);const showNotification = (n: NotifyEvent) => {+ // Another space's news is the shell's to show, with a way to switch there.+ if (n.space_id && n.space_id !== space.id) return;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)) {@@ -310,15 +376,15 @@ export const App: React.FC = () => {};const [isNewAgentOpen, setIsNewAgentOpen] = useState(false);- // Team that a newly created agent should join (set by a team's "Add member")+ // 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 [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.+ // Skills waiting for review, for the counts on the bot's header and Skills tab.const [pendingSkills, setPendingSkills] = useState<Skill[]>([]);- // Agents' questions by id: open ones from the server, plus every question_updated since.+ // Bots' questions by id: open ones from the server, plus every question_updated since.const [questions, setQuestions] = useState<Record<string, Question>>({});const questionsRef = useRef(questions);questionsRef.current = questions;@@ -357,14 +423,26 @@ export const App: React.FC = () => {setChannels(cRes);setTeams(normalizedTeams);- if (cRes.length > 0) {- const initId = cRes[0].id;+ // The chat asked for (a link, a notification, the last one open here) if it still exists.+ const wantBot = initialTarget?.botId ? (kRes as Kwant[]).find((k) => k.id === initialTarget.botId) : undefined;+ const wantChannel = initialTarget?.channelId+ ? (cRes as Channel[]).find((c) => c.id === initialTarget.channelId)+ : (cRes as Channel[]).find((c) => c.id === space.general_channel_id);+ if (wantBot && !wantChannel) {+ setSelectedId(wantBot.id);+ selectedIdRef.current = wantBot.id;+ setIsChannel(false);+ isChannelRef.current = false;+ setSelectedTeamId(null);+ } else if (wantChannel || cRes.length > 0) {+ const init: Channel = wantChannel ?? cRes[0];+ const initId = init.id;setSelectedId(initId);selectedIdRef.current = initId;setIsChannel(true);isChannelRef.current = true;const matchedTeam = normalizedTeams.find(- (t) => `team-${t.name}` === cRes[0].name || t.id === cRes[0].id+ (t) => `team-${t.name}` === init.name || t.id === init.id);setSelectedTeamId(matchedTeam ? matchedTeam.id : null);} else if (kRes.length > 0) {@@ -377,6 +455,8 @@ export const App: React.FC = () => {}} catch (err) {console.error('Failed to load initial data:', err);+ } finally {+ setLoaded(true);}}loadInitialData();@@ -400,7 +480,7 @@ export const App: React.FC = () => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [openCtx]);- // An agent's conversations load when its chat opens; SSE keeps them current from then on.+ // A bot's conversations load when its chat opens; SSE keeps them current from then on.useEffect(() => {if (!selectedId || isChannel || threadsByKwantRef.current[selectedId] !== undefined) return;loadThreads(selectedId);@@ -423,7 +503,7 @@ export const App: React.FC = () => {// Connect to SSE streamuseEffect(() => {- const sse = new EventSource('/api/events');+ const sse = new EventSource(eventsUrl(space.id));let dropped = false;/** TurnComplete already refreshed these turns' chats; their turn_ended needn't again. */const completed = new Set<string>();@@ -457,7 +537,7 @@ export const App: React.FC = () => {dropped = true;};// First connect and every reconnect: running turns from the server. After a drop, also- // whatever changed meanwhile in the open chat and the open agent's conversations.+ // whatever changed meanwhile in the open chat and the open bot's conversations.sse.onopen = () => {hydrateFromServer();if (dropped) {@@ -629,6 +709,9 @@ export const App: React.FC = () => {kwantTitle: event.data?.kwant_title,reason: event.data?.reason,mode: event.data?.mode,+ candidateCount: typeof event.data?.candidate_count === 'number' ? event.data.candidate_count : prev?.candidateCount ?? null,+ fallback: !!event.data?.fallback,+ matchedTerms: Array.isArray(event.data?.matched_terms) ? event.data.matched_terms : undefined,}));if (name && (ctx || targetId) && (ctx || targetId) in liveRef.current) markLive(ctx || targetId, name);playSfx('blip');@@ -876,7 +959,7 @@ export const App: React.FC = () => {const threadId = openThreadId;const isTargetChannel = isChannel;const targetTeam = selectedTeamId;- const speakerName = !isTargetChannel ? (currentKwant?.name || 'Agent') : chatTitle;+ const speakerName = !isTargetChannel ? (currentKwant?.name || 'Bot') : chatTitle;if (!threadId) {discussionInProgressRef.current = false;@@ -968,6 +1051,7 @@ export const App: React.FC = () => {const handleSelectTeam = (team: Team) => {setOpenThreadId(null);setShowAway(false);+ setPhoneView('chat');setSelectedTeamId(team.id);const targetChannel = channels.find((c) => c.name === `team-${team.name}` || c.id === team.id@@ -1007,6 +1091,7 @@ export const App: React.FC = () => {const handleSelectChannel = (channel: Channel) => {setOpenThreadId(null);setShowAway(false);+ setPhoneView('chat');setSelectedId(channel.id);selectedIdRef.current = channel.id;setIsChannel(true);@@ -1022,6 +1107,7 @@ export const App: React.FC = () => {const handleSelectKwant = (kwant: Kwant) => {setOpenThreadId(null);setShowAway(false);+ setPhoneView('chat');setSelectedId(kwant.id);selectedIdRef.current = kwant.id;setIsChannel(false);@@ -1031,7 +1117,7 @@ export const App: React.FC = () => {playSfx('click');};- /** Opens a channel, or the direct chat with a kwant when there's no channel. False if it's gone. */+ /** Opens a channel, or the direct chat with a bot when there's no channel. False if it's gone. */const openTarget = (t: { channel_id: string | null; kwant_id: string | null }): boolean => {if (t.channel_id) {const channel = channels.find((c) => c.id === t.channel_id);@@ -1068,11 +1154,11 @@ export const App: React.FC = () => {setToasts((prev) => [...prev.slice(-2), { id, title, detail }]);};- /** Opens one of an agent's threads (from the thread list, a delegation card or a badge). */+ /** Opens one of a bot's threads (from the thread list, a delegation card or a badge). */const openThread = (kwantId: string, threadId: string) => {const kwant = kwants.find((k) => k.id === kwantId);if (!kwant) {- pushToast('That agent no longer exists.');+ pushToast('That bot no longer exists.');return;}knownThreadsRef.current.add(threadId);@@ -1099,6 +1185,15 @@ export const App: React.FC = () => {};const errText = (err: unknown) => (err instanceof Error ? err.message : 'Something went wrong.');+ /** The server's own `error` text, e.g. why a team name isn't allowed. */+ const serverError = async (res: Response): Promise<string | null> => {+ try {+ const body = await res.clone().json();+ return typeof body?.error === 'string' && body.error ? body.error : null;+ } catch {+ return null;+ }+ };const handleNewThread = async (): Promise<string | void> => {const kwantId = selectedIdRef.current;@@ -1286,9 +1381,9 @@ export const App: React.FC = () => {headers: { 'Content-Type': 'application/json' },body: JSON.stringify(kwantData),});- if (res.status === 409) return `Another agent is already named "${agentData.name}".`;- if (res.status === 400) return 'Check the name (no spaces or @) and that the profile belongs to the chosen engine.';- if (!res.ok) return `Saving failed (HTTP ${res.status}).`;+ if (res.status === 409) return `Another bot in ${space.name} is already named "${agentData.name}".`;+ if (res.status === 400) return (await serverError(res)) ?? 'Check the name (no spaces or @) and that the account belongs to the chosen engine.';+ if (!res.ok) return `Couldn't save the bot (HTTP ${res.status}).`;const updated: Kwant = await res.json();setKwants((prev) => prev.map((k) => (k.id === updated.id ? updated : k)));@@ -1306,7 +1401,7 @@ export const App: React.FC = () => {if (mcpError) return mcpError;playSfx('click');} catch (err) {- console.error('Failed updating Agent:', err);+ console.error('Failed updating bot:', err);return 'Could not reach the server.';}};@@ -1345,8 +1440,15 @@ export const App: React.FC = () => {handleSelectTeam(team);return;}+ // The first bot opens the space's #general; counts change either way.+ onSpacesChanged();+ fetch('/api/channels')+ .then((r) => (r.ok ? r.json() : null))+ .then((fresh: Channel[] | null) => fresh && setChannels(fresh))+ .catch(() => undefined);setSelectedId(created.id);selectedIdRef.current = created.id;+ setPhoneView('chat');setIsChannel(false);isChannelRef.current = false;setSelectedTeamId(null);@@ -1354,11 +1456,11 @@ export const App: React.FC = () => {setMessages([]);return;}- if (res.status === 409) return `Another agent is already named "${agentData.name}".`;- if (res.status === 400) return 'Check the name (no spaces or @) and that the profile belongs to the chosen engine.';- return `Creating failed (HTTP ${res.status}).`;+ if (res.status === 409) return `Another bot in ${space.name} is already named "${agentData.name}".`;+ if (res.status === 400) return (await serverError(res)) ?? 'Check the name (no spaces or @) and that the account belongs to the chosen engine.';+ return `Couldn't create the bot (HTTP ${res.status}).`;} catch (err) {- console.error('Failed creating Agent:', err);+ console.error('Failed creating bot:', err);return 'Could not reach the server.';}};@@ -1413,9 +1515,13 @@ export const App: React.FC = () => {setIsNewTeamOpen(false);playSfx('fanfare');+ onSpacesChanged();+ return;}+ throw new Error((await serverError(res)) ?? `Couldn't create the team (HTTP ${res.status}).`);} catch (err) {console.error('Failed creating team:', err);+ throw err instanceof Error ? err : new Error('Could not reach the server.');}};@@ -1457,9 +1563,12 @@ export const App: React.FC = () => {setEditingTeam(null);playSfx('fanfare');+ return;}+ throw new Error((await serverError(res)) ?? `Couldn't save the team (HTTP ${res.status}).`);} catch (err) {console.error('Failed updating team:', err);+ throw err instanceof Error ? err : new Error('Could not reach the server.');}};@@ -1481,13 +1590,14 @@ export const App: React.FC = () => {member_kwants: memberIds,}),});- if (!res.ok) throw new Error(`HTTP ${res.status}`);+ if (!res.ok) throw new Error((await serverError(res)) ?? `HTTP ${res.status}`);const cRes = await fetch('/api/channels');if (cRes.ok) setChannels(await cRes.json());playSfx('click');} catch (err) {console.error('Failed updating team members:', err);setTeams(previous);+ pushToast("Couldn't change the team.", err instanceof Error ? err.message : undefined);}};@@ -1551,17 +1661,19 @@ export const App: React.FC = () => {: [];const chatTitle = !isChannel- ? currentKwant?.name || 'Agent'+ ? currentKwant?.name || 'Bot': currentTeam? `@${currentTeam.name}`: currentChannel?.name.startsWith('team-')? `@${currentChannel.name.replace(/^team-/, '')}`: `#${currentChannel?.name || 'general'}`;- const boundProfile = currentKwant?.profile_id ? profiles.find((p) => p.id === currentKwant.profile_id) : undefined;+ const isGeneral = isChannel && !currentTeam && currentChannel?.name === 'general';const chatSubtitle = !isChannel- ? `${currentKwant?.title || 'Specialist'} [Laya Auto-Fleet]${boundProfile ? ` · profile: ${boundProfile.name}` : ''}`- : currentTeam?.description || currentChannel?.description || 'Team collaboration room';+ ? currentKwant?.title || 'Kwant bot'+ : isGeneral+ ? `Laya picks who answers, from the ${kwants.length} ${kwants.length === 1 ? 'bot' : 'bots'} in ${space.name}`+ : currentTeam?.description || currentChannel?.description || `A team in ${space.name}`;// Load container status and screenshot for active team or botuseEffect(() => {@@ -1689,17 +1801,27 @@ export const App: React.FC = () => {};+ useEffect(() => onTokensUsed(tokensUsed), [tokensUsed, onTokensUsed]);++ // The address bar and "reopen where I was" follow the open chat.+ const chatChangeRef = useRef(onChatChange);+ chatChangeRef.current = onChatChange;+ useEffect(() => {+ if (!loaded || !selectedId) return;+ chatChangeRef.current(isChannel ? { channelId: selectedId } : { botId: selectedId });+ }, [loaded, selectedId, isChannel]);+const isCurrentContextStreaming = openCtx in live;const openTurns = turnsIn(turns, openCtx);- // Turns paused on a question wait for the person; they don't make the agent "busy".+ // Turns paused on a question wait for the person; they don't make the bot "busy".const awaitingTurns = turnsAwaitingAnswer(questions);const awaitingHere = openTurns.some((t) => t.state === 'running' && awaitingTurns.has(t.turn_id)) && !openTurns.some((t) => t.state === 'running' && !awaitingTurns.has(t.turn_id));const waiting = openTurns.some((t) => t.state === 'running') ? undefined : openTurns.find((t) => t.state === 'queued');const queuedHere: QueuedState | null = waiting- ? { position: queuePosition(turns, waiting.turn_id), reason: waiting.reason ?? 'agent_busy', speaker: kwantName(waiting.kwant_id) ?? live[openCtx] ?? 'The agent' }+ ? { position: queuePosition(turns, waiting.turn_id), reason: waiting.reason ?? 'agent_busy', speaker: kwantName(waiting.kwant_id) ?? live[openCtx] ?? 'The bot' }: null;- // The agent's conversations, the open thread's controls, and "working on…" elsewhere.+ // The bot's conversations, the open thread's controls, and "working on…" elsewhere.const agentThreads = currentKwant ? threadsByKwant[currentKwant.id] : undefined;const shownThread = openThreadId ? agentThreads?.find((t) => t.id === openThreadId) ?? null : null;const elsewhere = currentKwant ? backgroundTurns(turns, currentKwant.id).filter((t) => t.context_id !== openCtx) : [];@@ -1744,7 +1866,7 @@ export const App: React.FC = () => {{pendingHere === 1 ? '1 skill to review' : `${pendingHere} skills to review`}</button>) : null;- // Sidebar: agents busy somewhere other than the open chat.+ // Sidebar: bots busy somewhere other than the open chat.const busyKwants: Record<string, string> = {};for (const t of Object.values(turns)) {if (t.context_id === openCtx || busyKwants[t.kwant_id]) continue;@@ -1811,65 +1933,136 @@ export const App: React.FC = () => {discussionState.teamId === selectedTeamId ||(isChannel && currentTeam && discussionState.teamId === currentTeam.id));- return (- <div className="h-screen w-screen flex flex-col bg-zinc-950 text-zinc-100 overflow-hidden font-sans">- {/* Modern App Header */}- <AppHeader- onOpenSettings={openSettings}- onOpenTools={() => setIsMcpOpen(true)}- onOpenSearch={() => setIsSearchOpen(true)}- onOpenRoutines={() => setIsRoutinesOpen(true)}- tokensUsed={tokensUsed}- activeModel={currentKwant?.preferred_model || 'auto'}- />+ const needsSetup = loaded && kwants.length === 0;+ const setupChecklist = (+ <main className="flex-1 min-w-0 overflow-y-auto flex items-start sm:items-center justify-center p-4 sm:p-8" data-space-checklist>+ <div className="w-full max-w-md rounded-2xl border border-zinc-800 bg-zinc-900/60 p-5 sm:p-6 space-y-4">+ <div className="flex items-center gap-3">+ <SpaceTile space={space} size={40} />+ <div className="min-w-0">+ <h1 className="text-base font-semibold text-zinc-100 truncate">Get {space.name} ready</h1>+ <p className="text-xs text-zinc-400">Bots, teams and accounts here stay in {space.name}.</p>+ </div>+ </div>+ <ol className="space-y-2">+ {[+ {+ done: (space.counts?.ready_accounts ?? 0) > 0,+ title: 'Connect an account',+ detail: 'Sign in with Claude, add a key, or use this machine.',+ action: { label: 'Accounts', icon: <KeyRound size={13} />, onClick: () => openSpaceSettings('accounts') },+ },+ {+ done: kwants.length > 0,+ title: 'Add your first bot',+ detail: `${space.name}'s #general opens with it.`,+ action: {+ label: 'New bot',+ icon: <Bot size={13} />,+ onClick: () => {+ setNewAgentTeam(null);+ setIsNewAgentOpen(true);+ playSfx('click');+ },+ },+ },+ { done: false, title: 'Message #general', detail: `Laya picks who answers, only from ${space.name}'s bots.` },+ ].map((step, i) => (+ <li key={step.title} className="flex items-start gap-3 rounded-xl border border-zinc-800 bg-zinc-950/50 p-3">+ <span+ className={`mt-0.5 w-5 h-5 shrink-0 rounded-full flex items-center justify-center text-[11px] font-semibold ${+ step.done ? 'bg-emerald-500 text-zinc-950' : 'bg-zinc-800 text-zinc-300'+ }`}+ aria-hidden="true"+ >+ {step.done ? <Check size={12} /> : i + 1}+ </span>+ <span className="flex-1 min-w-0">+ <span className={`block text-xs font-medium ${step.done ? 'text-zinc-400 line-through' : 'text-zinc-100'}`}>+ {step.title}+ {step.done && <span className="sr-only"> (done)</span>}+ </span>+ <span className="block text-[11px] text-zinc-500">{step.detail}</span>+ </span>+ {step.action && !step.done && (+ <button+ type="button"+ onClick={step.action.onClick}+ className="shrink-0 flex items-center gap-1 px-2.5 py-1 rounded-lg text-[11px] font-medium text-white bg-sky-600 hover:bg-sky-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-300"+ >+ {step.action.icon}+ {step.action.label}+ </button>+ )}+ </li>+ ))}+ </ol>+ </div>+ </main>+ );- {/* Main Workspace Shell */}- <div className="flex-1 flex overflow-hidden">- <Sidebar- onOpenSettings={openSettings}- onSignInClaude={openClaudeSignIn}- enginesRefreshKey={settingsClosedCount}- kwants={kwants}- channels={channels}- teams={teams}- selectedId={selectedId}- isChannel={isChannel}- selectedTeamId={selectedTeamId}- busyKwants={busyKwants}- onSelectKwant={handleSelectKwant}- onSelectChannel={handleSelectChannel}- onSelectTeam={handleSelectTeam}- onUpdateTeamMembers={handleUpdateTeamMembers}- onManageTeam={(team) => {- setEditingTeam(team);- playSfx('click');- }}- onEditKwant={(kwant) => {- openAgentSettings(kwant);- }}- onSummonKwant={(team) => {- setNewAgentTeam(team ?? null);- setIsNewAgentOpen(true);- playSfx('click');- }}- onCreateTeam={() => {- setIsNewTeamOpen(true);- playSfx('click');- }}- awayCount={awayCount}- awayActive={showAway}- onOpenAway={() => {- setShowAway(true);- playSfx('click');- }}- />+ const sidebar = (section: 'all' | 'chats' | 'bots') => (+ <Sidebar+ space={space}+ spaces={spaces}+ onSwitchSpace={onSwitchSpace}+ onCreateSpace={onCreateSpace}+ onOpenSpaceSettings={() => openSpaceSettings('general')}+ onOpenArchived={onOpenArchived}+ onOpenSearch={() => setIsSearchOpen(true)}+ onOpenRoutines={() => setIsRoutinesOpen(true)}+ section={section}+ phone={isPhone}+ onOpenAccounts={openSettings}+ onSignInClaude={openClaudeSignIn}+ enginesRefreshKey={settingsClosedCount}+ kwants={kwants}+ channels={channels}+ teams={teams}+ selectedId={selectedId}+ isChannel={isChannel}+ selectedTeamId={selectedTeamId}+ busyKwants={busyKwants}+ onSelectKwant={handleSelectKwant}+ onSelectChannel={handleSelectChannel}+ onSelectTeam={handleSelectTeam}+ onUpdateTeamMembers={handleUpdateTeamMembers}+ onManageTeam={(team) => {+ setEditingTeam(team);+ playSfx('click');+ }}+ onEditKwant={(kwant) => {+ openAgentSettings(kwant);+ }}+ onSummonKwant={(team) => {+ setNewAgentTeam(team ?? null);+ setIsNewAgentOpen(true);+ playSfx('click');+ }}+ onCreateTeam={() => {+ setIsNewTeamOpen(true);+ playSfx('click');+ }}+ awayCount={awayCount}+ awayActive={showAway}+ onOpenAway={() => {+ setShowAway(true);+ setPhoneView('chat');+ playSfx('click');+ }}+ />+ );- {showAway ? (- <AwayPage since={awaySinceRef.current} onSince={(t) => (awaySinceRef.current = t)} onOpen={openAwayItem} onCounts={setAwayCount} />- ) : (+ const away = (+ <AwayPage since={awaySinceRef.current} onSince={(t) => (awaySinceRef.current = t)} onOpen={openAwayItem} onCounts={setAwayCount} />+ );+ const chat = (<ChatViewtitle={chatTitle}subtitle={chatSubtitle}+ spaceName={space.name}+ isGeneral={isGeneral}+ onBack={isPhone ? () => setPhoneView('list') : undefined}messages={viewingHistory ? historyWindow.messages : messages}viewingHistory={viewingHistory}onJumpToLatest={() => setHistoryWindow(null)}@@ -1942,10 +2135,89 @@ export const App: React.FC = () => {awaitingAnswer={awaitingHere}contextKey={openCtx}/>- )}- </div>+ );+ const mainPane = needsSetup ? setupChecklist : showAway ? away : !loaded ? (+ <main className="flex-1 flex items-center justify-center text-xs text-zinc-500">+ <Loader2 size={14} className="mr-2 animate-spin motion-reduce:animate-none" aria-hidden="true" /> Opening {space.name}…+ </main>+ ) : chat;++ const phoneTabs: Array<{ id: PhoneTab; label: string; icon: React.ReactNode; badge?: number }> = [+ { id: 'chats', label: 'Chats', icon: <MessageSquare size={18} /> },+ { id: 'bots', label: 'Bots', icon: <Bot size={18} /> },+ { id: 'inbox', label: 'Inbox', icon: <Inbox size={18} />, badge: awayCount },+ { id: 'space', label: 'Space', icon: <Settings size={18} /> },+ ];+ const showPhoneList = isPhone && phoneView === 'list' && !needsSetup;- {/* New Agent Modal */}+ return (+ <div className="flex-1 min-w-0 h-full flex flex-col bg-zinc-950 text-zinc-100 overflow-hidden" data-space={space.id}>+ {/* The open space's colour, so it's clear where a message goes */}+ <div className="h-[3px] shrink-0" style={{ background: spaceColor(space) }} aria-hidden="true" />++ {isPhone ? (+ <>+ {showPhoneList || needsSetup ? (+ <div className="flex-1 min-h-0 flex flex-col">+ {needsSetup ? (+ <>+ {sidebar('chats')}+ {setupChecklist}+ </>+ ) : (+ sidebar(phoneTab === 'bots' ? 'bots' : 'chats')+ )}+ </div>+ ) : (+ <div className="flex-1 min-h-0 flex">{mainPane}</div>+ )}+ {(showPhoneList || needsSetup) && (+ <nav aria-label={`${space.name} sections`} className="shrink-0 grid grid-cols-4 border-t border-zinc-800 bg-zinc-900/95 pb-[env(safe-area-inset-bottom)]">+ {phoneTabs.map((t) => {+ const active = t.id === phoneTab;+ return (+ <button+ key={t.id}+ type="button"+ aria-current={active ? 'page' : undefined}+ onClick={() => {+ playSfx('click');+ if (t.id === 'inbox') {+ setShowAway(true);+ setPhoneView('chat');+ return;+ }+ if (t.id === 'space') {+ openSpaceSettings('general');+ return;+ }+ setPhoneTab(t.id);+ }}+ className={`relative flex flex-col items-center gap-0.5 py-2 text-[11px] font-medium focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500 ${+ active ? 'text-sky-300' : 'text-zinc-400 hover:text-zinc-200'+ }`}+ >+ {t.icon}+ {t.label}+ {!!t.badge && (+ <span className="absolute top-1 left-1/2 ml-2 min-w-[16px] px-1 rounded-full bg-amber-500 text-zinc-950 text-[9px] font-semibold text-center">+ {badgeText(t.badge)}+ </span>+ )}+ </button>+ );+ })}+ </nav>+ )}+ </>+ ) : (+ <div className="flex-1 min-h-0 flex overflow-hidden">+ {sidebar('all')}+ {mainPane}+ </div>+ )}++ {/* New bot */}<Suspense fallback={null}><NewAgentModalisOpen={isNewAgentOpen}@@ -1964,7 +2236,7 @@ export const App: React.FC = () => {onSubmit={handleCreateAgent}/>- {/* Edit Agent Modal */}+ {/* Edit a bot */}<NewAgentModalisOpen={!!editingKwant}initial={editingKwant}@@ -2002,24 +2274,38 @@ export const App: React.FC = () => {onDeleteTeam={handleDeleteTeam}/>- {/* Settings Modal */}- <Suspense fallback={null}>- <SettingsModal- isOpen={isSettingsOpen}+ {spaceSettingsTab && (+ <SpaceSettings+ space={space}+ spaces={spaces}+ tab={spaceSettingsTab}+ onTab={setSpaceSettingsTab}+ onClose={closeSpaceSettings}+ kwants={kwants}+ channels={channels}+ teams={teams}focusClaudeSignIn={claudeSignInFocus}- onClose={() => {- setIsSettingsOpen(false);- setSettingsClosedCount((n) => n + 1);+ onProfilesChanged={setProfiles}+ pendingSkills={pendingSkillCounts}+ onSpaceSaved={() => onSpacesChanged()}+ onArchived={(s) => {+ setSpaceSettingsTab(null);+ onSpaceArchived(s);}}- onOpenTools={() => {- setIsSettingsOpen(false);- setIsMcpOpen(true);+ onNewBot={() => {+ setNewAgentTeam(null);+ setIsNewAgentOpen(true);}}- onProfilesChanged={setProfiles}+ onEditBot={(k) => openAgentSettings(k)}+ onOpenSkills={(k) => openAgentSettings(k, 'skills')}+ onNewTeam={() => setIsNewTeamOpen(true)}+ onManageTeam={(t) => setEditingTeam(t)}+ onOpenTools={() => setIsMcpOpen(true)}+ onOpenAppSettings={onOpenAppSettings}/>- </Suspense>+ )}- {/* MCP tool servers (opened last so it sits above the agent modal) */}+ {/* MCP tool servers (opened last so it sits above the bot form) */}<Suspense fallback={null}><McpServersModal isOpen={isMcpOpen} onClose={() => setIsMcpOpen(false)} kwants={kwants} />{isSearchOpen && <SearchModal isOpen onClose={() => setIsSearchOpen(false)} kwants={kwants} onJump={handleJump} />}diff --git a/frontend/src/Shell.tsx b/frontend/src/Shell.tsxnew file mode 100644index 00000000..d3be256f--- /dev/null+++ b/frontend/src/Shell.tsx@@ -0,0 +1,264 @@+// The app shell: the spaces, the rail, space dialogs and App settings. Everything inside a space+// lives in <SpaceApp key={space.id}>, so switching remounts it: fresh state, a fresh event stream+// for the new space, and nothing from the old space can flash.+import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react';+import { AlertTriangle, Loader2 } from 'lucide-react';+import { SpaceApp, SpaceTarget } from './App';+import { ArchivedSpacesModal, NewSpaceModal, SpaceRail } from './components/Spaces';+import { Toasts, Toast } from './components/Toasts';+import { playSfx } from './audio/chiptune';+import {+ Space,+ eventsUrl,+ lastChat,+ lastSpace,+ parseSpacePath,+ pickSpace,+ rememberChat,+ rememberSpace,+ setCurrentSpace,+ spacePath,+ spacesApi,+} from './spaces';+import { NotifyEvent, TOAST_KINDS, browserNotifyEnabled, notificationPermission, shouldShowOsNotification } from './continuity';++const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) => ({ default: m.SettingsModal })));++const POLL_MS = 15000;++export const App: React.FC = () => {+ const [spaces, setSpaces] = useState<Space[] | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [currentId, setCurrentId] = useState<string | null>(null);+ // Where to land in the space being opened (a link, a notification, the last chat there).+ const [target, setTarget] = useState<SpaceTarget | null>(null);+ const [creating, setCreating] = useState<Space[] | null>(null);+ const [showArchived, setShowArchived] = useState(false);+ const [appSettingsOpen, setAppSettingsOpen] = useState(false);+ const [tokensUsed, setTokensUsed] = useState(0);+ const [toasts, setToasts] = useState<Toast[]>([]);+ const toastIdRef = useRef(0);+ const dismissToast = useCallback((id: number) => setToasts((prev) => prev.filter((t) => t.id !== id)), []);+ const currentRef = useRef(currentId);+ currentRef.current = currentId;++ const reload = useCallback(async () => {+ try {+ const list = await spacesApi.list();+ setSpaces(list);+ setLoadError(null);+ return list;+ } catch (e) {+ setLoadError(e instanceof Error ? e.message : 'Couldn’t load spaces.');+ return null;+ }+ }, []);++ /** Opens a space: the request scope changes before the new space renders. */+ const open = useCallback((id: string, to?: SpaceTarget | null, replace = false) => {+ const t = to ?? lastChat(id) ?? null;+ setCurrentSpace(id);+ rememberSpace(id);+ setTarget(t);+ setCurrentId(id);+ const path = spacePath(id, t ?? undefined);+ if (window.location.pathname !== path) {+ if (replace) window.history.replaceState(null, '', path);+ else window.history.pushState(null, '', path);+ }+ }, []);++ // First load: the space in the address, then the last one used, then Default.+ useEffect(() => {+ reload().then((list) => {+ if (!list) return;+ const route = parseSpacePath(window.location.pathname);+ const s = pickSpace(list, route.spaceId, lastSpace());+ if (!s) return;+ const fromUrl = route.spaceId === s.id && (route.channelId || route.botId) ? { channelId: route.channelId, botId: route.botId } : null;+ open(s.id, fromUrl, true);+ });+ }, [reload, open]);++ // Back and forward between spaces.+ useEffect(() => {+ const onPop = () => {+ const route = parseSpacePath(window.location.pathname);+ if (route.spaceId && route.spaceId !== currentRef.current && spaces?.some((s) => s.id === route.spaceId)) {+ setCurrentSpace(route.spaceId);+ setTarget({ channelId: route.channelId, botId: route.botId });+ setCurrentId(route.spaceId);+ }+ };+ window.addEventListener('popstate', onPop);+ return () => window.removeEventListener('popstate', onPop);+ }, [spaces]);++ // Unread counts for the other spaces.+ useEffect(() => {+ const t = setInterval(() => !document.hidden && reload(), POLL_MS);+ const onFocus = () => reload();+ window.addEventListener('focus', onFocus);+ return () => {+ clearInterval(t);+ window.removeEventListener('focus', onFocus);+ };+ }, [reload]);++ const switchTo = useCallback(+ (id: string, to?: SpaceTarget | null) => {+ if (id === currentRef.current && !to) return;+ playSfx('click');+ open(id, to);+ reload();+ },+ [open, reload],+ );++ // Ctrl/⌘ 1–9 switches spaces.+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return;+ const n = Number(e.key);+ if (!Number.isInteger(n) || n < 1 || n > 9) return;+ const s = spaces?.[n - 1];+ if (!s) return;+ e.preventDefault();+ switchTo(s.id);+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [spaces, switchTo]);++ // Notifications from the other spaces: the open space's own stream only carries its events.+ const activeCount = spaces?.length ?? 0;+ useEffect(() => {+ if (activeCount < 2) return;+ const sse = new EventSource(eventsUrl(null));+ sse.onmessage = (e) => {+ if (typeof e.data !== 'string' || !e.data.includes('otify')) return;+ try {+ const event = JSON.parse(e.data);+ if (event.type !== 'notify' && event.type !== 'Notify') return;+ const n = event.data as NotifyEvent;+ const sid = n.space_id ?? event.space_id;+ if (!sid || sid === currentRef.current) return;+ const name = n.space_name ?? 'another space';+ const go = () => switchTo(sid, n.channel_id ? { channelId: n.channel_id } : n.kwant_id ? { botId: n.kwant_id } : null);+ reload();+ if (!document.hidden && (TOAST_KINDS as string[]).includes(n.kind)) {+ const id = ++toastIdRef.current;+ setToasts((prev) => [...prev.slice(-2), { id, title: n.title, detail: n.body, action: { label: `Open in ${name}`, onClick: go } }]);+ return;+ }+ if (!shouldShowOsNotification({ enabled: browserNotifyEnabled(), permission: notificationPermission(), hidden: document.hidden, kind: n.kind })) return;+ try {+ const note = new Notification(n.title, { body: n.body, tag: `kwnt-${sid}-${n.kind}-${n.channel_id ?? n.kwant_id}` });+ note.onclick = () => {+ window.focus();+ go();+ note.close();+ };+ } catch {+ // Some mobile browsers only allow notifications from a service worker.+ }+ } catch {+ // not an event we know+ }+ };+ return () => sse.close();+ }, [activeCount, switchTo, reload]);++ const openCreate = useCallback(() => {+ playSfx('click');+ // Archived spaces keep their names and colours, so they count as taken.+ spacesApi.archived().then(+ (archived) => setCreating([...(spaces ?? []), ...archived]),+ () => setCreating(spaces ?? []),+ );+ }, [spaces]);++ const current = spaces?.find((s) => s.id === currentId) ?? null;++ if (!spaces || !current) {+ return (+ <div className="h-[100dvh] w-screen flex items-center justify-center bg-zinc-950 text-zinc-400 text-xs">+ {loadError ? (+ <div role="alert" className="flex flex-col items-center gap-3">+ <p className="flex items-center gap-2 text-rose-300">+ <AlertTriangle size={14} /> {loadError}+ </p>+ <button type="button" onClick={() => window.location.reload()} className="px-3 py-1.5 rounded-lg bg-zinc-800 text-zinc-200 hover:bg-zinc-700">+ Try again+ </button>+ </div>+ ) : spaces && spaces.length === 0 ? (+ <p>No spaces yet.</p>+ ) : (+ <p className="flex items-center gap-2">+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" /> Loading…+ </p>+ )}+ </div>+ );+ }++ return (+ <div className="h-[100dvh] w-screen flex bg-zinc-950 text-zinc-100 overflow-hidden font-sans">+ <SpaceRail spaces={spaces} currentId={current.id} onSwitch={switchTo} onCreate={openCreate} onOpenAppSettings={() => setAppSettingsOpen(true)} />+ <SpaceApp+ key={current.id}+ space={current}+ spaces={spaces}+ initialTarget={target}+ onSwitchSpace={switchTo}+ onCreateSpace={openCreate}+ onOpenArchived={() => setShowArchived(true)}+ onOpenAppSettings={() => setAppSettingsOpen(true)}+ onSpacesChanged={reload}+ onSpaceArchived={(s) => {+ reload().then((list) => {+ const next = list?.find((x) => x.is_default) ?? list?.[0];+ if (next) open(next.id);+ });+ const id = ++toastIdRef.current;+ setToasts((prev) => [...prev, { id, title: `${s.name} is archived`, detail: 'Its routines are paused. Restore it from Archived spaces.' }]);+ }}+ onChatChange={(t) => {+ rememberChat(current.id, t);+ const path = spacePath(current.id, t);+ if (window.location.pathname !== path) window.history.replaceState(null, '', path);+ }}+ onTokensUsed={setTokensUsed}+ />++ {creating && (+ <NewSpaceModal+ spaces={creating}+ onClose={() => setCreating(null)}+ onCreated={(s) => {+ setCreating(null);+ setSpaces((prev) => (prev ? [...prev, s] : [s]));+ open(s.id, null);+ reload();+ }}+ />+ )}+ {showArchived && (+ <ArchivedSpacesModal+ onClose={() => setShowArchived(false)}+ onRestored={(s) => {+ setShowArchived(false);+ setSpaces((prev) => (prev ? [...prev.filter((x) => x.id !== s.id), s] : [s]));+ open(s.id, null);+ reload();+ }}+ />+ )}+ <Suspense fallback={null}>+ <SettingsModal isOpen={appSettingsOpen} onClose={() => setAppSettingsOpen(false)} tokensUsed={tokensUsed} />+ </Suspense>+ <Toasts toasts={toasts} onDismiss={dismissToast} position="top" />+ </div>+ );+};diff --git a/frontend/src/auth.ts b/frontend/src/auth.tsindex 85f8c842..86f3f9af 100644--- a/frontend/src/auth.ts+++ b/frontend/src/auth.ts@@ -1,5 +1,7 @@// API token handling: the `#kwnt_token=` link, the session cookie and 401s from any `/api` call.+import { getCurrentSpace, withSpace } from './spaces';+/** Fired on `window` when an `/api` call answers 401 (the token is missing or no longer valid). */export const UNAUTHORIZED_EVENT = 'kwnt:unauthorized';@@ -33,12 +35,14 @@ export function isGuardedApiUrl(url: string, origin: string): boolean {let installed = false;-/** Wraps `window.fetch` so every component's `/api` 401 reaches the auth gate. */+/** Wraps `window.fetch` so every component's `/api` 401 reaches the auth gate, and space-scoped+ * `/api` calls carry the open space as `?space=`. */export function installUnauthorizedListener(): void {if (installed || typeof window === 'undefined') return;installed = true;const original = window.fetch.bind(window);window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {+ if (typeof input === 'string') input = withSpace(input, window.location.origin, getCurrentSpace());const res = await original(input, init);if (res.status === 401) {const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;diff --git a/frontend/src/components/AppHeader.tsx b/frontend/src/components/AppHeader.tsxdeleted file mode 100644index cde78f85..00000000--- a/frontend/src/components/AppHeader.tsx+++ /dev/null@@ -1,189 +0,0 @@-import React from 'react';-import { Settings, Volume2, VolumeX, Cpu, Plug, Search, CalendarClock } from 'lucide-react';-import { ModernAvatar } from './ModernAvatar';-import { isSfxMuted, toggleSfxMute, playSfx } from '../audio/chiptune';-import { pickLabel } from '../engines';--interface AppHeaderProps {- onOpenSettings: () => void;- onOpenTools: () => void;- onOpenSearch: () => void;- onOpenRoutines: () => void;- tokensUsed: number;- activeModel?: string;-}--const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);--type LayaState = 'unknown' | 'external' | 'installing' | 'starting' | 'online' | 'offline' | 'failed';--interface LayaStatus {- state: LayaState;- detail: string;- url: string;- managed: boolean;-}--const useLayaStatus = (): LayaStatus | null => {- const [status, setStatus] = React.useState<LayaStatus | null>(null);- React.useEffect(() => {- let cancelled = false;- let timer: ReturnType<typeof setTimeout>;- const poll = async () => {- let next: LayaStatus | null = null;- try {- const res = await fetch('/api/laya/status');- if (res.ok) next = await res.json();- } catch {- // server restarting; keep the last known status- }- if (cancelled) return;- if (next) setStatus(next);- const up = next?.state === 'online' || next?.state === 'external';- timer = setTimeout(poll, up ? 20000 : 4000);- };- poll();- return () => {- cancelled = true;- clearTimeout(timer);- };- }, []);- return status;-};--const layaPill = (status: LayaStatus | null, activeModel: string) => {- const ready = activeModel === 'auto' ? 'Laya • Dynamic Effort' : `Laya ➔ ${pickLabel(activeModel)}`;- switch (status?.state) {- case 'online':- case 'external':- return { dot: 'bg-emerald-400', label: ready };- case 'installing':- return { dot: 'bg-amber-400 animate-pulse', label: 'Laya installing… • keyword routing' };- case 'starting':- return { dot: 'bg-amber-400 animate-pulse', label: 'Laya loading model… • keyword routing' };- case 'failed':- case 'offline':- return { dot: 'bg-rose-500', label: 'Laya offline • keyword routing' };- default:- return { dot: 'bg-zinc-500 animate-pulse', label: 'Laya…' };- }-};--export const AppHeader: React.FC<AppHeaderProps> = ({- onOpenSettings,- onOpenTools,- onOpenSearch,- onOpenRoutines,- tokensUsed,- activeModel = 'auto',-}) => {- const [sfxMuted, setSfxMuted] = React.useState(isSfxMuted());- const laya = useLayaStatus();- const pill = layaPill(laya, activeModel);- const pillTitle = laya ? `${laya.detail || laya.state}\n${laya.url}${laya.managed ? ' (managed by Kwant)' : ''}` : 'Checking Laya…';-- const handleToggleSfx = () => {- const next = toggleSfxMute();- setSfxMuted(next);- };-- return (- <header className="h-14 border-b border-zinc-800/80 bg-zinc-900/70 backdrop-blur-md px-4 flex items-center justify-between select-none z-30">- {/* Brand & Fleet status */}- <div className="flex items-center gap-3">- <div className="flex items-center gap-2 font-semibold text-sm tracking-tight text-zinc-100">- <ModernAvatar role="brand" name="Kwant" size={30} />- <span className="text-[15px]">Kwant</span>- </div>- <span className="text-[11px] font-medium text-zinc-500 hidden sm:inline-block">- your team of super-intelligent bots (kwants)- </span>- </div>-- {/* Center: Laya Decision Engine pill */}- <div- className="hidden md:flex items-center gap-2 bg-zinc-950/60 border border-zinc-800 px-3 py-1 rounded-full text-xs text-zinc-400 shadow-inner"- title={pillTitle}- >- <span className={`w-2 h-2 rounded-full ${pill.dot}`} />- <span className="text-zinc-500 font-medium">ROUTER:</span>- <span className="text-zinc-200 font-semibold flex items-center gap-1">- <Cpu size={13} className="text-sky-400" />- <span>{pill.label}</span>- </span>- </div>-- {/* Right Controls */}- <div className="flex items-center gap-2">- {/* Token / Usage Counter */}- <div className="hidden lg:flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs text-zinc-400 bg-zinc-800/40 border border-zinc-800">- <span className="text-zinc-500 font-mono text-[11px]">Usage:</span>- <span className="font-mono text-zinc-200 font-medium">{tokensUsed} tk</span>- </div>-- {/* Audio Toggle */}- <button- onClick={handleToggleSfx}- className="p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800/80 transition-colors"- title={sfxMuted ? 'Unmute UI sounds' : 'Mute UI sounds'}- >- {sfxMuted ? <VolumeX size={17} /> : <Volume2 size={17} />}- </button>-- <button- onClick={() => {- playSfx('click');- onOpenSearch();- }}- title="Search all chats (Ctrl/⌘ K)"- aria-label="Search"- aria-keyshortcuts="Control+K Meta+K"- className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-200 bg-zinc-800 hover:bg-zinc-700/80 border border-zinc-700/60 transition-all hover:border-zinc-600 shadow-sm"- >- <Search size={14} className="text-zinc-400" />- <span className="hidden md:inline">Search</span>- <kbd className="hidden md:inline text-[10px] font-mono text-zinc-500">{isMac ? '⌘K' : 'Ctrl K'}</kbd>- </button>-- <button- onClick={() => {- playSfx('click');- onOpenRoutines();- }}- title="Routines: scheduled work for your kwants"- aria-label="Routines"- className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-200 bg-zinc-800 hover:bg-zinc-700/80 border border-zinc-700/60 transition-all hover:border-zinc-600 shadow-sm"- >- <CalendarClock size={14} className="text-amber-300" />- <span className="hidden sm:inline">Routines</span>- </button>-- {/* MCP Tools Button */}- <button- onClick={() => {- playSfx('click');- onOpenTools();- }}- title="Tool servers (MCP) your kwants can use"- aria-label="Tools"- className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-200 bg-zinc-800 hover:bg-zinc-700/80 border border-zinc-700/60 transition-all hover:border-zinc-600 shadow-sm"- >- <Plug size={14} className="text-sky-400" />- <span className="hidden sm:inline">Tools</span>- </button>-- {/* Settings Button */}- <button- onClick={() => {- playSfx('click');- onOpenSettings();- }}- className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-200 bg-zinc-800 hover:bg-zinc-700/80 border border-zinc-700/60 transition-all hover:border-zinc-600 shadow-sm"- >- <Settings size={14} className="text-zinc-400" />- <span>Settings</span>- </button>- </div>- </header>- );-};diff --git a/frontend/src/components/AuthGate.tsx b/frontend/src/components/AuthGate.tsxindex c8f0b0f8..8dcb5a53 100644--- a/frontend/src/components/AuthGate.tsx+++ b/frontend/src/components/AuthGate.tsx@@ -84,7 +84,7 @@ export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children })<ModernAvatar role="brand" name="Kwant" size={36} /><div><h1 className="text-sm font-semibold">Kwant</h1>- <p className="text-xs text-zinc-400">your team of super-intelligent bots</p>+ <p className="text-xs text-zinc-400">Your team of kwant bots</p></div></div>{state.kind === 'checking' && (diff --git a/frontend/src/components/AwayView.tsx b/frontend/src/components/AwayView.tsxindex f5ba4932..10503735 100644--- a/frontend/src/components/AwayView.tsx+++ b/frontend/src/components/AwayView.tsx@@ -125,7 +125,7 @@ export const AwayView: React.FC<AwayViewProps> = ({ data, loading, error, notice<div className="min-w-0"><h2 className="text-sm font-semibold text-zinc-100 truncate">While you were away</h2><p className="text-[11px] text-zinc-400 truncate mt-0.5">- {data ? windowLabel(data.since, now) : 'What your agents need, finished and failed'}+ {data ? windowLabel(data.since, now) : 'What your bots need, finished and failed'}</p></div><buttondiff --git a/frontend/src/components/ChannelInstructionsModal.tsx b/frontend/src/components/ChannelInstructionsModal.tsxindex e2716248..7023fd1a 100644--- a/frontend/src/components/ChannelInstructionsModal.tsx+++ b/frontend/src/components/ChannelInstructionsModal.tsx@@ -73,7 +73,7 @@ export const ChannelInstructionsModal: React.FC<{onChange={setText}autoFocuslabel="Channel instructions"- hint="Every kwant reads these before each turn in this channel. Leave empty to unpin."+ hint="Every bot reads these before each turn in this channel. Leave empty to unpin."rows={7}/>{error && (diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 964a4b93..0bec3c0b 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -1,5 +1,5 @@import React, { useState, useRef, useEffect } from 'react';-import { ArrowDown, ArrowUp, Paperclip, Sparkles, ChevronDown, ChevronRight, Copy, Check, Cpu, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin } from 'lucide-react';+import { ArrowDown, ArrowUp, Paperclip, Sparkles, ChevronDown, ChevronRight, Copy, Check, ChevronLeft, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';import { MentionPopover, MentionItem } from './MentionPopover';@@ -28,6 +28,7 @@ import {} from '../attachments';import { FileTiles, UploadChip } from './Attachments';import { ranOnLabel } from '../engines';+import { parseRoutingMeta, ranOnAccount, routingLine } from '../spaces';export interface ChatMessage {id: string;@@ -82,11 +83,21 @@ export interface RoutingState {kwantTitle?: string;reason?: string;mode?: 'direct' | 'discuss' | string;+ /** How many bots Laya chose from, and whether keyword matching stood in for her. */+ candidateCount?: number | null;+ fallback?: boolean;+ matchedTerms?: string[];}export interface ChatViewProps {title: string;subtitle: string;+ /** The open space, for "Message #general in Work" and Laya's lines. */+ spaceName?: string;+ /** #general, where Laya picks who answers. */+ isGeneral?: boolean;+ /** Phones: back to the list. */+ onBack?: () => void;messages: ChatMessage[];streamingText: string;streamingThinking: string;@@ -131,15 +142,15 @@ export interface ChatViewProps {viewingHistory?: boolean;/** Leaves that window for the latest messages. */onJumpToLatest?: () => void;- /** Under the header: the agent's conversations and the open thread's controls. */+ /** Under the header: the bot's conversations and the open thread's controls. */subHeader?: React.ReactNode;- /** Next to the title, e.g. "Working on …" while the agent has background turns. */+ /** Next to the title, e.g. "Working on …" while the bot has background turns. */titleExtra?: React.ReactNode;/** Set while the open chat's turn waits in the queue. */queued?: QueuedState | null;/** Draws a delegation note or result (messages with delegation `meta`). */renderDelegation?: (msg: ChatMessage, meta: DelegationMeta, flash: boolean) => React.ReactNode;- /** Draws an agent's question card (messages with `ask_user` meta). */+ /** Draws a bot's question card (messages with `ask_user` meta). */renderQuestion?: (msg: ChatMessage, meta: QuestionMeta, flash: boolean) => React.ReactNode;/** The open chat's turn is paused on a question: it is waiting for the person, not working. */awaitingAnswer?: boolean;@@ -165,9 +176,11 @@ export const renderFormattedText = (text: string): React.ReactNode => {});};-const LayaRoutingCard: React.FC<{ routing: RoutingState }> = ({ routing }) => {+const LayaRoutingCard: React.FC<{ routing: RoutingState; spaceName?: string }> = ({ routing, spaceName }) => {const deciding = routing.phase === 'deciding';const isDiscuss = routing.mode === 'discuss';+ const pool = routing.candidateCount ?? (routing.candidates.length || null);+ const where = spaceName ? ` in ${spaceName}` : '';return (<div className="flex items-start gap-3.5 w-full max-w-5xl" aria-live="polite">@@ -182,7 +195,9 @@ const LayaRoutingCard: React.FC<{ routing: RoutingState }> = ({ routing }) => {<div className="px-4 py-3 rounded-2xl rounded-tl-sm bg-violet-950/20 border border-violet-500/20 text-sm text-zinc-200 shadow-sm w-full">{deciding ? (<div className="flex items-center gap-2">- <span>Choosing who's best to answer your question</span>+ <span>+ {pool ? `Choosing from ${pool} ${pool === 1 ? 'bot' : 'bots'}${where}` : `Choosing who's best to answer${where}`}+ </span><span className="inline-flex gap-0.5" aria-hidden="true">{[0, 1, 2].map((i) => (<span@@ -201,6 +216,7 @@ const LayaRoutingCard: React.FC<{ routing: RoutingState }> = ({ routing }) => {{routing.kwantTitle && <span className="text-zinc-400 text-xs">({routing.kwantTitle})</span>}</div>{routing.reason && <span className="text-xs text-zinc-400">{routing.reason}</span>}+ {routing.fallback && <span className="text-xs text-amber-300/90">Picked by keywords (Laya is offline)</span>}</div>)}@@ -238,6 +254,9 @@ const LayaRoutingCard: React.FC<{ routing: RoutingState }> = ({ routing }) => {export const ChatView: React.FC<ChatViewProps> = ({title,subtitle,+ spaceName,+ isGeneral,+ onBack,messages,streamingText,streamingThinking,@@ -618,10 +637,12 @@ export const ChatView: React.FC<ChatViewProps> = ({if (question && renderQuestion) return <React.Fragment key={msg.id}>{renderQuestion(msg, question, flashId === msg.id)}</React.Fragment>;const isUser = msg.sender_role === 'user';const files = msg.meta ? parseAttachments(msg.meta) : [];- // An agent's share_file note: the file tiles say it all.+ // A bot's share_file note: the file tiles say it all.const filesOnly = files.length > 0 && isSharedFileMessage(msg.meta);const isThoughtOpen = !!openThoughts[msg.id];const ranOn = isUser ? null : ranOnLabel(msg.meta);+ const account = isUser ? null : ranOnAccount(msg.meta);+ const routed = isUser || !isGeneral ? null : parseRoutingMeta(msg.meta);const displayName = isUser ? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);return (@@ -647,21 +668,29 @@ export const ChatView: React.FC<ChatViewProps> = ({{ranOn}</span>)}+ {account && <span className="text-zinc-500 text-[10px] truncate max-w-[12rem]">ran on {account}</span>}{msg.tokens_used ? (<span className="text-zinc-500 font-mono text-[10px]">({msg.tokens_used} tokens)</span>) : null}</div>+ {routed && (+ <p className={`-mt-1 mb-1.5 text-[11px] ${routed.fallback ? 'text-amber-300/80' : 'text-violet-300/80'} break-words`} data-routing-line>+ <Sparkles size={10} className="inline -mt-0.5 mr-1" aria-hidden="true" />+ {routingLine(routed, spaceName ?? 'this space')}+ </p>+ )}+{/* Collapsible Reasoning Disclosure */}{msg.reasoning_content && (<div className="mb-2 max-w-full"><buttontype="button"onClick={() => toggleThought(msg.id)}- className="flex items-center gap-2 px-3 py-1.5 rounded-xl text-xs font-mono text-zinc-400 hover:text-zinc-200 bg-zinc-900/80 hover:bg-zinc-900 border border-zinc-800 hover:border-zinc-700/80 transition-all cursor-pointer shadow-sm group"+ className="max-w-full min-w-0 flex items-center gap-2 px-3 py-1.5 rounded-xl text-xs font-mono text-zinc-400 hover:text-zinc-200 bg-zinc-900/80 hover:bg-zinc-900 border border-zinc-800 hover:border-zinc-700/80 transition-all cursor-pointer shadow-sm group"><Sparkles size={13} className="text-violet-400 group-hover:rotate-12 transition-transform flex-shrink-0" />- <span className="truncate max-w-xs sm:max-w-md">+ <span className="truncate min-w-0 sm:max-w-md">{msg.reasoning_content.split('\n')[0].replace(/^🔮\s*/, '')}</span>{isThoughtOpen ? <ChevronDown size={13} className="text-zinc-500 flex-shrink-0" /> : <ChevronRight size={13} className="text-zinc-500 flex-shrink-0" />}@@ -725,9 +754,19 @@ export const ChatView: React.FC<ChatViewProps> = ({return (<div className="flex-1 flex flex-col h-full bg-zinc-950 overflow-hidden">- {/* Channel / Agent Header */}- <div className="h-14 border-b border-zinc-800/80 px-6 flex items-center justify-between bg-zinc-900/30 backdrop-blur-sm select-none">- <div>+ {/* Channel / bot header */}+ <div className="h-14 shrink-0 border-b border-zinc-800/80 px-2 sm:px-6 gap-2 flex items-center justify-between bg-zinc-900/30 backdrop-blur-sm select-none">+ {onBack && (+ <button+ type="button"+ onClick={onBack}+ aria-label="Back to chats"+ className="shrink-0 p-2 -ml-0.5 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ <ChevronLeft size={18} />+ </button>+ )}+ <div className="min-w-0 flex-1"><h2 className="text-sm font-semibold text-zinc-100 flex items-center gap-2 min-w-0"><span className="truncate">{title}</span>{titleExtra}@@ -735,7 +774,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<p className="text-[11px] text-zinc-400 truncate max-w-lg mt-0.5">{subtitle}</p></div>- <div className="flex items-center gap-3">+ <div className="flex items-center gap-1.5 sm:gap-3 shrink-0">{/* Active Team Workspace Badge */}{(workspacePath || repoUrl) && (<div@@ -756,8 +795,8 @@ export const ChatView: React.FC<ChatViewProps> = ({)}{teamMembers && teamMembers.length > 0 && (- <div className="flex items-center gap-2 pl-3 border-l border-zinc-800">- <div className="flex -space-x-2 items-center px-1 py-1 -my-0.5">+ <div className="flex items-center gap-2 sm:pl-3 sm:border-l border-zinc-800">+ <div className="hidden sm:flex -space-x-2 items-center px-1 py-1 -my-0.5">{teamMembers.map((member) => (<divkey={member.id}@@ -773,10 +812,11 @@ export const ChatView: React.FC<ChatViewProps> = ({type="button"onClick={onManageTeam}className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800/80 hover:bg-zinc-700/80 hover:text-zinc-100 border border-zinc-700/60 transition-colors shadow-sm cursor-pointer"- title="Manage Team members and settings"+ title="Team members and settings"+ aria-label="Manage team"><Settings2 size={12} className="text-zinc-400" />- <span>Manage</span>+ <span className="hidden sm:inline">Manage</span></button>)}</div>@@ -787,7 +827,7 @@ export const ChatView: React.FC<ChatViewProps> = ({type="button"onClick={onEditInstructions}className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800/80 hover:bg-zinc-700/80 hover:text-zinc-100 border border-zinc-700/60 transition-colors shadow-sm cursor-pointer"- title="Pin instructions every kwant reads in this channel"+ title="Pin instructions every bot reads in this channel"aria-label="Pin instructions"><Pin size={12} className="text-amber-300" />@@ -801,9 +841,10 @@ export const ChatView: React.FC<ChatViewProps> = ({onClick={onEditKwant}className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800/80 hover:bg-zinc-700/80 hover:text-zinc-100 border border-zinc-700/60 transition-colors shadow-sm cursor-pointer"title={`Edit ${title}'s name, avatar, model and persona`}+ aria-label={`Edit ${title}`}><Pencil size={12} className="text-zinc-400" />- <span>Edit</span>+ <span className="hidden sm:inline">Edit</span></button>)}@@ -830,16 +871,13 @@ export const ChatView: React.FC<ChatViewProps> = ({? 'text-sky-300 bg-sky-500/20 border-sky-500/40': 'text-zinc-300 bg-zinc-900 hover:bg-zinc-800 border-zinc-700/60 hover:text-zinc-100'}`}- title="Toggle Bot Browser Pane"+ title="Show or hide the bot's browser"+ aria-label="Bot browser"+ aria-pressed={vmOpen}>- <span className="text-xs">🖥️</span>- <span>Bot Browser</span>+ <span className="text-xs" aria-hidden="true">🖥️</span>+ <span className="hidden sm:inline">Bot browser</span></button>-- <div className="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium text-sky-400 bg-sky-500/10 border border-sky-500/20 shadow-sm">- <Cpu size={13} />- <span>Laya Auto-Fleet</span>- </div></div></div>@@ -935,7 +973,7 @@ export const ChatView: React.FC<ChatViewProps> = ({{/* Laya routing: which agent will answer */}{isStreaming && routingState && !discussionState?.inProgress && (- <LayaRoutingCard routing={routingState} />+ <LayaRoutingCard routing={routingState} spaceName={spaceName} />)}{/* Live Streaming Assistant Message (or its place in the queue, in the same frame) */}@@ -1159,7 +1197,9 @@ export const ChatView: React.FC<ChatViewProps> = ({checkMention(inputVal, (e.target as HTMLTextAreaElement).selectionStart);}}}- placeholder={`Message ${title}... (Enter to send, Shift+Enter for newline, @ to mention)`}+ placeholder={spaceName ? `Message ${title} in ${spaceName}` : `Message ${title}`}+ title="Enter to send, Shift+Enter for a new line, @ to mention"+className="flex-1 min-w-0 bg-transparent px-3 py-1.5 text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none resize-none max-h-40 leading-relaxed font-sans"/><inputdiff --git a/frontend/src/components/ClaudeSignIn.tsx b/frontend/src/components/ClaudeSignIn.tsxindex aa530734..6baad515 100644--- a/frontend/src/components/ClaudeSignIn.tsx+++ b/frontend/src/components/ClaudeSignIn.tsx@@ -365,7 +365,7 @@ export const ClaudeSignOut: React.FC<{ onSignedOut: (engines: EngineInfo[]) => vSign out of Claude?</h4><div id="claude-signout-desc" className="space-y-1.5 text-xs text-zinc-300 leading-relaxed">- <p>Every kwant on this server will stop using Claude until you sign in again.</p>+ <p>Every bot in this space will stop using this account until you sign in again.</p><p className="text-zinc-400">This signs Claude Code out on this computer, so anything else here that uses the same Claude Code login is signed out too.</p></div>{error && (diff --git a/frontend/src/components/EngineAccounts.tsx b/frontend/src/components/EngineAccounts.tsxindex b8203243..60943d89 100644--- a/frontend/src/components/EngineAccounts.tsx+++ b/frontend/src/components/EngineAccounts.tsx@@ -47,7 +47,7 @@ export interface RowStatus {export function accountStatus(p: Profile, engine: EngineInfo, now = Date.now()): RowStatus {if (engine.enabled === false || engine.status === 'disabled') return { tone: 'muted', label: 'Off', detail: `Not checked while ${engine.name} is off` };if (p.kind !== 'system') return accountState(p, now);- if (!p.enabled) return { tone: 'muted', label: 'Off', detail: 'Kwants skip it while another account here is on' };+ if (!p.enabled) return { tone: 'muted', label: 'Off', detail: 'Bots skip it while another account here is on' };switch (engine.status) {case 'ready':return isThirdPartyLabel(p.account_label) ? accountState(p, now) : { tone: 'ok', label: 'Ready', detail: p.account_label };@@ -71,7 +71,7 @@ const Switch: React.FC<{ on: boolean; label: string; disabled?: boolean; onChangrole="switch"aria-checked={on}aria-label={label}- title={on ? 'On: kwants may use it' : 'Off: kwants skip it'}+ title={on ? 'On: bots may use it' : 'Off: bots skip it'}disabled={disabled}onClick={() => {playSfx('click');@@ -364,7 +364,7 @@ const AccountRow: React.FC<{</span>)}{p.is_default && (- <span className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-md bg-sky-500/15 text-[10px] text-sky-200" title="Kwants try this account first">+ <span className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-md bg-sky-500/15 text-[10px] text-sky-200" title="Bots try this account first"><Star size={9} aria-hidden="true" /> Default</span>)}@@ -382,7 +382,7 @@ const AccountRow: React.FC<{<Switchon={p.enabled}disabled={busy}- label={`Use ${isSystem ? KIND_LABELS.system : p.name} for kwants`}+ label={`Use ${isSystem ? KIND_LABELS.system : p.name} for bots`}onChange={(on) => run(() => profilesApi.update(p.id, { enabled: on }))}/></div>@@ -482,7 +482,7 @@ const AccountRow: React.FC<{onKeyDown={(e) => e.key === 'Enter' && (e.currentTarget as HTMLInputElement).blur()}className="w-16 bg-zinc-950 border border-zinc-800 rounded-md px-1.5 py-0.5 text-[11px] text-zinc-100 focus:border-sky-500 focus:outline-none"/>- <span className="text-zinc-500">After the default, kwants try lower numbers first.</span>+ <span className="text-zinc-500">After the default, bots try lower numbers first.</span></label>{p.home_dir && (<p className="text-[10.5px] text-zinc-500">@@ -492,7 +492,7 @@ const AccountRow: React.FC<{</div>)}- {confirmDelete && <p className="text-[11px] text-zinc-500">Kwants pinned to it go back to the default. Its folder stays on disk.</p>}+ {confirmDelete && <p className="text-[11px] text-zinc-500">Bots pinned to it go back to the default. Its folder stays on disk.</p>}{keyOpen && p.kind === 'api_key' && (<formdiff --git a/frontend/src/components/EnginesPanel.tsx b/frontend/src/components/EnginesPanel.tsxindex 29387c32..2b6c05bc 100644--- a/frontend/src/components/EnginesPanel.tsx+++ b/frontend/src/components/EnginesPanel.tsx@@ -137,7 +137,7 @@ const hostAction = (e: EngineInfo, api: EnginesApi, onSignedIn: () => void, focufunction headline(engines: EngineInfo[], profiles: Profile[] | null, now: number): string {const ready = engines.filter(isUsable).length;if (ready > 0) {- return `${ready} ready${onlyCliReady(engines) ? ', all through your signed-in CLIs, so no API keys are needed' : ''}. Kwants only use engines that are ready.`;+ return `${ready} ready${onlyCliReady(engines) ? ', all through your signed-in CLIs, so no API keys are needed' : ''}. Bots only use engines that are ready.`;}// An engine that's off but has an account ready is the quickest fix.for (const e of sortEngines(engines)) {@@ -154,7 +154,7 @@ function headline(engines: EngineInfo[], profiles: Profile[] | null, now: numberexport const RouteSummary: React.FC<{ rows: RouteRow[]; pending: boolean }> = ({ rows, pending }) => (<div data-route-summary className="rounded-xl border border-sky-500/25 bg-gradient-to-b from-sky-500/[0.07] to-transparent p-3 space-y-2.5"><h4 className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-200">- <Route size={13} aria-hidden="true" /> What runs your kwants+ <Route size={13} aria-hidden="true" /> What runs your kwant bots</h4><ul className="space-y-2.5">{rows.map((r) => (@@ -171,14 +171,14 @@ export const RouteSummary: React.FC<{ rows: RouteRow[]; pending: boolean }> = ({<p className="mt-1 pl-0 sm:pl-[3.875rem] text-zinc-500">{r.note && <span className="text-amber-200">{r.note} </span>}{r.then.length > 0 ? `If it’s out of usage or signed out: ${r.then.join(', then ')}.` : r.note ? '' : 'No backup account is ready.'}- {r.defaultModel && <> Kwants on Auto get {r.defaultModel}.</>}+ {r.defaultModel && <> Bots on Auto get {r.defaultModel}.</>}</p>{r.fallback && <p className="pl-0 sm:pl-[3.875rem] text-zinc-500">{r.fallback}</p>}</li>))}</ul><p className="text-[10.5px] text-zinc-500 border-t border-zinc-800/80 pt-2">- {pending ? 'Loading accounts… ' : ''}A kwant set to a specific account in its own settings starts with that account instead.+ {pending ? 'Loading accounts… ' : ''}A bot set to a specific account in its own settings starts with that account instead.</p></div>);diff --git a/frontend/src/components/KwantToolsPicker.tsx b/frontend/src/components/KwantToolsPicker.tsxindex d59e329f..97e12460 100644--- a/frontend/src/components/KwantToolsPicker.tsx+++ b/frontend/src/components/KwantToolsPicker.tsx@@ -11,7 +11,7 @@ interface KwantToolsPickerProps {}/**- * "Tools this kwant can use": one switch per registered MCP server. Every server is on for every+ * "Tools this bot can use": one switch per registered MCP server. Every server is on for every* kwant unless switched off here. A server paused in Tools shows greyed and keeps this kwant's* choice, so turning it back on there restores it.*/@@ -47,7 +47,7 @@ export const KwantToolsPicker: React.FC<KwantToolsPickerProps> = ({ model, selec<div><div className="flex items-center justify-between mb-1"><label className="text-xs font-medium text-zinc-400">- Tools this kwant can use <span className="text-zinc-600 font-normal">· asks you before each use</span>+ Tools this bot can use <span className="text-zinc-600 font-normal">· asks you before each use</span></label>{onManageServers && servers && servers.length > 0 && (<button type="button" onClick={onManageServers} className="text-[11px] text-sky-300 hover:text-sky-200">@@ -58,7 +58,7 @@ export const KwantToolsPicker: React.FC<KwantToolsPickerProps> = ({ model, selec{servers && servers.length > 0 && (<p className="mb-1.5 text-[11px] text-zinc-500 leading-snug">- Every tool server is on by default, including ones you add later. Switch off any this kwant shouldn’t have+ Every tool server is on by default, including ones you add later. Switch off any this bot shouldn’t have{offCount > 0 && <span className="text-zinc-400"> · {offCount} off</span>}.</p>)}@@ -116,7 +116,7 @@ export const KwantToolsPicker: React.FC<KwantToolsPickerProps> = ({ model, selec<span className="block text-xs text-zinc-200 truncate">{s.name}</span>{paused && (<span className="block text-[10px] text-zinc-500">- Paused in Tools{selected.includes(s.id) ? '. This kwant gets it once it’s on.' : ''}+ Paused in Tools{selected.includes(s.id) ? '. This bot gets it once it’s on.' : ''}</span>)}</span>diff --git a/frontend/src/components/LayaStatus.tsx b/frontend/src/components/LayaStatus.tsxnew file mode 100644index 00000000..dab19f67--- /dev/null+++ b/frontend/src/components/LayaStatus.tsx@@ -0,0 +1,85 @@+// Laya's status, shown in App settings (it used to be the header's ROUTER pill).+import React from 'react';+import { Cpu } from 'lucide-react';++export const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);++type LayaState = 'unknown' | 'external' | 'installing' | 'starting' | 'online' | 'offline' | 'failed';++interface LayaStatus {+ state: LayaState;+ detail: string;+ url: string;+ managed: boolean;+}++export const useLayaStatus = (): LayaStatus | null => {+ const [status, setStatus] = React.useState<LayaStatus | null>(null);+ React.useEffect(() => {+ let cancelled = false;+ let timer: ReturnType<typeof setTimeout>;+ const poll = async () => {+ let next: LayaStatus | null = null;+ try {+ const res = await fetch('/api/laya/status');+ if (res.ok) next = await res.json();+ } catch {+ // server restarting; keep the last known status+ }+ if (cancelled) return;+ if (next) setStatus(next);+ const up = next?.state === 'online' || next?.state === 'external';+ timer = setTimeout(poll, up ? 20000 : 4000);+ };+ poll();+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, []);+ return status;+};++export const layaPill = (status: LayaStatus | null) => {+ const ready = 'Laya is online · picks the best bot for each message';+ switch (status?.state) {+ case 'online':+ case 'external':+ return { dot: 'bg-emerald-400', label: ready };+ case 'installing':+ return { dot: 'bg-amber-400 animate-pulse', label: 'Laya is installing · picking by keywords meanwhile' };+ case 'starting':+ return { dot: 'bg-amber-400 animate-pulse', label: 'Laya is loading its model · picking by keywords meanwhile' };+ case 'failed':+ case 'offline':+ return { dot: 'bg-rose-500', label: 'Laya is offline · picking by keywords' };+ default:+ return { dot: 'bg-zinc-500 animate-pulse', label: 'Checking Laya…' };+ }+};+++/** Laya's state for App settings. */+export const LayaStatusRow: React.FC = () => {+ const laya = useLayaStatus();+ const pill = layaPill(laya);+ return (+ <div className="flex items-start gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800">+ <Cpu size={15} className="mt-0.5 text-sky-400 shrink-0" aria-hidden="true" />+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-zinc-200">Laya, the router</p>+ <p className="mt-0.5 flex items-center gap-1.5 text-[11px] text-zinc-400" role="status">+ <span className={`w-2 h-2 rounded-full shrink-0 ${pill.dot}`} aria-hidden="true" />+ <span>{pill.label}</span>+ </p>+ {laya && (+ <p className="mt-0.5 text-[11px] text-zinc-500 break-all">+ {laya.url}+ {laya.managed ? ' (started by Kwant)' : ''}+ {laya.detail ? ` · ${laya.detail}` : ''}+ </p>+ )}+ </div>+ </div>+ );+};diff --git a/frontend/src/components/ManageTeamModal.tsx b/frontend/src/components/ManageTeamModal.tsxindex 7ea20727..49c5a0b5 100644--- a/frontend/src/components/ManageTeamModal.tsx+++ b/frontend/src/components/ManageTeamModal.tsx@@ -111,7 +111,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({playSfx('click');if (memberIds.includes(kwantId)) {if (memberIds.length <= 1) {- setError('A team must have at least one agent.');+ setError('A team needs at least one bot.');return;}setError(null);@@ -134,7 +134,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({return;}if (memberIds.length === 0) {- setError('Select at least one agent for this team.');+ setError('Pick at least one bot for this team.');return;}if (instructions.length > MAX_INSTRUCTIONS) {@@ -159,7 +159,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({onClose();} catch (err) {setIsSaving(false);- setError('Failed to update team. Please try again.');+ setError(err instanceof Error && err.message ? err.message : 'Couldn’t save the team. Try again.');}};@@ -193,7 +193,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({</div><div><h3 id="manage-team-title" className="text-sm font-semibold text-zinc-100">Manage Team: @{team.name}</h3>- <p className="text-[11px] text-zinc-400">Configure team roster, lead agent, and permissions</p>+ <p className="text-[11px] text-zinc-400">Members, lead and instructions</p></div></div><button@@ -246,7 +246,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({value={instructions}onChange={setInstructions}label="Team instructions"- hint="Pinned for every kwant in this team, before each turn. Leave empty to unpin."+ hint="Pinned for every bot in this team, before each turn. Leave empty to unpin."rows={4}/>diff --git a/frontend/src/components/McpServersModal.tsx b/frontend/src/components/McpServersModal.tsxindex 725e6252..21418134 100644--- a/frontend/src/components/McpServersModal.tsx+++ b/frontend/src/components/McpServersModal.tsx@@ -600,10 +600,10 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos<Plug size={26} /></div><div className="space-y-1.5 max-w-md mx-auto">- <h3 className="text-sm font-semibold text-zinc-100">Give your kwants new abilities</h3>+ <h3 className="text-sm font-semibold text-zinc-100">Give your bots new abilities</h3><p className="text-xs text-zinc-400 leading-relaxed">- MCP servers are small add-ons that hand your kwants tools, like reading files, browsing the web or working with GitHub.- Add one here and every kwant can use it; switch it off for a kwant in that kwant’s edit screen. They always ask you before using a tool.+ MCP servers are small add-ons that hand your bots tools, like reading files, browsing the web or working with GitHub.+ Add one here and every bot in this space can use it; switch it off for a bot in that bot’s edit screen. They always ask you before using a tool.Pick a popular one below and just add your key or sign in.</p></div>@@ -655,7 +655,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos<Users size={11} className="flex-shrink-0 mt-[3px] text-zinc-500" aria-hidden="true" /><span className="min-w-0 break-words">{usage.allKwants ? (- server.enabled ? 'Used by all kwants' : 'All kwants get it once it’s on'+ server.enabled ? 'Used by every bot in this space' : 'Every bot here gets it once it’s on') : (<>{server.enabled ? 'Off for: ' : 'Once it’s on, off for: '}@@ -720,7 +720,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos<div className="mt-3 pt-2.5 border-t border-zinc-800/70 flex flex-wrap items-center justify-between gap-2">{confirmDisconnect === server.id ? (<div className="flex flex-wrap items-center gap-2 text-[11px] text-zinc-300">- <span>Sign out of {server.name}? Kwants can’t use its tools until you connect again.</span>+ <span>Sign out of {server.name}? Bots can’t use its tools until you connect again.</span><buttontype="button"onClick={() => setConfirmDisconnect(null)}@@ -738,7 +738,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos</div>) : confirmDelete === server.id ? (<div className="flex flex-wrap items-center gap-2 text-[11px] text-zinc-300">- <span>Delete {server.name}? Kwants using it lose these tools.</span>+ <span>Delete {server.name}? Bots using it lose these tools.</span><buttontype="button"onClick={() => setConfirmDelete(null)}@@ -924,7 +924,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClosclassName={`${inputCls} font-mono`}/><p className="mt-1 text-[11px] text-zinc-500">- Short and simple: letters, numbers, - or _. Kwants see its tools as <span className="font-mono text-zinc-400">{form.name.trim() || 'name'} · tool</span>.+ Short and simple: letters, numbers, - or _. Bots see its tools as <span className="font-mono text-zinc-400">{form.name.trim() || 'name'} · tool</span>.</p></div>@@ -1086,7 +1086,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos)}<div className="min-w-0"><h2 id="mcp-title" className="text-sm font-semibold text-zinc-100 truncate">- {editing === 'new' || picking ? 'Add a tool server' : editing ? `Edit ${form.name || 'server'}` : 'Tools for your kwants'}+ {editing === 'new' || picking ? 'Add a tool server' : editing ? `Edit ${form.name || 'server'}` : 'Tools for your kwant bots'}</h2><p className="text-xs text-zinc-400 truncate">{picking@@ -1095,7 +1095,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos? 'Pick how it connects, then fill in the details': editing? 'Saved secrets stay hidden and are kept unless you change them'- : 'MCP servers your kwants can use, with your approval'}+ : 'MCP servers your bots can use, with your approval'}</p></div></div>diff --git a/frontend/src/components/MemoryPanel.tsx b/frontend/src/components/MemoryPanel.tsxindex aba1b328..db1a63ed 100644--- a/frontend/src/components/MemoryPanel.tsx+++ b/frontend/src/components/MemoryPanel.tsx@@ -12,7 +12,7 @@ const inputClass =const SourceBadge: React.FC<{ source: Memory['source'] }> = ({ source }) =>source === 'agent' ? (<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-violet-500/10 text-violet-300 border border-violet-500/20">- <Bot size={10} aria-hidden="true" /> Agent+ <Bot size={10} aria-hidden="true" /> Bot</span>) : (<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-sky-500/10 text-sky-300 border border-sky-500/20">diff --git a/frontend/src/components/MentionPopover.tsx b/frontend/src/components/MentionPopover.tsxindex 69aadc41..6a765656 100644--- a/frontend/src/components/MentionPopover.tsx+++ b/frontend/src/components/MentionPopover.tsx@@ -57,7 +57,7 @@ export const MentionPopover: React.FC<MentionPopoverProps> = ({<React.Fragment key={`${item.type}-${item.id}`}>{showSectionHeader && (<div className="text-[10px] font-semibold text-zinc-500 uppercase tracking-wider px-2.5 py-1 select-none">- {item.type === 'kwant' ? 'Agents' : 'Teams'}+ {item.type === 'kwant' ? 'Bots' : 'Teams'}</div>)}<buttondiff --git a/frontend/src/components/ModelPicker.tsx b/frontend/src/components/ModelPicker.tsxindex 572031b2..7382a1cf 100644--- a/frontend/src/components/ModelPicker.tsx+++ b/frontend/src/components/ModelPicker.tsx@@ -167,7 +167,7 @@ const PickHint: React.FC<{ id: string; health: ReturnType<typeof pickHealth>; on</p><p className="text-amber-200/80">{health.reason ? `${health.reason.replace(/`/g, '').replace(/\.$/, '')}. ` : ''}- This kwant won't switch engine by itself: fix it, or pick another engine.{' '}+ This bot won't switch engine by itself: fix it, or pick another engine.{' '}{health.family === 'claude' && onSignInClaude ? <SignInClaudeLink onSignInClaude={onSignInClaude} /> : <SettingsLink onOpenSettings={onOpenSettings} />}</p></div>diff --git a/frontend/src/components/ModernApprovalCard.tsx b/frontend/src/components/ModernApprovalCard.tsxindex 2e995261..b6203dfc 100644--- a/frontend/src/components/ModernApprovalCard.tsx+++ b/frontend/src/components/ModernApprovalCard.tsx@@ -58,7 +58,7 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({{shell ? (<div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs space-y-2 mb-3">- <p className="text-zinc-300">A kwant wants to run a command on your computer.</p>+ <p className="text-zinc-300">A bot wants to run a command on your computer.</p><pre className="font-mono text-[11px] text-zinc-100 bg-zinc-950/70 border border-zinc-800 rounded-md p-2 whitespace-pre-wrap break-all max-h-64 overflow-y-auto">{shell.command || '(empty command)'}</pre>@@ -71,7 +71,7 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({) : mcp ? (<div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs space-y-2 mb-3"><p className="text-zinc-300">- {mcp.kwant ? <span className="font-medium text-zinc-100">{mcp.kwant}</span> : 'A kwant'} wants to use{' '}+ {mcp.kwant ? <span className="font-medium text-zinc-100">{mcp.kwant}</span> : 'A bot'} wants to use{' '}<span className="font-medium text-sky-200">{humanizeToolName(mcp.tool)}</span>{mcp.server && (<>@@ -123,7 +123,7 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({{!shell && (<buttononClick={() => handleDecision('always_allow')}- title={mcp ? 'Allow this tool for this kwant until kwnt restarts' : undefined}+ title={mcp ? 'Allow this tool for this bot until Kwant restarts' : undefined}className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm"><CheckCheck size={14} />diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsxindex ee80cdcf..ed158824 100644--- a/frontend/src/components/NewAgentModal.tsx+++ b/frontend/src/components/NewAgentModal.tsx@@ -209,7 +209,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({{isEdit ? <Pencil size={14} /> : <Sparkles size={15} />}</div><h3 id="agent-modal-title" className="text-sm font-semibold text-zinc-100">- {isEdit ? `Edit ${initial?.name}` : joinTeamName ? `New Agent for @${joinTeamName}` : 'Create New AI Agent'}+ {isEdit ? `Edit ${initial?.name}` : joinTeamName ? `New bot for @${joinTeamName}` : 'New kwant bot'}</h3></div><button@@ -225,7 +225,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({</div>{isEdit && kwantId && (- <div className="flex p-0.5 rounded-lg bg-zinc-950 border border-zinc-800" role="tablist" aria-label="Agent settings">+ <div className="flex p-0.5 rounded-lg bg-zinc-950 border border-zinc-800" role="tablist" aria-label="Bot settings">{EDIT_TABS.map(({ id, label, Icon }) => (<buttonkey={id}@@ -255,12 +255,12 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({{isEdit && kwantId && tab === 'memory' && (<div role="tabpanel" id="agent-panel-memory" aria-labelledby="agent-tab-memory">- <MemoryPanel kwantId={kwantId} kwantName={initial?.name ?? 'This kwant'} />+ <MemoryPanel kwantId={kwantId} kwantName={initial?.name ?? 'This bot'} /></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'} />+ <SkillsPanel kwantId={kwantId} kwantName={initial?.name ?? 'This bot'} /></div>)}{isEdit && kwantId && tab === 'routines' && (@@ -323,7 +323,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({)}<div>- <label className="block text-xs font-medium text-zinc-400 mb-1">Agent Name</label>+ <label className="block text-xs font-medium text-zinc-400 mb-1">Name</label><inputtype="text"required@@ -425,7 +425,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({rows={isEdit || presetId ? 6 : 3}value={prompt}onChange={(e) => setPrompt(e.target.value)}- placeholder="What this agent does: expertise, responsibilities, and how it should work..."+ placeholder="What this bot does: expertise, responsibilities, and how it should work..."className="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 resize-none"/></div>@@ -467,7 +467,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({disabled={submitting || !name.trim()}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">- {isEdit ? 'Save Changes' : joinTeamName ? 'Create & Add to Team' : 'Create Agent'}+ {isEdit ? 'Save changes' : joinTeamName ? 'Create and add to team' : 'Create bot'}</button></div></form>diff --git a/frontend/src/components/NewTeamModal.tsx b/frontend/src/components/NewTeamModal.tsxindex d950f23c..605dce12 100644--- a/frontend/src/components/NewTeamModal.tsx+++ b/frontend/src/components/NewTeamModal.tsx@@ -126,7 +126,7 @@ export const NewTeamModal: React.FC<NewTeamModalProps> = ({return;}if (selectedMembers.length === 0) {- setError('Select at least one agent for this team.');+ setError('Pick at least one bot for this team.');return;}@@ -398,7 +398,7 @@ export const NewTeamModal: React.FC<NewTeamModalProps> = ({{/* Lead agent */}<div><label className="block text-xs font-medium text-zinc-400 mb-1">- Team Lead Agent+ Team lead</label><selectvalue={leadKwantId}@@ -465,7 +465,7 @@ export const NewTeamModal: React.FC<NewTeamModalProps> = ({})}{kwants.length === 0 && (<div className="p-3 text-center text-xs text-zinc-500">- No agents available to assign.+ No bots to add yet.</div>)}</div>diff --git a/frontend/src/components/RoutinesModal.tsx b/frontend/src/components/RoutinesModal.tsxindex 67277b48..068864fc 100644--- a/frontend/src/components/RoutinesModal.tsx+++ b/frontend/src/components/RoutinesModal.tsx@@ -36,7 +36,7 @@ export const RoutinesModal: React.FC<{ isOpen: boolean; onClose: () => void; kwa</div><div><h2 id="routines-title" className="text-sm font-semibold text-zinc-100">Routines</h2>- <p className="text-xs text-zinc-400">Scheduled work for all your kwants</p>+ <p className="text-xs text-zinc-400">Scheduled work for the bots in this space</p></div></div><buttondiff --git a/frontend/src/components/RoutinesPanel.tsx b/frontend/src/components/RoutinesPanel.tsxindex 1e137f69..8d644516 100644--- a/frontend/src/components/RoutinesPanel.tsx+++ b/frontend/src/components/RoutinesPanel.tsx@@ -75,8 +75,8 @@ const RoutineForm: React.FC<{const submit = async (e: React.FormEvent) => {e.preventDefault();if (!f.name.trim()) return setError('Give the routine a name.');- if (!f.instructions.trim()) return setError('Say what the kwant should do.');- if (!f.kwantId) return setError('Pick a kwant.');+ if (!f.instructions.trim()) return setError('Say what the bot should do.');+ if (!f.kwantId) return setError('Pick a bot.');const built = scheduleFromForm(s);if ('error' in built) return setError(built.error);setSaving(true);@@ -111,7 +111,7 @@ const RoutineForm: React.FC<{</div>{!fixedKwantId && (<div>- <label htmlFor={id('kwant')} className={labelClass}>Kwant</label>+ <label htmlFor={id('kwant')} className={labelClass}>Bot</label><select id={id('kwant')} value={f.kwantId} onChange={(e) => setF({ ...f, kwantId: e.target.value })} className={inputClass}>{kwants.map((k) => (<option key={k.id} value={k.id}>{k.name}</option>@@ -122,7 +122,7 @@ const RoutineForm: React.FC<{<div><label htmlFor={id('channel')} className={labelClass}>Posts in</label><select id={id('channel')} value={f.channelId} onChange={(e) => setF({ ...f, channelId: e.target.value })} className={inputClass}>- <option value="">Direct chat with the kwant</option>+ <option value="">Direct chat with the bot</option>{channels.map((c) => (<option key={c.id} value={c.id}>{channelLabel(c.name)}</option>))}@@ -414,7 +414,7 @@ export const RoutinesPanel: React.FC<{ kwantId?: string; kwants: Kwant[]; channe<div className="space-y-3"><div className="flex items-center justify-between gap-2"><p className="text-[11px] text-zinc-500 leading-relaxed">- A routine posts its instructions to the kwant on a schedule, then the kwant answers as usual.+ A routine posts its instructions to the bot on a schedule, then the bot answers as usual.</p>{editing !== 'new' && (<button@@ -462,7 +462,7 @@ export const RoutinesPanel: React.FC<{ kwantId?: string; kwants: Kwant[]; channe<RoutineRowkey={r.id}routine={r}- kwantName={kwantId ? undefined : kwantName(r.kwant_id) ?? 'deleted kwant'}+ kwantName={kwantId ? undefined : kwantName(r.kwant_id) ?? 'deleted bot'}placeLabel={place(r)}tick={tick}onEdit={() => setEditing(r)}diff --git a/frontend/src/components/SandboxViewer.tsx b/frontend/src/components/SandboxViewer.tsxindex 4e2c4523..ebedd1c0 100644--- a/frontend/src/components/SandboxViewer.tsx+++ b/frontend/src/components/SandboxViewer.tsx@@ -143,7 +143,7 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {}, [teamId, applyUrl]);useEffect(() => {- document.title = `${title || url || 'Sandbox browser'} · Kwant sandbox`;+ document.title = `${title || url || 'Sandbox browser'} · Kwant browser`;}, [title, url]);const toViewport = (clientX: number, clientY: number) => {@@ -243,10 +243,10 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {<divclassName="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium text-emerald-300 bg-emerald-500/10 border border-emerald-500/30 flex-shrink-0"- title="This is the same browser your agents use. They will see the current page on their next reply."+ title="This is the same browser your bots use. They will see the current page on their next reply."><Share2 size={12} />- <span>Shared with your agents</span>+ <span>Shared with your bots</span></div></header>@@ -256,7 +256,7 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {<span>{isFocused? 'Controlling the sandbox: clicks, scrolling, typing and paste go to the page.'- : 'Click the page to take control. Your agents will see wherever you leave this browser.'}+ : 'Click the page to take control. Your bots will see wherever you leave this browser.'}</span>{title && <span className="ml-auto truncate text-zinc-400">{title}</span>}</div>diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex ee498a6f..9717a1fb 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -1,5 +1,5 @@import React, { useState, useEffect, useRef } from 'react';-import { Key, Globe, X, Sparkles, Check, Plug, ChevronDown, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor } from 'lucide-react';+import { Key, Globe, X, Settings, Check, ChevronDown, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge } from 'lucide-react';import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';import {BROWSER_NOTIFY_KEY,@@ -10,13 +10,11 @@ import {notificationPermission,webhookUrlError,} from '../continuity';-import { playSfx } from '../audio/chiptune';+import { isSfxMuted, playSfx, toggleSfxMute } from '../audio/chiptune';import { useAuth } from './AuthGate';import { ComputerModeControl, useComputerMode } from './ComputerModeSwitch';-import { EnginesPanel } from './EnginesPanel';import { useEngines } from '../useEngines';-import { useProfiles } from '../useProfiles';-import type { Profile } from '../profiles';+import { LayaStatusRow } from './LayaStatus';interface SettingsData {anthropic_api_key: string;@@ -40,26 +38,25 @@ interface SettingsData {}const LIMIT_FIELDS: { key: TurnLimitKey; label: string; hint: string }[] = [- { key: 'max_turns_per_agent', label: 'Replies at once per agent', hint: 'More than this and an agent’s next request waits in line.' },- { key: 'max_turns_global', label: 'Replies at once in total', hint: 'Across all agents; keeps the server responsive.' },+ { key: 'max_turns_per_agent', label: 'Replies at once per bot', hint: 'More than this and a bot’s next request waits in line.' },+ { key: 'max_turns_global', label: 'Replies at once in total', hint: 'Across all bots in every space; keeps the server responsive.' },{ key: 'delegation_follow_up_minutes', label: 'Check on delegated work after (minutes)', hint: '0 turns the check-in off.' },];interface SettingsModalProps {isOpen: boolean;onClose: () => void;- onOpenTools?: () => void;- /** Gets the accounts list after every change, so kwant pickers stay current. */- onProfilesChanged?: (profiles: Profile[]) => void;- /** Changes to focus "Sign in with Claude" in Engines. */- focusClaudeSignIn?: number;+ /** Tokens used in the open chat, shown under Usage. */+ tokensUsed?: number;}-export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, onOpenTools, onProfilesChanged, focusClaudeSignIn }) => {+/** App settings: shared by every space (keys, Laya, limits, notifications, sounds). Accounts,+ * bots and tools are per space, in Space settings. */+export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tokensUsed = 0 }) => {const { authRequired, signOut } = useAuth();const computer = useComputerMode(isOpen);const engines = useEngines(isOpen);- const accounts = useProfiles(isOpen, onProfilesChanged);+ const [sfxMuted, setSfxMuted] = useState(isSfxMuted);const [settings, setSettings] = useState<SettingsData | null>(null);const [anthropicKey, setAnthropicKey] = useState('');const [xaiKey, setXaiKey] = useState('');@@ -200,11 +197,11 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o<div className="flex items-center justify-between border-b border-zinc-800 pb-4"><div className="flex items-center gap-2.5"><div className="w-8 h-8 rounded-lg bg-sky-500/10 border border-sky-500/20 flex items-center justify-center text-sky-400">- <Sparkles size={17} />+ <Settings size={17} /></div><div>- <h2 id="settings-title" className="text-sm font-semibold text-zinc-100">Settings</h2>- <p className="text-xs text-zinc-400">What runs your kwants, the accounts they use, and how they work</p>+ <h2 id="settings-title" className="text-sm font-semibold text-zinc-100">App settings</h2>+ <p className="text-xs text-zinc-400">Shared by every space. Accounts, bots and tools are in each space’s settings.</p></div></div>@@ -220,7 +217,33 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o</button></div>- <EnginesPanel api={engines} accounts={accounts} focusClaudeSignIn={focusClaudeSignIn} />+ <LayaStatusRow />++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div className="flex items-center gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800">+ <span className="flex-1 text-xs font-medium text-zinc-200 flex items-center gap-2">+ {sfxMuted ? <VolumeX size={15} className="text-zinc-500" aria-hidden="true" /> : <Volume2 size={15} className="text-sky-400" aria-hidden="true" />}+ <span id="sfx-label">UI sounds</span>+ </span>+ <button+ type="button"+ role="switch"+ aria-checked={!sfxMuted}+ aria-labelledby="sfx-label"+ onClick={() => setSfxMuted(toggleSfxMute())}+ className={`relative shrink-0 w-9 h-5 rounded-full transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${+ !sfxMuted ? 'bg-sky-600' : 'bg-zinc-700'+ }`}+ >+ <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform motion-reduce:transition-none ${!sfxMuted ? 'translate-x-4' : ''}`} />+ </button>+ </div>+ <div className="flex items-center gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800">+ <Gauge size={15} className="text-zinc-500" aria-hidden="true" />+ <span className="flex-1 text-xs font-medium text-zinc-200">Token usage, open chat</span>+ <span className="font-mono text-xs text-zinc-300">{tokensUsed} tk</span>+ </div>+ </div>{computer.state.settings && (<div className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3">@@ -235,26 +258,6 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o</div>)}- {onOpenTools && (- <button- type="button"- onClick={() => {- playSfx('click');- onOpenTools();- }}- className="w-full flex items-center gap-3 p-3 rounded-xl border border-zinc-800 bg-zinc-950/60 hover:border-sky-500/40 text-left transition-colors group"- >- <span className="w-8 h-8 rounded-lg bg-sky-500/10 border border-sky-500/20 flex items-center justify-center text-sky-400">- <Plug size={15} />- </span>- <span className="flex-1">- <span className="block text-xs font-medium text-zinc-200">Tools (MCP servers)</span>- <span className="block text-[11px] text-zinc-500">Give kwants abilities like files, web pages or GitHub</span>- </span>- <ChevronRight size={15} className="text-zinc-500 group-hover:text-sky-300" />- </button>- )}-{/* Cloud API Keys Form */}<form onSubmit={handleSave} className="space-y-4"><div className="rounded-xl border border-zinc-800 bg-zinc-950/60">@@ -269,7 +272,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o<span className="flex-1"><span className="block text-xs font-medium text-zinc-200">API keys and Ollama</span><span className="block text-[11px] text-zinc-500">- Optional. {keysSaved ? `${keysSaved} saved. ` : ''}Not needed when you sign in to a CLI above.+ Optional, for every space. {keysSaved ? `${keysSaved} saved. ` : ''}Not needed when a space’s bots use a signed-in CLI.</span></span>{keysOpen ? <ChevronDown size={15} className="text-zinc-500" aria-hidden="true" /> : <ChevronRight size={15} className="text-zinc-500" aria-hidden="true" />}@@ -277,7 +280,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o<div id="settings-api-keys" hidden={!keysOpen} className="space-y-3 px-3 pb-3"><p className="text-[11px] text-zinc-500">- One key per provider for the API-key engines. To keep several keys for one provider, add them as accounts on its engine card above.+ One key per provider for the API-key engines. To keep several keys for one provider, add them as accounts in a space’s settings → Accounts.</p><div><label className="block text-xs font-medium text-zinc-400 mb-1">@@ -373,7 +376,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o</div>{perAgentOverGlobal && (<p className="text-[11px] text-amber-300" role="status">- The total is lower than the per-agent limit, so an agent never gets more than {limits.max_turns_global} at once.+ The total is lower than the per-bot limit, so a bot never gets more than {limits.max_turns_global} at once.</p>)}</fieldset>@@ -382,9 +385,9 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o{agentTools !== null && (<div className="flex items-start gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800"><div className="flex-1">- <p id="agent-tools-label" className="text-xs font-medium text-zinc-200">Agents can use their own tools</p>+ <p id="agent-tools-label" className="text-xs font-medium text-zinc-200">Bots can use their own tools</p><p id="agent-tools-hint" className="text-[11px] text-zinc-500">- Delegating to each other, asking you questions, sharing files, skills, searching earlier chats and keeping notes. Off, agents just reply.+ Delegating to each other, asking you questions, sharing files, skills, searching earlier chats and keeping notes. Off, bots just reply.</p></div><button@@ -418,7 +421,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o<div className="flex-1"><p id="browser-notify-label" className="text-xs font-medium text-zinc-200">Notify me on this computer</p><p className="text-[11px] text-zinc-500">- Only while kwnt is in a background tab.+ Only while Kwant is in a background tab. Each notification names its space.{permission === 'denied' && <span className="text-amber-300"> Blocked by your browser; allow notifications for this site in its settings.</span>}{permission === 'unsupported' && <span className="text-amber-300"> This browser can't show notifications.</span>}</p>@@ -477,7 +480,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o? 'A webhook is saved. Type a new URL to replace it.': settings?.notify_webhook_url === MASK && !webhookUrl.trim()? 'Saving will remove the webhook.'- : 'https only. kwnt posts a short title and line, never message text.')}+ : 'https only. Kwant posts a short title and line, never message text.')}</p></div>@@ -507,7 +510,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o{saveSuccess && (<div className="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-3 py-2 rounded-lg text-xs flex items-center gap-2"><Check size={14} />- <span>Settings saved successfully to database</span>+ <span>Saved for every space</span></div>)}@@ -540,7 +543,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, odisabled={saving || !!webhookError || limitsInvalid}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">- {saving ? 'Saving...' : 'Save Settings'}+ {saving ? 'Saving…' : 'Save'}</button></div></form>diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 5a7a3a6b..0330c3a2 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -1,11 +1,14 @@-import React, { useEffect, useState } from 'react';-import { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox } from 'lucide-react';+import React, { useCallback, useEffect, useState } from 'react';+import { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, CalendarClock } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { playSfx } from '../audio/chiptune';import { badgeText } from '../away';import { isUsable, pickLabel } from '../engines';import { useEngines } from '../useEngines';import { claudeNeedsSignIn } from '../claudeLogin';+import { Space, spaceSummary } from '../spaces';+import { SpaceSwitcher, SpaceTile } from './Spaces';+import { isMac } from './LayaStatus';export interface Kwant {id: string;@@ -46,14 +49,28 @@ export interface Team {instructions?: string | null;}+/** What the sidebar shows: everything, or one phone tab. */+export type SidebarSection = 'all' | 'chats' | 'bots';+export interface SidebarProps {+ space: Space;+ spaces: Space[];+ onSwitchSpace: (id: string) => void;+ onCreateSpace: () => void;+ onOpenSpaceSettings: () => void;+ onOpenArchived: () => void;+ onOpenSearch: () => void;+ onOpenRoutines: () => void;+ /** Phones show one tab at a time, full width. */+ section?: SidebarSection;+ phone?: boolean;kwants: Kwant[];channels: Channel[];teams: Team[];selectedId: string;isChannel: boolean;selectedTeamId?: string | null;- /** Agents busy outside the open chat -> "Working on …", shown under their name. */+ /** Bots busy outside the open chat -> "Working on …", shown under their name. */busyKwants?: Record<string, string>;onSelectKwant: (kwant: Kwant) => void;onSelectChannel: (channel: Channel) => void;@@ -61,21 +78,26 @@ export interface SidebarProps {onManageTeam?: (team: Team) => void;onUpdateTeamMembers?: (team: Team, memberIds: string[]) => void;onEditKwant?: (kwant: Kwant) => void;- /** Opens the new-agent form; with a team, the new agent joins it. */+ /** Opens the new-bot form; with a team, the new bot joins it. */onSummonKwant: (team?: Team) => void;onCreateTeam: () => void;/** "While you were away": unseen count for the badge, whether it's open, and how to open it. */awayCount?: number;awayActive?: boolean;onOpenAway?: () => void;- /** Opens Settings → Engines from the footer. */- onOpenSettings?: () => void;- /** Opens Settings at "Sign in with Claude", when Claude being signed out is why nothing runs. */+ /** Opens Space settings → Accounts from the footer. */+ onOpenAccounts?: () => void;+ /** Opens Accounts at "Sign in with Claude", when Claude being signed out is why nothing runs. */onSignInClaude?: () => void;- /** Changes when Settings closes, so the footer reads engine status again. */+ /** Changes when Space settings closes, so the footer reads account status again. */enginesRefreshKey?: number;}+const navRow = (active: boolean) =>+ `w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${+ active ? 'bg-zinc-800 text-zinc-100 shadow-sm border border-zinc-700/50' : 'text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800/50 border border-transparent'+ }`;+export const memberIdsOf = (t: Team): string[] =>Array.isArray(t.member_kwants)? t.member_kwants@@ -84,6 +106,16 @@ export const memberIdsOf = (t: Team): string[] =>: [];export const Sidebar: React.FC<SidebarProps> = ({+ space,+ spaces,+ onSwitchSpace,+ onCreateSpace,+ onOpenSpaceSettings,+ onOpenArchived,+ onOpenSearch,+ onOpenRoutines,+ section = 'all',+ phone = false,kwants,channels,teams = [],@@ -102,7 +134,7 @@ export const Sidebar: React.FC<SidebarProps> = ({awayCount = 0,awayActive = false,onOpenAway,- onOpenSettings,+ onOpenAccounts,onSignInClaude,enginesRefreshKey = 0,}) => {@@ -111,19 +143,18 @@ export const Sidebar: React.FC<SidebarProps> = ({useEffect(() => {if (enginesRefreshKey) reloadEngines();}, [enginesRefreshKey, reloadEngines]);- const readyCount = engines.engines?.filter(isUsable).length ?? null;+ const ready = engines.engines?.filter(isUsable) ?? null;+ const readyCount = ready?.length ?? null;+ const runsOn = ready?.map((e) => e.uses?.label ?? e.name) ?? [];// Nothing can run and Claude only needs signing in: the footer goes straight to that.const offerClaude = readyCount === 0 && !!onSignInClaude && claudeNeedsSignIn(engines.engines);const [teamsOpen, setTeamsOpen] = useState(true);- const [fleetOpen, setFleetOpen] = useState(() => localStorage.getItem('kwant.fleetOpen') === '1');const [collapsedTeams, setCollapsedTeams] = useState<Set<string>>(new Set());const [addingTo, setAddingTo] = useState<string | null>(null);-- const toggleFleet = () => {- const next = !fleetOpen;- setFleetOpen(next);- localStorage.setItem('kwant.fleetOpen', next ? '1' : '0');- };+ const [switcherOpen, setSwitcherOpen] = useState(false);+ const closeSwitcher = useCallback(() => setSwitcherOpen(false), []);+ const showChats = section !== 'bots';+ const showBots = section !== 'chats';const toggleTeam = (id: string) =>setCollapsedTeams((prev) => {@@ -157,30 +188,58 @@ export const Sidebar: React.FC<SidebarProps> = ({};return (- <aside className="w-64 border-r border-zinc-800/80 bg-zinc-900/40 flex flex-col h-full select-none flex-shrink-0">- {/* Top Header & New Agent Action */}- <div className="p-3 border-b border-zinc-800/60 flex items-center justify-between">- <span className="text-xs font-semibold uppercase tracking-wider text-zinc-400">Workspace</span>+ <aside+ aria-label={`${space.name} chats and kwant bots`}+ className={`${phone ? 'w-full flex-1 min-h-0' : 'w-64 h-full border-r border-zinc-800/80'} bg-zinc-900/40 flex flex-col select-none flex-shrink-0`}+ >+ {/* The open space: tap to switch, create or open its settings */}+ <div className="relative p-2 border-b border-zinc-800/60"><button- onClick={() => onSummonKwant()}- className="flex items-center gap-1 px-2 py-1 text-xs font-medium text-sky-400 hover:text-sky-300 hover:bg-sky-500/10 rounded-md border border-sky-500/20 transition-all"+ type="button"+ onClick={() => {+ playSfx('click');+ setSwitcherOpen((v) => !v);+ }}+ data-space-toggle+ aria-haspopup="menu"+ aria-expanded={switcherOpen}+ className="w-full flex items-center gap-2.5 px-1.5 py-1.5 rounded-lg text-left hover:bg-zinc-800/60 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500">- <Plus size={13} />- <span>New Agent</span>+ <SpaceTile space={space} size={32} />+ <span className="flex-1 min-w-0">+ <span className="block text-sm font-semibold text-zinc-100 truncate">{space.name}</span>+ <span className="block text-[11px] text-zinc-500 truncate">{spaceSummary(space.counts)}</span>+ </span>+ <ChevronDown size={14} className={`shrink-0 text-zinc-500 transition-transform ${switcherOpen ? 'rotate-180' : ''}`} aria-hidden="true" /></button>+ {switcherOpen && (+ <SpaceSwitcher+ spaces={spaces}+ currentId={space.id}+ onSwitch={onSwitchSpace}+ onCreate={onCreateSpace}+ onOpenSpaceSettings={onOpenSpaceSettings}+ onOpenArchived={onOpenArchived}+ onClose={closeSwitcher}+ sheet={phone}+ />+ )}</div><div className="flex-1 overflow-y-auto p-2 space-y-4">- {onOpenAway && (+ {showChats && (+ <div className="space-y-0.5">+ <button type="button" onClick={onOpenSearch} className={navRow(false)}>+ <Search size={15} className="text-zinc-500" aria-hidden="true" />+ <span className="truncate flex-1">Search {space.name}</span>+ {!phone && <kbd className="shrink-0 text-[10px] font-sans text-zinc-500">{isMac ? '⌘K' : 'Ctrl K'}</kbd>}+ </button>+ {onOpenAway && !phone && (<buttontype="button"onClick={onOpenAway}aria-current={awayActive ? 'page' : undefined}- className={`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${- awayActive- ? 'bg-zinc-800 text-zinc-100 shadow-sm border border-zinc-700/50'- : 'text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800/50 border border-transparent'- }`}+ className={navRow(awayActive)}><Inbox size={15} className={awayActive ? 'text-sky-400' : 'text-zinc-500'} aria-hidden="true" /><span className="truncate flex-1">While you were away</span>@@ -191,9 +250,16 @@ export const Sidebar: React.FC<SidebarProps> = ({</span>)}</button>+ )}+ <button type="button" onClick={onOpenRoutines} className={navRow(false)}>+ <CalendarClock size={15} className="text-zinc-500" aria-hidden="true" />+ <span className="truncate flex-1">Routines</span>+ </button>+ </div>)}{/* Channels Section */}+ {showChats && (<div><div className="px-2 py-1 text-[11px] font-semibold text-zinc-500 uppercase tracking-wider">Channels@@ -212,14 +278,24 @@ export const Sidebar: React.FC<SidebarProps> = ({}`}><Hash size={15} className={active ? 'text-sky-400' : 'text-zinc-500'} />- <span className="truncate">{c.name}</span>+ <span className="truncate flex-1">{c.name}</span>+ {c.name === 'general' && (+ <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>+ )}</button>);})}+ {displayChannels.length === 0 && (+ <div className="px-2.5 py-1.5 text-[11px] text-zinc-500">#general opens once {space.name} has a bot.</div>+ )}</div></div>+ )}{/* Teams Section */}+ {showChats && (<div><div className="px-2 py-1 flex items-center justify-between text-[11px] font-semibold text-zinc-500 uppercase tracking-wider"><button@@ -237,10 +313,10 @@ export const Sidebar: React.FC<SidebarProps> = ({type="button"onClick={onCreateTeam}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"- title="Create New Team"+ title={`New team in ${space.name}`}><Plus size={11} />- <span>New Team</span>+ <span>New team</span></button></div>@@ -417,7 +493,7 @@ export const Sidebar: React.FC<SidebarProps> = ({</button>))}{candidates.length === 0 && (- <div className="px-1.5 py-1 text-[11px] text-zinc-500">Every agent is already in this team.</div>+ <div className="px-1.5 py-1 text-[11px] text-zinc-500">Every bot is already in this team.</div>)}<buttontype="button"@@ -428,7 +504,7 @@ export const Sidebar: React.FC<SidebarProps> = ({className="w-full flex items-center gap-2 px-1.5 py-1 rounded-md text-[11px] text-sky-400 hover:bg-sky-500/10 border-t border-zinc-800 mt-0.5 pt-1.5"><UserPlus size={13} />- <span>Create a new agent…</span>+ <span>Create a new bot…</span></button></div>)}@@ -439,38 +515,34 @@ export const Sidebar: React.FC<SidebarProps> = ({})}{teams.length === 0 && (<div className="px-2.5 py-1.5 text-[11px] text-zinc-500 italic">- No teams yet. Click + New Team to create.+ No teams in {space.name} yet.</div>)}</div>)}</div>- {/* AI Agents Fleet Section */}+ )}++ {/* Every bot in this space */}+ {showBots && (<div>- <button- type="button"- onClick={toggleFleet}- className="w-full px-2 py-1 flex items-center justify-between text-[11px] font-semibold text-zinc-500 uppercase tracking-wider hover:text-zinc-300 transition-colors"- title={fleetOpen ? 'Collapse agent fleet' : 'Show all agents'}- >- <span className="flex items-center gap-1">- <ChevronDown size={12} className={`transition-transform duration-150 ${fleetOpen ? '' : '-rotate-90'}`} />- <span>Agent Fleet ({kwants.length})</span>- </span>- {!fleetOpen && (- <span className="flex items-center -space-x-1">- {kwants.slice(0, 6).map((k) => (- <ModernAvatar key={k.id} role={k.avatar_sprite} name={k.name} size={16} kwantId={k.id} />- ))}- {kwants.length > 6 && (- <span className="pl-1.5 text-[10px] font-mono normal-case text-zinc-500">+{kwants.length - 6}</span>- )}- </span>- )}- </button>- {fleetOpen && (+ <div className="px-2 py-1 flex items-center justify-between text-[11px] font-semibold text-zinc-500 uppercase tracking-wider">+ <h2>Kwant bots ({kwants.length})</h2>+ <button+ type="button"+ onClick={() => onSummonKwant()}+ 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"+ title={`New bot in ${space.name}`}+ >+ <Plus size={11} />+ <span>New bot</span>+ </button>+ </div><div className="mt-1 space-y-1">+ {kwants.length === 0 && (+ <div className="px-2.5 py-1.5 text-[11px] text-zinc-500">No bots in {space.name} yet.</div>+ )}{kwants.map((k) => {const active = !isChannel && selectedId === k.id;return (@@ -525,18 +597,19 @@ export const Sidebar: React.FC<SidebarProps> = ({);})}</div>- )}</div>+ )}</div>- {/* Footer: how many engines can run, from the real checks */}- {engines.engines?.length !== 0 && (+ {/* Footer: what this space's bots run on, from the real checks */}+ {engines.engines?.length !== 0 && section !== 'chats' ? (<div className="p-3 border-t border-zinc-800/60 bg-zinc-950/40 text-[11px] text-zinc-500"><buttontype="button"- onClick={offerClaude ? onSignInClaude : onOpenSettings}- disabled={!onOpenSettings && !offerClaude}- className="flex items-center gap-1.5 hover:text-zinc-300 disabled:hover:text-zinc-500 transition-colors"+ onClick={offerClaude ? onSignInClaude : onOpenAccounts}+ disabled={!onOpenAccounts && !offerClaude}+ className="w-full flex items-center gap-1.5 min-w-0 hover:text-zinc-300 disabled:hover:text-zinc-500 transition-colors"+ title={runsOn.length > 1 ? `Runs on ${runsOn.join(', ')}` : undefined}>{readyCount === null ? (<Loader2 size={13} className="text-sky-400 animate-spin motion-reduce:animate-none" aria-hidden="true" />@@ -545,18 +618,18 @@ export const Sidebar: React.FC<SidebarProps> = ({) : (<AlertTriangle size={13} className="text-amber-400" aria-hidden="true" />)}- <span>+ <span className="truncate">{readyCount === null- ? 'Checking engines…'+ ? 'Checking accounts…': readyCount === 0? offerClaude- ? 'No engine can run · Sign in with Claude'- : 'No engine can run · check Settings'- : `${readyCount} ${readyCount === 1 ? 'engine' : 'engines'} ready`}+ ? 'Nothing can run here · Sign in with Claude'+ : 'Nothing can run here · Add an account'+ : `Runs on ${runsOn[0]}${runsOn.length > 1 ? ` +${runsOn.length - 1}` : ''}`}</span></button></div>- )}+ ) : null}</aside>);};diff --git a/frontend/src/components/SkillsPanel.tsx b/frontend/src/components/SkillsPanel.tsxindex 96d06668..ec769872 100644--- a/frontend/src/components/SkillsPanel.tsx+++ b/frontend/src/components/SkillsPanel.tsx@@ -199,7 +199,7 @@ const SkillMeta: React.FC<{ skill: Skill; replaces?: Skill }> = ({ skill, replac)}{skill.kwant_id === null && (<Badge tone="bg-zinc-800 text-zinc-300 border-zinc-700">- <Globe2 size={10} aria-hidden="true" /> Every agent+ <Globe2 size={10} aria-hidden="true" /> Every bot in this space</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>}@@ -337,7 +337,7 @@ const ActiveSkill: React.FC<{ skill: Skill }> = ({ skill }) => {<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" />}+ {skill.kwant_id === null && <Globe2 size={11} className="shrink-0 text-zinc-500" aria-label="Every bot in this space" />}</span>{skill.description && <span className="block mt-0.5 pl-[18px] text-[11px] text-zinc-400 break-words">{skill.description}</span>}</button>@@ -430,7 +430,7 @@ export const SkillsPanel: React.FC<{ kwantId: string; kwantName: string }> = ({<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.+ are instructions only and never give a bot new tools.</p>{writing ? (diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsxnew file mode 100644index 00000000..0e96d932--- /dev/null+++ b/frontend/src/components/SpaceSettings.tsx@@ -0,0 +1,417 @@+import React, { useEffect, useRef, useState } from 'react';+import {+ AlertTriangle,+ Archive,+ ArrowLeft,+ Bot,+ CalendarClock,+ Check,+ KeyRound,+ Loader2,+ Pencil,+ Plug,+ Plus,+ Settings,+ Settings2,+ Sparkles,+ Users,+ X,+} from 'lucide-react';+import { playSfx } from '../audio/chiptune';+import { SPACE_COLORS, SPACE_ICONS, Space, spaceColor, spaceNameError, spacesApi } from '../spaces';+import { useEngines } from '../useEngines';+import { useProfiles } from '../useProfiles';+import type { Profile } from '../profiles';+import { EnginesPanel } from './EnginesPanel';+import { RoutinesPanel } from './RoutinesPanel';+import { ModernAvatar } from './ModernAvatar';+import { SpaceTile } from './Spaces';+import { memberIdsOf, type Channel, type Kwant, type Team } from './Sidebar';++export type SpaceSettingsTab = 'general' | 'accounts' | 'bots' | 'teams' | 'tools' | 'skills' | 'routines';++const TABS: Array<{ id: SpaceSettingsTab; label: string; icon: React.ReactNode }> = [+ { id: 'general', label: 'General', icon: <Settings2 size={15} /> },+ { id: 'accounts', label: 'Accounts', icon: <KeyRound size={15} /> },+ { id: 'bots', label: 'Kwant bots', icon: <Bot size={15} /> },+ { id: 'teams', label: 'Teams', icon: <Users size={15} /> },+ { id: 'tools', label: 'Tools', icon: <Plug size={15} /> },+ { id: 'skills', label: 'Skills', icon: <Sparkles size={15} /> },+ { id: 'routines', label: 'Routines', icon: <CalendarClock size={15} /> },+];++interface Props {+ space: Space;+ /** Every space, for taken names. */+ spaces: Space[];+ tab: SpaceSettingsTab;+ onTab: (tab: SpaceSettingsTab) => void;+ onClose: () => void;+ kwants: Kwant[];+ channels: Channel[];+ teams: Team[];+ /** Changes to focus "Sign in with Claude" in Accounts. */+ focusClaudeSignIn?: number;+ onProfilesChanged?: (profiles: Profile[]) => void;+ pendingSkills?: Record<string, number>;+ onSpaceSaved: (space: Space) => void;+ onArchived: (space: Space) => void;+ onNewBot: () => void;+ onEditBot: (k: Kwant) => void;+ onOpenSkills: (k: Kwant) => void;+ onNewTeam: () => void;+ onManageTeam: (t: Team) => void;+ onOpenTools: () => void;+ onOpenAppSettings: () => void;+}++const card = 'rounded-xl border border-zinc-800 bg-zinc-950/60';+const rowBtn =+ 'flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-300 border border-zinc-700/60 bg-zinc-800/60 hover:bg-zinc-700/70 hover:text-zinc-100 transition-colors';+const primaryBtn =+ 'flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors disabled:opacity-50';++/** Space settings: everything here belongs to the open space only. */+export const SpaceSettings: React.FC<Props> = (p) => {+ const { space, tab, onTab, onClose } = p;+ const closeRef = useRef(onClose);+ closeRef.current = onClose;+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ // Dialogs opened from here (bot editor, tools) close themselves first.+ if (e.key === 'Escape' && !document.querySelector('[role="dialog"]:not([data-space-settings])')) closeRef.current();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, []);++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="space-settings-title"+ data-space-settings+ className="fixed inset-0 z-40 bg-zinc-950 text-zinc-100 flex flex-col md:flex-row overflow-hidden"+ >+ {/* Tab list: a column on desktop, scrolling chips on phones */}+ <div className="md:w-60 shrink-0 border-b md:border-b-0 md:border-r border-zinc-800/80 bg-zinc-900/40 flex flex-col">+ <div className="flex items-center gap-2.5 p-3 md:p-4">+ <button type="button" onClick={onClose} aria-label="Back to chats" className="p-1.5 -ml-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800">+ <ArrowLeft size={17} />+ </button>+ <SpaceTile space={space} size={28} />+ <div className="min-w-0">+ <h2 id="space-settings-title" className="text-sm font-semibold truncate">{space.name} settings</h2>+ <p className="text-[11px] text-zinc-500">Only affects this space</p>+ </div>+ </div>+ <nav aria-label="Space settings" className="flex md:flex-col gap-1 px-3 pb-3 md:px-2 overflow-x-auto md:overflow-visible">+ {TABS.map((t) => (+ <button+ key={t.id}+ type="button"+ aria-current={tab === t.id ? 'page' : undefined}+ onClick={() => {+ playSfx('click');+ onTab(t.id);+ }}+ className={`shrink-0 flex items-center gap-2 px-3 py-1.5 md:py-2 rounded-full md:rounded-lg text-xs font-medium transition-colors ${+ tab === t.id ? 'bg-zinc-800 text-zinc-100 border border-zinc-700/60' : 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800/50 border border-transparent'+ }`}+ >+ <span className={tab === t.id ? 'text-sky-400' : 'text-zinc-500'} aria-hidden="true">{t.icon}</span>+ {t.label}+ </button>+ ))}+ </nav>+ <div className="hidden md:block mt-auto p-3 border-t border-zinc-800/60">+ <button type="button" onClick={p.onOpenAppSettings} className="flex items-center gap-2 text-xs text-zinc-400 hover:text-zinc-100">+ <Settings size={14} /> App settings (every space)+ </button>+ </div>+ </div>++ <div className="flex-1 min-w-0 overflow-y-auto">+ <div className="max-w-2xl mx-auto p-4 sm:p-6 space-y-5">+ <div className="flex items-center justify-between gap-3">+ <div>+ <h3 className="text-base font-semibold">{TABS.find((t) => t.id === tab)?.label}</h3>+ <p className="text-[11px] text-zinc-500">Only affects this space ({space.name})</p>+ </div>+ <button type="button" onClick={onClose} aria-label="Close space settings" className="hidden md:block p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800">+ <X size={18} />+ </button>+ </div>+ {tab === 'general' && <GeneralTab {...p} />}+ {tab === 'accounts' && <AccountsTab {...p} />}+ {tab === 'bots' && <BotsTab {...p} />}+ {tab === 'teams' && <TeamsTab {...p} />}+ {tab === 'tools' && (+ <div className={`${card} p-4 space-y-3`}>+ <p className="text-xs text-zinc-300">Tool servers (MCP) give the bots in {space.name} abilities like files, web pages or GitHub.</p>+ <button type="button" onClick={p.onOpenTools} className={primaryBtn}>+ <Plug size={13} /> Manage tools+ </button>+ </div>+ )}+ {tab === 'skills' && <SkillsTab {...p} />}+ {tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} />}+ <div className="md:hidden pt-2">+ <button type="button" onClick={p.onOpenAppSettings} className="flex items-center gap-2 text-xs text-zinc-400 hover:text-zinc-100">+ <Settings size={14} /> App settings (every space)+ </button>+ </div>+ </div>+ </div>+ </div>+ );+};++const GeneralTab: React.FC<Props> = ({ space, spaces, onSpaceSaved, onArchived }) => {+ const [name, setName] = useState(space.name);+ const [icon, setIcon] = useState(space.icon);+ // "amber" from the server shows as its swatch.+ const initialColor = space.color ? spaceColor(space) : '';+ const [color, setColor] = useState(initialColor);+ const [saving, setSaving] = useState(false);+ const [saved, setSaved] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [confirmArchive, setConfirmArchive] = useState(false);+ const [archiving, setArchiving] = useState(false);+ const nameErr = spaceNameError(name, spaces.filter((s) => s.id !== space.id).map((s) => s.name));+ const dirty = name.trim() !== space.name || icon !== space.icon || color !== initialColor;++ const save = async (e: React.FormEvent) => {+ e.preventDefault();+ if (nameErr || !dirty) return;+ setSaving(true);+ setError(null);+ try {+ const next = await spacesApi.patch(space.id, { name: name.trim(), icon, color: color || null });+ onSpaceSaved(next);+ setSaved(true);+ setTimeout(() => setSaved(false), 2000);+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Couldn’t save the space.');+ } finally {+ setSaving(false);+ }+ };++ const archive = async () => {+ setArchiving(true);+ setError(null);+ try {+ const next = await spacesApi.patch(space.id, { archived: true });+ onArchived(next);+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Couldn’t archive the space.');+ setArchiving(false);+ setConfirmArchive(false);+ }+ };++ return (+ <>+ <form onSubmit={save} className={`${card} p-4 space-y-4`}>+ <div className="flex items-center gap-3">+ <SpaceTile space={{ id: space.id, icon, color: color || null }} size={44} />+ <div className="flex-1 min-w-0">+ <label htmlFor="space-rename" className="block text-xs font-medium text-zinc-300 mb-1">+ Name {space.is_default && <span className="ml-1 px-1.5 py-px rounded bg-zinc-800 text-[10px] text-zinc-400">Default</span>}+ </label>+ <input+ id="space-rename"+ value={name}+ maxLength={60}+ onChange={(e) => setName(e.target.value)}+ aria-invalid={!!nameErr}+ aria-describedby="space-rename-error"+ className={`w-full bg-zinc-950 border rounded-lg px-3 py-2 text-sm text-zinc-100 focus:outline-none ${nameErr ? 'border-rose-500/70' : 'border-zinc-800 focus:border-sky-500'}`}+ />+ <p id="space-rename-error" className="mt-1 text-[11px] text-rose-300 min-h-[1em]">{nameErr}</p>+ </div>+ </div>+ <fieldset>+ <legend className="text-xs font-medium text-zinc-300 mb-1.5">Icon</legend>+ <div className="flex flex-wrap gap-1.5">+ {SPACE_ICONS.map((i) => (+ <button+ key={i}+ type="button"+ aria-pressed={icon === i}+ aria-label={`Icon ${i}`}+ onClick={() => setIcon(i)}+ className={`w-9 h-9 rounded-lg text-lg flex items-center justify-center border ${icon === i ? 'border-sky-400 bg-sky-500/10' : 'border-zinc-800 hover:border-zinc-600'}`}+ >+ {i}+ </button>+ ))}+ </div>+ </fieldset>+ <fieldset>+ <legend className="text-xs font-medium text-zinc-300 mb-1.5">Colour</legend>+ <div className="flex flex-wrap gap-2">+ {SPACE_COLORS.map((c) => (+ <button+ key={c}+ type="button"+ aria-pressed={color === c}+ aria-label={`Colour ${c}`}+ onClick={() => setColor(c)}+ className={`w-7 h-7 rounded-full ${color === c ? 'ring-2 ring-white ring-offset-2 ring-offset-zinc-900' : ''}`}+ style={{ background: c }}+ />+ ))}+ </div>+ </fieldset>+ {error && (+ <p role="alert" className="flex items-center gap-2 text-xs text-rose-300">+ <AlertTriangle size={13} /> {error}+ </p>+ )}+ <div className="flex justify-end items-center gap-2">+ {saved && (+ <span className="flex items-center gap-1 text-xs text-emerald-400" role="status">+ <Check size={13} /> Saved+ </span>+ )}+ <button type="submit" disabled={!dirty || !!nameErr || saving} className={primaryBtn}>+ {saving ? 'Saving…' : 'Save'}+ </button>+ </div>+ </form>++ <div className={`${card} p-4 space-y-3`}>+ <p className="flex items-center gap-2 text-xs font-medium text-zinc-200">+ <Archive size={14} className="text-zinc-400" /> Archive space+ </p>+ {space.is_default ? (+ <p className="text-[11px] text-zinc-500">The Default space can be renamed but can’t be archived.</p>+ ) : confirmArchive ? (+ <div className="space-y-2.5" role="alert">+ <p className="text-xs text-zinc-300">+ Archive {space.name}? Its routines pause and nothing new can run in it. Its bots, chats and accounts stay, and you can restore it from Archived spaces.+ </p>+ <div className="flex gap-2">+ <button type="button" onClick={() => setConfirmArchive(false)} className={rowBtn}>+ Cancel+ </button>+ <button+ type="button"+ onClick={archive}+ disabled={archiving}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-rose-600 hover:bg-rose-500 disabled:opacity-50"+ >+ {archiving && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" />}+ Archive {space.name}+ </button>+ </div>+ </div>+ ) : (+ <>+ <p className="text-[11px] text-zinc-500">Pauses its routines and stops anything new from running. You can restore it any time.</p>+ <button type="button" onClick={() => setConfirmArchive(true)} className={rowBtn}>+ <Archive size={13} /> Archive space…+ </button>+ </>+ )}+ </div>+ </>+ );+};++const AccountsTab: React.FC<Props> = ({ space, focusClaudeSignIn, onProfilesChanged }) => {+ const engines = useEngines(true);+ const accounts = useProfiles(true, onProfilesChanged);+ return (+ <div className="space-y-3">+ <p className="text-xs text-zinc-400">What runs your kwant bots in {space.name}: the accounts here, and This machine when it’s on.</p>+ <EnginesPanel api={engines} accounts={accounts} focusClaudeSignIn={focusClaudeSignIn} />+ </div>+ );+};++const BotsTab: React.FC<Props> = ({ space, kwants, onNewBot, onEditBot }) => (+ <div className="space-y-3">+ <div className="flex items-center justify-between gap-3">+ <p className="text-xs text-zinc-400">+ {kwants.length} {kwants.length === 1 ? 'bot' : 'bots'} in {space.name}. Laya only picks from these.+ </p>+ <button type="button" onClick={onNewBot} className={primaryBtn}>+ <Plus size={13} /> New bot+ </button>+ </div>+ <ul className="space-y-1.5">+ {kwants.map((k) => (+ <li key={k.id} className={`${card} flex items-center gap-3 p-2.5`}>+ <ModernAvatar role={k.avatar_sprite} name={k.name} size={30} kwantId={k.id} />+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-zinc-200 truncate">{k.name}</p>+ <p className="text-[11px] text-zinc-500 truncate">{k.title}</p>+ </div>+ <button type="button" onClick={() => onEditBot(k)} className={rowBtn} aria-label={`Edit ${k.name}`}>+ <Pencil size={12} /> Edit+ </button>+ </li>+ ))}+ </ul>+ {kwants.length === 0 && <p className="text-xs text-zinc-500">No bots yet. New spaces start empty.</p>}+ </div>+);++const TeamsTab: React.FC<Props> = ({ space, teams, kwants, onNewTeam, onManageTeam }) => (+ <div className="space-y-3">+ <div className="flex items-center justify-between gap-3">+ <p className="text-xs text-zinc-400">+ {teams.length} {teams.length === 1 ? 'team' : 'teams'} in {space.name}.+ </p>+ <button type="button" onClick={onNewTeam} disabled={kwants.length === 0} className={primaryBtn} title={kwants.length === 0 ? 'Create a bot first' : undefined}>+ <Plus size={13} /> New team+ </button>+ </div>+ <ul className="space-y-1.5">+ {teams.map((t) => {+ const ids = memberIdsOf(t);+ const lead = kwants.find((k) => k.id === t.lead_kwant_id);+ return (+ <li key={t.id} className={`${card} flex items-center gap-3 p-2.5`}>+ <Users size={16} className="text-zinc-500 shrink-0" aria-hidden="true" />+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-zinc-200 truncate">@{t.name}</p>+ <p className="text-[11px] text-zinc-500 truncate">+ {ids.length} {ids.length === 1 ? 'member' : 'members'}+ {lead ? ` · lead ${lead.name}` : ''}+ </p>+ </div>+ <button type="button" onClick={() => onManageTeam(t)} className={rowBtn} aria-label={`Manage @${t.name}`}>+ <Settings2 size={12} /> Manage+ </button>+ </li>+ );+ })}+ </ul>+ {teams.length === 0 && <p className="text-xs text-zinc-500">No teams yet.</p>}+ </div>+);++const SkillsTab: React.FC<Props> = ({ space, kwants, pendingSkills = {}, onOpenSkills }) => (+ <div className="space-y-3">+ <p className="text-xs text-zinc-400">Skills are shared by the bots in {space.name}. Open a bot to see, approve or write its skills.</p>+ <ul className="space-y-1.5">+ {kwants.map((k) => (+ <li key={k.id} className={`${card} flex items-center gap-3 p-2.5`}>+ <ModernAvatar role={k.avatar_sprite} name={k.name} size={26} kwantId={k.id} />+ <p className="flex-1 min-w-0 text-xs font-medium text-zinc-200 truncate">{k.name}</p>+ {(pendingSkills[k.id] ?? 0) > 0 && (+ <span className="px-1.5 py-px rounded-full bg-amber-500 text-zinc-950 text-[10px] font-semibold">{pendingSkills[k.id]} to review</span>+ )}+ <button type="button" onClick={() => onOpenSkills(k)} className={rowBtn}>+ <Sparkles size={12} /> Skills+ </button>+ </li>+ ))}+ </ul>+ {kwants.length === 0 && <p className="text-xs text-zinc-500">Skills show up once this space has a bot.</p>}+ </div>+);diff --git a/frontend/src/components/Spaces.tsx b/frontend/src/components/Spaces.tsxnew file mode 100644index 00000000..f0100e8d--- /dev/null+++ b/frontend/src/components/Spaces.tsx@@ -0,0 +1,448 @@+import React, { useEffect, useRef, useState } from 'react';+import { Archive, Check, Loader2, Plus, RotateCcw, Settings, X, AlertTriangle } from 'lucide-react';+import { playSfx } from '../audio/chiptune';+import {+ SPACE_COLORS,+ SPACE_ICONS,+ Space,+ firstUnusedColor,+ spaceColor,+ spaceIcon,+ spaceNameError,+ spaceSummary,+ spacesApi,+} from '../spaces';++const badge = (n: number) => (n > 99 ? '99+' : String(n));++/** A space's emoji on its colour. */+export const SpaceTile: React.FC<{ space: Pick<Space, 'id' | 'icon' | 'color'>; size?: number; className?: string }> = ({+ space,+ size = 40,+ className = '',+}) => (+ <span+ aria-hidden="true"+ className={`inline-flex items-center justify-center shrink-0 rounded-xl ${className}`}+ style={{ width: size, height: size, background: `${spaceColor(space)}33`, boxShadow: `inset 0 0 0 1px ${spaceColor(space)}66`, fontSize: size * 0.5 }}+ >+ {spaceIcon(space)}+ </span>+);++// ---------------------------------------------------------------------------+// Desktop rail++interface RailProps {+ spaces: Space[];+ currentId: string | null;+ onSwitch: (id: string) => void;+ onCreate: () => void;+ onOpenAppSettings: () => void;+}++export const SpaceRail: React.FC<RailProps> = ({ spaces, currentId, onSwitch, onCreate, onOpenAppSettings }) => (+ <nav aria-label="Spaces" className="hidden md:flex w-[68px] shrink-0 flex-col items-center gap-2 py-3 border-r border-zinc-800/80 bg-zinc-950 select-none">+ <ul className="flex flex-col items-center gap-2 flex-1 overflow-y-auto overflow-x-hidden w-full">+ {spaces.map((s, i) => {+ const active = s.id === currentId;+ const unread = active ? 0 : s.counts?.unread ?? 0;+ return (+ <li key={s.id} className="relative w-full flex justify-center">+ {active && <span className="absolute left-0 top-1.5 bottom-1.5 w-1 rounded-r bg-zinc-100" aria-hidden="true" />}+ <button+ type="button"+ onClick={() => onSwitch(s.id)}+ aria-current={active ? 'true' : undefined}+ aria-label={`${s.name}${unread ? `, ${unread} unread` : ''}`}+ title={`${s.name}${i < 9 ? ` (Ctrl/⌘ ${i + 1})` : ''}`}+ className={`relative rounded-xl transition-all focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 ${+ active ? 'ring-2 ring-offset-2 ring-offset-zinc-950' : 'opacity-75 hover:opacity-100'+ }`}+ style={active ? ({ '--tw-ring-color': spaceColor(s) } as React.CSSProperties) : undefined}+ >+ <SpaceTile space={s} size={40} />+ {unread > 0 && (+ <span className="absolute -top-1.5 -right-1.5 min-w-[18px] px-1 py-px rounded-full bg-rose-500 text-white text-[10px] font-semibold text-center border-2 border-zinc-950">+ {badge(unread)}+ </span>+ )}+ </button>+ </li>+ );+ })}+ <li>+ <button+ type="button"+ onClick={onCreate}+ aria-label="New space"+ title="New space"+ className="w-10 h-10 rounded-xl border border-dashed border-zinc-700 text-zinc-400 hover:text-zinc-100 hover:border-zinc-500 flex items-center justify-center transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"+ >+ <Plus size={18} />+ </button>+ </li>+ </ul>+ <button+ type="button"+ onClick={onOpenAppSettings}+ aria-label="App settings"+ title="App settings"+ className="w-10 h-10 rounded-xl text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 flex items-center justify-center transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"+ >+ <Settings size={18} />+ </button>+ </nav>+);++// ---------------------------------------------------------------------------+// Switcher: a popover under the space header (desktop) or a bottom sheet (phone)++interface SwitcherProps {+ spaces: Space[];+ currentId: string | null;+ onSwitch: (id: string) => void;+ onCreate: () => void;+ onOpenSpaceSettings: () => void;+ onOpenArchived: () => void;+ onClose: () => void;+ /** Bottom sheet on phones. */+ sheet?: boolean;+}++export const SpaceSwitcher: React.FC<SwitcherProps> = ({ spaces, currentId, onSwitch, onCreate, onOpenSpaceSettings, onOpenArchived, onClose, sheet }) => {+ const ref = useRef<HTMLDivElement>(null);+ const current = spaces.find((s) => s.id === currentId);+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose();+ const onDown = (e: MouseEvent) =>+ !sheet &&+ ref.current &&+ !ref.current.contains(e.target as Node) &&+ !(e.target as Element).closest?.('[data-space-toggle]') &&+ onClose();+ window.addEventListener('keydown', onKey);+ window.addEventListener('mousedown', onDown);+ ref.current?.querySelector<HTMLElement>('[aria-current="true"]')?.focus();+ return () => {+ window.removeEventListener('keydown', onKey);+ window.removeEventListener('mousedown', onDown);+ };+ }, [onClose, sheet]);++ const item = 'w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-left text-xs transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400';+ const list = (+ <div ref={ref} role="menu" aria-label="Switch space" className="space-y-0.5">+ {spaces.map((s) => {+ const active = s.id === currentId;+ return (+ <button+ key={s.id}+ type="button"+ role="menuitem"+ aria-current={active ? 'true' : undefined}+ onClick={() => {+ onClose();+ if (!active) onSwitch(s.id);+ }}+ className={`${item} ${active ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-300 hover:bg-zinc-800/60'}`}+ >+ <SpaceTile space={s} size={28} />+ <span className="flex-1 min-w-0">+ <span className="block font-medium truncate">{s.name}</span>+ <span className="block text-[11px] text-zinc-500 truncate">{spaceSummary(s.counts)}</span>+ </span>+ {!active && (s.counts?.unread ?? 0) > 0 && (+ <span className="min-w-[18px] px-1.5 py-px rounded-full bg-rose-500 text-white text-[10px] font-semibold text-center">{badge(s.counts.unread)}</span>+ )}+ {active && <Check size={14} className="text-sky-400" aria-hidden="true" />}+ </button>+ );+ })}+ <div className="my-1 border-t border-zinc-800" />+ <button type="button" role="menuitem" onClick={() => { onClose(); onCreate(); }} className={`${item} text-sky-300 hover:bg-sky-500/10`}>+ <Plus size={15} aria-hidden="true" /> New space+ </button>+ {current && (+ <button type="button" role="menuitem" onClick={() => { onClose(); onOpenSpaceSettings(); }} className={`${item} text-zinc-300 hover:bg-zinc-800/60`}>+ <Settings size={15} aria-hidden="true" /> {current.name} settings+ </button>+ )}+ <button type="button" role="menuitem" onClick={() => { onClose(); onOpenArchived(); }} className={`${item} text-zinc-300 hover:bg-zinc-800/60`}>+ <Archive size={15} aria-hidden="true" /> Archived spaces+ </button>+ </div>+ );++ if (sheet) {+ return (+ <div className="fixed inset-0 z-50 bg-black/60 flex items-end" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>+ <div className="kw-sheet w-full max-h-[80vh] overflow-y-auto rounded-t-2xl bg-zinc-900 border-t border-zinc-800 p-3 pb-6 shadow-2xl">+ <div className="mx-auto mb-2 h-1 w-10 rounded-full bg-zinc-700" aria-hidden="true" />+ <p className="px-2.5 pb-2 text-[11px] font-semibold uppercase tracking-wider text-zinc-500">Spaces</p>+ {list}+ </div>+ </div>+ );+ }+ return <div className="absolute left-2 right-2 top-full mt-1 z-40 rounded-xl border border-zinc-700/70 bg-zinc-900 p-1.5 shadow-2xl">{list}</div>;+};++// ---------------------------------------------------------------------------+// Dialog frame shared by the space dialogs++const Dialog: React.FC<{ title: string; subtitle?: string; labelId: string; onClose: () => void; children: React.ReactNode; wide?: boolean }> = ({+ title,+ subtitle,+ labelId,+ onClose,+ children,+ wide,+}) => {+ const closeRef = useRef(onClose);+ closeRef.current = onClose;+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => e.key === 'Escape' && closeRef.current();+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, []);+ return (+ <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-end sm:items-center justify-center sm:p-4" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby={labelId}+ className={`bg-zinc-900 border border-zinc-800 rounded-t-2xl sm:rounded-2xl w-full ${wide ? 'sm:max-w-xl' : 'sm:max-w-md'} max-h-[92vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-5`}+ >+ <div className="flex items-start justify-between gap-3">+ <div>+ <h2 id={labelId} className="text-sm font-semibold text-zinc-100">{title}</h2>+ {subtitle && <p className="mt-0.5 text-xs text-zinc-400">{subtitle}</p>}+ </div>+ <button type="button" onClick={onClose} aria-label="Close" className="p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors">+ <X size={18} />+ </button>+ </div>+ {children}+ </div>+ </div>+ );+};++// ---------------------------------------------------------------------------+// New space++interface NewSpaceProps {+ /** Every space, archived ones too, for taken names and colours. */+ spaces: Space[];+ onClose: () => void;+ onCreated: (space: Space) => void;+}++export const NewSpaceModal: React.FC<NewSpaceProps> = ({ spaces, onClose, onCreated }) => {+ const [name, setName] = useState('');+ // Like the colour, the first icon no other space uses, so two spaces don't look alike on the rail.+ const [icon, setIcon] = useState(() => SPACE_ICONS.find((i) => !spaces.some((s) => s.icon === i)) ?? SPACE_ICONS[0]);+ const [color, setColor] = useState(() => firstUnusedColor(spaces));+ const [thisMachine, setThisMachine] = useState(true);+ const [touched, setTouched] = useState(false);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const nameErr = spaceNameError(name, spaces.map((s) => s.name));+ const nameRef = useRef<HTMLInputElement>(null);+ useEffect(() => nameRef.current?.focus(), []);++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ setTouched(true);+ if (nameErr || saving) return;+ setSaving(true);+ setError(null);+ try {+ const space = await spacesApi.create({ name: name.trim(), icon, color, this_machine_enabled: thisMachine });+ playSfx('coin');+ onCreated(space);+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Couldn’t create the space.');+ setSaving(false);+ }+ };++ const preview = { id: 'preview', icon, color };+ return (+ <Dialog title="New space" subtitle="Its own bots, teams, accounts and chats. Nothing is shared with your other spaces." labelId="new-space-title" onClose={onClose}>+ <form onSubmit={submit} className="space-y-4" noValidate>+ <div className="flex items-center gap-3">+ <SpaceTile space={preview} size={48} />+ <div className="flex-1 min-w-0">+ <label htmlFor="space-name" className="block text-xs font-medium text-zinc-300 mb-1">Name</label>+ <input+ id="space-name"+ ref={nameRef}+ value={name}+ maxLength={60}+ onChange={(e) => setName(e.target.value)}+ onBlur={() => setTouched(true)}+ placeholder="Personal"+ aria-invalid={touched && !!nameErr}+ aria-describedby="space-name-error"+ className={`w-full bg-zinc-950 border rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-600 focus:outline-none ${+ touched && nameErr ? 'border-rose-500/70' : 'border-zinc-800 focus:border-sky-500'+ }`}+ />+ </div>+ </div>+ <p id="space-name-error" className="-mt-2 text-[11px] text-rose-300 min-h-[1em]">{touched ? nameErr : ''}</p>++ <fieldset>+ <legend className="text-xs font-medium text-zinc-300 mb-1.5">Icon</legend>+ <div className="flex flex-wrap gap-1.5">+ {SPACE_ICONS.map((i) => (+ <button+ key={i}+ type="button"+ aria-pressed={icon === i}+ aria-label={`Icon ${i}`}+ onClick={() => setIcon(i)}+ className={`w-9 h-9 rounded-lg text-lg flex items-center justify-center border transition-colors ${+ icon === i ? 'border-sky-400 bg-sky-500/10' : 'border-zinc-800 hover:border-zinc-600'+ }`}+ >+ {i}+ </button>+ ))}+ </div>+ </fieldset>++ <fieldset>+ <legend className="text-xs font-medium text-zinc-300 mb-1.5">Colour</legend>+ <div className="flex flex-wrap gap-2">+ {SPACE_COLORS.map((c) => (+ <button+ key={c}+ type="button"+ aria-pressed={color === c}+ aria-label={`Colour ${c}`}+ onClick={() => setColor(c)}+ className={`w-7 h-7 rounded-full transition-transform ${color === c ? 'ring-2 ring-white ring-offset-2 ring-offset-zinc-900 scale-110' : 'hover:scale-110'}`}+ style={{ background: c }}+ />+ ))}+ </div>+ </fieldset>++ <div className="flex items-start gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800">+ <div className="flex-1">+ <p id="space-this-machine" className="text-xs font-medium text-zinc-200">Use This machine</p>+ <p className="text-[11px] text-zinc-500">+ Bots here can use the CLIs signed in on this computer. Turn it off to keep this space on its own accounts only; bots never fall back to it.+ </p>+ </div>+ <button+ type="button"+ role="switch"+ aria-checked={thisMachine}+ aria-labelledby="space-this-machine"+ onClick={() => setThisMachine((v) => !v)}+ className={`relative shrink-0 w-9 h-5 rounded-full transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${thisMachine ? 'bg-sky-600' : 'bg-zinc-700'}`}+ >+ <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform motion-reduce:transition-none ${thisMachine ? 'translate-x-4' : ''}`} />+ </button>+ </div>++ <fieldset className="space-y-1.5">+ <legend className="text-xs font-medium text-zinc-300 mb-1.5">Start with</legend>+ <label className="flex items-center gap-2.5 p-2.5 rounded-lg border border-sky-500/40 bg-sky-500/5 text-xs text-zinc-200">+ <input type="radio" name="space-start" checked readOnly className="accent-sky-500" />+ An empty space+ </label>+ <label className="flex items-center gap-2.5 p-2.5 rounded-lg border border-zinc-800 text-xs text-zinc-500 cursor-not-allowed">+ <input type="radio" name="space-start" disabled className="accent-sky-500" />+ <span className="flex-1">Copy bots from another space</span>+ <span className="px-1.5 py-px rounded bg-zinc-800 text-[10px] text-zinc-400">Coming soon</span>+ </label>+ </fieldset>++ {error && (+ <div role="alert" className="bg-rose-500/10 border border-rose-500/20 text-rose-300 px-3 py-2 rounded-lg text-xs flex items-center gap-2">+ <AlertTriangle size={14} /> <span>{error}</span>+ </div>+ )}++ <div className="flex justify-end gap-2 pt-1">+ <button type="button" onClick={onClose} className="px-3.5 py-2 rounded-lg text-xs font-medium text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800">+ Cancel+ </button>+ <button+ type="submit"+ disabled={saving}+ className="px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 disabled:opacity-50 flex items-center gap-1.5"+ >+ {saving && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}+ {saving ? 'Creating…' : 'Create space'}+ </button>+ </div>+ </form>+ </Dialog>+ );+};++// ---------------------------------------------------------------------------+// Archived spaces++export const ArchivedSpacesModal: React.FC<{ onClose: () => void; onRestored: (space: Space) => void }> = ({ onClose, onRestored }) => {+ const [list, setList] = useState<Space[] | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState<string | null>(null);+ useEffect(() => {+ spacesApi.archived().then(setList, (e) => setError(e instanceof Error ? e.message : 'Couldn’t load archived spaces.'));+ }, []);++ const restore = async (s: Space) => {+ setBusy(s.id);+ setError(null);+ try {+ const restored = await spacesApi.patch(s.id, { archived: false });+ setList((prev) => prev?.filter((x) => x.id !== s.id) ?? null);+ playSfx('coin');+ onRestored(restored);+ } catch (e) {+ setError(e instanceof Error ? e.message : 'Couldn’t restore the space.');+ } finally {+ setBusy(null);+ }+ };++ return (+ <Dialog title={`Archived spaces${list ? ` (${list.length})` : ''}`} subtitle="Their routines are paused and nothing new runs until you restore them." labelId="archived-title" onClose={onClose}>+ {error && <p role="alert" className="text-xs text-rose-300">{error}</p>}+ {!list && !error && (+ <p className="flex items-center gap-2 text-xs text-zinc-400"><Loader2 size={13} className="animate-spin motion-reduce:animate-none" /> Loading…</p>+ )}+ {list?.length === 0 && <p className="text-xs text-zinc-500">No archived spaces.</p>}+ <ul className="space-y-1.5">+ {list?.map((s) => (+ <li key={s.id} className="flex items-center gap-3 p-2.5 rounded-xl border border-zinc-800 bg-zinc-950/50">+ <SpaceTile space={s} size={32} />+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-zinc-200 truncate">{s.name}</p>+ <p className="text-[11px] text-zinc-500 truncate">+ {spaceSummary(s.counts)}+ {s.paused_routines ? ` · ${s.paused_routines} ${s.paused_routines === 1 ? 'routine' : 'routines'} paused` : ''}+ </p>+ </div>+ <button+ type="button"+ disabled={busy === s.id}+ onClick={() => restore(s)}+ className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-sky-300 border border-sky-500/30 bg-sky-500/10 hover:bg-sky-500/20 disabled:opacity-50"+ >+ {busy === s.id ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" /> : <RotateCcw size={12} />}+ Restore+ </button>+ </li>+ ))}+ </ul>+ </Dialog>+ );+};diff --git a/frontend/src/components/ThreadBar.tsx b/frontend/src/components/ThreadBar.tsxindex 9e12ec05..aa15dc8a 100644--- a/frontend/src/components/ThreadBar.tsx+++ b/frontend/src/components/ThreadBar.tsx@@ -222,7 +222,7 @@ export const ThreadHeader: React.FC<ThreadHeaderProps> = ({ thread, badge, deleg{thread.title}</h3><span className="text-zinc-500 shrink-0 hidden sm:inline">- {thread.kind === 'delegation' ? `Delegated by ${delegatedBy ?? 'another agent'}` : 'Separate conversation'}+ {thread.kind === 'delegation' ? `Delegated by ${delegatedBy ?? 'another bot'}` : 'Separate conversation'}</span>{badge && <StatusBadge badge={badge} />}{thread.archived && <span className="text-[10px] text-zinc-500">Archived</span>}diff --git a/frontend/src/components/Toasts.tsx b/frontend/src/components/Toasts.tsxindex 80e4173f..ef497304 100644--- a/frontend/src/components/Toasts.tsx+++ b/frontend/src/components/Toasts.tsx@@ -47,12 +47,17 @@ const ToastItem: React.FC<{ toast: Toast; onDismiss: (id: number) => void }> = ();};-/** Short notices in the corner; screen readers hear them without moving focus. */-export const Toasts: React.FC<{ toasts: Toast[]; onDismiss: (id: number) => void }> = ({ toasts, onDismiss }) => (+/** Short notices in the corner; screen readers hear them without moving focus. News from other+ * spaces sits at the top, so it never covers the open space's own notices or the composer. */+export const Toasts: React.FC<{ toasts: Toast[]; onDismiss: (id: number) => void; position?: 'bottom' | 'top' }> = ({+ toasts,+ onDismiss,+ position = 'bottom',+}) => (<divrole="status"aria-live="polite"- className="pointer-events-none fixed bottom-4 right-4 left-4 sm:left-auto z-[60] flex flex-col items-end gap-2 sm:w-80"+ className={`pointer-events-none fixed ${position === 'top' ? 'top-4' : 'bottom-4'} right-4 left-4 sm:left-auto z-[60] flex flex-col items-end gap-2 sm:w-80`}>{toasts.map((t) => (<ToastItem key={t.id} toast={t} onDismiss={onDismiss} />diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsxindex a6d7f27b..8c5405cf 100644--- a/frontend/src/components/VirtualMachinePane.tsx+++ b/frontend/src/components/VirtualMachinePane.tsx@@ -513,7 +513,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({target="_blank"rel="noopener"className="text-zinc-400 hover:text-sky-400 p-0.5 flex-shrink-0"- title="Open the live sandbox browser in a new tab (shared with your agents)"+ title="Open the live sandbox browser in a new tab (shared with your bots)"><ExternalLink size={12} /></a>diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.tsindex 2fa9e9f4..cf88b470 100644--- a/frontend/src/continuity.ts+++ b/frontend/src/continuity.ts@@ -90,13 +90,13 @@ export type NotifyKind =| '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: 'turn_finished', label: 'A bot finished replying' },+ { id: 'approval_needed', label: 'A bot 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' },+ { id: 'skill_proposed', label: 'A bot proposed a skill to review' },+ { id: 'question_asked', label: 'A bot has a question for you' },];/** Kinds also shown as an in-app toast while kwnt is visible (the others only matter in the background). */@@ -109,6 +109,9 @@ export interface NotifyEvent {channel_id: string | null;title: string;body: string;+ /** The space it happened in (servers with spaces). */+ space_id?: string;+ space_name?: string;}// ---------------------------------------------------------------------------@@ -168,7 +171,7 @@ export function groupHits(hits: SearchHit[], kwantName: (id: string) => string |if (!g) {const label = h.channel_id? channelLabel(h.channel_name ?? h.channel_id)- : `Direct chat · ${(h.kwant_id && kwantName(h.kwant_id)) || 'kwant'}`;+ : `Direct chat · ${(h.kwant_id && kwantName(h.kwant_id)) || 'bot'}`;g = { key, channel_id: h.channel_id, kwant_id: h.channel_id ? null : h.kwant_id, label, hits: [] };groups.set(key, g);}diff --git a/frontend/src/engines.ts b/frontend/src/engines.tsindex b1f30201..012a763c 100644--- a/frontend/src/engines.ts+++ b/frontend/src/engines.ts@@ -300,7 +300,7 @@ export function engineSummary(e: EngineInfo, accounts: SummaryAccount[] = []): {if (next) return { text: `Off · Turn on to use ${next.name}`, tone: 'muted' };return { text: e.kind === 'local' || accounts.length === 0 ? 'Off · Turn on to use it' : 'Off · Turn on, then sign in to an account', tone: 'muted' };}- if (isUsable(e)) return e.uses ? { text: `Kwants use ${e.uses.label}`, tone: 'ok' } : { text: 'Kwants can use it', tone: 'ok' };+ if (isUsable(e)) return e.uses ? { text: `Bots use ${e.uses.label}`, tone: 'ok' } : { text: 'Bots can use it', tone: 'ok' };switch (e.status) {case 'checking':return { text: 'Checking…', tone: 'busy' };diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex 44829c1a..795b1bc8 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -1,6 +1,6 @@import React from 'react';import ReactDOM from 'react-dom/client';-import { App } from './App';+import { App } from './Shell';import { SandboxViewer } from './components/SandboxViewer';import { AuthGate } from './components/AuthGate';import './styles/modern.css';diff --git a/frontend/src/mcp.ts b/frontend/src/mcp.tsindex eb1dcbe3..57caaa10 100644--- a/frontend/src/mcp.ts+++ b/frontend/src/mcp.ts@@ -224,7 +224,7 @@ export const MCP_PRESETS: McpPreset[] = [// npm @modelcontextprotocol/server-memory 1.0.0id: 'memory',label: 'Memory',- blurb: 'A small knowledge graph kwants can save facts to and recall later.',+ blurb: 'A small knowledge graph bots can save facts to and recall later.',category: 'data',needs: ['Node.js'],source: 'https://github.com/modelcontextprotocol/servers/tree/main/src/memory',@@ -274,7 +274,7 @@ export const MCP_PRESETS: McpPreset[] = [// npm @modelcontextprotocol/server-sequential-thinking 1.0.0id: 'sequential-thinking',label: 'Sequential thinking',- blurb: 'Helps a kwant plan step by step and revise its plan on hard problems.',+ blurb: 'Helps a bot plan step by step and revise its plan on hard problems.',category: 'devtools',needs: ['Node.js'],source: 'https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking',diff --git a/frontend/src/profiles.ts b/frontend/src/profiles.tsindex 50383abe..d21028ef 100644--- a/frontend/src/profiles.ts+++ b/frontend/src/profiles.ts@@ -108,7 +108,7 @@ export interface AccountState {/** The state of an added account (This machine's comes from its engine's check; see accountStatus). */export function accountState(p: Profile, now = Date.now()): AccountState {- if (!p.enabled) return { label: 'Off', tone: 'muted', detail: 'Kwants skip this account' };+ if (!p.enabled) return { label: 'Off', tone: 'muted', detail: 'Bots skip this account' };const limit = activeLimit(p.limited_until, now);if (limit) return { label: 'Out of usage', tone: 'warn', detail: `Back ${formatUntil(limit, now)}` };if (p.last_error === 'auth') return { label: 'Needs sign-in', tone: 'error', detail: 'Its login stopped working. Sign in again.' };@@ -194,7 +194,7 @@ export interface ProfileSwitchedEvent {/** Toast text for a `profile_switched` event. */export function describeProfileSwitch(e: ProfileSwitchedEvent, kwantName: string | undefined, now = Date.now()) {- const who = kwantName || 'A kwant';+ const who = kwantName || 'A bot';const limit = activeLimit(e.retry_at ?? null, now);const why =e.class === 'auth'diff --git a/frontend/src/routing.ts b/frontend/src/routing.tsindex 736c6d99..d7dd62a5 100644--- a/frontend/src/routing.ts+++ b/frontend/src/routing.ts@@ -60,10 +60,10 @@ export function tryOrder(profiles: Profile[], family: Family, now = Date.now()):/** Why a turn's first account may not run, or null when it was ready on its last check. */function startNote(p: Profile, now: number): string | null {- if (activeLimit(p.limited_until, now)) return 'It’s out of usage and nothing else is ready, so kwants will stop and say so.';- if (p.kind === 'api_key') return p.has_key ? null : 'It has no key and nothing else is ready, so kwants will stop and say so.';- if (p.signed_in === false) return 'It needs sign-in and nothing else is ready, so kwants will stop and say so.';- if (p.signed_in === null && p.kind !== 'system') return 'Its sign-in hasn’t been checked yet. Kwants try it anyway.';+ if (activeLimit(p.limited_until, now)) return 'It’s out of usage and nothing else is ready, so bots will stop and say so.';+ if (p.kind === 'api_key') return p.has_key ? null : 'It has no key and nothing else is ready, so bots will stop and say so.';+ if (p.signed_in === false) return 'It needs sign-in and nothing else is ready, so bots will stop and say so.';+ if (p.signed_in === null && p.kind !== 'system') return 'Its sign-in hasn’t been checked yet. Bots try it anyway.';return null;}@@ -98,7 +98,7 @@ export function routeSummary(engines: EngineInfo[], profiles: Profile[] | null,const then = route.slice(1).map(accountName);const hostOff = !!host && !host.enabled;const fallback = hostOff && engine.kind === 'cli' && mine.some((p) => p.kind !== 'system')- ? `If you switch off every ${familyName(family)} account, kwants use This machine.`+ ? `If you switch off every ${familyName(family)} account, bots in this space use This machine.`: null;const defaultModel = engine.models.find((m) => m.default)?.label ?? null;return [{ family, label: familyName(family), engine: engine.name, account, note, then, defaultModel, fallback }];diff --git a/frontend/src/spaces.ts b/frontend/src/spaces.tsnew file mode 100644index 00000000..b116d1c6--- /dev/null+++ b/frontend/src/spaces.ts@@ -0,0 +1,297 @@+// Spaces: separate sets of bots, teams, channels and accounts. The open space rides on every+// `/api` call as `?space=` (added by the fetch wrapper in auth.ts) and on the event stream.++export interface SpaceCounts {+ bots: number;+ ready_accounts: number;+ unread: number;+}++export interface Space {+ id: string;+ name: string;+ /** An emoji, or "box" from an older server. */+ icon: string;+ color: string | null;+ sort: number;+ is_default: boolean;+ archived_at: string | null;+ created_at: string;+ /** Null until the space's first bot exists. */+ general_channel_id: string | null;+ counts: SpaceCounts;+ paused_routines?: number;+}++export interface NewSpace {+ name: string;+ icon: string;+ color: string;+ this_machine_enabled: boolean;+}++export interface SpacePatch {+ name?: string;+ icon?: string;+ color?: string | null;+ archived?: boolean;+}++export const DEFAULT_SPACE_ID = 'spc_default';++/** The icons offered when creating a space. */+export const SPACE_ICONS = ['💼', '🌿', '📚', '🎮', '🏠', '🚀', '🎨', '🧪'];++/** Space colours, in the order a new space takes the first unused one. */+export const SPACE_COLORS = ['#f59e0b', '#10b981', '#0ea5e9', '#8b5cf6', '#f43f5e', '#14b8a6', '#eab308', '#ec4899'];++const FALLBACK_ICON = '📦';++/** The emoji to draw for a space; older rows store a word like "box". */+export function spaceIcon(s: Pick<Space, 'icon'>): string {+ const icon = (s.icon || '').trim();+ return !icon || /^[a-z_-]+$/i.test(icon) ? FALLBACK_ICON : icon;+}++/** Colour words older rows and the server's Default use ("amber"). */+const NAMED_COLORS: Record<string, string> = {+ amber: '#f59e0b',+ emerald: '#10b981',+ sky: '#0ea5e9',+ violet: '#8b5cf6',+ rose: '#f43f5e',+ teal: '#14b8a6',+ yellow: '#eab308',+ pink: '#ec4899',+};++const hexOf = (c: string | null | undefined): string | null => {+ const v = (c || '').trim().toLowerCase();+ if (/^#[0-9a-f]{3,8}$/.test(v)) return v;+ return NAMED_COLORS[v] ?? null;+};++/** The space's colour, or a stable one from the palette when it has none. */+export function spaceColor(s: Pick<Space, 'id' | 'color'>): string {+ const hex = hexOf(s.color);+ if (hex) return hex;+ let h = 0;+ for (const ch of s.id) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ return SPACE_COLORS[h % SPACE_COLORS.length];+}++/** The first palette colour no other space uses yet (archived ones included); the first when all are taken. */+export function firstUnusedColor(spaces: Array<Pick<Space, 'color'>>): string {+ const used = new Set(spaces.map((s) => hexOf(s.color)));+ return SPACE_COLORS.find((c) => !used.has(c)) ?? SPACE_COLORS[0];+}++/** Why a space name can't be saved, or null when it can. `taken` are the other spaces' names. */+export function spaceNameError(name: string, taken: string[]): string | null {+ const n = name.trim();+ if (!n) return 'Give the space a name.';+ if (n.length > 60) return 'Keep the name under 60 characters.';+ if (taken.some((t) => t.trim().toLowerCase() === n.toLowerCase())) return `You already have a space called ${n}.`;+ return null;+}++/** "6 kwant bots · 2 accounts ready" under the space name. */+export function spaceSummary(c: SpaceCounts | undefined): string {+ if (!c) return '';+ const bots = `${c.bots} kwant ${c.bots === 1 ? 'bot' : 'bots'}`;+ const accounts = `${c.ready_accounts} ${c.ready_accounts === 1 ? 'account' : 'accounts'} ready`;+ return `${bots} · ${accounts}`;+}++// ---- The open space, for every request ----++let currentSpaceId: string | null = null;++export const setCurrentSpace = (id: string | null) => {+ currentSpaceId = id;+};+export const getCurrentSpace = () => currentSpaceId;++/** API paths that are app-wide, so they never get `?space=`. */+const GLOBAL_PREFIXES = [+ '/api/auth',+ '/api/spaces',+ '/api/health',+ '/api/settings',+ '/api/laya',+ '/api/system',+ '/api/mcp/oauth/callback',+ '/api/attachments',+ '/api/mcp/permission',+ '/api/mcp/gateway',+ '/api/mcp/self',+];++/** Adds `space=<id>` to a same-origin `/api` URL that's space-scoped and doesn't already name one. */+export function withSpace(url: string, origin: string, spaceId: string | null): string {+ if (!spaceId) return url;+ let parsed: URL;+ try {+ parsed = new URL(url, origin);+ } catch {+ return url;+ }+ if (parsed.origin !== origin || !parsed.pathname.startsWith('/api/')) return url;+ if (GLOBAL_PREFIXES.some((p) => parsed.pathname === p || parsed.pathname.startsWith(`${p}/`))) return url;+ if (parsed.searchParams.has('space')) return url;+ parsed.searchParams.set('space', spaceId);+ // Keep relative URLs relative.+ return /^https?:/i.test(url) ? parsed.href : `${parsed.pathname}${parsed.search}${parsed.hash}`;+}++/** The event stream for one space. */+export const eventsUrl = (spaceId: string | null) => (spaceId ? `/api/events?space=${encodeURIComponent(spaceId)}` : '/api/events');++// ---- Addresses: /s/<space>/c/<channel>, /s/<space>/b/<bot> ----++export interface SpaceRoute {+ spaceId: string | null;+ channelId?: string;+ botId?: string;+}++export function parseSpacePath(path: string): SpaceRoute {+ const m = path.match(/^\/s\/([^/]+)(?:\/(c|b)\/([^/]+))?\/?$/);+ if (!m) return { spaceId: null };+ const spaceId = decodeURIComponent(m[1]);+ if (m[2] === 'c') return { spaceId, channelId: decodeURIComponent(m[3]) };+ if (m[2] === 'b') return { spaceId, botId: decodeURIComponent(m[3]) };+ return { spaceId };+}++export function spacePath(spaceId: string, target?: { channelId?: string | null; botId?: string | null }): string {+ const base = `/s/${encodeURIComponent(spaceId)}`;+ if (target?.channelId) return `${base}/c/${encodeURIComponent(target.channelId)}`;+ if (target?.botId) return `${base}/b/${encodeURIComponent(target.botId)}`;+ return base;+}++const LAST_SPACE_KEY = 'kwant.lastSpace';+const lastChatKey = (spaceId: string) => `kwant.lastChat.${spaceId}`;++export function rememberSpace(id: string) {+ try {+ localStorage.setItem(LAST_SPACE_KEY, id);+ } catch {+ // private mode+ }+}+export function lastSpace(): string | null {+ try {+ return localStorage.getItem(LAST_SPACE_KEY);+ } catch {+ return null;+ }+}++/** The chat open in a space, so switching back reopens it. */+export function rememberChat(spaceId: string, target: { channelId?: string | null; botId?: string | null }) {+ try {+ localStorage.setItem(lastChatKey(spaceId), JSON.stringify({ channelId: target.channelId ?? null, botId: target.botId ?? null }));+ } catch {+ // private mode+ }+}+export function lastChat(spaceId: string): { channelId?: string; botId?: string } | null {+ try {+ const raw = localStorage.getItem(lastChatKey(spaceId));+ if (!raw) return null;+ const v = JSON.parse(raw);+ return { channelId: v?.channelId ?? undefined, botId: v?.botId ?? undefined };+ } catch {+ return null;+ }+}++/** Which space to open: the address, then the last one used, then Default, then the first active one. */+export function pickSpace(spaces: Space[], fromUrl: string | null, remembered: string | null): Space | null {+ const active = spaces.filter((s) => !s.archived_at);+ return (+ active.find((s) => s.id === fromUrl) ??+ active.find((s) => s.id === remembered) ??+ active.find((s) => s.is_default) ??+ active[0] ??+ null+ );+}++// ---- #general: what Laya did ----++export interface RoutingMeta {+ kwant_id?: string;+ kwant_name?: string;+ reason?: string;+ candidate_count?: number | null;+ fallback?: boolean;+ matched_terms?: string[];+}++export function parseRoutingMeta(meta: string | null | undefined): RoutingMeta | null {+ if (!meta) return null;+ try {+ const r = JSON.parse(meta)?.routing;+ return r && typeof r === 'object' && typeof r.kwant_name === 'string' ? (r as RoutingMeta) : null;+ } catch {+ return null;+ }+}++/** "Laya picked Lin from 6 bots in Work · matched 'migration', 'SQLite'", or the keyword-fallback line. */+export function routingLine(r: RoutingMeta, spaceName: string): string {+ const n = typeof r.candidate_count === 'number' && r.candidate_count > 0 ? r.candidate_count : null;+ const pool = n ? `from ${n} ${n === 1 ? 'bot' : 'bots'} in ${spaceName}` : `in ${spaceName}`;+ const matched = r.matched_terms?.length ? ` · matched ${r.matched_terms.map((t) => `'${t}'`).join(', ')}` : '';+ if (r.fallback) return `Picked by keywords (Laya is offline) · ${r.kwant_name} ${pool}${matched}`;+ return `Laya picked ${r.kwant_name} ${pool}${matched}`;+}++/** "ran on Work account" from a reply's `ran_on`, or null. */+export function ranOnAccount(meta: string | null | undefined): string | null {+ if (!meta) return null;+ try {+ const a = JSON.parse(meta)?.ran_on?.account;+ return typeof a === 'string' && a.trim() ? a.trim() : null;+ } catch {+ return null;+ }+}++// ---- API ----++async function errorText(res: Response, fallback: string): Promise<string> {+ try {+ const body = await res.json();+ if (body && typeof body.error === 'string') return body.error;+ } catch {+ // not JSON+ }+ return `${fallback} (HTTP ${res.status}).`;+}++async function json<T>(res: Response, fallback: string): Promise<T> {+ if (!res.ok) throw new Error(await errorText(res, fallback));+ return res.json() as Promise<T>;+}++export const spacesApi = {+ list: (): Promise<Space[]> => fetch('/api/spaces', { cache: 'no-store' }).then((r) => json<Space[]>(r, 'Couldn’t load spaces')),+ archived: (): Promise<Space[]> =>+ fetch('/api/spaces?archived=1', { cache: 'no-store' })+ .then((r) => json<Space[]>(r, 'Couldn’t load archived spaces'))+ .then((all) => all.filter((s) => !!s.archived_at)),+ create: (body: NewSpace): Promise<Space> =>+ fetch('/api/spaces', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then((r) =>+ json<Space>(r, 'Couldn’t create the space'),+ ),+ patch: (id: string, body: SpacePatch): Promise<Space> =>+ fetch(`/api/spaces/${encodeURIComponent(id)}`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ }).then((r) => json<Space>(r, 'Couldn’t save the space')),+};diff --git a/frontend/tests/away.test.mjs b/frontend/tests/away.test.mjsindex 9bd93311..51f4e01f 100644--- a/frontend/tests/away.test.mjs+++ b/frontend/tests/away.test.mjs@@ -130,7 +130,11 @@ test('empty, loading, error and expired states', () => {});test('sidebar entry shows the unseen badge only when there is something new', () => {- const base = { kwants: [], channels: [], teams: [], selectedId: '', isChannel: true, onSelectKwant: noop, onSelectChannel: noop,+ const space = { id: 'spc_default', name: 'Default', icon: '💼', color: '#f59e0b', sort: 0, is_default: true, archived_at: null,+ created_at: '', general_channel_id: null, counts: { bots: 0, ready_accounts: 0, unread: 0 } };+ const base = { space, spaces: [space], onSwitchSpace: noop, onCreateSpace: noop, onOpenSpaceSettings: noop, onOpenArchived: noop,+ onOpenSearch: noop, onOpenRoutines: noop,+ kwants: [], channels: [], teams: [], selectedId: '', isChannel: true, onSelectKwant: noop, onSelectChannel: noop,onSelectTeam: noop, onSummonKwant: noop, onCreateTeam: noop, onOpenAway: noop };const withNew = ui.sidebar({ ...base, awayCount: 7 });assert.match(withNew, /While you were away/);diff --git a/frontend/tests/engines.test.mjs b/frontend/tests/engines.test.mjsindex d24dfb1c..3916c8f8 100644--- a/frontend/tests/engines.test.mjs+++ b/frontend/tests/engines.test.mjs@@ -111,7 +111,7 @@ test('ready engines come first; not-installed ones fold under "Not available ontest('the headline gives way to the route summary once something is ready', () => {// With something ready, the route summary answers "what runs" instead of a count.- assert.match(panel(live), /What runs your kwants/);+ assert.match(panel(live), /What runs your kwant bots/);assert.doesNotMatch(panel(live), /no API keys are needed/);assert.match(panel(live.map((e) => ({ ...e, status: 'signed_out' }))), /No engine can run right now/);assert.match(panel(null), /Checking which engines can run/);@@ -177,7 +177,7 @@ test('a saved engine that can no longer run stays selected with a warning', () =assert.ok(options(html, 0).some(([v, l]) => v === 'codex' && l === 'Codex (OpenAI) (can't run now)'));assert.match(html, /<option value="codex" selected="">/);assert.match(html, /Codex \(OpenAI\) can('|')t run right now/);- assert.match(html, /Not signed in: run codex login\. This kwant won('|')t switch engine by itself/);+ assert.match(html, /Not signed in: run codex login\. This bot won('|')t switch engine by itself/);assert.match(html, /aria-invalid="true"/);assert.deepEqual(m.pickHealth('codex', live), { kind: 'engine_unavailable', family: 'codex', reason: 'Not signed in: run `codex login`' });// A model the engine stopped offering.diff --git a/frontend/tests/enginesAccounts.test.mjs b/frontend/tests/enginesAccounts.test.mjsindex 646da28d..d4db364c 100644--- a/frontend/tests/enginesAccounts.test.mjs+++ b/frontend/tests/enginesAccounts.test.mjs@@ -64,15 +64,15 @@ test('ready comes from `ready`, not the host login or the model list', () => {assert.ok(m.claudeNeedsSignIn([{ ...oleksOn, ready: false, uses: null }]));});-test('Oleks: one Claude card says kwants use Personal, with This machine first and signed out', () => {+test('Oleks: one Claude card says bots use Personal, with This machine first and signed out', () => {const html = panel([oleksOn]);assert.match(html, /Engines & accounts/);// The summary replaces the headline: Claude runs on Claude Code CLI through Personal.- assert.match(html, /What runs your kwants/);+ assert.match(html, /What runs your kwant bots/);assert.match(html, /data-route="claude"[\s\S]*?Claude Code CLI[\s\S]*?>Personal</);assert.match(html, /No backup account is ready\./);assert.match(html, /data-engine="claude" data-status="ready"/);- assert.equal(summary(html, 'claude'), 'Kwants use Personal');+ assert.equal(summary(html, 'claude'), 'Bots use Personal');const names = [...card(html, 'claude').matchAll(/id="account-[^"]+-name"[^>]*>([^<]+)</g)].map((x) => x[1]);assert.deepEqual(names, ['This machine', 'Personal']);// This machine: not signed in, with the Batch 9 sign-in on its row; Personal is in use.@@ -95,7 +95,7 @@ test('switched off with Personal signed in: "Off · Turn on to use Personal"', (assert.match(html, /No engine can run right now\. Claude Code CLI is off: turn it on to use Personal\./);assert.match(html, /role="switch" aria-checked="false"/);assert.match(html, /Not checked while Claude Code CLI is off/);- assert.doesNotMatch(html, /What runs your kwants/);+ assert.doesNotMatch(html, /What runs your kwant bots/);// Nothing to sign in to while it's off.assert.doesNotMatch(html, /Sign in with Claude/);});@@ -127,7 +127,7 @@ test('API-key accounts sit on the API engine card; an engine missing but with anconst apiEngine = engine('anthropic_api', { status: 'not_installed', ready: true, uses: { profile_id: 'prf_key', label: 'Team key' } });const html = panel([oleksOn, apiEngine, engine('ollama', { status: 'not_installed', ready: false })], [machine, personal, key]);assert.match(html, /data-engine="anthropic_api" data-status="ready"/);- assert.equal(summary(html, 'anthropic_api'), 'Kwants use Team key');+ assert.equal(summary(html, 'anthropic_api'), 'Bots use Team key');assert.match(html, /Not available on this computer \(1\)/);// Ollama has no accounts section.assert.doesNotMatch(html, /Ollama accounts/);diff --git a/frontend/tests/profiles.test.mjs b/frontend/tests/profiles.test.mjsindex 6f716946..aaebfcb6 100644--- a/frontend/tests/profiles.test.mjs+++ b/frontend/tests/profiles.test.mjs@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';import { readFile } from 'node:fs/promises';import test from 'node:test';import ts from 'typescript';+import { loadBundled } from './bundle.mjs';const load = async (path) => {const source = await readFile(new URL(path, import.meta.url), 'utf8');@@ -10,7 +11,8 @@ const load = async (path) => {};const profiles = await load('../src/profiles.ts');-const auth = await load('../src/auth.ts');+// auth.ts imports spaces.ts, so it's bundled.+const auth = await loadBundled("export * from './src/auth.ts';");const activity = await load('../src/kwantActivity.ts');const profile = (over) => ({diff --git a/frontend/tests/routing.test.mjs b/frontend/tests/routing.test.mjsindex 5d30cb32..3be881ba 100644--- a/frontend/tests/routing.test.mjs+++ b/frontend/tests/routing.test.mjs@@ -44,7 +44,7 @@ test("Oleks: Claude runs on Claude Code CLI through Personal, with the This machassert.deepEqual(row.account, { name: 'Personal', detail: '[email protected]', otherProvider: false });assert.deepEqual(row.then, []);assert.equal(row.defaultModel, 'Claude Sonnet');- assert.equal(row.fallback, 'If you switch off every Claude account, kwants use This machine.');+ assert.equal(row.fallback, 'If you switch off every Claude account, bots in this space use This machine.');});test('backups are listed in order', () => {diff --git a/frontend/tests/spaces.test.mjs b/frontend/tests/spaces.test.mjsnew file mode 100644index 00000000..80705533--- /dev/null+++ b/frontend/tests/spaces.test.mjs@@ -0,0 +1,84 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };++const m = await loadBundled(`+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { SpaceRail, NewSpaceModal } from './src/components/Spaces';+ export * from './src/spaces';+ export const rail = (props) => renderToStaticMarkup(React.createElement(SpaceRail, props));+ export const newSpace = (props) => renderToStaticMarkup(React.createElement(NewSpaceModal, props));+`);++const noop = () => {};+const space = (over = {}) => ({+ id: 'spc_default', name: 'Default', icon: '💼', color: '#f59e0b', sort: 0, is_default: true, archived_at: null,+ created_at: '', general_channel_id: 'ch1', counts: { bots: 6, ready_accounts: 2, unread: 0 }, ...over,+});++test('the open space rides on scoped /api calls, never on app-wide ones', () => {+ const o = 'http://kwnt.test';+ assert.equal(m.withSpace('/api/kwants', o, 'spc_b'), '/api/kwants?space=spc_b');+ assert.equal(m.withSpace('/api/channels?x=1', o, 'spc_b'), '/api/channels?x=1&space=spc_b');+ assert.equal(m.withSpace('/api/spaces', o, 'spc_b'), '/api/spaces');+ assert.equal(m.withSpace('/api/auth/status', o, 'spc_b'), '/api/auth/status');+ assert.equal(m.withSpace('/api/settings', o, 'spc_b'), '/api/settings');+ assert.equal(m.withSpace('/api/kwants?space=spc_a', o, 'spc_b'), '/api/kwants?space=spc_a');+ assert.equal(m.withSpace('https://other.test/api/kwants', o, 'spc_b'), 'https://other.test/api/kwants');+ assert.equal(m.withSpace('/api/kwants', o, null), '/api/kwants');+ assert.equal(m.eventsUrl('spc b'), '/api/events?space=spc%20b');+ assert.equal(m.eventsUrl(null), '/api/events');+});++test('addresses round-trip and the right space opens first', () => {+ assert.deepEqual(m.parseSpacePath('/s/spc_b/c/ch9'), { spaceId: 'spc_b', channelId: 'ch9' });+ assert.deepEqual(m.parseSpacePath('/s/spc_b/b/k1'), { spaceId: 'spc_b', botId: 'k1' });+ assert.deepEqual(m.parseSpacePath('/'), { spaceId: null });+ assert.equal(m.spacePath('spc_b', { channelId: 'ch9' }), '/s/spc_b/c/ch9');+ const list = [space(), space({ id: 'spc_b', name: 'B', is_default: false }), space({ id: 'spc_c', is_default: false, archived_at: 'x' })];+ assert.equal(m.pickSpace(list, 'spc_b', 'spc_default').id, 'spc_b');+ assert.equal(m.pickSpace(list, 'spc_c', null).id, 'spc_default', 'an archived space never opens');+ assert.equal(m.pickSpace(list, 'gone', 'spc_b').id, 'spc_b');+});++test('names, colours and the summary line', () => {+ assert.equal(m.spaceNameError(' ', []), 'Give the space a name.');+ assert.equal(m.spaceNameError('work', ['Work']), 'You already have a space called work.');+ assert.equal(m.spaceNameError('Home', ['Work']), null);+ assert.equal(m.firstUnusedColor([{ color: '#F59E0B' }]), '#10b981');+ assert.equal(m.firstUnusedColor([{ color: 'amber' }]), '#10b981', "the server's Default is 'amber'");+ assert.equal(m.spaceColor({ id: 'spc_default', color: 'amber' }), '#f59e0b');+ assert.equal(m.spaceIcon({ icon: 'box' }), '📦');+ assert.equal(m.spaceSummary({ bots: 1, ready_accounts: 0, unread: 0 }), '1 kwant bot · 0 accounts ready');+});++test('Laya says who she picked, from how many bots, in which space', () => {+ const meta = JSON.stringify({ routing: { kwant_name: 'Lin', candidate_count: 6, matched_terms: ['migration', 'SQLite'] }, ran_on: { account: 'Work' } });+ const r = m.parseRoutingMeta(meta);+ assert.equal(m.routingLine(r, 'Work'), "Laya picked Lin from 6 bots in Work · matched 'migration', 'SQLite'");+ assert.equal(m.routingLine({ kwant_name: 'Lin', candidate_count: 1, fallback: true }, 'B'), 'Picked by keywords (Laya is offline) · Lin from 1 bot in B');+ assert.equal(m.ranOnAccount(meta), 'Work');+ assert.equal(m.parseRoutingMeta('{"ran_on":{}}'), null);+ assert.equal(m.parseRoutingMeta('not json'), null);+});++test('the rail marks the open space and shows other spaces’ unread', () => {+ const html = m.rail({+ spaces: [space(), space({ id: 'spc_b', name: 'Side', is_default: false, counts: { bots: 1, ready_accounts: 1, unread: 3 } })],+ currentId: 'spc_default', onSwitch: noop, onCreate: noop, onOpenAppSettings: noop,+ });+ assert.match(html, /aria-current="(page|true)"/);+ assert.match(html, /Side/);+ assert.match(html, />3</);+ assert.doesNotMatch(html, /\b[Aa]gents?\b/);+});++test('a new space preselects the first unused colour and offers Copy bots as coming soon', () => {+ const html = m.newSpace({ spaces: [space()], onClose: noop, onCreated: noop });+ assert.match(html, /#10b981/);+ assert.match(html, /This machine/);+ assert.match(html, /Coming soon/);+});