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
Approvals switch UI: space setting with a plain confirm, per-bot override, "Approvals off" markers
Lin (kwant bot)92d50af0382a
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 7773161a..bcf4ce8b 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -5,6 +5,8 @@ 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 { ApprovalsOffBadge } from './components/ApprovalsSetting';+import { approvalsOff } from './approvalMode';import { QuestionCard } from './components/QuestionCard';import { McpSuggestionCard } from './components/McpSuggestionCard';import { Suggestion, SuggestionMeta, applySuggestion, suggestionsApi } from './mcpSuggestions';@@ -2142,6 +2144,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({) : null;const pendingSkillCounts = pendingByKwant(pendingSkills);const pendingHere = currentKwant ? pendingSkillCounts[currentKwant.id] ?? 0 : 0;+ const approvalsBadge = approvalsOff(currentKwant) ? (+ <ApprovalsOffBadge onClick={() => currentKwant && openAgentSettings(currentKwant)} title={`${currentKwant?.name} runs commands, file writes and tools without asking. Open its settings to change it.`} />+ ) : null;const skillsBadge =currentKwant && pendingHere > 0 ? (<button@@ -2485,8 +2490,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({onOpenAccounts={openSettings}canRun={canRun}titleExtra={- workingBadge || skillsBadge ? (+ workingBadge || skillsBadge || approvalsBadge ? (<>+ {approvalsBadge}{workingBadge}{skillsBadge}</>@@ -2621,6 +2627,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({onClose={() => setEditingKwant(null)}onSubmit={(data) => (editingKwant ? handleUpdateAgent(editingKwant, data) : undefined)}onRequestDelete={editingKwant ? () => setDeletingKwant(editingKwant) : undefined}+ onApprovalsChanged={refreshRoster}/>{deletingKwant && (@@ -2680,6 +2687,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({onOpenTools={() => setIsMcpOpen(true)}onOpenAppSettings={onOpenAppSettings}routineFocus={routineFocus}+ onApprovalsChanged={refreshRoster}onImported={() => {// New bots, teams and their team chats.refreshRoster();diff --git a/frontend/src/approvalMode.ts b/frontend/src/approvalMode.tsnew file mode 100644index 00000000..ac81c62c--- /dev/null+++ b/frontend/src/approvalMode.ts@@ -0,0 +1,123 @@+// The person's approvals switch: "ask" (a card before a bot's tool runs) or "off" (it runs and is+// recorded). Set per space, with a per-bot override. Only the person changes it; a bot's token+// gets 403. No event fires on a change, so callers load bots and spaces again after a save.++export type SpaceApprovals = 'ask' | 'off';+export type BotApprovals = 'inherit' | 'ask' | 'off';++/** GET/PUT /api/kwants/:id/approvals */+export interface BotApprovalsState {+ kwant_id: string;+ approvals: BotApprovals;+ approvals_effective: SpaceApprovals;+ space_approvals: SpaceApprovals;+}++const spaceMode = (v: unknown): SpaceApprovals => (v === 'off' ? 'off' : 'ask');+const botMode = (v: unknown): BotApprovals => (v === 'off' || v === 'ask' ? v : 'inherit');++/** True when this bot runs everything without asking. Older servers send nothing: that's "ask". */+export const approvalsOff = (k: { approvals_effective?: string | null } | null | undefined): boolean => k?.approvals_effective === 'off';++/** What a bot's setting comes to: its own choice, else the space's. */+export const effectiveApprovals = (bot: BotApprovals, space: SpaceApprovals): SpaceApprovals => (bot === 'inherit' ? space : bot);++export function parseBotApprovals(raw: unknown): BotApprovalsState | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const o = raw as Record<string, unknown>;+ if (typeof o.kwant_id !== 'string') return null;+ const approvals = botMode(o.approvals);+ const space = spaceMode(o.space_approvals);+ return {+ kwant_id: o.kwant_id,+ approvals,+ space_approvals: space,+ approvals_effective: o.approvals_effective === 'off' || o.approvals_effective === 'ask' ? o.approvals_effective : effectiveApprovals(approvals, space),+ };+}++export const SPACE_OPTIONS: Array<{ value: SpaceApprovals; label: string; hint: string }> = [+ { value: 'ask', label: 'Ask before running commands', hint: 'A card asks you before a bot runs a command, writes a file or uses a tool.' },+ { value: 'off', label: 'Don’t ask', hint: 'Bots run everything without approval.' },+];++/** The per-bot choices; "Same as space" names what the space is set to. */+export function botOptions(space: SpaceApprovals): Array<{ value: BotApprovals; label: string }> {+ return [+ { value: 'inherit', label: `Same as space (${space === 'off' ? 'Don’t ask' : 'Ask'})` },+ { value: 'ask', label: 'Ask before running commands' },+ { value: 'off', label: 'Don’t ask' },+ ];+}++/** What turning approvals off means, said plainly on the confirm. */+export const OFF_CONSEQUENCES = [+ 'Shell commands run without asking you.',+ 'Files can be written or deleted anywhere the computer allows, not just in the bot’s folder.',+ 'Tools (MCP servers, browser, web) run without asking.',+ 'No approval cards appear. Everything that runs is still recorded.',+];++export function offConfirmTitle(who: { space: string } | { bot: string }): string {+ return 'space' in who ? `Turn off approvals for every bot in ${who.space}?` : `Let ${who.bot} run everything without approval?`;+}++/** A line for the space header: null when nothing runs without asking. */+export function spaceOffLine(space: SpaceApprovals | undefined, bots: Array<{ approvals_effective?: string | null }>): string | null {+ if (space === 'off') {+ const asking = bots.filter((b) => b.approvals_effective === 'ask').length;+ return asking ? `Approvals off (${asking} ${asking === 1 ? 'bot still asks' : 'bots still ask'})` : 'Approvals off';+ }+ const off = bots.filter(approvalsOff).length;+ return off ? `Approvals off for ${off} ${off === 1 ? 'bot' : 'bots'}` : null;+}++async function errorText(res: Response, fallback: string): Promise<string> {+ try {+ const body = await res.json();+ if (typeof body?.error === 'string' && body.error) {+ if (res.status === 403) return 'Only you can change approvals, from the app.';+ if (res.status === 409) return 'This space is archived. Restore it to change its approvals.';+ return `${fallback} (${body.error}).`;+ }+ } catch {+ /* not JSON */+ }+ if (res.status === 404 || res.status === 405) return 'This server can’t change approvals yet. Update the app and try again.';+ return `${fallback} (HTTP ${res.status}).`;+}++async function put(url: string, approvals: string, fallback: string): Promise<unknown> {+ let res: Response;+ try {+ res = await fetch(url, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ approvals }) });+ } catch {+ throw new Error('Couldn’t reach the server. Check your connection and try again.');+ }+ if (!res.ok) throw new Error(await errorText(res, fallback));+ return res.json();+}++const enc = encodeURIComponent;++export const approvalModeApi = {+ /** Resolves to the space's new value. */+ setSpace: async (spaceId: string, approvals: SpaceApprovals): Promise<SpaceApprovals> => {+ const body = (await put(`/api/spaces/${enc(spaceId)}/approvals`, approvals, 'Couldn’t change approvals')) as { approvals?: unknown };+ return spaceMode(body?.approvals);+ },+ /** null when the server has no such endpoint or the call fails. */+ bot: async (kwantId: string): Promise<BotApprovalsState | null> => {+ try {+ const res = await fetch(`/api/kwants/${enc(kwantId)}/approvals`, { cache: 'no-store' });+ return res.ok ? parseBotApprovals(await res.json()) : null;+ } catch {+ return null;+ }+ },+ setBot: async (kwantId: string, approvals: BotApprovals): Promise<BotApprovalsState> => {+ const state = parseBotApprovals(await put(`/api/kwants/${enc(kwantId)}/approvals`, approvals, 'Couldn’t change this bot’s approvals'));+ if (!state) throw new Error('The server sent an answer the app can’t read. Reload and check the setting.');+ return state;+ },+};diff --git a/frontend/src/components/ApprovalsSetting.tsx b/frontend/src/components/ApprovalsSetting.tsxnew file mode 100644index 00000000..5a332e6d--- /dev/null+++ b/frontend/src/components/ApprovalsSetting.tsx@@ -0,0 +1,254 @@+// The approvals switch: the space's setting, a bot's override, and the marker shown wherever a+// bot runs without asking. The marker always has an icon and words, never colour alone.++import React, { useEffect, useId, useState } from 'react';+import { AlertTriangle, Loader2, ShieldCheck, ShieldOff } from 'lucide-react';+import {+ BotApprovals,+ BotApprovalsState,+ OFF_CONSEQUENCES,+ SPACE_OPTIONS,+ SpaceApprovals,+ approvalModeApi,+ botOptions,+ effectiveApprovals,+ offConfirmTitle,+} from '../approvalMode';++/** "Approvals off": in a chat header (full) or a sidebar row (icon, with the words for screen readers). */+export const ApprovalsOffBadge: React.FC<{ compact?: boolean; onClick?: () => void; title?: string }> = ({ compact, onClick, title }) => {+ const tip = title ?? 'Approvals are off: this bot runs commands, file writes and tools without asking.';+ if (compact) {+ return (+ <span className="shrink-0 inline-flex items-center text-amber-300" title={tip}>+ <ShieldOff size={11} aria-hidden="true" />+ <span className="sr-only">Approvals off</span>+ </span>+ );+ }+ const cls =+ 'inline-flex items-center gap-1 shrink-0 px-2 py-0.5 rounded-full border border-amber-500/40 bg-amber-500/10 text-[11px] font-medium text-amber-200';+ const body = (+ <>+ <ShieldOff size={11} aria-hidden="true" />+ Approvals off+ </>+ );+ return onClick ? (+ <button type="button" onClick={onClick} title={tip} className={`${cls} hover:bg-amber-500/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400`}>+ {body}+ </button>+ ) : (+ <span className={cls} title={tip}>+ {body}+ </span>+ );+};++/** The plain-words confirm before anything runs without asking. */+export const OffConfirm: React.FC<{ title: string; busy: boolean; onCancel: () => void; onConfirm: () => void }> = ({ title, busy, onCancel, onConfirm }) => {+ const id = useId();+ return (+ <div role="alertdialog" aria-labelledby={`${id}-t`} aria-describedby={`${id}-d`} className="rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 space-y-2.5">+ <p id={`${id}-t`} className="flex items-center gap-2 text-xs font-semibold text-amber-100">+ <AlertTriangle size={14} aria-hidden="true" /> {title}+ </p>+ <ul id={`${id}-d`} className="list-disc pl-5 space-y-1 text-[11px] text-amber-100/90">+ {OFF_CONSEQUENCES.map((l) => (+ <li key={l}>{l}</li>+ ))}+ </ul>+ <p className="text-[11px] text-amber-100/80">Bots can’t change this. You can turn approvals back on here at any time.</p>+ <div className="flex flex-wrap gap-2">+ <button+ type="button"+ onClick={onCancel}+ autoFocus+ className="px-3 py-1.5 rounded-lg text-xs font-medium text-zinc-200 border border-zinc-700/60 bg-zinc-800/60 hover:bg-zinc-700/70"+ >+ Keep asking+ </button>+ <button+ type="button"+ onClick={onConfirm}+ disabled={busy}+ 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"+ >+ {busy && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}+ Turn approvals off+ </button>+ </div>+ </div>+ );+};++const radioCls = (on: boolean) =>+ `flex items-start gap-2.5 p-2.5 rounded-lg border cursor-pointer transition-colors ${on ? 'border-sky-500/60 bg-sky-500/10' : 'border-zinc-800 hover:border-zinc-700'}`;++/** Space settings: Ask (default) / Don't ask. Ask saves at once; Don't ask needs the confirm. */+export const SpaceApprovalsSetting: React.FC<{+ spaceId: string;+ spaceName: string;+ value: SpaceApprovals;+ /** Bots in the space that override it, so the person knows who won't follow. */+ overrides?: { ask: string[]; off: string[] };+ onChanged: (v: SpaceApprovals) => void;+ /** Tests open it with the confirm showing. */+ initialConfirm?: boolean;+}> = ({ spaceId, spaceName, value, overrides, onChanged, initialConfirm = false }) => {+ const [current, setCurrent] = useState<SpaceApprovals>(value);+ const [confirming, setConfirming] = useState(initialConfirm);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => setCurrent(value), [value]);++ const save = async (v: SpaceApprovals) => {+ setBusy(true);+ setError(null);+ try {+ const next = await approvalModeApi.setSpace(spaceId, v);+ setCurrent(next);+ setConfirming(false);+ onChanged(next);+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Couldn’t change approvals.');+ } finally {+ setBusy(false);+ }+ };+ const pick = (v: SpaceApprovals) => {+ if (v === current || busy) return;+ if (v === 'off') setConfirming(true);+ else save(v);+ };+ const exceptions = current === 'off' ? overrides?.ask ?? [] : overrides?.off ?? [];++ return (+ <div className="rounded-xl border border-zinc-800 bg-zinc-950/60 p-4 space-y-3">+ <p className="flex items-center gap-2 text-xs font-medium text-zinc-200">+ {current === 'off' ? <ShieldOff size={14} className="text-amber-300" aria-hidden="true" /> : <ShieldCheck size={14} className="text-zinc-400" aria-hidden="true" />}+ Approvals+ {current === 'off' && <ApprovalsOffBadge title={`Approvals are off in ${spaceName}.`} />}+ </p>+ <div role="radiogroup" aria-label={`Approvals in ${spaceName}`} className="space-y-1.5">+ {SPACE_OPTIONS.map((o) => (+ <label key={o.value} className={radioCls(current === o.value)}>+ <input+ type="radio"+ name={`approvals-${spaceId}`}+ value={o.value}+ checked={current === o.value}+ disabled={busy}+ onChange={() => pick(o.value)}+ className="mt-0.5 accent-sky-500"+ />+ <span className="min-w-0">+ <span className="block text-xs font-medium text-zinc-200">+ {o.label}+ {o.value === 'ask' && <span className="ml-1 text-zinc-500 font-normal">(default)</span>}+ </span>+ <span className="block text-[11px] text-zinc-500">{o.hint}</span>+ </span>+ </label>+ ))}+ </div>+ {confirming && <OffConfirm title={offConfirmTitle({ space: spaceName })} busy={busy} onCancel={() => setConfirming(false)} onConfirm={() => save('off')} />}+ {exceptions.length > 0 && !confirming && (+ <p className="text-[11px] text-zinc-500">+ {current === 'off' ? 'Still asks, set on the bot: ' : 'Runs without asking, set on the bot: '}+ {exceptions.join(', ')}.+ </p>+ )}+ {busy && !confirming && (+ <p role="status" className="text-[11px] text-zinc-400">+ Saving…+ </p>+ )}+ {error && (+ <p role="alert" className="flex items-center gap-2 text-[11px] text-rose-300">+ <AlertTriangle size={12} aria-hidden="true" /> {error}+ </p>+ )}+ </div>+ );+};++/** A bot's override, in its settings. Loads its own state; saves on change, with the confirm when it turns off. */+export const BotApprovalsSetting: React.FC<{+ kwantId: string;+ kwantName: string;+ onChanged?: (s: BotApprovalsState) => void;+ /** Tests pass the loaded state instead of fetching it. */+ initial?: BotApprovalsState | null;+}> = ({ kwantId, kwantName, onChanged, initial }) => {+ const [state, setState] = useState<BotApprovalsState | null | undefined>(initial === undefined ? undefined : initial);+ const [pending, setPending] = useState<BotApprovals | null>(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const selectId = useId();++ useEffect(() => {+ if (initial !== undefined) return;+ let live = true;+ setState(undefined);+ approvalModeApi.bot(kwantId).then((s) => live && setState(s));+ return () => {+ live = false;+ };+ }, [kwantId, initial]);++ if (state === undefined) return <p className="text-[11px] text-zinc-500">Loading approvals…</p>;+ // An older server without the switch: show nothing rather than a control that can't save.+ if (state === null) return null;++ const save = async (v: BotApprovals) => {+ setBusy(true);+ setError(null);+ try {+ const next = await approvalModeApi.setBot(kwantId, v);+ setState(next);+ setPending(null);+ onChanged?.(next);+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Couldn’t change this bot’s approvals.');+ } finally {+ setBusy(false);+ }+ };+ const pick = (v: BotApprovals) => {+ if (v === state.approvals || busy) return;+ if (effectiveApprovals(v, state.space_approvals) === 'off' && state.approvals_effective !== 'off') setPending(v);+ else save(v);+ };++ return (+ <div className="space-y-1.5">+ <div className="flex items-center justify-between gap-2">+ <label htmlFor={selectId} className="text-xs font-medium text-zinc-400">+ Approvals+ </label>+ {state.approvals_effective === 'off' && <ApprovalsOffBadge title={`${kwantName} runs commands, file writes and tools without asking.`} />}+ </div>+ <select+ id={selectId}+ value={pending ?? state.approvals}+ disabled={busy}+ onChange={(e) => pick(e.target.value as BotApprovals)}+ 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 disabled:opacity-60"+ >+ {botOptions(state.space_approvals).map((o) => (+ <option key={o.value} value={o.value}>+ {o.label}+ </option>+ ))}+ </select>+ <p className="text-[11px] text-zinc-500">Saved as soon as you change it.</p>+ {pending && <OffConfirm title={offConfirmTitle({ bot: kwantName })} busy={busy} onCancel={() => setPending(null)} onConfirm={() => save(pending)} />}+ {error && (+ <p role="alert" className="flex items-center gap-2 text-[11px] text-rose-300">+ <AlertTriangle size={12} aria-hidden="true" /> {error}+ </p>+ )}+ </div>+ );+};diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsxindex e61b3dca..609591c9 100644--- a/frontend/src/components/NewAgentModal.tsx+++ b/frontend/src/components/NewAgentModal.tsx@@ -12,6 +12,7 @@ import { MemoryPanel } from './MemoryPanel';import { RoutinesPanel } from './RoutinesPanel';import { SkillsPanel } from './SkillsPanel';import type { Channel, Kwant } from './Sidebar';+import { BotApprovalsSetting } from './ApprovalsSetting';export type EditTab = 'profile' | 'memory' | 'skills' | 'routines';const EDIT_TABS: Array<{ id: EditTab; label: string; Icon: typeof Brain }> = [@@ -69,6 +70,8 @@ interface NewAgentModalProps {pendingSkills?: number;/** Editing only: opens the Delete bot confirm. */onRequestDelete?: () => void;+ /** Editing only: the approvals override saved; load bots again for the markers. */+ onApprovalsChanged?: () => void;}export const NewAgentModal: React.FC<NewAgentModalProps> = ({@@ -90,6 +93,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({initialTab = 'profile',pendingSkills = 0,onRequestDelete,+ onApprovalsChanged,}) => {const [tab, setTab] = useState<EditTab>('profile');const [name, setName] = useState('');@@ -427,6 +431,8 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({</div>)}+ {isEdit && kwantId && <BotApprovalsSetting kwantId={kwantId} kwantName={initial?.name ?? name} onChanged={() => onApprovalsChanged?.()} />}+{mcpIds !== undefined && (<KwantToolsPicker model={model} selected={mcpIds} onChange={setMcpIds} onManageServers={onManageServers} />)}diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex e90a23bf..aa304809 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -1,5 +1,5 @@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 { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, CalendarClock, ShieldOff } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { playSfx } from '../audio/chiptune';import { badgeText } from '../away';@@ -9,6 +9,8 @@ import { claudeNeedsSignIn } from '../claudeLogin';import { Space, spaceSummary } from '../spaces';import { SpaceSwitcher, SpaceTile } from './Spaces';import { isMac } from './LayaStatus';+import { ApprovalsOffBadge } from './ApprovalsSetting';+import { approvalsOff, spaceOffLine } from '../approvalMode';export interface Kwant {id: string;@@ -23,6 +25,9 @@ export interface Kwant {profile_id?: string | null;/** Whether turns may move to the engine's next profile when this one is out of usage. */profile_failover?: boolean;+ /** Its own approvals setting, and what it comes to with the space's; absent on older servers. */+ approvals?: 'inherit' | 'ask' | 'off';+ approvals_effective?: 'ask' | 'off';}export interface Channel {@@ -192,6 +197,8 @@ export const Sidebar: React.FC<SidebarProps> = ({return selectedId === c.id;};+ const offLine = spaceOffLine(space.approvals, kwants);+return (<asidearia-label={`${space.name} chats and kwant bots`}@@ -217,6 +224,17 @@ export const Sidebar: React.FC<SidebarProps> = ({</span><ChevronDown size={14} className={`shrink-0 text-zinc-500 transition-transform ${switcherOpen ? 'rotate-180' : ''}`} aria-hidden="true" /></button>+ {offLine && (+ <button+ type="button"+ onClick={onOpenSpaceSettings}+ title="Bots here run commands, file writes and tools without asking. Change it in Space settings."+ className="mt-1 w-full flex items-center gap-1.5 px-2 py-1 rounded-md border border-amber-500/30 bg-amber-500/10 text-[11px] font-medium text-amber-200 hover:bg-amber-500/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400"+ >+ <ShieldOff size={12} aria-hidden="true" className="shrink-0" />+ <span className="truncate">{offLine}</span>+ </button>+ )}{switcherOpen && (<SpaceSwitcherspaces={spaces}@@ -576,6 +594,7 @@ export const Sidebar: React.FC<SidebarProps> = ({<div className="flex-1 min-w-0"><div className="flex items-center justify-between gap-1"><span className="text-xs font-semibold text-zinc-200 truncate">{k.name}</span>+ {approvalsOff(k) && <ApprovalsOffBadge compact title={`${k.name} runs commands, file writes and tools without asking.`} />}{onEditKwant && (<buttontype="button"diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsxindex afb67ed4..dceb86b0 100644--- a/frontend/src/components/SpaceSettings.tsx+++ b/frontend/src/components/SpaceSettings.tsx@@ -32,6 +32,7 @@ import { SpaceTile } from './Spaces';import { ImportDialog, RecentImports } from './ImportDialog';import { ImportError, ImportRecord, downloadExport, importApi, importErrorText } from '../imports';import { memberIdsOf, type Channel, type Kwant, type Team } from './Sidebar';+import { SpaceApprovalsSetting } from './ApprovalsSetting';export type SpaceSettingsTab = 'general' | 'accounts' | 'bots' | 'teams' | 'tools' | 'skills' | 'routines' | 'import';@@ -73,6 +74,8 @@ interface Props {routineFocus?: RoutineFocus | null;/** After an import or its undo: load bots, teams and chats again. */onImported?: () => void;+ /** After the approvals switch changes: load bots and spaces again (no event fires). */+ onApprovalsChanged?: () => void;}/** What the tabs get on top of the props: opening the Import dialog. */@@ -291,7 +294,7 @@ const ImportTab: React.FC<TabProps> = ({ space, kwants, onOpenImport, onImported);};-const GeneralTab: React.FC<Props> = ({ space, spaces, onSpaceSaved, onArchived }) => {+const GeneralTab: React.FC<Props> = ({ space, spaces, kwants, onSpaceSaved, onArchived, onApprovalsChanged }) => {const [name, setName] = useState(space.name);const [icon, setIcon] = useState(space.icon);// "amber" from the server shows as its swatch.@@ -406,6 +409,18 @@ const GeneralTab: React.FC<Props> = ({ space, spaces, onSpaceSaved, onArchived }</div></form>+ <SpaceApprovalsSetting+ key={space.id}+ spaceId={space.id}+ spaceName={space.name}+ value={space.approvals ?? 'ask'}+ overrides={{+ ask: kwants.filter((k) => k.approvals === 'ask').map((k) => k.name),+ off: kwants.filter((k) => k.approvals === 'off').map((k) => k.name),+ }}+ onChanged={() => onApprovalsChanged?.()}+ />+<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 spacediff --git a/frontend/src/spaces.ts b/frontend/src/spaces.tsindex 324fbe4a..bcab8cb1 100644--- a/frontend/src/spaces.ts+++ b/frontend/src/spaces.ts@@ -23,6 +23,8 @@ export interface Space {general_channel_id: string | null;counts: SpaceCounts;paused_routines?: number;+ /** The approvals switch; older servers leave it out ("ask"). */+ approvals?: 'ask' | 'off';}export interface NewSpace {diff --git a/frontend/tests/approvalsOff.test.mjs b/frontend/tests/approvalsOff.test.mjsnew file mode 100644index 00000000..85f40fe1--- /dev/null+++ b/frontend/tests/approvalsOff.test.mjs@@ -0,0 +1,201 @@+// Oleks (2026-10-20): a switch that turns every approval off, per space with a per-bot override,+// and a marker wherever a bot runs without asking.+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 { SpaceApprovalsSetting, BotApprovalsSetting, ApprovalsOffBadge } from './src/components/ApprovalsSetting';+ import { Sidebar } from './src/components/Sidebar';+ export * from './src/approvalMode';+ const r = (C, p) => renderToStaticMarkup(React.createElement(C, p));+ export const spaceSetting = (p) => r(SpaceApprovalsSetting, { spaceId: 'spc_1', spaceName: 'Work', value: 'ask', onChanged: () => {}, ...p });+ export const botSetting = (p) => r(BotApprovalsSetting, { kwantId: 'k1', kwantName: 'Dev', ...p });+ export const badge = (p) => r(ApprovalsOffBadge, p);+ const engines = { engines: [], loading: false, error: null, refresh: () => {} };+ export const sidebar = (p) =>+ r(Sidebar, {+ spaces: [], onSwitchSpace() {}, onCreateSpace() {}, onOpenSpaceSettings() {}, onOpenArchived() {}, onOpenSearch() {}, onOpenRoutines() {},+ channels: [], teams: [], selectedId: '', isChannel: false, onSelectKwant() {}, onSelectChannel() {}, onSelectTeam() {}, onSummonKwant() {}, onCreateTeam() {},+ engines, ...p,+ });+`);++const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/’/g, "'").replace(/'|'/g, "'").replace(/"/g, '"').replace(/&/g, '&').replace(/\s+/g, ' ').trim();+const buttons = (html) => [...html.matchAll(/<button[^>]*>([\s\S]*?)<\/button>/g)].map((x) => text(x[1]));+const space = (approvals) => ({ id: 'spc_1', name: 'Work', icon: '💼', color: null, sort: 0, is_default: false, archived_at: null, created_at: '', general_channel_id: null, counts: { bots: 2, ready_accounts: 1, unread: 0 }, approvals });+const bot = (id, name, approvals, effective) => ({ id, name, title: 'Coder', persona_prompt: '', avatar_sprite: 'coder', driver_type: 'claude', preferred_model: 'claude:sonnet', approvals, approvals_effective: effective });++// ---------------------------------------------------------------- the model++test('effective value: the bot override wins, inherit follows the space, older servers mean ask', () => {+ assert.equal(m.effectiveApprovals('inherit', 'off'), 'off');+ assert.equal(m.effectiveApprovals('ask', 'off'), 'ask');+ assert.equal(m.effectiveApprovals('off', 'ask'), 'off');+ assert.equal(m.approvalsOff({ approvals_effective: 'off' }), true);+ assert.equal(m.approvalsOff({ approvals_effective: 'ask' }), false);+ assert.equal(m.approvalsOff({}), false, 'no field (older server) is not "off"');+ assert.equal(m.approvalsOff(null), false);+});++test('parseBotApprovals reads Lin\'s shape and fills a missing effective value', () => {+ assert.deepEqual(m.parseBotApprovals({ kwant_id: 'k1', approvals: 'inherit', approvals_effective: 'off', space_approvals: 'off' }), {+ kwant_id: 'k1', approvals: 'inherit', approvals_effective: 'off', space_approvals: 'off',+ });+ assert.equal(m.parseBotApprovals({ kwant_id: 'k1', approvals: 'off', space_approvals: 'ask' }).approvals_effective, 'off');+ assert.equal(m.parseBotApprovals({ kwant_id: 'k1', approvals: 'weird' }).approvals, 'inherit');+ assert.equal(m.parseBotApprovals(null), null);+ assert.equal(m.parseBotApprovals([]), null);+});++test('the space line counts bots that differ from the space', () => {+ assert.equal(m.spaceOffLine('ask', [{ approvals_effective: 'ask' }]), null);+ assert.equal(m.spaceOffLine(undefined, []), null);+ assert.equal(m.spaceOffLine('off', [{ approvals_effective: 'off' }]), 'Approvals off');+ assert.equal(m.spaceOffLine('off', [{ approvals_effective: 'ask' }, { approvals_effective: 'off' }]), 'Approvals off (1 bot still asks)');+ assert.equal(m.spaceOffLine('ask', [{ approvals_effective: 'off' }, { approvals_effective: 'off' }]), 'Approvals off for 2 bots');+});++// ---------------------------------------------------------------- the API calls++const withFetch = async (impl, fn) => {+ const calls = [];+ const prev = globalThis.fetch;+ globalThis.fetch = async (url, init) => {+ calls.push({ url, init });+ return impl(url, init);+ };+ try {+ await fn(calls);+ } finally {+ globalThis.fetch = prev;+ }+};+const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });++test('setSpace PUTs {approvals} to the space and returns the new value', async () => {+ await withFetch(() => json(200, { space_id: 'spc_1', approvals: 'off', bots: [] }), async (calls) => {+ assert.equal(await m.approvalModeApi.setSpace('spc_1', 'off'), 'off');+ assert.equal(calls[0].url, '/api/spaces/spc_1/approvals');+ assert.equal(calls[0].init.method, 'PUT');+ assert.deepEqual(JSON.parse(calls[0].init.body), { approvals: 'off' });+ });+});++test('setBot PUTs the override and returns the effective value', async () => {+ await withFetch(() => json(200, { kwant_id: 'k 1', approvals: 'ask', approvals_effective: 'ask', space_approvals: 'off' }), async (calls) => {+ const s = await m.approvalModeApi.setBot('k 1', 'ask');+ assert.equal(calls[0].url, '/api/kwants/k%201/approvals');+ assert.deepEqual(JSON.parse(calls[0].init.body), { approvals: 'ask' });+ assert.equal(s.approvals_effective, 'ask');+ assert.equal(s.space_approvals, 'off');+ });+});++test('errors are sentences: 403 (a bot token), 409 (archived), no endpoint, no network', async () => {+ await withFetch(() => json(403, { error: 'only the person changes approvals' }), async () => {+ await assert.rejects(m.approvalModeApi.setSpace('s', 'off'), /Only you can change approvals/);+ });+ await withFetch(() => json(409, { error: 'archived' }), async () => {+ await assert.rejects(m.approvalModeApi.setSpace('s', 'off'), /archived\. Restore it/);+ });+ await withFetch(() => new Response('', { status: 405 }), async () => {+ await assert.rejects(m.approvalModeApi.setBot('k', 'off'), /can't change approvals yet|can’t change approvals yet/);+ });+ await withFetch(() => { throw new TypeError('fetch failed'); }, async () => {+ await assert.rejects(m.approvalModeApi.setBot('k', 'off'), /Couldn’t reach the server/);+ });+ await withFetch(() => new Response('', { status: 404 }), async () => {+ assert.equal(await m.approvalModeApi.bot('k'), null, 'an older server: the bot control hides');+ });+});++// ---------------------------------------------------------------- the space control++test('space control: Ask is the default and checked, Don\'t ask explains itself, no confirm yet', () => {+ const html = m.spaceSetting({});+ const t = text(html);+ assert.match(html, /role="radiogroup" aria-label="Approvals in Work"/);+ assert.match(t, /Ask before running commands \(default\)/);+ assert.match(t, /Don't ask Bots run everything without approval\./);+ assert.match(html, /checked="" value="ask"/);+ assert.doesNotMatch(html, /checked="" value="off"/);+ assert.doesNotMatch(html, /alertdialog/);+ assert.doesNotMatch(t, /Approvals off/, 'no marker while asking');+});++test('space control: the confirm says plainly what off means, and Keep asking is the safe default focus', () => {+ const html = m.spaceSetting({ initialConfirm: true });+ const t = text(html);+ assert.match(html, /role="alertdialog"/);+ assert.match(t, /Turn off approvals for every bot in Work\?/);+ assert.match(t, /Shell commands run without asking you\./);+ assert.match(t, /written or deleted anywhere/);+ assert.match(t, /Tools \(MCP servers, browser, web\) run without asking\./);+ assert.match(t, /No approval cards appear\. Everything that runs is still recorded\./);+ assert.match(t, /Bots can't change this\./);+ assert.deepEqual(buttons(html).slice(-2), ['Keep asking', 'Turn approvals off']);+ assert.match(html, /<button type="button"[^>]*autofocus=""[^>]*>Keep asking/i);+});++test('space control when off: Don\'t ask is checked, the marker shows, and bots that still ask are named', () => {+ const html = m.spaceSetting({ value: 'off', overrides: { ask: ['Reviewer'], off: [] } });+ const t = text(html);+ assert.match(html, /checked="" value="off"/);+ assert.match(t, /Approvals off/);+ assert.match(t, /Still asks, set on the bot: Reviewer\./);+});++// ---------------------------------------------------------------- the bot override++test('bot override: three choices, "Same as space" names the space value, the marker when it runs free', () => {+ const html = m.botSetting({ initial: { kwant_id: 'k1', approvals: 'inherit', approvals_effective: 'off', space_approvals: 'off' } });+ const opts = [...html.matchAll(/<option[^>]*value="([^"]+)"[^>]*>([^<]*)</g)].map((x) => [x[1], text(x[2])]);+ assert.deepEqual(opts, [+ ['inherit', "Same as space (Don't ask)"],+ ['ask', 'Ask before running commands'],+ ['off', "Don't ask"],+ ]);+ assert.match(html, /<label for="([^"]+)"[^>]*>Approvals<\/label>/);+ assert.match(text(html), /Approvals off/);+});++test('bot override: an asking bot shows no marker; an older server shows nothing', () => {+ const html = m.botSetting({ initial: { kwant_id: 'k1', approvals: 'ask', approvals_effective: 'ask', space_approvals: 'off' } });+ assert.doesNotMatch(text(html), /Approvals off/);+ assert.match(html, /<option value="ask" selected="">/);+ assert.equal(m.botSetting({ initial: null }), '');+});++// ---------------------------------------------------------------- markers++test('the marker has an icon and words, not colour alone', () => {+ const full = m.badge({});+ assert.match(full, /<svg/);+ assert.equal(text(full), 'Approvals off');+ const compact = m.badge({ compact: true });+ assert.match(compact, /<svg[^>]*aria-hidden="true"/);+ assert.match(compact, /class="sr-only">Approvals off</, 'screen readers hear it in the bot list');+ assert.match(m.badge({ onClick: () => {} }), /^<button type="button"/);+});++test('sidebar: the bot list marks only bots that run without asking, and the space header says so', () => {+ const html = m.sidebar({ space: space('ask'), kwants: [bot('k1', 'Dev', 'off', 'off'), bot('k2', 'Writer', 'inherit', 'ask')] });+ const rows = html.split('group/fleet').slice(1);+ assert.equal(rows.length, 2);+ assert.match(rows[0], /Dev[\s\S]*sr-only">Approvals off/);+ assert.doesNotMatch(rows[1], /Approvals off/);+ assert.match(text(html), /Approvals off for 1 bot/);+});++test('sidebar: space off shows the header line; nothing at all while every bot asks', () => {+ assert.match(text(m.sidebar({ space: space('off'), kwants: [bot('k1', 'Dev', 'inherit', 'off')] })), /Approvals off/);+ const asking = m.sidebar({ space: space('ask'), kwants: [bot('k1', 'Dev', 'inherit', 'ask')] });+ assert.doesNotMatch(text(asking), /Approvals off/);+ const older = m.sidebar({ space: space(undefined), kwants: [bot('k1', 'Dev', undefined, undefined)] });+ assert.doesNotMatch(text(older), /Approvals off/);+});