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
Add Local computer / VM switch to settings and the browser pane
Pixel (kwant bot)07e846d2de8b
diff --git a/frontend/src/components/ComputerModeSwitch.tsx b/frontend/src/components/ComputerModeSwitch.tsxnew file mode 100644index 00000000..51a73c62--- /dev/null+++ b/frontend/src/components/ComputerModeSwitch.tsx@@ -0,0 +1,191 @@+import React, { useCallback, useEffect, useReducer, useRef } from 'react';+import { AlertTriangle, Box, Laptop, Loader2, X } from 'lucide-react';+import { playSfx } from '../audio/chiptune';+import {+ COMPUTER_MODES,+ COMPUTER_MODE_EVENT,+ LOCAL_BROWSER_NOTE,+ ComputerMode,+ ComputerSettings,+ SwitchState,+ fetchComputerSettings,+ initialSwitchState,+ modeLabel,+ otherMode,+ saveComputerMode,+ shownMode,+ switchReducer,+ unavailableReason,+} from '../computerMode';++export interface ComputerModeApi {+ state: SwitchState;+ /** Saves at once; on failure the control goes back and `state.error` says why. */+ select: (mode: ComputerMode) => void;+ dismissError: () => void;+}++/** Loads the setting while `enabled`, and follows switches made elsewhere in this tab. */+export function useComputerMode(enabled: boolean): ComputerModeApi {+ const [state, dispatch] = useReducer(switchReducer, initialSwitchState);+ const stateRef = useRef(state);+ stateRef.current = state;++ useEffect(() => {+ if (!enabled) return;+ let alive = true;+ fetchComputerSettings()+ .then((s) => alive && s && dispatch({ type: 'loaded', settings: s }))+ .catch(() => {});+ const onSwitched = (e: Event) => dispatch({ type: 'loaded', settings: (e as CustomEvent<ComputerSettings>).detail });+ window.addEventListener(COMPUTER_MODE_EVENT, onSwitched);+ return () => {+ alive = false;+ window.removeEventListener(COMPUTER_MODE_EVENT, onSwitched);+ };+ }, [enabled]);++ const select = useCallback((mode: ComputerMode) => {+ const { settings, pending } = stateRef.current;+ if (!settings || pending || mode === settings.mode) return;+ playSfx('click');+ dispatch({ type: 'start', mode });+ saveComputerMode(mode).then((r) => {+ if (r.ok) {+ dispatch({ type: 'saved', settings: r.settings });+ window.dispatchEvent(new CustomEvent(COMPUTER_MODE_EVENT, { detail: r.settings }));+ } else {+ dispatch({ type: 'failed', error: r.error });+ }+ });+ }, []);++ const dismissError = useCallback(() => dispatch({ type: 'dismiss' }), []);+ return { state, select, dismissError };+}++const ICONS: Record<ComputerMode, typeof Laptop> = { local: Laptop, vm: Box };++export const ComputerModeError: React.FC<{ error: string; onDismiss?: () => void }> = ({ error, onDismiss }) => (+ <div role="alert" className="flex items-start gap-2 px-3 py-2 rounded-lg bg-rose-500/10 border border-rose-500/20 text-rose-300 text-[11px]">+ <AlertTriangle size={13} className="shrink-0 mt-px" aria-hidden="true" />+ <span className="flex-1">{error}</span>+ {onDismiss && (+ <button type="button" onClick={onDismiss} aria-label="Dismiss" className="shrink-0 text-rose-300/70 hover:text-rose-200">+ <X size={12} />+ </button>+ )}+ </div>+);++/** Two-option control for the Settings screen. Renders nothing until the setting is loaded. */+export const ComputerModeControl: React.FC<{ api: ComputerModeApi }> = ({ api }) => {+ const { state, select, dismissError } = api;+ const refs = useRef<Partial<Record<ComputerMode, HTMLButtonElement | null>>>({});+ const settings = state.settings;+ if (!settings) return null;+ const selected = shownMode(state);++ const onKeyDown = (e: React.KeyboardEvent, mode: ComputerMode) => {+ if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) return;+ e.preventDefault();+ const next = otherMode(mode);+ if (unavailableReason(settings, next)) return;+ refs.current[next]?.focus();+ select(next);+ };++ return (+ <div className="space-y-2">+ <div role="radiogroup" aria-labelledby="computer-mode-label" className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ {COMPUTER_MODES.map(({ id, label, hint }) => {+ const Icon = ICONS[id];+ const reason = unavailableReason(settings, id);+ const checked = selected === id;+ const saving = state.pending === id;+ return (+ <button+ key={id}+ ref={(el) => (refs.current[id] = el)}+ type="button"+ role="radio"+ aria-checked={checked}+ aria-disabled={!!reason || undefined}+ aria-describedby={`computer-mode-${id}-hint`}+ tabIndex={checked || (!selected && id === 'local') ? 0 : -1}+ // Not disabled while saving, so keyboard focus stays put; select() ignores it.+ disabled={!!reason}+ aria-busy={saving || undefined}+ onClick={() => select(id)}+ onKeyDown={(e) => onKeyDown(e, id)}+ className={`text-left p-3 rounded-xl border transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${+ checked+ ? 'border-sky-500/60 bg-sky-500/10'+ : reason+ ? 'border-zinc-800 bg-zinc-950/40 cursor-not-allowed'+ : 'border-zinc-800 bg-zinc-950/60 hover:border-sky-500/40'+ } ${state.pending && !saving ? 'opacity-60' : ''}`}+ >+ <span className={`flex items-center gap-2 text-xs font-medium ${reason ? 'text-zinc-500' : 'text-zinc-100'}`}>+ {saving ? <Loader2 size={14} className="animate-spin text-sky-400" aria-hidden="true" /> : <Icon size={14} className={checked ? 'text-sky-400' : 'text-zinc-500'} aria-hidden="true" />}+ {label}+ {saving && <span className="sr-only">(switching)</span>}+ </span>+ <span id={`computer-mode-${id}-hint`} className="block mt-1 text-[11px] leading-snug">+ <span className={reason ? 'text-zinc-600' : 'text-zinc-500'}>{hint}</span>+ {reason && <span className="block mt-1 text-amber-300/90">Unavailable: {reason}</span>}+ </span>+ </button>+ );+ })}+ </div>+ {state.error && <ComputerModeError error={state.error} onDismiss={dismissError} />}+ </div>+ );+};++/** One-click switch for the browser pane header. Renders nothing until the setting is loaded. */+export const ComputerModeChip: React.FC<{ api: ComputerModeApi }> = ({ api }) => {+ const { state, select } = api;+ const settings = state.settings;+ const current = shownMode(state);+ if (!settings || !current) return null;+ const next = otherMode(current);+ const reason = unavailableReason(settings, next);+ const Icon = ICONS[current];+ const short = COMPUTER_MODES.find((m) => m.id === current)!.short;+ const title = state.pending+ ? `Switching to ${modeLabel(current)}…`+ : reason+ ? `Using ${modeLabel(current)}. ${modeLabel(next)} is unavailable: ${reason}`+ : `Using ${modeLabel(current)}. Click to switch to ${modeLabel(next)}.`;+ return (+ <button+ type="button"+ onClick={() => select(next)}+ disabled={!!reason}+ aria-busy={!!state.pending || undefined}+ title={title}+ aria-label={title}+ className={`flex items-center gap-1 px-1.5 py-1 rounded-md border text-[10px] font-semibold transition-colors disabled:cursor-not-allowed focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${+ current === 'local'+ ? 'border-amber-500/30 bg-amber-500/10 text-amber-200 enabled:hover:bg-amber-500/20'+ : 'border-sky-500/30 bg-sky-500/10 text-sky-200 enabled:hover:bg-sky-500/20'+ }`}+ >+ {state.pending ? <Loader2 size={12} className="animate-spin" aria-hidden="true" /> : <Icon size={12} aria-hidden="true" />}+ <span>{short}</span>+ </button>+ );+};++/** Shown in place of the live stream while kwant drives a real Chrome window. */+export const LocalBrowserNote: React.FC = () => (+ <div className="flex-1 flex items-center justify-center p-6 rounded-xl border border-zinc-800 bg-zinc-950 text-center">+ <div className="max-w-xs space-y-2">+ <Laptop size={28} className="mx-auto text-amber-300/80" aria-hidden="true" />+ <p className="text-xs font-medium text-zinc-200">{LOCAL_BROWSER_NOTE}</p>+ <p className="text-[11px] text-zinc-500">Watch and use that window directly. Switch to VM to see a live view here instead.</p>+ </div>+ </div>+);diff --git a/frontend/src/components/SandboxViewer.tsx b/frontend/src/components/SandboxViewer.tsxindex f028548d..4e2c4523 100644--- a/frontend/src/components/SandboxViewer.tsx+++ b/frontend/src/components/SandboxViewer.tsx@@ -1,5 +1,6 @@import React, { useCallback, useEffect, useRef, useState } from 'react';import { Globe, Loader2, RefreshCw, Share2, MousePointerClick } from 'lucide-react';+import { ComputerModeChip, ComputerModeError, LocalBrowserNote, useComputerMode } from './ComputerModeSwitch';// Must match the sandbox Chromium --window-size (docker/entrypoint.sh)const VIEWPORT_W = 1280;@@ -34,6 +35,8 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {const urlInputFocusedRef = useRef(false);const lastWheelRef = useRef(0);const api = `/api/sandbox/${encodeURIComponent(teamId)}`;+ const computer = useComputerMode(true);+ const isLocal = computer.state.settings?.mode === 'local';const applyUrl = useCallback((next?: string) => {if (!next || next === 'about:blank') return;@@ -110,12 +113,13 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {// Initial load + polling so page changes (loads, animations, bot actions) show upuseEffect(() => {+ if (isLocal) return;refresh();const timer = window.setInterval(() => {if (document.visibilityState === 'visible') refresh();}, POLL_MS);return () => window.clearInterval(timer);- }, [refresh]);+ }, [refresh, isLocal]);// Live updates when the bot (or the in-app pane) drives the same browseruseEffect(() => {@@ -235,6 +239,8 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {<RefreshCw size={14} /></button>+ <ComputerModeChip api={computer} />+<divclassName="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium text-emerald-300 bg-emerald-500/10 border border-emerald-500/30 flex-shrink-0"title="This is the same browser your agents use. They will see the current page on their next reply."@@ -244,18 +250,30 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {</div></header>- <div className="px-4 py-1.5 text-[11px] text-zinc-500 border-b border-zinc-900 flex items-center gap-2">- <MousePointerClick size={12} className={isFocused ? 'text-sky-400' : ''} />- <span>- {isFocused- ? 'Controlling the sandbox: clicks, scrolling, typing and paste go to the page.'- : 'Click the page to take control. Your agents will see wherever you leave this browser.'}- </span>- {title && <span className="ml-auto truncate text-zinc-400">{title}</span>}- </div>+ {!isLocal && (+ <div className="px-4 py-1.5 text-[11px] text-zinc-500 border-b border-zinc-900 flex items-center gap-2">+ <MousePointerClick size={12} className={isFocused ? 'text-sky-400' : ''} />+ <span>+ {isFocused+ ? 'Controlling the sandbox: clicks, scrolling, typing and paste go to the page.'+ : 'Click the page to take control. Your agents will see wherever you leave this browser.'}+ </span>+ {title && <span className="ml-auto truncate text-zinc-400">{title}</span>}+ </div>+ )}++ {computer.state.error && (+ <div className="px-4 pt-2">+ <ComputerModeError error={computer.state.error} onDismiss={computer.dismissError} />+ </div>+ )}<main className="flex-1 min-h-0 flex items-center justify-center p-4 overflow-hidden">- {error && !screenshot ? (+ {isLocal ? (+ <div className="w-full max-w-md flex">+ <LocalBrowserNote />+ </div>+ ) : error && !screenshot ? (<div className="text-sm text-zinc-400">{error}</div>) : (<divdiff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex b9d7e2b1..5832a1ee 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -1,5 +1,5 @@import React, { useState, useEffect, useRef } from 'react';-import { Cpu, Key, Globe, X, Sparkles, Check, Plug, ChevronRight, UserRound, LogOut, Bell, AlertTriangle, Layers } from 'lucide-react';+import { Cpu, Key, Globe, X, Sparkles, Check, Plug, ChevronRight, UserRound, LogOut, Bell, AlertTriangle, Layers, Monitor } from 'lucide-react';import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';import {BROWSER_NOTIFY_KEY,@@ -12,6 +12,7 @@ import {} from '../continuity';import { playSfx } from '../audio/chiptune';import { useAuth } from './AuthGate';+import { ComputerModeControl, useComputerMode } from './ComputerModeSwitch';interface SettingsData {anthropic_api_key: string;@@ -49,6 +50,7 @@ interface SettingsModalProps {export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, onOpenTools, onOpenProfiles }) => {const { authRequired, signOut } = useAuth();+ const computer = useComputerMode(isOpen);const [settings, setSettings] = useState<SettingsData | null>(null);const [anthropicKey, setAnthropicKey] = useState('');const [xaiKey, setXaiKey] = useState('');@@ -246,6 +248,19 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o</div></div>+ {computer.state.settings && (+ <div className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3">+ <div>+ <p id="computer-mode-label" className="flex items-center gap-2 text-xs font-medium text-zinc-300">+ <Monitor size={15} className="text-sky-400" aria-hidden="true" />+ <span>Computer for browsing and commands</span>+ </p>+ <p className="mt-1 text-[11px] text-zinc-500">Switches right away, no need to save.</p>+ </div>+ <ComputerModeControl api={computer} />+ </div>+ )}+{onOpenProfiles && (<buttontype="button"diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsxindex 26c87a6c..4129df58 100644--- a/frontend/src/components/VirtualMachinePane.tsx+++ b/frontend/src/components/VirtualMachinePane.tsx@@ -19,10 +19,12 @@ import {MousePointerClick,Keyboard,Loader2,+ Laptop,} from 'lucide-react';import { playSfx } from '../audio/chiptune';import { mapBrowserPoint } from '../browserViewport';import { useBrowserStream } from '../useBrowserStream';+import { ComputerModeChip, ComputerModeError, LocalBrowserNote, useComputerMode } from './ComputerModeSwitch';export interface TerminalLogEntry {command: string;@@ -83,8 +85,12 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({const [newPassword, setNewPassword] = useState('');const [isSubmitting, setIsSubmitting] = useState(false);+ // Local mode drives a real Chrome window, so there's no stream to show. Unknown counts as vm.+ const computer = useComputerMode(isOpen);+ const isLocal = computer.state.settings?.mode === 'local';+// Interactive Remote Control State- const stream = useBrowserStream(teamId, isOpen && activeTab === 'browser');+ const stream = useBrowserStream(teamId, isOpen && activeTab === 'browser' && !isLocal);const isControlMode = stream.controlling;const isInteracting = stream.busy;const [quickTypeText, setQuickTypeText] = useState('');@@ -309,38 +315,42 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({return (<div className="w-96 border-l border-zinc-800 bg-zinc-950 flex flex-col h-full shadow-2xl z-30 select-none animate-in slide-in-from-right duration-200">{/* Top Header */}- <div className="h-14 border-b border-zinc-800 px-4 flex items-center justify-between bg-zinc-900/60">- <div className="flex items-center gap-2">- <div className={`w-2.5 h-2.5 rounded-full ${(stream.connected || isRunning) ? 'bg-emerald-400 animate-pulse' : 'bg-zinc-500'}`} />- <div>+ <div className="h-14 border-b border-zinc-800 px-4 flex items-center justify-between gap-2 bg-zinc-900/60">+ <div className="flex items-center gap-2 min-w-0">+ <div className={`shrink-0 w-2.5 h-2.5 rounded-full ${(stream.connected || isRunning) ? 'bg-emerald-400 animate-pulse' : 'bg-zinc-500'}`} />+ <div className="min-w-0"><div className="text-xs font-semibold text-zinc-100 flex items-center gap-1.5">- <span>Bot Browser</span>- <span className="text-[10px] font-mono text-zinc-400">(@{teamName})</span>+ <span className="whitespace-nowrap">Bot Browser</span>+ <span className="text-[10px] font-mono text-zinc-400 truncate">(@{teamName})</span></div>- <p className="text-[10px] text-zinc-400">Live Chromium • Separate code sandbox</p>+ <p className="text-[10px] text-zinc-400 truncate">{isLocal ? 'Your Chrome • Commands ask first' : 'Live Chromium • Separate code sandbox'}</p></div></div>- <div className="flex items-center gap-1">+ <div className="flex items-center gap-1 shrink-0">+ <ComputerModeChip api={computer} />+{/* Interactive Control Toggle */}- <button- type="button"- onClick={() => {- playSfx('click');- stream.send({ action: isControlMode ? 'release_control' : 'take_control' });- if (!isControlMode) setActiveTab('browser');- }}- disabled={!stream.connected}- title={isControlMode ? 'Exit Control Mode' : 'Take Control of Bot Browser'}- className={`p-1.5 rounded-md transition-colors cursor-pointer flex items-center gap-1 ${- isControlMode- ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/40 shadow-sm shadow-cyan-500/20 animate-pulse'- : 'text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800'- }`}- >- <MousePointerClick size={13} className={isControlMode ? 'text-cyan-400' : ''} />- <span className="text-[10px] font-semibold">{isControlMode ? 'Controlling' : 'Take Control'}</span>- </button>+ {!isLocal && (+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ stream.send({ action: isControlMode ? 'release_control' : 'take_control' });+ if (!isControlMode) setActiveTab('browser');+ }}+ disabled={!stream.connected}+ title={isControlMode ? 'Exit Control Mode' : 'Take Control of Bot Browser'}+ className={`p-1.5 rounded-md transition-colors cursor-pointer flex items-center gap-1 ${+ isControlMode+ ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/40 shadow-sm shadow-cyan-500/20 animate-pulse'+ : 'text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800'+ }`}+ >+ <MousePointerClick size={13} className={isControlMode ? 'text-cyan-400' : ''} />+ <span className="text-[10px] font-semibold whitespace-nowrap">{isControlMode ? 'Controlling' : 'Take Control'}</span>+ </button>+ )}<buttontype="button"@@ -392,6 +402,12 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({</div></div>+ {computer.state.error && (+ <div className="px-3 pt-2">+ <ComputerModeError error={computer.state.error} onDismiss={computer.dismissError} />+ </div>+ )}+{/* Tabs */}<div className="flex border-b border-zinc-800 bg-zinc-900/30 text-xs font-medium"><button@@ -448,7 +464,11 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({{/* Content Area */}<div className="flex-1 overflow-hidden flex flex-col">- {activeTab === 'browser' ? (+ {activeTab === 'browser' && isLocal ? (+ <div className="flex-1 flex flex-col p-3 overflow-hidden">+ <LocalBrowserNote />+ </div>+ ) : activeTab === 'browser' ? (<div className="flex-1 flex flex-col p-3 gap-2 overflow-hidden">{/* Browser Address Bar */}<div className="flex items-center gap-1.5 p-1.5 bg-zinc-900 border border-zinc-800 rounded-lg text-xs">@@ -867,11 +887,18 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({{/* Footer Status */}<div className="p-2.5 border-t border-zinc-800 bg-zinc-900/60 flex items-center justify-between text-[11px] text-zinc-400">- <div className="flex items-center gap-1.5">- <Cpu size={12} className={(stream.connected || isRunning) ? 'text-emerald-400' : 'text-zinc-500'} />- <span>{(stream.connected || isRunning) ? 'Browser Ready' : 'Browser Offline'}</span>- </div>- {onRestartVm && (+ {isLocal ? (+ <div className="flex items-center gap-1.5">+ <Laptop size={12} className="text-amber-300/80" />+ <span>Chrome on your computer</span>+ </div>+ ) : (+ <div className="flex items-center gap-1.5">+ <Cpu size={12} className={(stream.connected || isRunning) ? 'text-emerald-400' : 'text-zinc-500'} />+ <span>{(stream.connected || isRunning) ? 'Browser Ready' : 'Browser Offline'}</span>+ </div>+ )}+ {onRestartVm && !isLocal && (<buttontype="button"onClick={() => {diff --git a/frontend/src/computerMode.ts b/frontend/src/computerMode.tsnew file mode 100644index 00000000..a7932032--- /dev/null+++ b/frontend/src/computerMode.ts@@ -0,0 +1,109 @@+// "Local computer" vs "VM (isolated)": which computer kwant's browser and shell use.+// Contract: GET/PUT /api/settings/computer (docs/browser-service.md)++export type ComputerMode = 'local' | 'vm';++export interface ComputerSettings {+ mode: ComputerMode;+ available: Record<ComputerMode, boolean>;+ reasons: Record<ComputerMode, string | null>;+}++export const COMPUTER_MODES: { id: ComputerMode; label: string; short: string; hint: string }[] = [+ { id: 'local', label: 'Local computer', short: 'Local', hint: 'Uses your Chrome and your files. Commands ask before running.' },+ { id: 'vm', label: 'VM (isolated)', short: 'VM', hint: 'Runs in Docker containers, isolated from your files.' },+];++export const LOCAL_BROWSER_NOTE = 'Kwant is using a Chrome window on your computer.';++/** Fired on window after a successful switch so every open control shows the new mode. */+export const COMPUTER_MODE_EVENT = 'kwnt:computer-mode';++const isMode = (v: unknown): v is ComputerMode => v === 'local' || v === 'vm';++/** The response, or null when it isn't the expected shape. */+export function parseComputerSettings(data: unknown): ComputerSettings | null {+ if (!data || typeof data !== 'object') return null;+ const d = data as Record<string, any>;+ if (!isMode(d.mode) || !d.available || typeof d.available !== 'object') return null;+ const reason = (m: ComputerMode) => (typeof d.reasons?.[m] === 'string' && d.reasons[m].trim() ? d.reasons[m] : null);+ return {+ mode: d.mode,+ available: { local: d.available.local === true, vm: d.available.vm === true },+ reasons: { local: reason('local'), vm: reason('vm') },+ };+}++export const otherMode = (m: ComputerMode): ComputerMode => (m === 'local' ? 'vm' : 'local');++export const modeLabel = (m: ComputerMode) => COMPUTER_MODES.find((x) => x.id === m)!.label;++/** Why `mode` can't be picked right now, or null when it can. */+export function unavailableReason(settings: ComputerSettings, mode: ComputerMode): string | null {+ if (settings.available[mode]) return null;+ return settings.reasons[mode] ?? `${modeLabel(mode)} isn't available on this computer.`;+}++export interface SwitchState {+ settings: ComputerSettings | null;+ /** The mode being saved; shown as selected until the server answers. */+ pending: ComputerMode | null;+ error: string | null;+}++export type SwitchAction =+ | { type: 'loaded'; settings: ComputerSettings }+ | { type: 'start'; mode: ComputerMode }+ | { type: 'saved'; settings: ComputerSettings }+ | { type: 'failed'; error: string }+ | { type: 'dismiss' };++export const initialSwitchState: SwitchState = { settings: null, pending: null, error: null };++export function switchReducer(state: SwitchState, action: SwitchAction): SwitchState {+ switch (action.type) {+ case 'loaded':+ return state.pending ? state : { ...state, settings: action.settings };+ case 'start':+ return { ...state, pending: action.mode, error: null };+ case 'saved':+ return { settings: action.settings, pending: null, error: null };+ case 'failed':+ // Dropping `pending` puts the control back on the saved mode.+ return { ...state, pending: null, error: action.error };+ case 'dismiss':+ return { ...state, error: null };+ }+}++/** The mode a control should show as selected. */+export const shownMode = (s: SwitchState): ComputerMode | null => s.pending ?? s.settings?.mode ?? null;++/** null when this server has no computer setting (older build) or it couldn't be read. */+export async function fetchComputerSettings(): Promise<ComputerSettings | null> {+ const res = await fetch('/api/settings/computer', { cache: 'no-store' });+ if (!res.ok) return null;+ return parseComputerSettings(await res.json().catch(() => null));+}++export async function saveComputerMode(+ mode: ComputerMode,+): Promise<{ ok: true; settings: ComputerSettings } | { ok: false; error: string }> {+ let res: Response;+ try {+ res = await fetch('/api/settings/computer', {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ mode }),+ });+ } catch {+ return { ok: false, error: 'Could not reach the server.' };+ }+ const data = await res.json().catch(() => null);+ if (!res.ok) {+ const msg = data && typeof data.error === 'string' && data.error.trim() ? data.error : `Switching failed (HTTP ${res.status}).`;+ return { ok: false, error: msg };+ }+ const settings = parseComputerSettings(data);+ return settings ? { ok: true, settings } : { ok: false, error: 'The server sent an unexpected answer.' };+}diff --git a/frontend/tests/computerMode.test.mjs b/frontend/tests/computerMode.test.mjsnew file mode 100644index 00000000..a502a78c--- /dev/null+++ b/frontend/tests/computerMode.test.mjs@@ -0,0 +1,118 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++// The sound effects module reads its mute flag on load.+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };++const m = await loadBundled(`+ export * from './src/computerMode';+ export { ComputerModeControl, ComputerModeChip, LocalBrowserNote } from './src/components/ComputerModeSwitch';+ export { renderToStaticMarkup } from 'react-dom/server.browser';+ export { createElement } from 'react';+`);++const settings = (mode, local = true, vm = true, reasons = {}) => ({+ mode,+ available: { local, vm },+ reasons: { local: null, vm: null, ...reasons },+});+const api = (state) => ({ state, select: () => {}, dismissError: () => {} });+const render = (C, state) => m.renderToStaticMarkup(m.createElement(C, { api: api(state) }));+const ready = (s) => ({ ...m.initialSwitchState, settings: s });++test('parseComputerSettings accepts the contract and rejects anything else', () => {+ const ok = m.parseComputerSettings({ mode: 'vm', available: { local: false, vm: true }, reasons: { local: 'No Chrome found', vm: null } });+ assert.deepEqual(ok, settings('vm', false, true, { local: 'No Chrome found' }));+ assert.equal(m.parseComputerSettings({ mode: 'VM', available: {} }), null);+ assert.equal(m.parseComputerSettings({ mode: 'local' }), null);+ assert.equal(m.parseComputerSettings(null), null);+ // Missing reasons and non-boolean availability are tolerated, read as false/null.+ assert.deepEqual(m.parseComputerSettings({ mode: 'local', available: { local: 1, vm: true } }), settings('local', false, true));+});++test('unavailableReason uses the server reason, with a fallback', () => {+ assert.equal(m.unavailableReason(settings('local', true, false, { vm: 'Docker is not installed' }), 'vm'), 'Docker is not installed');+ assert.match(m.unavailableReason(settings('local', true, false), 'vm'), /VM \(isolated\) isn't available/);+ assert.equal(m.unavailableReason(settings('local'), 'vm'), null);+});++test('a failed PUT reverts the control and keeps the error', () => {+ let s = m.switchReducer(m.initialSwitchState, { type: 'loaded', settings: settings('local') });+ s = m.switchReducer(s, { type: 'start', mode: 'vm' });+ assert.equal(m.shownMode(s), 'vm');+ s = m.switchReducer(s, { type: 'failed', error: 'Docker is not running' });+ assert.equal(m.shownMode(s), 'local');+ assert.equal(s.error, 'Docker is not running');+ s = m.switchReducer(s, { type: 'start', mode: 'vm' });+ assert.equal(s.error, null, 'a new attempt clears the old error');+ s = m.switchReducer(s, { type: 'saved', settings: settings('vm') });+ assert.equal(m.shownMode(s), 'vm');+ assert.equal(s.pending, null);+});++test('a refetch while saving does not override the pending choice', () => {+ let s = m.switchReducer(ready(settings('local')), { type: 'start', mode: 'vm' });+ s = m.switchReducer(s, { type: 'loaded', settings: settings('local') });+ assert.equal(m.shownMode(s), 'vm');+});++test('saveComputerMode surfaces the 400 error body and network failures', async () => {+ const realFetch = globalThis.fetch;+ try {+ globalThis.fetch = async () => new Response(JSON.stringify({ error: 'Docker is not installed' }), { status: 400 });+ assert.deepEqual(await m.saveComputerMode('vm'), { ok: false, error: 'Docker is not installed' });+ globalThis.fetch = async () => new Response('oops', { status: 500 });+ assert.deepEqual(await m.saveComputerMode('vm'), { ok: false, error: 'Switching failed (HTTP 500).' });+ globalThis.fetch = async () => { throw new TypeError('offline'); };+ assert.deepEqual(await m.saveComputerMode('vm'), { ok: false, error: 'Could not reach the server.' });+ let body;+ globalThis.fetch = async (_u, init) => { body = init.body; return new Response(JSON.stringify(settings('vm')), { status: 200 }); };+ assert.deepEqual(await m.saveComputerMode('vm'), { ok: true, settings: settings('vm') });+ assert.equal(body, '{"mode":"vm"}');+ globalThis.fetch = async () => new Response('', { status: 404 });+ assert.equal(await m.fetchComputerSettings(), null, 'older servers without the route hide the switch');+ } finally {+ globalThis.fetch = realFetch;+ }+});++test('control: both available', () => {+ const html = render(m.ComputerModeControl, ready(settings('local')));+ assert.match(html, /role="radiogroup"/);+ assert.match(html, /aria-checked="true"[^>]*>.*Local computer/);+ assert.match(html, /Uses your Chrome and your files\. Commands ask before running\./);+ assert.match(html, /Runs in Docker containers, isolated from your files\./);+ assert.doesNotMatch(html, /disabled=""/);+ assert.doesNotMatch(html, /Unavailable/);+});++test('control: one unavailable is disabled and says why', () => {+ const html = render(m.ComputerModeControl, ready(settings('local', true, false, { vm: 'Docker is not installed' })));+ assert.match(html, /aria-disabled="true"[^>]*disabled=""[^>]*>.*VM \(isolated\)/);+ assert.match(html, /Unavailable: Docker is not installed/);+});++test('control: PUT failed shows the error inline on the saved mode', () => {+ const html = render(m.ComputerModeControl, { settings: settings('local'), pending: null, error: 'Docker is not running' });+ assert.match(html, /role="alert"[^>]*>.*Docker is not running/);+ assert.match(html, /aria-checked="true"[^>]*>.*Local computer/);+});++test('control and chip render nothing before the setting loads', () => {+ assert.equal(render(m.ComputerModeControl, m.initialSwitchState), '');+ assert.equal(render(m.ComputerModeChip, m.initialSwitchState), '');+});++test('chip names the current mode and offers the other one', () => {+ const vm = render(m.ComputerModeChip, ready(settings('vm')));+ assert.match(vm, />VM</);+ assert.match(vm, /Click to switch to Local computer/);+ const blocked = render(m.ComputerModeChip, ready(settings('local', true, false, { vm: 'Docker is not installed' })));+ assert.match(blocked, /disabled=""/);+ assert.match(blocked, /VM \(isolated\) is unavailable: Docker is not installed/);+});++test('local note text', () => {+ assert.match(m.renderToStaticMarkup(m.createElement(m.LocalBrowserNote)), /Kwant is using a Chrome window on your computer\./);+});