settings refactor

This commit is contained in:
2026-02-16 23:39:06 +00:00
parent 9f720e1804
commit c21353dbba
13 changed files with 322 additions and 14 deletions
@@ -0,0 +1,93 @@
import { useState } from 'react';
import { toast } from 'sonner';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { useForm } from 'hooks/useForm';
import { useAuth } from 'hooks/useAuth';
type PasswordFormState = {
password?: string;
newPassword?: string;
confirmPassword?: string;
};
const validate = (state: Partial<PasswordFormState>) => {
const { password, newPassword, confirmPassword } = state;
return !!(password && newPassword && confirmPassword && newPassword === confirmPassword);
};
export const ChangePassword = () => {
const { changePassword } = useAuth();
const [isChanging, setIsChanging] = useState(false);
const form = useForm<PasswordFormState>({}, validate);
const handleSubmit = async (ev: React.FormEvent) => {
ev.preventDefault();
if (!form.isValid || isChanging) return;
setIsChanging(true);
try {
await changePassword({
password: form.state.password!,
newPassword: form.state.newPassword!,
confirmPassword: form.state.confirmPassword!,
});
toast.success('Password changed');
form.update({ password: '', newPassword: '', confirmPassword: '' });
} catch (ex) {
const error = ex as { message?: string };
toast.error(error.message || 'Failed to change password');
form.update({ password: '', newPassword: '', confirmPassword: '' });
} finally {
setIsChanging(false);
}
};
return (
<div>
<form ref={form.formRef} onSubmit={handleSubmit} className="grid gap-4">
<Label className="grid gap-2">
<span className="text-duck-dark/70">Current Password</span>
<Input
className="h-11 bg-white/60 border-duck-dark/20 text-duck-dark placeholder:text-duck-dark/40"
type="password"
name="password"
placeholder="Current password"
autoComplete="current-password"
/>
</Label>
<Label className="grid gap-2">
<span className="text-duck-dark/70">New Password</span>
<Input
className="h-11 bg-white/60 border-duck-dark/20 text-duck-dark placeholder:text-duck-dark/40"
type="password"
name="newPassword"
placeholder="New password"
autoComplete="new-password"
/>
</Label>
<Label className="grid gap-2">
<span className="text-duck-dark/70">Confirm New Password</span>
<Input
className="h-11 bg-white/60 border-duck-dark/20 text-duck-dark placeholder:text-duck-dark/40"
type="password"
name="confirmPassword"
placeholder="Confirm new password"
autoComplete="new-password"
/>
</Label>
<Button
type="submit"
disabled={!form.isValid || isChanging}
className="w-full h-11 bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold transition-all duration-200 hover:scale-105 cursor-pointer disabled:opacity-50 disabled:hover:scale-100"
>
{isChanging ? 'Changing...' : 'Change Password'}
</Button>
</form>
</div>
);
};
@@ -0,0 +1,140 @@
import { useState } from 'react';
import { X } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { useSettings } from '@/state/useSettings';
const LANGUAGES = [
{ code: 'en', label: 'English' },
{ code: 'pt', label: 'Portuguese' },
{ code: 'es', label: 'Spanish' },
{ code: 'fr', label: 'French' },
{ code: 'de', label: 'German' },
{ code: 'it', label: 'Italian' },
{ code: 'nl', label: 'Dutch' },
{ code: 'ru', label: 'Russian' },
{ code: 'zh', label: 'Chinese' },
{ code: 'ja', label: 'Japanese' },
{ code: 'ko', label: 'Korean' },
{ code: 'ar', label: 'Arabic' },
{ code: 'hi', label: 'Hindi' },
{ code: 'tr', label: 'Turkish' },
{ code: 'pl', label: 'Polish' },
{ code: 'sv', label: 'Swedish' },
{ code: 'da', label: 'Danish' },
{ code: 'no', label: 'Norwegian' },
{ code: 'fi', label: 'Finnish' },
{ code: 'uk', label: 'Ukrainian' },
{ code: 'cs', label: 'Czech' },
{ code: 'ro', label: 'Romanian' },
{ code: 'el', label: 'Greek' },
{ code: 'he', label: 'Hebrew' },
{ code: 'th', label: 'Thai' },
{ code: 'vi', label: 'Vietnamese' },
{ code: 'id', label: 'Indonesian' },
{ code: 'ms', label: 'Malay' },
];
const getLabel = (code: string) => LANGUAGES.find((l) => l.code === code)?.label ?? code;
export const Languages = () => {
const { settings, saveSettings } = useSettings();
const { spoken, default: defaultLang, translateTo } = settings.languages;
const [addingLang, setAddingLang] = useState('');
const save = (languages: typeof settings.languages) => {
saveSettings({ ...settings, languages });
};
const addSpoken = (code: string) => {
if (!code || spoken.includes(code)) return;
save({ ...settings.languages, spoken: [...spoken, code] });
setAddingLang('');
};
const removeSpoken = (code: string) => {
const next = spoken.filter((s) => s !== code);
const updates = { ...settings.languages, spoken: next };
if (defaultLang === code) updates.default = next[0] ?? 'en';
if (translateTo === code) updates.translateTo = next[0] ?? 'en';
save(updates);
};
const availableToAdd = LANGUAGES.filter((l) => !spoken.includes(l.code));
return (
<div className="grid gap-5">
{/* Spoken languages */}
<div className="grid gap-2">
<span className="text-sm font-medium text-duck-dark/70">Languages you speak</span>
<div className="flex flex-wrap gap-2">
{spoken.map((code) => (
<span
key={code}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-duck-teal/10 text-duck-teal text-sm font-medium"
>
{getLabel(code)}
{spoken.length > 1 && (
<button
onClick={() => removeSpoken(code)}
className="hover:text-red-500 cursor-pointer transition-colors"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</span>
))}
</div>
{availableToAdd.length > 0 && (
<div className="flex items-center gap-2 mt-1">
<select
value={addingLang}
onChange={(ev) => addSpoken(ev.target.value)}
className="text-sm border border-duck-dark/20 rounded-md px-3 py-1.5 bg-white/60 text-duck-dark cursor-pointer"
>
<option value="">Add a language...</option>
{availableToAdd.map((l) => (
<option key={l.code} value={l.code}>
{l.label}
</option>
))}
</select>
</div>
)}
</div>
{/* Default language */}
<Label className="grid gap-2">
<span className="text-duck-dark/70">Default language</span>
<select
value={defaultLang}
onChange={(ev) => save({ ...settings.languages, default: ev.target.value })}
className="text-sm border border-duck-dark/20 rounded-md px-3 py-2 bg-white/60 text-duck-dark cursor-pointer"
>
{spoken.map((code) => (
<option key={code} value={code}>
{getLabel(code)}
</option>
))}
</select>
<span className="text-xs text-duck-dark/40">Used for future UI localization.</span>
</Label>
{/* Translate from */}
<Label className="grid gap-2">
<span className="text-duck-dark/70">Translate to</span>
<select
value={translateTo}
onChange={(ev) => save({ ...settings.languages, translateTo: ev.target.value })}
className="text-sm border border-duck-dark/20 rounded-md px-3 py-2 bg-white/60 text-duck-dark cursor-pointer"
>
{LANGUAGES.map((l) => (
<option key={l.code} value={l.code}>
{l.label}
</option>
))}
</select>
<span className="text-xs text-duck-dark/40">Target language when translating content you don't speak.</span>
</Label>
</div>
);
};
@@ -0,0 +1,99 @@
import { useState, useEffect, useMemo } from 'react';
import { toast } from 'sonner';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useSettings } from '@/state/useSettings';
import { useVisibleClaudeModels, useVisibleOpenCodeModels } from '@/state/useModels';
export const TaskDefaults = () => {
const { settings, saveSettings } = useSettings();
const claudeModels = useVisibleClaudeModels();
const openCodeModels = useVisibleOpenCodeModels();
const [isSaving, setIsSaving] = useState(false);
const [model, setModel] = useState<string | null>(settings.tasks.defaultModel);
useEffect(() => {
setModel(settings.tasks.defaultModel);
}, [settings]);
const openCodeGroups = useMemo(() => {
const groups: Record<string, { id: string; name: string }[]> = {};
for (const m of openCodeModels) {
const provider = m.provider ?? 'OpenCode';
if (!groups[provider]) groups[provider] = [];
groups[provider].push({ id: m.id, name: m.name });
}
return Object.entries(groups)
.sort(([a], [b]) => a.localeCompare(b))
.map(([provider, models]) => ({ provider, models: models.sort((a, b) => a.name.localeCompare(b.name)) }));
}, [openCodeModels]);
const handleSave = async () => {
if (isSaving) return;
setIsSaving(true);
try {
const isOpenCode = openCodeModels.some((m) => m.id === model);
const defaultProvider = isOpenCode ? ('opencode' as const) : ('claude' as const);
await saveSettings({ ...settings, tasks: { defaultProvider, defaultModel: model } });
toast.success('Task defaults saved');
} catch {
toast.error('Failed to save settings');
} finally {
setIsSaving(false);
}
};
return (
<div className="grid gap-4">
<Label className="grid gap-2">
<span className="text-duck-dark/70">Default Model</span>
<Select value={model ?? ''} onValueChange={(v) => setModel(v || null)}>
<SelectTrigger className="h-11 bg-white/60 border-duck-dark/20 text-duck-dark">
<SelectValue placeholder="Same as chat default" />
</SelectTrigger>
<SelectContent className="z-[600] max-h-[300px]">
{claudeModels.length > 0 && (
<SelectGroup>
<SelectLabel>Claude</SelectLabel>
{claudeModels.map((m) => (
<SelectItem key={m.id} value={m.id}>
{m.name}
</SelectItem>
))}
</SelectGroup>
)}
{openCodeGroups.map(({ provider, models }) => (
<SelectGroup key={provider}>
<SelectLabel>{provider} (OpenCode)</SelectLabel>
{models.map((m) => (
<SelectItem key={`${provider}:${m.id}`} value={m.id}>
{m.name}
</SelectItem>
))}
</SelectGroup>
))}
</SelectContent>
</Select>
</Label>
<Button
type="button"
onClick={handleSave}
disabled={isSaving}
className="w-full h-11 bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold transition-all duration-200 hover:scale-105 cursor-pointer disabled:opacity-50 disabled:hover:scale-100"
>
{isSaving ? 'Saving...' : 'Save'}
</Button>
</div>
);
};
@@ -0,0 +1,126 @@
import { useRef, useState } from 'react';
import { toast } from 'sonner';
import { Camera } from 'lucide-react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { useForm } from 'hooks/useForm';
import { useAuth } from 'hooks/useAuth';
type ProfileFormState = {
name?: string;
};
const MAX_AVATAR_SIZE = 384_000; // ~384KB to stay under 512KB varchar after base64 overhead
const readFileAsBase64 = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(file);
});
};
export const UserData = () => {
const { user, updateUser } = useAuth();
const [isUpdating, setIsUpdating] = useState(false);
const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const profileForm = useForm<ProfileFormState>({ name: user?.name ?? '' });
const handleAvatarChange = async (ev: React.ChangeEvent<HTMLInputElement>) => {
const file = ev.target.files?.[0];
if (!file) return;
if (!file.type.startsWith('image/')) {
toast.error('Please select an image file');
return;
}
if (file.size > MAX_AVATAR_SIZE) {
toast.error('Image must be smaller than 384KB');
return;
}
const base64 = await readFileAsBase64(file);
setAvatarPreview(base64);
};
const handleSubmit = async (ev: React.FormEvent) => {
ev.preventDefault();
if (isUpdating) return;
setIsUpdating(true);
try {
await updateUser({
name: profileForm.state.name ?? '',
avatar: avatarPreview ?? user?.avatar ?? '',
});
toast.success('Profile updated');
setAvatarPreview(null);
} catch (ex) {
const error = ex as { message?: string };
toast.error(error.message || 'Failed to update profile');
} finally {
setIsUpdating(false);
}
};
const displayAvatar = avatarPreview ?? user?.avatar ?? undefined;
return (
<div>
<div className="flex justify-center mb-6">
<button
type="button"
className="relative group cursor-pointer rounded-full"
onClick={() => fileInputRef.current?.click()}
>
<Avatar className="h-20 w-20 rounded-full">
<AvatarImage src={displayAvatar} />
<AvatarFallback className="bg-duck-teal text-duck-yellow text-2xl font-bold rounded-full">
{user?.name?.charAt(0).toUpperCase() ?? '?'}
</AvatarFallback>
</Avatar>
<div className="absolute inset-0 rounded-full bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
<Camera className="h-6 w-6 text-white" />
</div>
</button>
<input ref={fileInputRef} type="file" accept="image/*" className="hidden" onChange={handleAvatarChange} />
</div>
<form ref={profileForm.formRef} onSubmit={handleSubmit} className="grid gap-4">
<Label className="grid gap-2">
<span className="text-duck-dark/70">Email</span>
<Input
className="h-11 bg-white/60 border-duck-dark/20 text-duck-dark placeholder:text-duck-dark/40"
type="email"
value={user?.email ?? ''}
disabled
/>
</Label>
<Label className="grid gap-2">
<span className="text-duck-dark/70">Name</span>
<Input
className="h-11 bg-white/60 border-duck-dark/20 text-duck-dark placeholder:text-duck-dark/40"
type="text"
name="name"
placeholder="Your name"
autoComplete="name"
/>
</Label>
<Button
type="submit"
disabled={isUpdating}
className="w-full h-11 bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold transition-all duration-200 hover:scale-105 cursor-pointer disabled:opacity-50 disabled:hover:scale-100"
>
{isUpdating ? 'Saving...' : 'Save'}
</Button>
</form>
</div>
);
};
@@ -0,0 +1,104 @@
import { useState, useEffect, useRef, useMemo } from 'react';
import { Search, User, Lock, Globe, ListChecks } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from '@/components/ui/accordion';
import { Card } from '@/components/Card';
import { DashboardLayout } from '../../Layout';
import { UserData } from './UserData';
import { ChangePassword } from './ChangePassword';
import { Languages } from './Languages';
import { TaskDefaults } from './TaskDefaults';
const sections = [
{
key: 'profile',
icon: User,
title: 'Profile',
description: 'Update your name and avatar.',
content: <UserData />,
},
{
key: 'tasks',
icon: ListChecks,
title: 'Tasks',
description: 'Default model for file browser tasks.',
content: <TaskDefaults />,
},
{
key: 'languages',
icon: Globe,
title: 'Languages',
description: 'Set your spoken languages and translation preferences.',
content: <Languages />,
},
{
key: 'change-password',
icon: Lock,
title: 'Change Password',
description: 'Update your account password.',
content: <ChangePassword />,
},
];
const allKeys = sections.map((s) => s.key);
export const ProfileSettings = () => {
const [search, setSearch] = useState('');
const [expanded, setExpanded] = useState<string[]>([]);
const sectionRefs = useRef<Record<string, HTMLDivElement | null>>({});
const matchingKeys = useMemo(() => {
if (!search) return allKeys;
const query = search.toLowerCase();
return sections
.filter((s) => {
const el = sectionRefs.current[s.key];
return (el?.textContent?.toLowerCase() ?? '').includes(query);
})
.map((s) => s.key);
}, [search]);
useEffect(() => {
if (search) setExpanded(matchingKeys);
}, [search, matchingKeys]);
return (
<DashboardLayout>
<div className="flex justify-center h-full px-4 py-8 overflow-y-auto">
<Card className="w-full max-w-2xl h-fit p-6">
<div className="relative mb-6">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-duck-dark/40" />
<Input
placeholder="Search settings..."
value={search}
onChange={(ev) => setSearch(ev.target.value)}
className="pl-9"
/>
</div>
<Accordion type="multiple" value={expanded} onValueChange={setExpanded}>
{sections.map((section) => (
<div
key={section.key}
ref={(el) => {
sectionRefs.current[section.key] = el;
}}
className={search && !matchingKeys.includes(section.key) ? 'hidden' : ''}
>
<AccordionItem value={section.key}>
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-3">
<section.icon className="h-5 w-5 text-duck-forest shrink-0" />
<div className="text-base font-bold text-duck-dark">{section.title}</div>
</div>
</AccordionTrigger>
<AccordionContent>{section.content}</AccordionContent>
</AccordionItem>
</div>
))}
</Accordion>
</Card>
</div>
</DashboardLayout>
);
};
@@ -0,0 +1,169 @@
import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { RefreshCw, Download, Circle, Copy, Check } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/Card';
import { useClient } from 'hooks/useClient';
import { DashboardLayout } from '../../Layout';
type AppStatus = {
id: string;
name: string;
description: string;
installed: boolean;
version: string | null;
running: boolean | null;
hasInstall: boolean;
hasUpdate: boolean;
manualInstallCommand: string | null;
manualUpdateCommand: string | null;
};
const CopyCommand = ({ command }: { command: string }) => {
const [copied, setCopied] = useState(false);
const copy = () => {
navigator.clipboard.writeText(command);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
};
return (
<div className="flex items-center gap-1 mt-1">
<code className="flex-1 bg-duck-dark/5 rounded px-2 py-1 text-xs text-duck-dark/70">{command}</code>
<button
type="button"
onClick={copy}
className="shrink-0 p-1 rounded hover:bg-duck-dark/10 cursor-pointer transition-colors"
>
{copied ? <Check className="h-3.5 w-3.5 text-green-600" /> : <Copy className="h-3.5 w-3.5 text-duck-dark/50" />}
</button>
</div>
);
};
export const ResourceSettings = () => {
const client = useClient();
const queryClient = useQueryClient();
const [actionInProgress, setActionInProgress] = useState<string | null>(null);
const { data: apps, isLoading } = useQuery({
queryKey: ['APPLICATIONS'],
queryFn: () => client.get<AppStatus[]>('/server-settings/applications'),
});
const runAction = async (id: string, action: 'install' | 'update') => {
setActionInProgress(id);
try {
await client.post<AppStatus>(`/server-settings/applications/${id}/${action}`);
await queryClient.invalidateQueries({ queryKey: ['APPLICATIONS'] });
toast.success(`${action === 'install' ? 'Installed' : 'Updated'} successfully`);
} catch (err) {
const message = err instanceof Error ? err.message : `${action} failed`;
toast.error(message);
} finally {
setActionInProgress(null);
}
};
const getManualCommand = (app: AppStatus): string | null => {
if (!app.installed) return app.manualInstallCommand;
return app.manualUpdateCommand ?? app.manualInstallCommand;
};
const hasAutoAction = (app: AppStatus): boolean => {
if (!app.installed) return app.hasInstall && !app.manualInstallCommand;
return app.hasUpdate && !(app.manualUpdateCommand ?? app.manualInstallCommand);
};
return (
<DashboardLayout>
<div className="flex justify-center h-full px-4 py-8 overflow-y-auto">
<Card className="w-full max-w-2xl h-fit p-6">
<h2 className="text-lg font-bold text-duck-dark mb-1">Applications</h2>
<p className="text-sm text-duck-dark/60 mb-6">System tools and dependencies used by Officer.dev</p>
{isLoading && <p className="text-sm text-duck-dark/50">Checking applications...</p>}
{apps && (
<div className="flex flex-col gap-3">
{apps.map((app: AppStatus) => {
const manualCmd = getManualCommand(app);
const canAutoRun = hasAutoAction(app);
return (
<div key={app.id} className="flex flex-col rounded-lg border border-duck-dark/10 px-4 py-3">
<div className="flex items-center justify-between gap-4">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-semibold text-duck-dark">{app.name}</span>
{app.installed && (
<span className="text-xs bg-green-100 text-green-700 rounded-full px-2 py-0.5">
{app.version}
</span>
)}
{!app.installed && (
<span className="text-xs bg-duck-dark/5 text-duck-dark/40 rounded-full px-2 py-0.5">
Not installed
</span>
)}
{app.running !== null && (
<Circle
className={`h-2.5 w-2.5 ${app.running ? 'fill-green-500 text-green-500' : 'fill-duck-dark/20 text-duck-dark/20'}`}
/>
)}
</div>
<p className="text-xs text-duck-dark/50 mt-0.5">{app.description}</p>
</div>
<div className="shrink-0">
{canAutoRun && !app.installed && (
<Button
size="sm"
className="bg-duck-teal text-duck-yellow hover:bg-duck-teal/90"
disabled={actionInProgress === app.id}
onClick={() => runAction(app.id, 'install')}
>
{actionInProgress === app.id ? (
<RefreshCw className="h-3.5 w-3.5 animate-spin" />
) : (
<Download className="h-3.5 w-3.5" />
)}
{actionInProgress === app.id ? 'Installing...' : 'Install'}
</Button>
)}
{canAutoRun && app.installed && (
<Button
size="sm"
variant="outline"
disabled={actionInProgress === app.id}
onClick={() => runAction(app.id, 'update')}
>
{actionInProgress === app.id ? (
<RefreshCw className="h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCw className="h-3.5 w-3.5" />
)}
{actionInProgress === app.id ? 'Updating...' : 'Update'}
</Button>
)}
</div>
</div>
{manualCmd && (
<div className="mt-2 text-xs text-duck-dark/50">
{app.installed ? 'Update' : 'Install'} manually:
<CopyCommand command={manualCmd} />
</div>
)}
</div>
);
})}
</div>
)}
</Card>
</div>
</DashboardLayout>
);
};
@@ -0,0 +1,215 @@
import { useState } from 'react';
import { Copy, Check } from 'lucide-react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { useClient } from 'hooks/useClient';
import { useServerSettings } from '@/state/useServerSettings';
type VersionInfo = { version: string | null; path: string | null; globalPath: string | null };
type ClaudeAuthInfo = { authenticated: boolean; loggedIn?: boolean; subscriptionType?: string };
type OpencodeAuthInfo = { authenticated: boolean; providers: string[] };
export const AIHarnessesSection = () => {
const client = useClient();
const queryClient = useQueryClient();
const { aiHarnesses, saveSettings } = useServerSettings();
const [installing, setInstalling] = useState<{ claudeCode: boolean; opencode: boolean }>({
claudeCode: false,
opencode: false,
});
const [copied, setCopied] = useState<string | null>(null);
const { data: opencodeVersion, isLoading: opencodeLoading } = useQuery({
queryKey: ['OPENCODE_VERSION'],
queryFn: () => client.get<VersionInfo>('/server-settings/opencode/version'),
enabled: !!aiHarnesses?.opencode,
refetchInterval: (query) => {
const data = query.state.data;
return data?.version && !data?.globalPath ? 1000 : false;
},
});
const { data: claudeVersion, isLoading: claudeLoading } = useQuery({
queryKey: ['CLAUDE_CODE_VERSION'],
queryFn: () => client.get<VersionInfo>('/server-settings/claude-code/version'),
enabled: !!aiHarnesses?.claudeCode,
refetchInterval: (query) => {
const data = query.state.data;
return data?.version && !data?.globalPath ? 1000 : false;
},
});
const { data: opencodeAuth } = useQuery({
queryKey: ['OPENCODE_AUTH'],
queryFn: () => client.get<OpencodeAuthInfo>('/server-settings/opencode/auth'),
enabled: !!opencodeVersion?.version,
refetchInterval: (query) => (!query.state.data?.authenticated ? 2000 : false),
});
const { data: claudeAuth } = useQuery({
queryKey: ['CLAUDE_CODE_AUTH'],
queryFn: () => client.get<ClaudeAuthInfo>('/server-settings/claude-code/auth'),
enabled: !!claudeVersion?.version,
refetchInterval: (query) => (!query.state.data?.authenticated ? 2000 : false),
});
const toggleHarness = (key: 'claudeCode' | 'opencode', checked: boolean) => {
const updated = { ...aiHarnesses, [key]: checked };
saveSettings({ aiHarnesses: updated });
};
const installClaude = async () => {
setInstalling((prev) => ({ ...prev, claudeCode: true }));
try {
const result = await client.post<VersionInfo>('/server-settings/claude-code/install');
queryClient.setQueryData(['CLAUDE_CODE_VERSION'], result);
} finally {
setInstalling((prev) => ({ ...prev, claudeCode: false }));
}
};
const installOpencode = async () => {
setInstalling((prev) => ({ ...prev, opencode: true }));
try {
const result = await client.post<VersionInfo>('/server-settings/opencode/install');
queryClient.setQueryData(['OPENCODE_VERSION'], result);
} finally {
setInstalling((prev) => ({ ...prev, opencode: false }));
}
};
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
setCopied(text);
setTimeout(() => setCopied(null), 1500);
};
const CopyCommand = ({ command }: { command: string }) => (
<div className="mt-2 text-xs text-amber-600">
Not globally accessible. Run:
<div className="flex items-center gap-1 mt-1">
<code className="flex-1 bg-duck-dark/5 rounded px-2 py-1 text-duck-dark/70">{command}</code>
<button
type="button"
onClick={() => copyToClipboard(command)}
className="shrink-0 p-1 rounded hover:bg-duck-dark/10 cursor-pointer transition-colors"
>
{copied === command ? (
<Check className="h-3.5 w-3.5 text-green-600" />
) : (
<Copy className="h-3.5 w-3.5 text-duck-dark/50" />
)}
</button>
</div>
</div>
);
return (
<div className="flex flex-col gap-4">
<div>
<label className="flex items-center gap-3 cursor-pointer">
<Checkbox
checked={!!aiHarnesses?.opencode}
onCheckedChange={(checked) => toggleHarness('opencode', !!checked)}
/>
<span className="text-sm font-medium text-duck-dark">Opencode</span>
</label>
{aiHarnesses?.opencode && (
<div className="ml-7 mt-2 text-xs text-duck-dark/50">
{opencodeLoading ? (
'Checking version...'
) : opencodeVersion?.version ? (
<>
<div>{opencodeVersion.version}</div>
<div>{opencodeVersion.path}</div>
{opencodeAuth && (
<div className={`mt-1 ${opencodeAuth.authenticated ? 'text-green-600' : 'text-amber-600'}`}>
{opencodeAuth.authenticated ? (
`Logged in (${opencodeAuth.providers.join(', ')})`
) : (
<div className="flex items-center gap-2">
<span>Not logged in</span>
<Button
size="sm"
className="bg-duck-teal text-duck-yellow hover:bg-duck-teal/90"
onClick={() => client.post('/server-settings/opencode/auth/login')}
>
Login
</Button>
</div>
)}
</div>
)}
{!opencodeVersion.globalPath && opencodeVersion.path && (
<CopyCommand command={`sudo ln -s ${opencodeVersion.path} /usr/local/bin/opencode`} />
)}
</>
) : (
<Button
size="sm"
className="bg-duck-teal text-duck-yellow hover:bg-duck-teal/90"
onClick={installOpencode}
disabled={installing.opencode}
>
{installing.opencode ? 'Installing...' : 'Install'}
</Button>
)}
</div>
)}
</div>
<div>
<label className="flex items-center gap-3 cursor-pointer">
<Checkbox
checked={!!aiHarnesses?.claudeCode}
onCheckedChange={(checked) => toggleHarness('claudeCode', !!checked)}
/>
<span className="text-sm font-medium text-duck-dark">Claude Code</span>
</label>
{aiHarnesses?.claudeCode && (
<div className="ml-7 mt-2 text-xs text-duck-dark/50">
{claudeLoading ? (
'Checking version...'
) : claudeVersion?.version ? (
<>
<div>{claudeVersion.version}</div>
<div>{claudeVersion.path}</div>
{claudeAuth && (
<div className={`mt-1 ${claudeAuth.authenticated ? 'text-green-600' : 'text-amber-600'}`}>
{claudeAuth.authenticated ? (
`Logged in (${claudeAuth.subscriptionType ?? 'unknown plan'})`
) : (
<div className="flex items-center gap-2">
<span>Not logged in</span>
<Button
size="sm"
className="bg-duck-teal text-duck-yellow hover:bg-duck-teal/90"
onClick={() => client.post('/server-settings/claude-code/auth/login')}
>
Login
</Button>
</div>
)}
</div>
)}
{!claudeVersion.globalPath && claudeVersion.path && (
<CopyCommand command={`sudo ln -s ${claudeVersion.path} /usr/local/bin/claude`} />
)}
</>
) : (
<Button
size="sm"
className="bg-duck-teal text-duck-yellow hover:bg-duck-teal/90"
onClick={installClaude}
disabled={installing.claudeCode}
>
{installing.claudeCode ? 'Installing...' : 'Install'}
</Button>
)}
</div>
)}
</div>
</div>
);
};
@@ -0,0 +1,39 @@
import { useQuery } from '@tanstack/react-query';
import { Switch } from '@/components/ui/switch';
import { useClient } from 'hooks/useClient';
import { useServerSettings } from '@/state/useServerSettings';
type PluginInfo = {
id: string;
name: string;
description: string;
enabled: boolean;
};
export const PluginsSection = () => {
const client = useClient();
const { plugins, saveSettings } = useServerSettings();
const { data: pluginList } = useQuery({
queryKey: ['PLUGINS_LIST'],
queryFn: () => client.get<PluginInfo[]>('/server-settings/plugins'),
});
const togglePlugin = (id: string, enabled: boolean) => {
saveSettings({ plugins: { ...plugins, [id]: enabled } });
};
return (
<div className="flex flex-col gap-4">
{pluginList?.map((p: PluginInfo) => (
<div key={p.id} className="flex items-center justify-between gap-4">
<div>
<div className="text-sm font-medium text-duck-dark">{p.name}</div>
<div className="text-xs text-duck-dark/50">{p.description}</div>
</div>
<Switch checked={plugins?.[p.id] !== false} onCheckedChange={(checked) => togglePlugin(p.id, !!checked)} />
</div>
))}
</div>
);
};
@@ -0,0 +1,20 @@
import { Switch } from '@/components/ui/switch';
import { useServerSettings } from '@/state/useServerSettings';
export const TerminalSection = () => {
const { terminalSandboxed, saveSettings } = useServerSettings();
const toggleSandbox = (checked: boolean) => {
saveSettings({ terminalSandboxed: checked });
};
return (
<div className="flex items-center justify-between gap-4">
<div>
<div className="text-sm font-medium text-duck-dark">Sandbox terminal (Docker)</div>
<div className="text-xs text-duck-dark/50">Restrict terminal access to the user's home directory.</div>
</div>
<Switch checked={terminalSandboxed === true} onCheckedChange={toggleSandbox} />
</div>
);
};
@@ -0,0 +1,99 @@
import { useState, useEffect, useRef, useMemo } from 'react';
import { Search, Terminal, Puzzle, Shield } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from '@/components/ui/accordion';
import { Card } from '@/components/Card';
import { DashboardLayout } from '../../Layout';
import { AIHarnessesSection } from './AIHarnessesSection';
import { PluginsSection } from './PluginsSection';
import { TerminalSection } from './TerminalSection';
const sections = [
{
key: 'ai-harnesses',
icon: Terminal,
title: 'AI Harnesses',
description: 'Which AI coding tools do you use?',
content: <AIHarnessesSection />,
},
{
key: 'plugins',
icon: Puzzle,
title: 'Plugins',
description: 'Enable or disable installed plugins.',
content: <PluginsSection />,
},
{
key: 'terminal',
icon: Shield,
title: 'Terminal',
description: 'Sandbox and access controls for the Terminal plugin.',
content: <TerminalSection />,
},
];
const allKeys = sections.map((s) => s.key);
export const ServerSettings = () => {
const [search, setSearch] = useState('');
const [expanded, setExpanded] = useState<string[]>(allKeys);
const sectionRefs = useRef<Record<string, HTMLDivElement | null>>({});
const matchingKeys = useMemo(() => {
if (!search) return allKeys;
const query = search.toLowerCase();
return sections
.filter((s) => {
const el = sectionRefs.current[s.key];
return (el?.textContent?.toLowerCase() ?? '').includes(query);
})
.map((s) => s.key);
}, [search]);
useEffect(() => {
setExpanded(search ? matchingKeys : allKeys);
}, [search, matchingKeys]);
return (
<DashboardLayout>
<div className="flex justify-center h-full px-4 py-8 overflow-y-auto">
<Card className="w-full max-w-2xl h-fit p-6">
<div className="relative mb-6">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-duck-dark/40" />
<Input
placeholder="Search settings..."
value={search}
onChange={(ev) => setSearch(ev.target.value)}
className="pl-9"
/>
</div>
<Accordion type="multiple" value={expanded} onValueChange={setExpanded}>
{sections.map((section) => (
<div
key={section.key}
ref={(el) => {
sectionRefs.current[section.key] = el;
}}
className={search && !matchingKeys.includes(section.key) ? 'hidden' : ''}
>
<AccordionItem value={section.key}>
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-3">
<section.icon className="h-5 w-5 text-duck-forest shrink-0" />
<div className="text-left">
<div className="text-base font-bold text-duck-dark">{section.title}</div>
<div className="text-sm font-normal text-duck-dark/70">{section.description}</div>
</div>
</div>
</AccordionTrigger>
<AccordionContent forceMount>{section.content}</AccordionContent>
</AccordionItem>
</div>
))}
</Accordion>
</Card>
</div>
</DashboardLayout>
);
};