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
frontend: LLM profiles, token sign-in and working avatars
Lin (kwant bot)ac03b39e69b6
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex b90c2965..666de52e 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -1,4 +1,4 @@-import React, { Suspense, lazy, useState, useEffect, useRef } from 'react';+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 { ChatView, ChatMessage, DiscussionState, RoutingState } from './components/ChatView';@@ -8,11 +8,15 @@ import type { AgentFormData } from './components/NewAgentModal';import { NewTeamModal } from './components/NewTeamModal';import { ManageTeamModal } from './components/ManageTeamModal';import { playSfx } from './audio/chiptune';+import { Toasts, Toast } from './components/Toasts';+import { clearAllTurns, turnEnded, turnStarted } from './kwantActivity';+import { Profile, describeProfileSwitch, profilesApi } from './profiles';// 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 ProfilesModal = lazy(() => import('./components/ProfilesModal').then((m) => ({ default: m.ProfilesModal })));export const App: React.FC = () => {const [kwants, setKwants] = useState<Kwant[]>([]);@@ -55,6 +59,14 @@ export const App: React.FC = () => {// Modals stateconst [isSettingsOpen, setIsSettingsOpen] = useState(false);const [isMcpOpen, setIsMcpOpen] = useState(false);+ const [isProfilesOpen, setIsProfilesOpen] = useState(false);+ const [profiles, setProfiles] = useState<Profile[]>([]);+ const [toasts, setToasts] = useState<Toast[]>([]);+ const toastIdRef = useRef(0);+ const dismissToast = useCallback((id: number) => setToasts((prev) => prev.filter((t) => t.id !== id)), []);+ const refreshProfiles = useCallback(() => {+ profilesApi.list().then(setProfiles, () => undefined);+ }, []);const [isNewAgentOpen, setIsNewAgentOpen] = useState(false);// Team that a newly created agent should join (set by a team's "Add member")const [newAgentTeam, setNewAgentTeam] = useState<Team | null>(null);@@ -119,7 +131,8 @@ export const App: React.FC = () => {}}loadInitialData();- }, []);+ refreshProfiles();+ }, [refreshProfiles]);// Load messages when selected channel/kwant changesuseEffect(() => {@@ -147,11 +160,38 @@ export const App: React.FC = () => {// Connect to SSE streamuseEffect(() => {const sse = new EventSource('/api/events');+ // After a reconnect a `turn_ended` may have been missed; drop working states rather than spin forever.+ let dropped = false;+ sse.onerror = () => {+ dropped = true;+ };+ sse.onopen = () => {+ if (dropped) clearAllTurns();+ dropped = false;+ };sse.onmessage = (e) => {try {const event = JSON.parse(e.data);switch (event.type) {+ case 'turn_started':+ case 'TurnStarted':+ turnStarted(event.data?.kwant_id, event.data?.context_id);+ break;+ case 'turn_ended':+ case 'TurnEnded':+ turnEnded(event.data?.kwant_id, event.data?.context_id);+ break;+ case 'profile_switched':+ case 'ProfileSwitched': {+ const kwantName = kwantsRef.current.find((k) => k.id === event.data?.kwant_id)?.name;+ const { title, detail } = describeProfileSwitch(event.data, kwantName);+ const id = ++toastIdRef.current;+ setToasts((prev) => [...prev.slice(-2), { id, title, detail }]);+ playSfx('alert');+ refreshProfiles();+ break;+ }case 'TextDelta':setStreamingText((prev) => prev + event.data);playSfx('blip');@@ -437,8 +477,9 @@ export const App: React.FC = () => {return () => {sse.close();+ clearAllTurns();};- }, []);+ }, [refreshProfiles]);const handleCancelDiscussion = async () => {const targetId = selectedIdRef.current;@@ -628,7 +669,7 @@ export const App: React.FC = () => {body: JSON.stringify(kwantData),});if (res.status === 409) return `Another agent is already named "${agentData.name}".`;- if (res.status === 400) return 'Name cannot be empty or contain spaces or @.';+ 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}).`;const updated: Kwant = await res.json();@@ -665,6 +706,8 @@ export const App: React.FC = () => {avatar_sprite: agentData.avatar_sprite,driver_type: 'api',preferred_model: agentData.preferred_model,+ ...(agentData.profile_id !== undefined ? { profile_id: agentData.profile_id } : {}),+ ...(agentData.profile_failover !== undefined ? { profile_failover: agentData.profile_failover } : {}),}),});@@ -694,7 +737,7 @@ export const App: React.FC = () => {return;}if (res.status === 409) return `Another agent is already named "${agentData.name}".`;- if (res.status === 400) return 'Name cannot be empty or contain spaces or @.';+ 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}).`;} catch (err) {console.error('Failed creating Agent:', err);@@ -896,8 +939,9 @@ export const App: React.FC = () => {? `@${currentChannel.name.replace(/^team-/, '')}`: `#${currentChannel?.name || 'general'}`;+ const boundProfile = currentKwant?.profile_id ? profiles.find((p) => p.id === currentKwant.profile_id) : undefined;const chatSubtitle = !isChannel- ? `${currentKwant?.title || 'Specialist'} [Laya Auto-Fleet]`+ ? `${currentKwant?.title || 'Specialist'} [Laya Auto-Fleet]${boundProfile ? ` · profile: ${boundProfile.name}` : ''}`: currentTeam?.description || currentChannel?.description || 'Team collaboration room';// Load container status and screenshot for active team or bot@@ -1025,6 +1069,8 @@ export const App: React.FC = () => {}};+ const closeProfiles = useCallback(() => setIsProfilesOpen(false), []);+const isCurrentContextStreaming = isStreaming && streamingContextId === selectedId;const isDiscussionActiveHere =discussionState.inProgress &&@@ -1135,6 +1181,8 @@ export const App: React.FC = () => {}}joinTeamName={newAgentTeam?.name}takenNames={kwants.map((k) => k.name)}+ profiles={profiles}+ onManageProfiles={() => setIsProfilesOpen(true)}onManageServers={() => setIsMcpOpen(true)}onSubmit={handleCreateAgent}/>@@ -1144,6 +1192,8 @@ export const App: React.FC = () => {isOpen={!!editingKwant}initial={editingKwant}kwantId={editingKwant?.id}+ profiles={profiles}+ onManageProfiles={() => setIsProfilesOpen(true)}onManageServers={() => setIsMcpOpen(true)}onClose={() => setEditingKwant(null)}onSubmit={(data) => (editingKwant ? handleUpdateAgent(editingKwant, data) : undefined)}@@ -1176,12 +1226,19 @@ export const App: React.FC = () => {setIsSettingsOpen(false);setIsMcpOpen(true);}}+ onOpenProfiles={() => {+ setIsSettingsOpen(false);+ setIsProfilesOpen(true);+ }}/>{/* MCP tool servers (opened last so it sits above the agent modal) */}<Suspense fallback={null}><McpServersModal isOpen={isMcpOpen} onClose={() => setIsMcpOpen(false)} kwants={kwants} />+ <ProfilesModal isOpen={isProfilesOpen} onClose={closeProfiles} onProfilesChanged={setProfiles} /></Suspense>++ <Toasts toasts={toasts} onDismiss={dismissToast} /></div>);};diff --git a/frontend/src/auth.ts b/frontend/src/auth.tsnew file mode 100644index 00000000..85f8c842--- /dev/null+++ b/frontend/src/auth.ts@@ -0,0 +1,92 @@+// API token handling: the `#kwnt_token=` link, the session cookie and 401s from any `/api` call.++/** Fired on `window` when an `/api` call answers 401 (the token is missing or no longer valid). */+export const UNAUTHORIZED_EVENT = 'kwnt:unauthorized';++export interface AuthStatus {+ auth_required: boolean;+ authenticated: boolean;+}++/** Splits `#kwnt_token=<t>` off a location hash, keeping any other fragment parameters. */+export function extractHashToken(hash: string): { token: string | null; rest: string } {+ const raw = hash.startsWith('#') ? hash.slice(1) : hash;+ if (!raw) return { token: null, rest: '' };+ const params = new URLSearchParams(raw);+ const token = params.get('kwnt_token');+ if (token === null) return { token: null, rest: hash };+ params.delete('kwnt_token');+ const rest = params.toString();+ return { token: token.trim(), rest: rest ? `#${rest}` : '' };+}++/** Whether a 401 from this URL means the API token is missing. The auth endpoints answer for themselves. */+export function isGuardedApiUrl(url: string, origin: string): boolean {+ let parsed: URL;+ try {+ parsed = new URL(url, origin);+ } catch {+ return false;+ }+ return parsed.origin === origin && parsed.pathname.startsWith('/api/') && !parsed.pathname.startsWith('/api/auth/');+}++let installed = false;++/** Wraps `window.fetch` so every component's `/api` 401 reaches the auth gate. */+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) => {+ const res = await original(input, init);+ if (res.status === 401) {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ if (isGuardedApiUrl(url, window.location.origin)) window.dispatchEvent(new Event(UNAUTHORIZED_EVENT));+ }+ return res;+ };+}++export async function fetchAuthStatus(): Promise<AuthStatus> {+ const res = await fetch('/api/auth/status', { cache: 'no-store' });+ if (res.status === 403) throw new Error("This page's address isn't allowed to use the API (403). Open kwnt at its own address.");+ if (!res.ok) throw new Error(`The server answered ${res.status}.`);+ return res.json();+}++/** Exchanges the token for the session cookie; resolves to false when the token is wrong. */+export async function startSession(token: string): Promise<boolean> {+ const res = await fetch('/api/auth/session', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token }),+ });+ if (res.status === 401) return false;+ if (!res.ok) throw new Error(`The server answered ${res.status}.`);+ return true;+}++export async function endSession(): Promise<void> {+ await fetch('/api/auth/session', { method: 'DELETE' });+}++let linkSession: Promise<string | null> | null = null;++/**+ * Signs in with a `#kwnt_token=` link and removes the token from the address bar (and history)+ * before any network call, so React's second effect run finds no token and shares the first one's+ * result. Resolves to an error message when the token was refused.+ */+export function consumeTokenLink(): Promise<string | null> {+ const { token, rest } = extractHashToken(window.location.hash);+ if (token === null) return linkSession ?? Promise.resolve(null);+ window.history.replaceState(window.history.state, '', `${window.location.pathname}${window.location.search}${rest}`);+ linkSession = !token+ ? Promise.resolve('The link has an empty token.')+ : startSession(token).then(+ (ok) => (ok ? null : "The link's token wasn't accepted. It may have been changed; paste the current one."),+ (e: unknown) => (e instanceof Error ? e.message : 'Could not reach the server.'),+ );+ return linkSession;+}diff --git a/frontend/src/components/AuthGate.tsx b/frontend/src/components/AuthGate.tsxnew file mode 100644index 00000000..c8f0b0f8--- /dev/null+++ b/frontend/src/components/AuthGate.tsx@@ -0,0 +1,193 @@+import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';+import { KeyRound, Loader2, RefreshCw, Terminal } from 'lucide-react';+import { ModernAvatar } from './ModernAvatar';+import {+ UNAUTHORIZED_EVENT,+ consumeTokenLink,+ endSession,+ fetchAuthStatus,+ installUnauthorizedListener,+ startSession,+} from '../auth';++interface AuthContextValue {+ /** True when this browser needs the API token (Docker, a VPS reached directly). */+ authRequired: boolean;+ signOut: () => Promise<void>;+}++const AuthContext = createContext<AuthContextValue>({ authRequired: false, signOut: async () => undefined });++export const useAuth = () => useContext(AuthContext);++type GateState =+ | { kind: 'checking' }+ | { kind: 'ready'; authRequired: boolean }+ | { kind: 'locked'; notice: string | null }+ | { kind: 'offline'; message: string };++installUnauthorizedListener();++/** Shows its children once the API answers, and the token screen while it needs a token. */+export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ const [state, setState] = useState<GateState>({ kind: 'checking' });+ const checking = useRef(false);++ const check = useCallback(async (notice: string | null = null) => {+ if (checking.current) return;+ checking.current = true;+ try {+ const s = await fetchAuthStatus();+ setState(s.auth_required && !s.authenticated ? { kind: 'locked', notice } : { kind: 'ready', authRequired: s.auth_required });+ } catch (e) {+ setState({ kind: 'offline', message: e instanceof Error && e.message !== 'Failed to fetch' ? e.message : "Can't reach kwnt. Is it running?" });+ } finally {+ checking.current = false;+ }+ }, []);++ useEffect(() => {+ let cancelled = false;+ consumeTokenLink().then((linkError) => {+ if (!cancelled) check(linkError);+ });+ const onUnauthorized = () => check('Your session ended. Paste the token again to continue.');+ // A token link opened in a tab that already shows kwnt only changes the hash.+ const onHash = () => {+ if (window.location.hash.includes('kwnt_token=')) consumeTokenLink().then((linkError) => check(linkError));+ };+ window.addEventListener(UNAUTHORIZED_EVENT, onUnauthorized);+ window.addEventListener('hashchange', onHash);+ return () => {+ cancelled = true;+ window.removeEventListener(UNAUTHORIZED_EVENT, onUnauthorized);+ window.removeEventListener('hashchange', onHash);+ };+ }, [check]);++ const signOut = useCallback(async () => {+ try {+ await endSession();+ } finally {+ setState({ kind: 'locked', notice: 'Signed out.' });+ }+ }, []);++ if (state.kind === 'ready') {+ return <AuthContext.Provider value={{ authRequired: state.authRequired, signOut }}>{children}</AuthContext.Provider>;+ }++ return (+ <div className="min-h-screen w-screen flex items-center justify-center bg-zinc-950 text-zinc-100 p-4 font-sans">+ <div className="w-full max-w-md bg-zinc-900 border border-zinc-800 rounded-2xl p-6 shadow-2xl space-y-5">+ <div className="flex items-center gap-3">+ <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>+ </div>+ </div>+ {state.kind === 'checking' && (+ <p className="flex items-center gap-2 text-xs text-zinc-400" role="status">+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" /> Connecting…+ </p>+ )}+ {state.kind === 'offline' && (+ <div className="space-y-3" role="alert">+ <p className="text-xs text-rose-300">{state.message}</p>+ <button+ type="button"+ onClick={() => {+ setState({ kind: 'checking' });+ check();+ }}+ className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 transition-colors"+ >+ <RefreshCw size={13} /> Try again+ </button>+ </div>+ )}+ {state.kind === 'locked' && <TokenForm notice={state.notice} onSignedIn={() => check()} />}+ </div>+ </div>+ );+};++const TokenForm: React.FC<{ notice: string | null; onSignedIn: () => void }> = ({ notice, onSignedIn }) => {+ const [token, setToken] = useState('');+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ const value = token.trim();+ if (!value) return;+ setBusy(true);+ setError(null);+ try {+ if (await startSession(value)) {+ setToken('');+ onSignedIn();+ return;+ }+ setError("That token isn't right. Copy it again from the command below.");+ } catch (err) {+ setError(err instanceof Error && err.message !== 'Failed to fetch' ? err.message : 'Could not reach the server.');+ } finally {+ setBusy(false);+ }+ };++ return (+ <form onSubmit={submit} className="space-y-4">+ <div className="space-y-1.5">+ <h2 className="flex items-center gap-2 text-sm font-medium">+ <KeyRound size={15} className="text-sky-400" /> Enter your access token+ </h2>+ <p className="text-xs text-zinc-400 leading-relaxed">+ This kwnt is reachable from other machines, so it needs its token once per browser. Get it on the server:+ </p>+ <div className="space-y-1 text-[11px] font-mono text-zinc-300">+ <p className="flex items-center gap-1.5 bg-zinc-950 border border-zinc-800 rounded-md px-2 py-1">+ <Terminal size={12} className="text-zinc-500" /> kwnt token+ </p>+ <p className="flex items-center gap-1.5 bg-zinc-950 border border-zinc-800 rounded-md px-2 py-1">+ <Terminal size={12} className="text-zinc-500" /> docker compose exec kwnt kwnt token+ </p>+ </div>+ </div>+ {notice && <p className="text-xs text-amber-300" role="status">{notice}</p>}+ <div>+ <label htmlFor="kwnt-token" className="block text-xs font-medium text-zinc-400 mb-1">+ Token+ </label>+ <input+ id="kwnt-token"+ type="password"+ autoComplete="off"+ spellCheck={false}+ autoFocus+ value={token}+ onChange={(e) => setToken(e.target.value)}+ aria-invalid={!!error}+ aria-describedby={error ? 'kwnt-token-error' : undefined}+ className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs font-mono text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors"+ placeholder="Paste the token"+ />+ {error && (+ <p id="kwnt-token-error" className="mt-1.5 text-[11px] text-rose-400" role="alert">+ {error}+ </p>+ )}+ </div>+ <button+ type="submit"+ disabled={busy || !token.trim()}+ className="w-full flex items-center justify-center gap-1.5 px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors disabled:opacity-50"+ >+ {busy && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" />} Continue+ </button>+ <p className="text-[11px] text-zinc-500">The browser keeps you signed in for a year. Anyone with the token controls this kwnt.</p>+ </form>+ );+};diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex bd9b65d8..03a22f14 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -544,7 +544,7 @@ export const ChatView: React.FC<ChatViewProps> = ({title={`${member.name} (${member.title})`}className="inline-block ring-2 ring-zinc-950 rounded-full">- <ModernAvatar role={member.avatar_sprite} name={member.name} size={24} />+ <ModernAvatar role={member.avatar_sprite} name={member.name} size={24} kwantId={member.id} /></div>))}</div>@@ -779,7 +779,7 @@ export const ChatView: React.FC<ChatViewProps> = ({className="flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-zinc-800/90 hover:bg-zinc-700 text-zinc-300 hover:text-zinc-100 border border-zinc-700/60 transition-all text-xs cursor-pointer shadow-sm active:scale-95"title={`Ask ${m.name}`}>- <ModernAvatar role={m.avatar_sprite} name={m.name} size={14} />+ <ModernAvatar role={m.avatar_sprite} name={m.name} size={14} kwantId={m.id} /><span>@{m.name}</span></button>))}diff --git a/frontend/src/components/ModernAvatar.tsx b/frontend/src/components/ModernAvatar.tsxindex 1159357f..f3e7838e 100644--- a/frontend/src/components/ModernAvatar.tsx+++ b/frontend/src/components/ModernAvatar.tsx@@ -1,4 +1,5 @@-import React from 'react';+import React, { useCallback, useSyncExternalStore } from 'react';+import { isKwantWorking, subscribeKwant } from '../kwantActivity';interface ModernAvatarProps {role?: string;@@ -6,8 +7,21 @@ interface ModernAvatarProps {size?: number; // pixel diameterisOnline?: boolean;className?: string;+ /** The kwant this avatar shows; it animates while that kwant is working on a turn. */+ kwantId?: string;}+const noopUnsubscribe = () => undefined;++/** Whether a kwant is mid-turn; only this kwant's turns re-render the caller. */+export const useKwantWorking = (kwantId: string | undefined): boolean => {+ const subscribe = useCallback(+ (onChange: () => void) => (kwantId ? subscribeKwant(kwantId, onChange) : noopUnsubscribe),+ [kwantId],+ );+ return useSyncExternalStore(subscribe, () => isKwantWorking(kwantId));+};+type Accessory =| 'antenna' | 'spikes' | 'ears' | 'horns' | 'sprout' | 'crown' | 'visor'| 'beret' | 'glasses' | 'goggles' | 'tie' | 'quill' | 'bulb'@@ -315,7 +329,9 @@ export const ModernAvatar: React.FC<ModernAvatarProps> = ({size = 36,isOnline,className = '',+ kwantId,}) => {+ const working = useKwantWorking(kwantId);const creature = pickCreature(role, name);// At tiny sizes the frame would dominate, so zoom in on the creature aloneconst framed = size > 20;@@ -324,10 +340,12 @@ export const ModernAvatar: React.FC<ModernAvatarProps> = ({return (<div- className={`relative inline-flex flex-shrink-0 select-none ${className}`}+ className={`kw-avatar relative inline-flex flex-shrink-0 select-none ${working ? 'kw-avatar-working' : ''} ${className}`}style={{ width: size, height: size }}- title={name || undefined}+ title={name ? (working ? `${name} is working…` : name) : undefined}+ data-working={working || undefined}>+ {working && <span className="kw-avatar-ring" aria-hidden="true" />}<svgviewBox={framed ? '0 0 26 26' : '5 2.5 16 17'}className="w-full h-full"@@ -342,9 +360,12 @@ export const ModernAvatar: React.FC<ModernAvatarProps> = ({<rect key={`scan-${i}`} x={3.5} y={4.5 + i} width={19} height={0.25} fill={SCAN} />))}<g transform={compact ? 'translate(13 13.2) scale(1.2) translate(-13 -12)' : undefined}>- {renderCreature(creature).filter((r) => framed && !compact || r.key !== 'shadow')}+ <g className="kw-avatar-body">+ {renderCreature(creature).filter((r) => framed && !compact || r.key !== 'shadow')}+ </g></g></svg>+ {working && <span className="kw-avatar-pip" aria-hidden="true" />}{isOnline !== undefined && (<spanclassName={`absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full ring-2 ring-zinc-950 ${diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsxindex 990b55dd..95f8cc2d 100644--- a/frontend/src/components/NewAgentModal.tsx+++ b/frontend/src/components/NewAgentModal.tsx@@ -1,10 +1,11 @@import React, { useEffect, useState } from 'react';-import { X, Sparkles, Pencil } from 'lucide-react';+import { X, Sparkles, Pencil, ChevronRight } from 'lucide-react';import { ModernAvatar, AVATAR_STYLES } from './ModernAvatar';import { AGENT_PRESETS, AgentPreset, PRESET_GROUPS, PresetGroup, uniqueAgentName } from '../agentPresets';import { playSfx } from '../audio/chiptune';import { KwantToolsPicker } from './KwantToolsPicker';import { McpServer, defaultKwantServerIds } from '../mcp';+import { ENGINES, Profile, engineOfModel, profileStatus, profilesForEngine } from '../profiles';export interface AgentFormData {name: string;@@ -15,6 +16,9 @@ export interface AgentFormData {preferred_model: string;/** MCP servers this kwant may use; undefined when they weren't loaded. */mcp_server_ids?: string[];+ /** Pinned LLM profile; null uses the engine's default. */+ profile_id?: string | null;+ profile_failover?: boolean;}const MODEL_OPTIONS = [@@ -38,6 +42,10 @@ interface NewAgentModalProps {kwantId?: string;/** Opens the MCP servers screen. */onManageServers?: () => void;+ /** Every LLM profile, for the profile picker. */+ profiles?: Profile[];+ /** Opens the LLM profiles screen. */+ onManageProfiles?: () => void;/** Resolves to an error message when saving failed. */onSubmit: (data: AgentFormData) => Promise<string | void> | void;}@@ -50,6 +58,8 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({joinTeamName,kwantId,onManageServers,+ profiles = [],+ onManageProfiles,onSubmit,}) => {const [name, setName] = useState('');@@ -63,7 +73,11 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({const [presetId, setPresetId] = useState<string | null>(null);const [presetGroup, setPresetGroup] = useState<PresetGroup>('tech');const [mcpIds, setMcpIds] = useState<string[] | undefined>(undefined);+ const [profileId, setProfileId] = useState<string | null>(null);+ const [failover, setFailover] = useState(true);const isEdit = !!initial;+ const engine = engineOfModel(model);+ const engineProfiles = profilesForEngine(profiles, engine);useEffect(() => {if (!isOpen) return;@@ -77,6 +91,8 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({setError(null);setPresetId(null);setMcpIds(undefined);+ setProfileId(initial?.profile_id ?? null);+ setFailover(initial?.profile_failover ?? true);let cancelled = false;// If a list can't load, the picker stays hidden and nothing is saved: saving an empty// list would switch every server off for this kwant.@@ -131,6 +147,11 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({avatar_sprite: roleStyle,preferred_model: model,mcp_server_ids: mcpIds,+ // A pin only makes sense for one engine; auto and Ollama run on the defaults. Until the+ // profiles have loaded, the current pin is left alone.+ profile_id:+ profiles.length === 0 ? undefined : engine && engineProfiles.some((p) => p.id === profileId) ? profileId : null,+ profile_failover: failover,});setSubmitting(false);@@ -284,6 +305,49 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({</select></div>+ {engine && (+ <div>+ <div className="flex items-center justify-between mb-1">+ <label htmlFor="agent-profile" className="text-xs font-medium text-zinc-400">+ Account (LLM profile)+ </label>+ {onManageProfiles && (+ <button+ type="button"+ onClick={onManageProfiles}+ className="flex items-center gap-0.5 text-[11px] text-zinc-500 hover:text-sky-300 transition-colors"+ >+ Manage profiles <ChevronRight size={11} />+ </button>+ )}+ </div>+ <select+ id="agent-profile"+ value={profileId ?? ''}+ onChange={(e) => setProfileId(e.target.value || null)}+ className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none transition-colors"+ >+ <option value="">+ {`${ENGINES.find((e) => e.id === engine)?.label} default${+ engineProfiles[0]?.is_default ? ` (${engineProfiles[0].name})` : ''+ }`}+ </option>+ {engineProfiles.map((p) => (+ <option key={p.id} value={p.id}>+ {`${p.name} · ${profileStatus(p).text}`}+ </option>+ ))}+ {profileId && !engineProfiles.some((p) => p.id === profileId) && (+ <option value={profileId}>Another engine's profile (cleared on save)</option>+ )}+ </select>+ <label className="mt-1.5 flex items-start gap-2 text-[11px] text-zinc-400">+ <input type="checkbox" checked={failover} onChange={(e) => setFailover(e.target.checked)} className="mt-0.5 accent-sky-500" />+ <span>Switch to the engine's next profile when this one runs out of usage or is signed out</span>+ </label>+ </div>+ )}+{mcpIds !== undefined && (<KwantToolsPicker model={model} selected={mcpIds} onChange={setMcpIds} onManageServers={onManageServers} />)}diff --git a/frontend/src/components/ProfilesModal.tsx b/frontend/src/components/ProfilesModal.tsxnew file mode 100644index 00000000..9b283872--- /dev/null+++ b/frontend/src/components/ProfilesModal.tsx@@ -0,0 +1,667 @@+import React, { useCallback, useEffect, useRef, useState } from 'react';+import {+ X,+ UserRound,+ Plus,+ Trash2,+ Pencil,+ Check,+ Star,+ KeyRound,+ LogIn,+ LogOut,+ Loader2,+ ExternalLink,+ Copy,+ RefreshCw,+} from 'lucide-react';+import { playSfx } from '../audio/chiptune';+import {+ ENGINES,+ Engine,+ KIND_LABELS,+ Login,+ Profile,+ isLoginDone,+ profileStatus,+ profilesApi,+ profilesForEngine,+ safeExternalUrl,+} from '../profiles';++interface ProfilesModalProps {+ isOpen: boolean;+ onClose: () => void;+ /** Called with the fresh list after every change, so kwant pickers stay current. */+ onProfilesChanged?: (profiles: Profile[]) => void;+}++const input =+ 'w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors';+const smallBtn =+ 'inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium border transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';+const quietBtn = `${smallBtn} border-zinc-700/70 bg-zinc-800/70 text-zinc-200 hover:bg-zinc-700`;+const toneClass = { ok: 'text-emerald-300', warn: 'text-amber-300', error: 'text-rose-300', muted: 'text-zinc-500' };+const dotClass = { ok: 'bg-emerald-400', warn: 'bg-amber-400', error: 'bg-rose-500', muted: 'bg-zinc-600' };++export const ProfilesModal: React.FC<ProfilesModalProps> = ({ isOpen, onClose, onProfilesChanged }) => {+ const [profiles, setProfiles] = useState<Profile[] | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [adding, setAdding] = useState<Engine | null>(null);+ const changedRef = useRef(onProfilesChanged);+ changedRef.current = onProfilesChanged;+ const closeRef = useRef(onClose);+ closeRef.current = onClose;++ const reload = useCallback(async () => {+ try {+ const list = await profilesApi.list();+ setProfiles(list);+ setLoadError(null);+ changedRef.current?.(list);+ } catch (e) {+ setLoadError(e instanceof Error ? e.message : 'Could not load profiles.');+ }+ }, []);++ useEffect(() => {+ if (!isOpen) return;+ setProfiles(null);+ setAdding(null);+ reload();+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') closeRef.current();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [isOpen, reload]);++ if (!isOpen) return null;++ return (+ <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-2 sm:p-4" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="profiles-title"+ className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-2xl w-full max-h-[94vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-5"+ >+ <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">+ <UserRound size={16} />+ </div>+ <div>+ <h2 id="profiles-title" className="text-sm font-semibold text-zinc-100">LLM profiles</h2>+ <p className="text-xs text-zinc-400">Accounts each engine can use, like a work and a personal subscription</p>+ </div>+ </div>+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ 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>++ <p className="text-[11px] text-zinc-500 leading-relaxed">+ Kwants use their engine's <span className="text-zinc-300">default</span> profile unless you pick one for them. When a profile runs out+ of usage or is signed out before anything happened in a turn, the turn moves to the next enabled profile (lowest priority number+ first).+ </p>++ {loadError && (+ <div className="flex items-center justify-between gap-2 bg-rose-500/10 border border-rose-500/20 text-rose-300 px-3 py-2 rounded-lg text-xs" role="alert">+ <span>{loadError}</span>+ <button type="button" onClick={reload} className={quietBtn}>+ <RefreshCw size={12} /> Retry+ </button>+ </div>+ )}++ {!profiles && !loadError && (+ <p className="flex items-center gap-2 text-xs text-zinc-400" role="status">+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" /> Loading profiles…+ </p>+ )}++ {profiles &&+ ENGINES.map((engine) => {+ const list = profilesForEngine(profiles, engine.id);+ return (+ <section key={engine.id} aria-labelledby={`engine-${engine.id}`} className="space-y-2">+ <div className="flex items-center justify-between">+ <h3 id={`engine-${engine.id}`} className="text-xs font-semibold text-zinc-300">+ {engine.label}+ </h3>+ {adding !== engine.id && (+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ setAdding(engine.id);+ }}+ className={quietBtn}+ >+ <Plus size={12} /> Add profile+ </button>+ )}+ </div>+ {list.length === 0 && adding !== engine.id && <p className="text-[11px] text-zinc-500">No profiles yet.</p>}+ <ul className="space-y-2">+ {list.map((p) => (+ <ProfileCard key={p.id} profile={p} onChanged={reload} />+ ))}+ </ul>+ {adding === engine.id && (+ <AddProfileForm+ engine={engine.id}+ onCancel={() => setAdding(null)}+ onCreated={async () => {+ setAdding(null);+ playSfx('coin');+ await reload();+ }}+ />+ )}+ </section>+ );+ })}+ </div>+ </div>+ );+};++const AddProfileForm: React.FC<{ engine: Engine; onCancel: () => void; onCreated: () => void }> = ({ engine, onCancel, onCreated }) => {+ const [name, setName] = useState('');+ const [kind, setKind] = useState<'cli_home' | 'api_key'>('cli_home');+ const [apiKey, setApiKey] = useState('');+ const [homeDir, setHomeDir] = useState('');+ const [isDefault, setIsDefault] = useState(false);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const id = `new-${engine}`;++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!name.trim()) return;+ setBusy(true);+ setError(null);+ try {+ await profilesApi.create({+ engine,+ name: name.trim(),+ kind,+ is_default: isDefault,+ ...(kind === 'api_key' && apiKey.trim() ? { api_key: apiKey.trim() } : {}),+ ...(kind === 'cli_home' && homeDir.trim() ? { home_dir: homeDir.trim() } : {}),+ });+ setApiKey('');+ onCreated();+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Could not create the profile.');+ } finally {+ setBusy(false);+ }+ };++ return (+ <form onSubmit={submit} className="bg-zinc-950/60 border border-sky-500/30 rounded-xl p-3 space-y-3">+ <div className="grid sm:grid-cols-2 gap-3">+ <div>+ <label htmlFor={`${id}-name`} className="block text-[11px] font-medium text-zinc-400 mb-1">+ Name+ </label>+ <input id={`${id}-name`} autoFocus required maxLength={60} value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Work" className={input} />+ </div>+ <fieldset>+ <legend className="block text-[11px] font-medium text-zinc-400 mb-1">Signs in with</legend>+ <div className="flex p-0.5 rounded-lg bg-zinc-950 border border-zinc-800">+ {(['cli_home', 'api_key'] as const).map((k) => (+ <label+ key={k}+ className={`flex-1 text-center px-2 py-1.5 rounded-md text-[11px] font-medium cursor-pointer transition-colors has-[:focus-visible]:outline has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-sky-500 ${+ kind === k ? 'bg-sky-500/15 text-sky-200' : 'text-zinc-500 hover:text-zinc-300'+ }`}+ >+ <input type="radio" name={`${id}-kind`} value={k} checked={kind === k} onChange={() => setKind(k)} className="sr-only" />+ {KIND_LABELS[k]}+ </label>+ ))}+ </div>+ </fieldset>+ </div>+ {kind === 'api_key' ? (+ <div>+ <label htmlFor={`${id}-key`} className="block text-[11px] font-medium text-zinc-400 mb-1">+ API key <span className="text-zinc-600 font-normal">· optional now, stored write-only</span>+ </label>+ <input id={`${id}-key`} type="password" autoComplete="off" spellCheck={false} value={apiKey} onChange={(e) => setApiKey(e.target.value)} className={input} />+ </div>+ ) : (+ <div>+ <label htmlFor={`${id}-home`} className="block text-[11px] font-medium text-zinc-400 mb-1">+ Config folder <span className="text-zinc-600 font-normal">· optional; empty keeps a private one kwnt manages</span>+ </label>+ <input id={`${id}-home`} value={homeDir} onChange={(e) => setHomeDir(e.target.value)} placeholder="/home/me/.claude-work" className={`${input} font-mono`} />+ <p className="mt-1 text-[11px] text-zinc-500">After creating it, use “Sign in” to log this profile into its own account.</p>+ </div>+ )}+ <label className="flex items-center gap-2 text-[11px] text-zinc-300">+ <input type="checkbox" checked={isDefault} onChange={(e) => setIsDefault(e.target.checked)} className="accent-sky-500" />+ Make it the default for this engine+ </label>+ {error && <p className="text-[11px] text-rose-400" role="alert">{error}</p>}+ <div className="flex justify-end gap-2">+ <button type="button" onClick={onCancel} className="px-3 py-1.5 rounded-lg text-xs font-medium text-zinc-300 hover:bg-zinc-800 transition-colors">+ Cancel+ </button>+ <button+ type="submit"+ disabled={busy || !name.trim()}+ className="inline-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"+ >+ {busy && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" />} Create profile+ </button>+ </div>+ </form>+ );+};++const ProfileCard: React.FC<{ profile: Profile; onChanged: () => Promise<void> }> = ({ profile: p, onChanged }) => {+ const [editingName, setEditingName] = useState(false);+ const [name, setName] = useState(p.name);+ const [priority, setPriority] = useState(String(p.priority));+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [confirmDelete, setConfirmDelete] = useState(false);+ const [keyOpen, setKeyOpen] = useState(false);+ const [keyValue, setKeyValue] = useState('');+ const [login, setLogin] = useState<Login | null>(null);+ const status = profileStatus(p);+ const isSystem = p.kind === 'system';++ useEffect(() => setName(p.name), [p.name]);+ useEffect(() => setPriority(String(p.priority)), [p.priority]);++ const run = async (action: () => Promise<unknown>, after?: () => void) => {+ setBusy(true);+ setError(null);+ try {+ await action();+ after?.();+ await onChanged();+ } catch (e) {+ setError(e instanceof Error ? e.message : 'That didn’t work.');+ } finally {+ setBusy(false);+ }+ };++ const saveName = () => {+ const next = name.trim();+ if (!next || next === p.name) {+ setName(p.name);+ setEditingName(false);+ return;+ }+ run(() => profilesApi.update(p.id, { name: next }), () => setEditingName(false));+ };++ const savePriority = () => {+ const n = Number.parseInt(priority, 10);+ if (!Number.isFinite(n) || n === p.priority) {+ setPriority(String(p.priority));+ return;+ }+ run(() => profilesApi.update(p.id, { priority: Math.min(10000, Math.max(0, n)) }));+ };++ return (+ <li className={`rounded-xl border p-3 space-y-2 ${p.enabled ? 'border-zinc-800 bg-zinc-950/60' : 'border-zinc-800/60 bg-zinc-950/30'}`}>+ <div className="flex flex-wrap items-center gap-2">+ {editingName ? (+ <form+ className="flex items-center gap-1.5"+ onSubmit={(e) => {+ e.preventDefault();+ saveName();+ }}+ >+ <label htmlFor={`name-${p.id}`} className="sr-only">+ Profile name+ </label>+ <input+ id={`name-${p.id}`}+ autoFocus+ maxLength={60}+ value={name}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ setName(p.name);+ setEditingName(false);+ }+ }}+ className={`${input} py-1 w-40`}+ />+ <button type="submit" disabled={busy} className={quietBtn} aria-label="Save name">+ <Check size={12} />+ </button>+ </form>+ ) : (+ <>+ <span className="text-xs font-semibold text-zinc-100 truncate max-w-[14rem]">{p.name}</span>+ <button type="button" onClick={() => setEditingName(true)} className="p-0.5 rounded text-zinc-500 hover:text-zinc-200" aria-label={`Rename ${p.name}`}>+ <Pencil size={11} />+ </button>+ </>+ )}+ <span className="px-1.5 py-0.5 rounded-md bg-zinc-800 text-[10px] text-zinc-400">{KIND_LABELS[p.kind]}</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">+ <Star size={9} /> Default+ </span>+ )}+ <span className={`ml-auto inline-flex items-center gap-1.5 text-[11px] ${toneClass[status.tone]}`}>+ <span className={`w-1.5 h-1.5 rounded-full ${dotClass[status.tone]}`} aria-hidden="true" />+ {status.text}+ </span>+ </div>++ {p.home_dir && <p className="text-[10px] font-mono text-zinc-600 truncate" title={p.home_dir}>{p.home_dir}</p>}++ <div className="flex flex-wrap items-center gap-2">+ <label className="inline-flex items-center gap-1.5 text-[11px] text-zinc-400">+ <input+ type="checkbox"+ checked={p.enabled}+ disabled={busy}+ onChange={(e) => run(() => profilesApi.update(p.id, { enabled: e.target.checked }))}+ className="accent-sky-500"+ />+ Enabled+ </label>+ <label className="inline-flex items-center gap-1 text-[11px] text-zinc-400">+ Priority+ <input+ type="number"+ min={0}+ max={10000}+ value={priority}+ disabled={busy}+ onChange={(e) => setPriority(e.target.value)}+ onBlur={savePriority}+ 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"+ />+ </label>+ <div className="ml-auto flex flex-wrap items-center gap-1.5">+ {!p.is_default && (+ <button type="button" disabled={busy} onClick={() => run(() => profilesApi.update(p.id, { is_default: true }))} className={quietBtn}>+ <Star size={11} /> Make default+ </button>+ )}+ {p.kind === 'cli_home' && !login && (+ <button type="button" disabled={busy} onClick={() => run(async () => setLogin(await profilesApi.startLogin(p.id)))} className={quietBtn}>+ <LogIn size={11} /> {p.signed_in ? 'Sign in again' : 'Sign in'}+ </button>+ )}+ {p.kind === 'cli_home' && p.signed_in && (+ <button type="button" disabled={busy} onClick={() => run(() => profilesApi.logout(p.id))} className={quietBtn}>+ <LogOut size={11} /> Sign out+ </button>+ )}+ {p.kind === 'api_key' && (+ <button type="button" disabled={busy} onClick={() => setKeyOpen((v) => !v)} className={quietBtn} aria-expanded={keyOpen}>+ <KeyRound size={11} /> {p.has_key ? 'Replace key' : 'Set key'}+ </button>+ )}+ {p.kind === 'api_key' && p.has_key && (+ <button type="button" disabled={busy} onClick={() => run(() => profilesApi.removeKey(p.id))} className={quietBtn}>+ Remove key+ </button>+ )}+ {!isSystem &&+ (confirmDelete ? (+ <span className="inline-flex items-center gap-1">+ <span className="text-[11px] text-rose-300">Delete?</span>+ <button+ type="button"+ disabled={busy}+ onClick={() => run(() => profilesApi.remove(p.id))}+ className={`${smallBtn} border-rose-500/40 bg-rose-500/15 text-rose-200 hover:bg-rose-500/25`}+ >+ Delete+ </button>+ <button type="button" onClick={() => setConfirmDelete(false)} className={quietBtn}>+ Keep+ </button>+ </span>+ ) : (+ <button type="button" disabled={busy} onClick={() => setConfirmDelete(true)} className={`${quietBtn} hover:text-rose-200`} aria-label={`Delete ${p.name}`}>+ <Trash2 size={11} />+ </button>+ ))}+ </div>+ </div>++ {confirmDelete && <p className="text-[11px] text-zinc-500">Kwants pinned to it go back to the default. Its folder stays on disk.</p>}++ {keyOpen && p.kind === 'api_key' && (+ <form+ className="flex items-center gap-1.5"+ onSubmit={(e) => {+ e.preventDefault();+ const k = keyValue.trim();+ if (!k) return;+ run(+ () => profilesApi.setKey(p.id, k),+ () => {+ setKeyValue('');+ setKeyOpen(false);+ },+ );+ }}+ >+ <label htmlFor={`key-${p.id}`} className="sr-only">+ API key for {p.name}+ </label>+ <input+ id={`key-${p.id}`}+ type="password"+ autoComplete="off"+ spellCheck={false}+ autoFocus+ value={keyValue}+ onChange={(e) => setKeyValue(e.target.value)}+ placeholder="Paste the key (it can't be shown again)"+ className={`${input} py-1`}+ />+ <button type="submit" disabled={busy || !keyValue.trim()} className={`${smallBtn} border-sky-500/40 bg-sky-600 text-white hover:bg-sky-500`}>+ Save+ </button>+ </form>+ )}++ {login && (+ <LoginPanel+ profileId={p.id}+ login={login}+ onUpdate={setLogin}+ onDone={async (succeeded) => {+ setLogin(null);+ if (succeeded) playSfx('coin');+ await onChanged();+ }}+ />+ )}++ {error && <p className="text-[11px] text-rose-400" role="alert">{error}</p>}+ </li>+ );+};++const LOGIN_POLL_MS = 1500;++const LoginPanel: React.FC<{+ profileId: string;+ login: Login;+ onUpdate: (l: Login) => void;+ onDone: (succeeded: boolean) => void;+}> = ({ profileId, login, onUpdate, onDone }) => {+ const [code, setCode] = useState('');+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [copied, setCopied] = useState(false);+ const done = isLoginDone(login.status);+ const url = safeExternalUrl(login.url);+ const finished = useRef(false);+ const finish = (succeeded: boolean) => {+ if (finished.current) return;+ finished.current = true;+ onDone(succeeded);+ };++ // Poll while the CLI is still waiting; stops on any final state and when the panel closes.+ useEffect(() => {+ if (done) return;+ let cancelled = false;+ const t = setTimeout(async () => {+ try {+ const next = await profilesApi.getLogin(profileId, login.flow_id);+ if (!cancelled) onUpdate(next);+ } catch (e) {+ if (!cancelled) setError(e instanceof Error ? e.message : 'Lost track of the sign-in.');+ }+ }, LOGIN_POLL_MS);+ return () => {+ cancelled = true;+ clearTimeout(t);+ };+ }, [login, done, profileId, onUpdate]);++ useEffect(() => {+ if (login.status === 'succeeded') finish(true);+ }, [login.status]);++ const cancel = async () => {+ setBusy(true);+ try {+ if (!done) await profilesApi.cancelLogin(profileId, login.flow_id);+ } catch {+ // already finished on the server+ } finally {+ setBusy(false);+ finish(false);+ }+ };++ const submitCode = async (e: React.FormEvent) => {+ e.preventDefault();+ const c = code.trim();+ if (!c) return;+ setBusy(true);+ setError(null);+ try {+ onUpdate(await profilesApi.submitCode(profileId, login.flow_id, c));+ setCode('');+ } catch (err) {+ setError(err instanceof Error ? err.message : 'The code was not accepted.');+ } finally {+ setBusy(false);+ }+ };++ const failure =+ login.status === 'failed'+ ? login.error || 'Sign-in failed.'+ : login.status === 'expired'+ ? 'The sign-in expired. Start it again.'+ : login.status === 'cancelled'+ ? 'Sign-in cancelled.'+ : null;++ return (+ <div className="rounded-lg border border-sky-500/30 bg-sky-500/5 p-3 space-y-2.5" aria-live="polite">+ {login.status === 'starting' && (+ <p className="flex items-center gap-2 text-[11px] text-zinc-300">+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" /> Starting the sign-in…+ </p>+ )}+ {login.status === 'waiting' && (+ <>+ <ol className="list-decimal list-inside space-y-1 text-[11px] text-zinc-300">+ <li>+ {url ? (+ <a href={url} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-sky-300 underline underline-offset-2 hover:text-sky-200">+ Open the sign-in page <ExternalLink size={11} />+ </a>+ ) : (+ 'Waiting for the sign-in link…'+ )}{' '}+ and sign in with the account for this profile.+ </li>+ {login.user_code && (+ <li>+ Enter this code there:{' '}+ <span className="font-mono text-sm tracking-wider text-zinc-100 bg-zinc-950 border border-zinc-800 rounded px-1.5 py-0.5 select-all">{login.user_code}</span>{' '}+ <button+ type="button"+ onClick={async () => {+ try {+ await navigator.clipboard.writeText(login.user_code ?? '');+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ } catch {+ // clipboard blocked (http): the code is selectable+ }+ }}+ className="inline-flex items-center gap-0.5 text-[10px] text-zinc-400 hover:text-zinc-100"+ >+ <Copy size={10} /> {copied ? 'Copied' : 'Copy'}+ </button>+ </li>+ )}+ {login.needs_code && <li>Paste the code the page shows you:</li>}+ </ol>+ {login.needs_code && (+ <form onSubmit={submitCode} className="flex items-center gap-1.5">+ <label htmlFor={`code-${login.flow_id}`} className="sr-only">+ Code from the sign-in page+ </label>+ <input+ id={`code-${login.flow_id}`}+ autoComplete="off"+ spellCheck={false}+ value={code}+ onChange={(e) => setCode(e.target.value)}+ placeholder="Code"+ className={`${input} py-1 font-mono`}+ />+ <button type="submit" disabled={busy || !code.trim()} className={`${smallBtn} border-sky-500/40 bg-sky-600 text-white hover:bg-sky-500`}>+ Submit+ </button>+ </form>+ )}+ <p className="flex items-center gap-1.5 text-[10px] text-zinc-500">+ <Loader2 size={10} className="animate-spin motion-reduce:animate-none" /> Waiting for you to finish…+ </p>+ </>+ )}+ {failure && <p className="text-[11px] text-rose-300" role="alert">{failure}</p>}+ {error && <p className="text-[11px] text-rose-400" role="alert">{error}</p>}+ <div className="flex justify-end">+ <button type="button" disabled={busy} onClick={cancel} className={quietBtn}>+ {done ? 'Close' : 'Cancel sign-in'}+ </button>+ </div>+ </div>+ );+};diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex f9ec12a9..67e31e0d 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -1,6 +1,7 @@import React, { useState, useEffect } from 'react';-import { Cpu, Key, Globe, X, Sparkles, Check, Plug, ChevronRight } from 'lucide-react';+import { Cpu, Key, Globe, X, Sparkles, Check, Plug, ChevronRight, UserRound, LogOut } from 'lucide-react';import { playSfx } from '../audio/chiptune';+import { useAuth } from './AuthGate';interface SettingsData {anthropic_api_key: string;@@ -19,9 +20,11 @@ interface SettingsModalProps {isOpen: boolean;onClose: () => void;onOpenTools?: () => void;+ onOpenProfiles?: () => void;}-export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, onOpenTools }) => {+export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, onOpenTools, onOpenProfiles }) => {+ const { authRequired, signOut } = useAuth();const [settings, setSettings] = useState<SettingsData | null>(null);const [anthropicKey, setAnthropicKey] = useState('');const [xaiKey, setXaiKey] = useState('');@@ -145,6 +148,26 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o</div></div>+ {onOpenProfiles && (+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ onOpenProfiles();+ }}+ 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">+ <UserRound size={15} />+ </span>+ <span className="flex-1">+ <span className="block text-xs font-medium text-zinc-200">LLM profiles</span>+ <span className="block text-[11px] text-zinc-500">Work and personal accounts per engine, with automatic failover</span>+ </span>+ <ChevronRight size={15} className="text-zinc-500 group-hover:text-sky-300" />+ </button>+ )}+{onOpenTools && (<buttontype="button"@@ -235,6 +258,19 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o)}<div className="flex items-center justify-end gap-2.5 pt-2 border-t border-zinc-800">+ {authRequired && (+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ signOut();+ }}+ title="Forget the access token in this browser"+ className="mr-auto flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-zinc-400 hover:text-rose-200 hover:bg-zinc-800 transition-colors"+ >+ <LogOut size={13} /> Sign out+ </button>+ )}<buttontype="button"onClick={() => {diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 89c57201..ed651749 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -12,6 +12,10 @@ export interface Kwant {avatar_sprite: string;driver_type: string;preferred_model: string;+ /** Pinned LLM profile; null uses the engine's default. */+ profile_id?: string | null;+ /** Whether turns may move to the engine's next profile when this one is out of usage. */+ profile_failover?: boolean;}export interface Channel {@@ -266,7 +270,7 @@ export const Sidebar: React.FC<SidebarProps> = ({}`}title={`Chat with ${k.name}`}>- <ModernAvatar role={k.avatar_sprite} name={k.name} size={18} />+ <ModernAvatar role={k.avatar_sprite} name={k.name} size={18} kwantId={k.id} /><span className="truncate flex-1">{k.name}</span>{onEditKwant && (<button@@ -344,7 +348,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-zinc-300 hover:bg-sky-500/10 hover:text-zinc-100 text-left">- <ModernAvatar role={k.avatar_sprite} name={k.name} size={18} />+ <ModernAvatar role={k.avatar_sprite} name={k.name} size={18} kwantId={k.id} /><span className="truncate flex-1">{k.name}</span><span className="text-[10px] text-zinc-500 truncate max-w-[80px]">{k.title}</span></button>@@ -394,7 +398,7 @@ export const Sidebar: React.FC<SidebarProps> = ({{!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} />+ <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>@@ -424,6 +428,7 @@ export const Sidebar: React.FC<SidebarProps> = ({name={k.name}size={32}isOnline={true}+ kwantId={k.id}/><div className="flex-1 min-w-0"><div className="flex items-center justify-between gap-1">diff --git a/frontend/src/components/Toasts.tsx b/frontend/src/components/Toasts.tsxnew file mode 100644index 00000000..979eb668--- /dev/null+++ b/frontend/src/components/Toasts.tsx@@ -0,0 +1,47 @@+import React, { useEffect } from 'react';+import { ArrowRightLeft, X } from 'lucide-react';++export interface Toast {+ id: number;+ title: string;+ detail?: string;+}++const TOAST_MS = 7000;++const ToastItem: React.FC<{ toast: Toast; onDismiss: (id: number) => void }> = ({ toast, onDismiss }) => {+ useEffect(() => {+ const t = setTimeout(() => onDismiss(toast.id), TOAST_MS);+ return () => clearTimeout(t);+ }, [toast.id, onDismiss]);+ return (+ <div className="kw-toast pointer-events-auto flex items-start gap-2.5 w-full bg-zinc-900/95 border border-zinc-700 rounded-xl px-3 py-2.5 shadow-xl text-xs">+ <ArrowRightLeft size={14} className="mt-0.5 shrink-0 text-amber-300" aria-hidden="true" />+ <div className="flex-1 min-w-0">+ <p className="font-medium text-zinc-100">{toast.title}</p>+ {toast.detail && <p className="mt-0.5 text-zinc-400">{toast.detail}</p>}+ </div>+ <button+ type="button"+ onClick={() => onDismiss(toast.id)}+ aria-label="Dismiss"+ className="p-0.5 rounded text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 transition-colors"+ >+ <X size={13} />+ </button>+ </div>+ );+};++/** 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 }) => (+ <div+ role="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"+ >+ {toasts.map((t) => (+ <ToastItem key={t.id} toast={t} onDismiss={onDismiss} />+ ))}+ </div>+);diff --git a/frontend/src/kwantActivity.ts b/frontend/src/kwantActivity.tsnew file mode 100644index 00000000..57d7a70d--- /dev/null+++ b/frontend/src/kwantActivity.ts@@ -0,0 +1,51 @@+// Which kwants are working right now, from `turn_started` / `turn_ended` events. Avatars subscribe to+// their own kwant only, so a turn starting re-renders just the avatars of that kwant.++type Listener = () => void;++/** kwant id -> the contexts it's working in (a kwant can run in a DM and a team at once). */+const active = new Map<string, Set<string>>();+const listeners = new Map<string, Set<Listener>>();++const notify = (kwantId: string) => listeners.get(kwantId)?.forEach((l) => l());++const contextKey = (contextId: string | null | undefined) => contextId ?? '';++export function turnStarted(kwantId: string, contextId?: string | null): void {+ if (!kwantId) return;+ const set = active.get(kwantId) ?? new Set<string>();+ const before = set.size;+ set.add(contextKey(contextId));+ active.set(kwantId, set);+ if (before === 0) notify(kwantId);+}++/** Ends a turn whatever its outcome; an unknown context clears the kwant entirely. */+export function turnEnded(kwantId: string, contextId?: string | null): void {+ const set = active.get(kwantId);+ if (!set) return;+ if (!set.delete(contextKey(contextId))) set.clear();+ if (set.size === 0) {+ active.delete(kwantId);+ notify(kwantId);+ }+}++/** Forgets every turn, e.g. after the event stream reconnected and may have missed `turn_ended`. */+export function clearAllTurns(): void {+ const ids = Array.from(active.keys());+ active.clear();+ ids.forEach(notify);+}++export const isKwantWorking = (kwantId: string | undefined): boolean => !!kwantId && active.has(kwantId);++export function subscribeKwant(kwantId: string, listener: Listener): () => void {+ const set = listeners.get(kwantId) ?? new Set<Listener>();+ set.add(listener);+ listeners.set(kwantId, set);+ return () => {+ set.delete(listener);+ if (set.size === 0) listeners.delete(kwantId);+ };+}diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex 21e77e6c..44829c1a 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -2,12 +2,15 @@ import React from 'react';import ReactDOM from 'react-dom/client';import { App } from './App';import { SandboxViewer } from './components/SandboxViewer';+import { AuthGate } from './components/AuthGate';import './styles/modern.css';const sandboxMatch = window.location.pathname.match(/^\/sandbox\/([^/]+)\/?$/);ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode>- {sandboxMatch ? <SandboxViewer teamId={decodeURIComponent(sandboxMatch[1])} /> : <App />}+ <AuthGate>+ {sandboxMatch ? <SandboxViewer teamId={decodeURIComponent(sandboxMatch[1])} /> : <App />}+ </AuthGate></React.StrictMode>,);diff --git a/frontend/src/profiles.ts b/frontend/src/profiles.tsnew file mode 100644index 00000000..c43f4fe8--- /dev/null+++ b/frontend/src/profiles.ts@@ -0,0 +1,175 @@+// LLM profiles: one account per engine (a work and a personal Claude, say). Keys are write-only.++export type Engine = 'claude' | 'codex' | 'grok';+export type ProfileKind = 'system' | 'cli_home' | 'api_key';++export interface Profile {+ id: string;+ engine: Engine;+ name: string;+ kind: ProfileKind;+ enabled: boolean;+ is_default: boolean;+ priority: number;+ home_dir: string | null;+ has_key: boolean;+ /** null: couldn't tell (CLI missing). */+ signed_in: boolean | null;+ account_label: string | null;+ limited_until: string | null;+ last_error: 'quota' | 'auth' | null;+}++export type LoginStatus = 'starting' | 'waiting' | 'succeeded' | 'failed' | 'expired' | 'cancelled';++export interface Login {+ flow_id: string;+ profile_id: string;+ status: LoginStatus;+ url: string | null;+ user_code: string | null;+ needs_code: boolean;+ error: string | null;+ expires_at: string;+}++export const ENGINES: Array<{ id: Engine; label: string }> = [+ { id: 'claude', label: 'Claude' },+ { id: 'codex', label: 'Codex (OpenAI)' },+ { id: 'grok', label: 'Grok (xAI)' },+];++export const KIND_LABELS: Record<ProfileKind, string> = {+ system: 'This machine',+ cli_home: 'Subscription',+ api_key: 'API key',+};++/** The engine a kwant's model runs on, like the server's `Engine::from_model`; null for auto and Ollama. */+export function engineOfModel(model: string | null | undefined): Engine | null {+ if (!model) return null;+ if (model.includes('claude')) return 'claude';+ if (model.includes('grok')) return 'grok';+ if (model.includes('codex') || model.includes('gpt') || model.includes('openai')) return 'codex';+ return null;+}++/** An engine's profiles in the order turns try them: default first, then by priority. */+export function profilesForEngine(profiles: Profile[], engine: Engine | null): Profile[] {+ if (!engine) return [];+ return profiles+ .filter((p) => p.engine === engine)+ .sort((a, b) => Number(b.is_default) - Number(a.is_default) || a.priority - b.priority || a.name.localeCompare(b.name));+}++export const isLoginDone = (s: LoginStatus) => s !== 'starting' && s !== 'waiting';++/** Only https links are opened, so a bad value can't run script in this page. */+export function safeExternalUrl(url: string | null): string | null {+ if (!url) return null;+ try {+ const u = new URL(url);+ return u.protocol === 'https:' ? u.href : null;+ } catch {+ return null;+ }+}++/** A limit still in force, or null once it has passed. */+export function activeLimit(limitedUntil: string | null, now = Date.now()): Date | null {+ if (!limitedUntil) return null;+ const at = new Date(limitedUntil);+ return Number.isNaN(at.getTime()) || at.getTime() <= now ? null : at;+}++/** "in 45 min", "in 3 h", or a date when it's further away. */+export function formatUntil(at: Date, now = Date.now()): string {+ const mins = Math.max(1, Math.round((at.getTime() - now) / 60000));+ if (mins < 60) return `in ${mins} min`;+ const hours = Math.round(mins / 60);+ if (hours < 24) return `in ${hours} h`;+ return at.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });+}++/** Short status for a profile: what a person needs to know before relying on it. */+export function profileStatus(p: Profile, now = Date.now()): { tone: 'ok' | 'warn' | 'error' | 'muted'; text: string } {+ if (!p.enabled) return { tone: 'muted', text: 'Turned off' };+ const limit = activeLimit(p.limited_until, now);+ if (limit) return { tone: 'warn', text: `Out of usage · back ${formatUntil(limit, now)}` };+ if (p.last_error === 'auth') return { tone: 'error', text: 'Signed out · sign in again' };+ if (p.kind === 'api_key') return p.has_key ? { tone: 'ok', text: 'Key saved' } : { tone: 'error', text: 'No key yet' };+ if (p.signed_in === true) return { tone: 'ok', text: p.account_label ? `Signed in as ${p.account_label}` : 'Signed in' };+ if (p.signed_in === false) return { tone: 'error', text: 'Not signed in' };+ return { tone: 'muted', text: p.kind === 'system' ? 'Uses this machine’s login' : 'Sign-in unknown (CLI missing?)' };+}++async function request<T>(method: string, url: string, body?: unknown): Promise<T> {+ const res = await fetch(url, {+ method,+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+ if (!res.ok) {+ let message = `Request failed (HTTP ${res.status}).`;+ try {+ const data = await res.json();+ if (data && typeof data.error === 'string' && data.error) message = data.error;+ } catch {+ // no JSON body+ }+ if (res.status === 409 && message.startsWith('Request failed')) message = 'A profile with that name or folder already exists.';+ throw new Error(message);+ }+ if (res.status === 204) return undefined as T;+ return res.json();+}++const enc = encodeURIComponent;++export const profilesApi = {+ list: () => request<Profile[]>('GET', '/api/profiles'),+ create: (body: {+ engine: Engine;+ name: string;+ kind: 'cli_home' | 'api_key';+ home_dir?: string;+ priority?: number;+ enabled?: boolean;+ is_default?: boolean;+ api_key?: string;+ }) => request<Profile>('POST', '/api/profiles', body),+ update: (id: string, body: { name?: string; priority?: number; enabled?: boolean; is_default?: boolean }) =>+ request<Profile>('PATCH', `/api/profiles/${enc(id)}`, body),+ remove: (id: string) => request<void>('DELETE', `/api/profiles/${enc(id)}`),+ setKey: (id: string, apiKey: string) => request<void>('PUT', `/api/profiles/${enc(id)}/key`, { api_key: apiKey }),+ removeKey: (id: string) => request<void>('DELETE', `/api/profiles/${enc(id)}/key`),+ startLogin: (id: string) => request<Login>('POST', `/api/profiles/${enc(id)}/login`),+ getLogin: (id: string, flow: string) => request<Login>('GET', `/api/profiles/${enc(id)}/login/${enc(flow)}`),+ submitCode: (id: string, flow: string, code: string) =>+ request<Login>('POST', `/api/profiles/${enc(id)}/login/${enc(flow)}/code`, { code }),+ cancelLogin: (id: string, flow: string) => request<void>('DELETE', `/api/profiles/${enc(id)}/login/${enc(flow)}`),+ logout: (id: string) => request<void>('POST', `/api/profiles/${enc(id)}/logout`),+};++export interface ProfileSwitchedEvent {+ kwant_id: string;+ from_profile_id: string;+ from_name: string;+ to_profile_id: string;+ to_name: string;+ class: 'quota' | 'auth' | string;+ retry_at?: string;+}++/** Toast text for a `profile_switched` event. */+export function describeProfileSwitch(e: ProfileSwitchedEvent, kwantName: string | undefined, now = Date.now()) {+ const who = kwantName || 'A kwant';+ const limit = activeLimit(e.retry_at ?? null, now);+ const why =+ e.class === 'auth'+ ? `${e.from_name} is signed out.`+ : limit+ ? `${e.from_name} is out of usage until it resets ${formatUntil(limit, now)}.`+ : `${e.from_name} is out of usage.`;+ return { title: `${who} switched to ${e.to_name}`, detail: why };+}diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.cssindex 084ca26d..0ad7ac16 100644--- a/frontend/src/styles/modern.css+++ b/frontend/src/styles/modern.css@@ -55,3 +55,72 @@color: theme('colors.sky.300') !important;font-family: theme('fontFamily.mono') !important;}++/* Working kwant avatars: transform and opacity only, so it stays on the compositor. */+@keyframes kw-avatar-bob {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(-0.9px); }+}++@keyframes kw-avatar-ring {+ 0%, 100% { opacity: 0.35; transform: scale(1); }+ 50% { opacity: 0.95; transform: scale(1.07); }+}++@keyframes kw-avatar-pip {+ 0%, 100% { opacity: 0.4; transform: scale(0.8); }+ 50% { opacity: 1; transform: scale(1); }+}++.kw-avatar-working .kw-avatar-body {+ transform-box: fill-box;+ transform-origin: center bottom;+ animation: kw-avatar-bob 0.9s ease-in-out infinite;+}++.kw-avatar-ring {+ position: absolute;+ inset: -2px;+ border-radius: 30%;+ box-shadow: 0 0 0 1.5px theme('colors.sky.400'), 0 0 8px 1px rgb(56 189 248 / 0.55);+ pointer-events: none;+ animation: kw-avatar-ring 1.4s ease-in-out infinite;+}++.kw-avatar-pip {+ position: absolute;+ top: -2px;+ right: -2px;+ width: 30%;+ max-width: 8px;+ min-width: 4px;+ aspect-ratio: 1;+ border-radius: 9999px;+ background: theme('colors.sky.300');+ box-shadow: 0 0 0 1.5px theme('colors.zinc.950');+ pointer-events: none;+ animation: kw-avatar-pip 0.7s ease-in-out infinite;+}++@media (prefers-reduced-motion: reduce) {+ .kw-avatar-working .kw-avatar-body,+ .kw-avatar-ring,+ .kw-avatar-pip {+ animation: none;+ }+ .kw-avatar-ring { opacity: 0.9; }+}++/* Toasts slide in; without motion they just appear. */+@keyframes kw-toast-in {+ from { opacity: 0; transform: translateY(8px); }+ to { opacity: 1; transform: translateY(0); }+}++.kw-toast {+ animation: kw-toast-in 0.18s ease-out;+}++@media (prefers-reduced-motion: reduce) {+ .kw-toast { animation: none; }+}diff --git a/frontend/tests/profiles.test.mjs b/frontend/tests/profiles.test.mjsnew file mode 100644index 00000000..c1ca408a--- /dev/null+++ b/frontend/tests/profiles.test.mjs@@ -0,0 +1,107 @@+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import test from 'node:test';+import ts from 'typescript';++const load = async (path) => {+ const source = await readFile(new URL(path, import.meta.url), 'utf8');+ const { outputText } = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext } });+ return import(`data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`);+};++const profiles = await load('../src/profiles.ts');+const auth = await load('../src/auth.ts');+const activity = await load('../src/kwantActivity.ts');++const profile = (over) => ({+ id: 'prf_x', engine: 'claude', name: 'Work', kind: 'cli_home', enabled: true, is_default: false, priority: 100,+ home_dir: null, has_key: false, signed_in: true, account_label: null, limited_until: null, last_error: null, ...over,+});++test('maps models to engines like the server', () => {+ const { engineOfModel } = profiles;+ assert.equal(engineOfModel('claude'), 'claude');+ assert.equal(engineOfModel('claude-opus-5-5'), 'claude');+ assert.equal(engineOfModel('grok-beta'), 'grok');+ assert.equal(engineOfModel('gpt-5'), 'codex');+ assert.equal(engineOfModel('codex'), 'codex');+ assert.equal(engineOfModel('auto'), null);+ assert.equal(engineOfModel('local_ollama'), null);+});++test('lists an engine default first, then by ascending priority', () => {+ const list = [+ profile({ id: 'a', priority: 50 }),+ profile({ id: 'b', priority: 10 }),+ profile({ id: 'sys', kind: 'system', is_default: true, priority: 100 }),+ profile({ id: 'g', engine: 'grok' }),+ ];+ assert.deepEqual(profiles.profilesForEngine(list, 'claude').map((p) => p.id), ['sys', 'b', 'a']);+ assert.deepEqual(profiles.profilesForEngine(list, null), []);+});++test('status explains usage limits, sign-in and keys without showing secrets', () => {+ const now = Date.parse('2026-10-16T12:00:00Z');+ const { profileStatus } = profiles;+ assert.deepEqual(profileStatus(profile({ limited_until: '2026-10-16T12:45:00Z' }), now), { tone: 'warn', text: 'Out of usage · back in 45 min' });+ assert.equal(profileStatus(profile({ limited_until: '2026-10-16T11:00:00Z', account_label: '[email protected]' }), now).text, 'Signed in as [email protected]');+ assert.equal(profileStatus(profile({ last_error: 'auth' }), now).tone, 'error');+ assert.equal(profileStatus(profile({ kind: 'api_key', has_key: false }), now).text, 'No key yet');+ assert.equal(profileStatus(profile({ kind: 'api_key', has_key: true }), now).text, 'Key saved');+ assert.equal(profileStatus(profile({ enabled: false, last_error: 'quota' }), now).text, 'Turned off');+ assert.equal(profileStatus(profile({ signed_in: null, kind: 'system' }), now).tone, 'muted');+});++test('only opens https sign-in links', () => {+ assert.equal(profiles.safeExternalUrl('https://claude.ai/oauth/authorize?x=1'), 'https://claude.ai/oauth/authorize?x=1');+ assert.equal(profiles.safeExternalUrl('javascript:alert(1)'), null);+ assert.equal(profiles.safeExternalUrl('http://evil.example'), null);+ assert.equal(profiles.safeExternalUrl(null), null);+});++test('describes a profile switch for the toast', () => {+ const now = Date.parse('2026-10-16T12:00:00Z');+ const ev = { kwant_id: 'k', from_profile_id: 'a', from_name: 'Work', to_profile_id: 'b', to_name: 'Personal', class: 'quota', retry_at: '2026-10-16T14:00:00Z' };+ assert.deepEqual(profiles.describeProfileSwitch(ev, 'Ada', now), { title: 'Ada switched to Personal', detail: 'Work is out of usage until it resets in 2 h.' });+ assert.equal(profiles.describeProfileSwitch({ ...ev, class: 'auth' }, undefined, now).detail, 'Work is signed out.');+});++test('takes the token from the link and keeps other fragment parts', () => {+ const { extractHashToken } = auth;+ assert.deepEqual(extractHashToken('#kwnt_token=abc123'), { token: 'abc123', rest: '' });+ assert.deepEqual(extractHashToken('#tab=x&kwnt_token=a%2Bb'), { token: 'a+b', rest: '#tab=x' });+ assert.deepEqual(extractHashToken('#section'), { token: null, rest: '#section' });+ assert.deepEqual(extractHashToken(''), { token: null, rest: '' });+});++test('only same-origin /api calls outside /api/auth count as missing the token', () => {+ const o = 'http://127.0.0.1:8799';+ assert.equal(auth.isGuardedApiUrl('/api/kwants', o), true);+ assert.equal(auth.isGuardedApiUrl(`${o}/api/profiles/x`, o), true);+ assert.equal(auth.isGuardedApiUrl('/api/auth/session', o), false);+ assert.equal(auth.isGuardedApiUrl('https://other.example/api/kwants', o), false);+ assert.equal(auth.isGuardedApiUrl('/apiary', o), false);+});++test('a kwant works until every turn it started has ended, whatever the outcome', () => {+ const seen = [];+ const off = activity.subscribeKwant('k1', () => seen.push(activity.isKwantWorking('k1')));+ activity.turnStarted('k1', 'dm');+ activity.turnStarted('k1', 'team');+ assert.equal(activity.isKwantWorking('k1'), true);+ activity.turnEnded('k1', 'dm');+ assert.equal(activity.isKwantWorking('k1'), true);+ activity.turnEnded('k1', 'team');+ assert.equal(activity.isKwantWorking('k1'), false);+ // An end for a context we never saw still stops the animation.+ activity.turnStarted('k1', null);+ activity.turnEnded('k1', 'unknown');+ assert.equal(activity.isKwantWorking('k1'), false);+ activity.turnStarted('k1', 'x');+ activity.clearAllTurns();+ assert.equal(activity.isKwantWorking('k1'), false);+ off();+ activity.turnStarted('k1', 'y');+ activity.turnEnded('k1', 'y');+ assert.deepEqual(seen, [true, false, true, false, true, false]);+});