Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: autosave Chief of Staff config changes
[._.]/ Adam Eivy6f52ee20e647
diff --git a/client/src/components/cos/tabs/ConfigRow.jsx b/client/src/components/cos/tabs/ConfigRow.jsxindex 2c6347ed62..982e656db2 100644--- a/client/src/components/cos/tabs/ConfigRow.jsx+++ b/client/src/components/cos/tabs/ConfigRow.jsx@@ -1,21 +1,41 @@-import { useId } from 'react';+import { useEffect, useId, useRef, useState } from 'react';export default function ConfigRow({label,description,- value,- editing,- type,inputValue,onChange,suffix,options = [],+ type,min,max,step,}) {const controlId = useId();const isCheckbox = type === 'checkbox';+ const numberFocusedRef = useRef(false);+ const [numberDraft, setNumberDraft] = useState(String(inputValue));++ useEffect(() => {+ if (!numberFocusedRef.current) setNumberDraft(String(inputValue));+ }, [inputValue]);++ const commitNumber = (event) => {+ const value = Number(numberDraft);+ if (+ numberDraft.trim() === ''+ || !Number.isFinite(value)+ || (min != null && value < min)+ || (max != null && value > max)+ || event.currentTarget.validity.stepMismatch+ ) {+ setNumberDraft(String(inputValue));+ return;+ }+ setNumberDraft(String(value));+ if (value !== inputValue) onChange(value);+ };return (<div className="flex min-h-24 flex-col justify-between gap-3 rounded-lg border border-port-border bg-port-card p-3.5">@@ -24,53 +44,55 @@ export default function ConfigRow({{description && <p className="mt-1 text-xs leading-relaxed text-port-text-muted">{description}</p>}</div>- {editing ? (- isCheckbox ? (- <label htmlFor={controlId} className="flex cursor-pointer items-center justify-between gap-3">- <span className={`text-xs font-medium ${inputValue ? 'text-port-success' : 'text-port-text-muted'}`}>- {inputValue ? 'Enabled' : 'Disabled'}- </span>- <span className={`relative inline-flex h-6 w-11 shrink-0 rounded-full transition-colors has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-port-accent has-[:focus-visible]:ring-offset-2 has-[:focus-visible]:ring-offset-port-card ${inputValue ? 'bg-port-accent' : 'bg-port-border'}`}>- <input- id={controlId}- type="checkbox"- checked={Boolean(inputValue)}- onChange={(event) => onChange(event.target.checked)}- className="peer sr-only"- />- <span className={`m-1 h-4 w-4 rounded-full bg-white transition-transform ${inputValue ? 'translate-x-5' : ''}`} />- </span>- </label>- ) : type === 'select' ? (- <select- id={controlId}- value={inputValue}- onChange={(event) => onChange(event.target.value)}- className="w-full rounded-md border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text"- >- {options.map((option) => (- <option key={option.value} value={option.value}>{option.label}</option>- ))}- </select>- ) : (- <div className="flex items-center gap-2">+ {isCheckbox ? (+ <label htmlFor={controlId} className="flex cursor-pointer items-center justify-between gap-3">+ <span className={`text-xs font-medium ${inputValue ? 'text-port-success' : 'text-port-text-muted'}`}>+ {inputValue ? 'Enabled' : 'Disabled'}+ </span>+ <span className={`relative inline-flex h-6 w-11 shrink-0 rounded-full transition-colors has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-port-accent has-[:focus-visible]:ring-offset-2 has-[:focus-visible]:ring-offset-port-card ${inputValue ? 'bg-port-accent' : 'bg-port-border'}`}><inputid={controlId}- type="number"- min={min}- max={max}- step={step}- value={inputValue}- onChange={(event) => onChange(Number(event.target.value))}- className="min-w-0 flex-1 rounded-md border border-port-border bg-port-bg px-3 py-2 text-right text-sm text-port-text"+ type="checkbox"+ checked={Boolean(inputValue)}+ onChange={(event) => onChange(event.target.checked)}+ className="peer sr-only"/>- {suffix && <span className="shrink-0 text-xs text-port-text-muted">{suffix}</span>}- </div>- )+ <span className={`m-1 h-4 w-4 rounded-full bg-white transition-transform ${inputValue ? 'translate-x-5' : ''}`} />+ </span>+ </label>+ ) : type === 'select' ? (+ <select+ id={controlId}+ value={inputValue}+ onChange={(event) => onChange(event.target.value)}+ className="w-full rounded-md border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text"+ >+ {options.map((option) => (+ <option key={option.value} value={option.value}>{option.label}</option>+ ))}+ </select>) : (- <span className={`text-sm font-semibold ${isCheckbox && inputValue ? 'text-port-success' : 'text-port-text'}`}>- {value}- </span>+ <div className="flex items-center gap-2">+ <input+ id={controlId}+ type="number"+ min={min}+ max={max}+ step={step}+ value={numberDraft}+ onFocus={() => { numberFocusedRef.current = true; }}+ onChange={(event) => setNumberDraft(event.target.value)}+ onBlur={(event) => {+ numberFocusedRef.current = false;+ commitNumber(event);+ }}+ onKeyDown={(event) => {+ if (event.key === 'Enter') event.currentTarget.blur();+ }}+ className="min-w-0 flex-1 rounded-md border border-port-border bg-port-bg px-3 py-2 text-right text-sm text-port-text"+ />+ {suffix && <span className="shrink-0 text-xs text-port-text-muted">{suffix}</span>}+ </div>)}</div>);diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsxindex 324f928b82..03c01a8320 100644--- a/client/src/components/cos/tabs/ConfigTab.jsx+++ b/client/src/components/cos/tabs/ConfigTab.jsx@@ -1,19 +1,16 @@-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Link } from 'react-router';import {Activity,Brain,- CheckCircle,Database,ExternalLink,FileText,Gauge,Palette,Server,- Settings,ShieldCheck,Sparkles,- X,} from 'lucide-react';import toast from '../../ui/Toast';import * as api from '../../../services/api';@@ -57,7 +54,6 @@ const getDefaultFormData = (config, avatarStyle) => ({healthCheckIntervalMs: config?.healthCheckIntervalMs ?? 900_000,maxConcurrentAgents: config?.maxConcurrentAgents ?? 3,maxConcurrentAgentsPerProject: config?.maxConcurrentAgentsPerProject ?? 2,- maxProcessMemoryMb: config?.maxProcessMemoryMb ?? 2_048,maxTotalProcesses: config?.maxTotalProcesses ?? 50,startOnBoot: Boolean(config?.alwaysOn || config?.autoStart),improvementEnabled: config?.improvementEnabled ?? config?.selfImprovementEnabled ?? true,@@ -70,26 +66,6 @@ const getDefaultFormData = (config, avatarStyle) => ({dynamicAvatar: config?.dynamicAvatar ?? true,});-const configPayload = (formData) => ({- healthCheckIntervalMs: formData.healthCheckIntervalMs,- maxConcurrentAgents: formData.maxConcurrentAgents,- maxConcurrentAgentsPerProject: formData.maxConcurrentAgentsPerProject,- maxProcessMemoryMb: formData.maxProcessMemoryMb,- maxTotalProcesses: formData.maxTotalProcesses,- alwaysOn: formData.startOnBoot,- // Clear the legacy alias so turning boot startup off is not defeated by the- // server's `alwaysOn || autoStart` compatibility read.- autoStart: false,- improvementEnabled: formData.improvementEnabled,- idleReviewEnabled: formData.idleReviewEnabled,- idleReviewPriority: formData.idleReviewPriority,- autonomousJobsEnabled: formData.autonomousJobsEnabled,- autoApproveInvestigations: formData.autoApproveInvestigations,- appReviewCooldownMs: formData.appReviewCooldownMs,- avatarStyle: formData.avatarStyle,- dynamicAvatar: formData.dynamicAvatar,-});-function SectionHeading({ icon: Icon, title, description }) {return (<div className="flex items-start gap-3">@@ -135,7 +111,7 @@ function DomainAutomationControl({ config, usage, onDomainChange, onBudgetChangetype="button"aria-pressed={active}title={mode.description}- onClick={() => onDomainChange(domain.id, mode.id, mode.label, domain.label)}+ onClick={() => onDomainChange(domain.id, mode.id)}className={`rounded-md border px-2 py-1.5 text-xs font-medium transition-colors ${active ? colors.active : colors.base}`}>{mode.label}@@ -163,7 +139,7 @@ function DomainAutomationControl({ config, usage, onDomainChange, onBudgetChangeinputMode="numeric"defaultValue={cap ?? ''}placeholder="Unlimited"- onBlur={(event) => onBudgetChange(domain.id, field.id, event.target.value, domain.label, field.label)}+ onBlur={(event) => onBudgetChange(domain.id, field.id, event.target.value)}className={`w-full rounded-md border bg-port-bg px-2 py-1.5 text-xs text-port-text ${capped ? 'border-port-warning' : 'border-port-border'}`}/></div>@@ -232,26 +208,110 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r} = useProviderModels();const [embeddingProviderId, setEmbeddingProviderId] = useState(config?.embeddingProviderId || 'lmstudio');const [embeddingModel, setEmbeddingModel] = useState(config?.embeddingModel || '');- const [editing, setEditing] = useState(false);- const [saving, setSaving] = useState(false);const [formData, setFormData] = useState(() => getDefaultFormData(config, avatarStyle));+ const [domainAutonomyOverrides, setDomainAutonomyOverrides] = useState({});+ const [domainBudgetOverrides, setDomainBudgetOverrides] = useState({});+ const [saveStatus, setSaveStatus] = useState('idle');+ const [profileSaving, setProfileSaving] = useState(false);const [budgetUsage, setBudgetUsage] = useState({});const [mindStatus, setMindStatus] = useState({ data: null, loaded: false, error: null });+ const configSaveQueueRef = useRef(Promise.resolve());+ const pendingSaveCountRef = useRef(0);+ const failedSaveKeysRef = useRef(new Set());+ const pendingConfigFieldsRef = useRef(new Map());++ const saveConfigPatch = useCallback((patch, { failureKeys = Object.keys(patch), onSuccess } = {}) => {+ pendingSaveCountRef.current += 1;+ setSaveStatus('saving');++ const request = configSaveQueueRef.current+ .catch(() => undefined)+ .then(() => api.updateCosConfig(patch, { silent: true }));+ configSaveQueueRef.current = request.catch(() => undefined);++ return request.then((result) => {+ failureKeys.forEach((key) => failedSaveKeysRef.current.delete(key));+ const reportRefreshError = (error) => toast.error(error?.message || 'Settings saved, but the page could not refresh');+ try {+ Promise.resolve(onSuccess?.(result)).catch(reportRefreshError);+ } catch (error) {+ reportRefreshError(error);+ }+ try {+ Promise.resolve(onUpdate?.()).catch(reportRefreshError);+ } catch (error) {+ reportRefreshError(error);+ }+ return result;+ }, (error) => {+ failureKeys.forEach((key) => failedSaveKeysRef.current.add(key));+ toast.error(error?.message || 'Configuration could not be saved');+ return null;+ }).finally(() => {+ pendingSaveCountRef.current -= 1;+ if (pendingSaveCountRef.current > 0) setSaveStatus('saving');+ else setSaveStatus(failedSaveKeysRef.current.size ? 'error' : 'saved');+ });+ }, [onUpdate]);++ const updateSetting = useCallback((field, value) => {+ pendingConfigFieldsRef.current.set(field, value);+ setFormData((current) => ({ ...current, [field]: value }));+ const patch = field === 'startOnBoot'+ ? { alwaysOn: value, autoStart: false }+ : { [field]: value };+ return saveConfigPatch(patch, { failureKeys: [field] });+ }, [saveConfigPatch]);useEffect(() => {- if (config?.embeddingProviderId) {- setEmbeddingProviderId(config.embeddingProviderId);- setProviderHook(config.embeddingProviderId);+ const savedFormData = getDefaultFormData(config, avatarStyle);+ setFormData(Object.fromEntries(Object.entries(savedFormData).map(([field, savedValue]) => {+ const pendingValue = pendingConfigFieldsRef.current.get(field);+ if (pendingConfigFieldsRef.current.has(field) && pendingValue !== savedValue) return [field, pendingValue];+ pendingConfigFieldsRef.current.delete(field);+ return [field, savedValue];+ })));++ const savedProviderId = config?.embeddingProviderId;+ if (savedProviderId !== undefined) {+ const pendingProviderId = pendingConfigFieldsRef.current.get('embeddingProviderId');+ if (!pendingConfigFieldsRef.current.has('embeddingProviderId') || pendingProviderId === savedProviderId) {+ pendingConfigFieldsRef.current.delete('embeddingProviderId');+ setEmbeddingProviderId(savedProviderId);+ setProviderHook(savedProviderId);+ }}- if (config?.embeddingModel) {- setEmbeddingModel(config.embeddingModel);- setModelHook(config.embeddingModel);+ const savedModel = config?.embeddingModel;+ if (savedModel !== undefined) {+ const pendingModel = pendingConfigFieldsRef.current.get('embeddingModel');+ if (!pendingConfigFieldsRef.current.has('embeddingModel') || pendingModel === savedModel) {+ pendingConfigFieldsRef.current.delete('embeddingModel');+ setEmbeddingModel(savedModel);+ setModelHook(savedModel);+ }}- }, [config?.embeddingProviderId, config?.embeddingModel, setProviderHook, setModelHook]);- useEffect(() => {- if (!editing) setFormData(getDefaultFormData(config, avatarStyle));- }, [config, avatarStyle, editing]);+ setDomainAutonomyOverrides((current) => Object.fromEntries(Object.entries(current).filter(+ ([domainId, mode]) => getDomainMode(config, domainId) !== mode,+ )));+ setDomainBudgetOverrides((current) => Object.fromEntries(Object.entries(current).flatMap(([domainId, fields]) => {+ const savedBudget = getDomainBudget(config, domainId);+ const remaining = Object.fromEntries(Object.entries(fields).filter(([field, value]) => (savedBudget[field] ?? null) !== value));+ return Object.keys(remaining).length ? [[domainId, remaining]] : [];+ })));+ }, [config, avatarStyle, setProviderHook, setModelHook]);++ const displayConfig = useMemo(() => {+ const domainBudgets = { ...(config?.domainBudgets || {}) };+ for (const [domainId, fields] of Object.entries(domainBudgetOverrides)) {+ domainBudgets[domainId] = { ...(domainBudgets[domainId] || {}), ...fields };+ }+ return {+ ...config,+ domainAutonomy: { ...(config?.domainAutonomy || {}), ...domainAutonomyOverrides },+ domainBudgets,+ };+ }, [config, domainAutonomyOverrides, domainBudgetOverrides]);const refreshBudgetUsage = useCallback(() => (api.getCosBudgetUsage({ silent: true })@@ -285,16 +345,10 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r})),]), [riggedAvatars]);- const avatarLabel = (style) => {- if (AVATAR_STYLE_LABELS[style]) return AVATAR_STYLE_LABELS[style];- const record = riggedRecordForStyle(riggedAvatars, style);- return record ? `${record.name} (rigged 3D)` : style;- };-- // Honest coverage note for the staged value: which states the character+ // Honest coverage note for the selected value: which states the character// covers, what the rest fall back to — or a warning when the record the// saved style points at is gone.- const stagedRiggedNote = useMemo(() => {+ const selectedRiggedNote = useMemo(() => {if (!isRiggedAvatarStyle(formData.avatarStyle)) return null;const record = riggedRecordForStyle(riggedAvatars, formData.avatarStyle);if (!record) return 'That animated record is no longer available — pick another avatar.';@@ -303,46 +357,33 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, rreturn `${coverageSummary(record.coverage)}. Covered: ${covered.join(', ') || 'none'}. ${fallback}`.trim();}, [formData.avatarStyle, riggedAvatars]);- const handleCancel = () => {- setFormData(getDefaultFormData(config, avatarStyle));- setEditing(false);+ const handleDomainChange = (domainId, mode) => {+ if (getDomainMode(displayConfig, domainId) === mode) return Promise.resolve();+ setDomainAutonomyOverrides((current) => ({ ...current, [domainId]: mode }));+ return saveConfigPatch({ domainAutonomy: { [domainId]: mode } }, {+ failureKeys: [`domainAutonomy:${domainId}`],+ onSuccess: refreshMindStatus,+ });};- const handleSave = () => {- setSaving(true);- return api.updateCosConfig(configPayload(formData), { silent: true })- .then(() => {- toast.success('Configuration updated');- setEditing(false);- onUpdate();- })- .catch((error) => toast.error(error.message))- .finally(() => setSaving(false));- };-- const handleDomainChange = (domainId, mode, modeLabel, domainLabel) => (- api.updateCosConfig({ domainAutonomy: { [domainId]: mode } }, { silent: true })- .then(() => {- toast.success(`${domainLabel} autonomy set to ${modeLabel}`);- onUpdate();- void refreshMindStatus();- })- .catch((error) => toast.error(error.message))- );-- const handleBudgetChange = (domainId, field, rawValue, domainLabel, fieldLabel) => {+ const handleBudgetChange = (domainId, field, rawValue) => {const value = normalizeBudgetLimit(rawValue);- const current = getDomainBudget(config, domainId)[field];+ const current = getDomainBudget(displayConfig, domainId)[field];if ((current ?? null) === value) return Promise.resolve();- return api.updateCosConfig({ domainBudgets: { [domainId]: { [field]: value } } }, { silent: true })- .then(() => {- toast.success(`${domainLabel} ${fieldLabel} ${value == null ? 'set to unlimited' : `capped at ${value}`}`);- onUpdate();- void refreshBudgetUsage();- })- .catch((error) => toast.error(error.message));+ setDomainBudgetOverrides((currentOverrides) => ({+ ...currentOverrides,+ [domainId]: { ...(currentOverrides[domainId] || {}), [field]: value },+ }));+ return saveConfigPatch({ domainBudgets: { [domainId]: { [field]: value } } }, {+ failureKeys: [`domainBudget:${domainId}:${field}`],+ onSuccess: refreshBudgetUsage,+ });};+ const displayedSaveStatus = saveStatus === 'error'+ ? 'error'+ : saveStatus === 'saving' || profileSaving ? 'saving' : saveStatus;+return (<div className="mx-auto max-w-6xl space-y-7 pb-6"><header className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">@@ -352,7 +393,13 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, rConfigure capacity, automatic work, the persistent mind, and supporting services. Domain guardrails are the authoritative autonomy controls.</p></div>- <div className="flex flex-wrap gap-2">+ <div className="flex flex-wrap items-center gap-3">+ <span data-testid="config-save-status" role={displayedSaveStatus === 'error' ? 'alert' : 'status'} aria-live="polite" className={`text-xs ${displayedSaveStatus === 'error' ? 'text-port-error' : 'text-port-text-muted'}`}>+ {displayedSaveStatus === 'saving' ? 'Saving changes…'+ : displayedSaveStatus === 'error' ? 'Some changes could not be saved. Change those settings to retry.'+ : displayedSaveStatus === 'saved' ? 'All changes saved'+ : 'Changes save automatically'}+ </span><buttontype="button"onClick={onEvaluate}@@ -361,34 +408,6 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r><Activity size={14} /> Force Evaluate</button>- {!editing ? (- <button- type="button"- onClick={() => setEditing(true)}- className="inline-flex items-center gap-2 rounded-lg bg-port-border px-3 py-2 text-sm text-port-text transition-colors hover:bg-port-border/80"- >- <Settings size={14} /> Edit settings- </button>- ) : (- <>- <button- type="button"- onClick={handleCancel}- disabled={saving}- className="inline-flex items-center gap-2 rounded-lg bg-port-border px-3 py-2 text-sm text-port-text-muted disabled:opacity-50"- >- <X size={14} /> Cancel- </button>- <button- type="button"- onClick={handleSave}- disabled={saving}- className="inline-flex items-center gap-2 rounded-lg bg-port-success/15 px-3 py-2 text-sm text-port-success transition-colors hover:bg-port-success/25 disabled:opacity-50"- >- <CheckCircle size={14} /> {saving ? 'Saving…' : 'Save settings'}- </button>- </>- )}</div></header>@@ -405,6 +424,7 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r<div className="rounded-lg border border-port-border bg-port-card p-4"><PersistentMindProfileControlsprofile={config?.persistentMindProfile}+ onSavingChange={setProfileSaving}onSaved={() => {onUpdate();void refreshMindStatus();@@ -423,7 +443,7 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r/></div><DomainAutomationControl- config={config}+ config={displayConfig}usage={budgetUsage}onDomainChange={handleDomainChange}onBudgetChange={handleBudgetChange}@@ -435,11 +455,11 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r<SectionHeading icon={Gauge} title="Capacity and health" description="Concurrency and health thresholds for the local CoS runtime." /></div><div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">- <ConfigRow label="Concurrent agents" description="Maximum active agents across all projects." value={formData.maxConcurrentAgents} editing={editing} type="number" inputValue={formData.maxConcurrentAgents} min={1} onChange={(value) => setFormData((current) => ({ ...current, maxConcurrentAgents: value }))} />- <ConfigRow label="Agents per project" description="Prevents one project from consuming every agent slot." value={formData.maxConcurrentAgentsPerProject} editing={editing} type="number" inputValue={formData.maxConcurrentAgentsPerProject} min={1} onChange={(value) => setFormData((current) => ({ ...current, maxConcurrentAgentsPerProject: value }))} />- <ConfigRow label="Process count alert" description="Flags an unexpectedly large PM2 process fleet." value={formData.maxTotalProcesses} editing={editing} type="number" inputValue={formData.maxTotalProcesses} min={1} onChange={(value) => setFormData((current) => ({ ...current, maxTotalProcesses: value }))} />- <ConfigRow label="Health check interval" description="How often CoS checks processes and memory." value={`${formData.healthCheckIntervalMs / 60_000} min`} editing={editing} type="number" inputValue={formData.healthCheckIntervalMs / 60_000} min={1} suffix="minutes" onChange={(value) => setFormData((current) => ({ ...current, healthCheckIntervalMs: value * 60_000 }))} />- <ConfigRow label="Start on server boot" description="Start the CoS daemon when PortOS starts." value={formData.startOnBoot ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.startOnBoot} onChange={(value) => setFormData((current) => ({ ...current, startOnBoot: value }))} />+ <ConfigRow label="Concurrent agents" description="Maximum active agents across all projects." type="number" inputValue={formData.maxConcurrentAgents} min={1} onChange={(value) => updateSetting('maxConcurrentAgents', value)} />+ <ConfigRow label="Agents per project" description="Prevents one project from consuming every agent slot." type="number" inputValue={formData.maxConcurrentAgentsPerProject} min={1} onChange={(value) => updateSetting('maxConcurrentAgentsPerProject', value)} />+ <ConfigRow label="Process count alert" description="Flags an unexpectedly large PM2 process fleet." type="number" inputValue={formData.maxTotalProcesses} min={1} onChange={(value) => updateSetting('maxTotalProcesses', value)} />+ <ConfigRow label="Health check interval" description="How often CoS checks processes and memory." type="number" inputValue={formData.healthCheckIntervalMs / 60_000} min={1} suffix="minutes" onChange={(value) => updateSetting('healthCheckIntervalMs', value * 60_000)} />+ <ConfigRow label="Start on server boot" description="Start the CoS daemon when PortOS starts." type="checkbox" inputValue={formData.startOnBoot} onChange={(value) => updateSetting('startOnBoot', value)} /></div></section>@@ -448,12 +468,12 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r<SectionHeading icon={Sparkles} title="Work generation and scheduling" description="Independent switches for how eligible work enters and moves through the queue." /></div><div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">- <ConfigRow label="Improvement tasks" description="Allow improvement work for PortOS and managed apps." value={formData.improvementEnabled ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.improvementEnabled} onChange={(value) => setFormData((current) => ({ ...current, improvementEnabled: value }))} />- <ConfigRow label="Idle app review" description="Look for app improvements when user work is idle." value={formData.idleReviewEnabled ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.idleReviewEnabled} onChange={(value) => setFormData((current) => ({ ...current, idleReviewEnabled: value }))} />- <ConfigRow label="Idle review priority" description="Priority assigned to newly generated idle-review tasks." value={PRIORITY_OPTIONS.find((option) => option.value === formData.idleReviewPriority)?.label} editing={editing} type="select" inputValue={formData.idleReviewPriority} options={PRIORITY_OPTIONS} onChange={(value) => setFormData((current) => ({ ...current, idleReviewPriority: value }))} />- <ConfigRow label="Scheduled agent jobs" description="Enable the global scheduler in addition to each job's own switch." value={formData.autonomousJobsEnabled ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.autonomousJobsEnabled} onChange={(value) => setFormData((current) => ({ ...current, autonomousJobsEnabled: value }))} />- <ConfigRow label="App review cooldown" description="Minimum time before CoS reviews the same app again." value={`${formData.appReviewCooldownMs / 60_000} min`} editing={editing} type="number" inputValue={formData.appReviewCooldownMs / 60_000} min={0} step="any" suffix="minutes" onChange={(value) => setFormData((current) => ({ ...current, appReviewCooldownMs: value * 60_000 }))} />- <ConfigRow label="Auto-approve investigations" description="Admit failure-loop and failure-storm investigations unattended." value={formData.autoApproveInvestigations ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.autoApproveInvestigations} onChange={(value) => setFormData((current) => ({ ...current, autoApproveInvestigations: value }))} />+ <ConfigRow label="Improvement tasks" description="Allow improvement work for PortOS and managed apps." type="checkbox" inputValue={formData.improvementEnabled} onChange={(value) => updateSetting('improvementEnabled', value)} />+ <ConfigRow label="Idle app review" description="Look for app improvements when user work is idle." type="checkbox" inputValue={formData.idleReviewEnabled} onChange={(value) => updateSetting('idleReviewEnabled', value)} />+ <ConfigRow label="Idle review priority" description="Priority assigned to newly generated idle-review tasks." type="select" inputValue={formData.idleReviewPriority} options={PRIORITY_OPTIONS} onChange={(value) => updateSetting('idleReviewPriority', value)} />+ <ConfigRow label="Scheduled agent jobs" description="Enable the global scheduler in addition to each job's own switch." type="checkbox" inputValue={formData.autonomousJobsEnabled} onChange={(value) => updateSetting('autonomousJobsEnabled', value)} />+ <ConfigRow label="App review cooldown" description="Minimum time before CoS reviews the same app again." type="number" inputValue={formData.appReviewCooldownMs / 60_000} min={0} step="any" suffix="minutes" onChange={(value) => updateSetting('appReviewCooldownMs', value * 60_000)} />+ <ConfigRow label="Auto-approve investigations" description="Admit failure-loop and failure-storm investigations unattended." type="checkbox" inputValue={formData.autoApproveInvestigations} onChange={(value) => updateSetting('autoApproveInvestigations', value)} /></div></section>@@ -462,11 +482,11 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r<SectionHeading icon={Palette} title="Appearance" description="Set the default avatar and whether active work may choose a matching style." /></div><div className="grid gap-3 sm:grid-cols-2">- <ConfigRow label="Default avatar" description="Visual style used by the CoS panel." value={avatarLabel(formData.avatarStyle)} editing={editing} type="select" inputValue={formData.avatarStyle} options={avatarOptions} onChange={(value) => setFormData((current) => ({ ...current, avatarStyle: value }))} />- <ConfigRow label="Dynamic avatar" description="Switch style based on task type, provider, or priority." value={formData.dynamicAvatar ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.dynamicAvatar} onChange={(value) => setFormData((current) => ({ ...current, dynamicAvatar: value }))} />+ <ConfigRow label="Default avatar" description="Visual style used by the CoS panel." type="select" inputValue={formData.avatarStyle} options={avatarOptions} onChange={(value) => updateSetting('avatarStyle', value)} />+ <ConfigRow label="Dynamic avatar" description="Switch style based on task type, provider, or priority." type="checkbox" inputValue={formData.dynamicAvatar} onChange={(value) => updateSetting('dynamicAvatar', value)} /></div>- {stagedRiggedNote && (- <p className="text-xs leading-relaxed text-port-text-muted">{stagedRiggedNote}</p>+ {selectedRiggedNote && (+ <p className="text-xs leading-relaxed text-port-text-muted">{selectedRiggedNote}</p>)}</section>@@ -483,23 +503,20 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, rselectedModel={embeddingModel || hookModel}availableModels={availableModels}onProviderChange={(id) => {+ pendingConfigFieldsRef.current.set('embeddingProviderId', id);+ pendingConfigFieldsRef.current.set('embeddingModel', '');setEmbeddingProviderId(id);setProviderHook(id);setEmbeddingModel('');- return api.updateCosConfig({ embeddingProviderId: id, embeddingModel: '' })- .then(() => {- toast.success('Embedding provider updated');- onUpdate();- });+ return saveConfigPatch({ embeddingProviderId: id, embeddingModel: '' }, {+ failureKeys: ['embeddingProviderId', 'embeddingModel'],+ });}}onModelChange={(model) => {+ pendingConfigFieldsRef.current.set('embeddingModel', model);setEmbeddingModel(model);setModelHook(model);- return api.updateCosConfig({ embeddingModel: model })- .then(() => {- toast.success('Embedding model updated');- onUpdate();- });+ return saveConfigPatch({ embeddingModel: model }, { failureKeys: ['embeddingModel'] });}}label="Embedding provider"/>diff --git a/client/src/components/cos/tabs/ConfigTab.test.jsx b/client/src/components/cos/tabs/ConfigTab.test.jsxindex 68ffa35d92..0ccd016e9e 100644--- a/client/src/components/cos/tabs/ConfigTab.test.jsx+++ b/client/src/components/cos/tabs/ConfigTab.test.jsx@@ -1,10 +1,9 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { MemoryRouter } from 'react-router';// Regression coverage for #2519 — failed CoS config calls must NOT flash a-// success toast, must keep the user in edit mode, and must revert optimistic-// state.+// success toast and must leave the user's value visible with a retry cue.const api = vi.hoisted(() => ({updateCosConfig: vi.fn(),getCosBudgetUsage: vi.fn(),@@ -42,7 +41,6 @@ const config = {healthCheckIntervalMs: 900000,maxConcurrentAgents: 3,maxConcurrentAgentsPerProject: 2,- maxProcessMemoryMb: 2048,maxTotalProcesses: 50,alwaysOn: false,autoStart: false,@@ -81,71 +79,83 @@ beforeEach(() => {});});-describe('ConfigTab handleSave', () => {- it('keeps the editor open and does not toast success when the save fails', async () => {- api.updateCosConfig.mockRejectedValue(new Error('network down'));- const onUpdate = vi.fn();- renderConfig({ onUpdate });-- fireEvent.click(screen.getByRole('button', { name: /Edit/i }));- fireEvent.click(screen.getByRole('button', { name: /Save/i }));-- await waitFor(() => expect(toast.error).toHaveBeenCalledWith('network down'));- expect(toast.success).not.toHaveBeenCalled();- expect(onUpdate).not.toHaveBeenCalled();- // Still in edit mode — the Save button is present (editor did not close).- expect(screen.getByRole('button', { name: /Save/i })).toBeInTheDocument();- });-- it('closes the editor and toasts success when the save resolves', async () => {+describe('ConfigTab autosave', () => {+ it('makes controls available immediately and saves checkbox changes as partial updates', async () => {api.updateCosConfig.mockResolvedValue({ success: true });const onUpdate = vi.fn();renderConfig({ onUpdate });+ await screen.findByText('Waiting for the next wake');- fireEvent.click(screen.getByRole('button', { name: /Edit/i }));- fireEvent.click(screen.getByRole('button', { name: /Save/i }));+ expect(screen.queryByRole('button', { name: /Edit settings/i })).not.toBeInTheDocument();+ const scheduledJobs = screen.getByRole('checkbox', { name: /Scheduled agent jobs/i });+ expect(scheduledJobs).toBeChecked();+ fireEvent.click(scheduledJobs);- await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Configuration updated'));- expect(onUpdate).toHaveBeenCalled();- // The PUT must pass { silent: true } so the custom catch is the only error toast.- expect(api.updateCosConfig).toHaveBeenCalledWith(expect.any(Object), { silent: true });- // Editor closed — the Edit button is back.- expect(screen.getByRole('button', { name: /Edit/i })).toBeInTheDocument();+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ { autonomousJobsEnabled: false },+ { silent: true },+ ));+ await waitFor(() => expect(screen.getByTestId('config-save-status')).toHaveTextContent('All changes saved'));+ expect(scheduledJobs).not.toBeChecked();+ expect(onUpdate).toHaveBeenCalledTimes(1);});- it('saves the newly exposed scheduler and health controls together', async () => {+ it('commits numeric fields on blur and discards an incomplete value', async () => {api.updateCosConfig.mockResolvedValue({ success: true });renderConfig();await screen.findByText('Waiting for the next wake');- fireEvent.click(screen.getByRole('button', { name: /Edit settings/i }));- fireEvent.change(screen.getByRole('spinbutton', { name: 'Process count alert' }), { target: { value: '64' } });- fireEvent.change(screen.getByRole('spinbutton', { name: 'App review cooldown' }), { target: { value: '45' } });- fireEvent.click(screen.getByRole('checkbox', { name: /Scheduled agent jobs/i }));- fireEvent.click(screen.getByRole('button', { name: /Save settings/i }));+ const processCount = screen.getByRole('spinbutton', { name: 'Process count alert' });+ fireEvent.change(processCount, { target: { value: '' } });+ fireEvent.blur(processCount);+ expect(api.updateCosConfig).not.toHaveBeenCalled();+ expect(processCount).toHaveValue(50);++ fireEvent.change(processCount, { target: { value: '64' } });+ expect(api.updateCosConfig).not.toHaveBeenCalled();+ fireEvent.blur(processCount);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- expect.objectContaining({- maxTotalProcesses: 64,- appReviewCooldownMs: 2_700_000,- autonomousJobsEnabled: false,- }),+ { maxTotalProcesses: 64 },{ silent: true },));});- it('preserves a valid sub-minute cooldown when saving unrelated settings', async () => {- api.updateCosConfig.mockResolvedValue({ success: true });- renderConfig({ config: { ...config, appReviewCooldownMs: 30_000 } });+ it('keeps a failed auto-save visible and reports the failure without a success toast', async () => {+ api.updateCosConfig.mockRejectedValue(new Error('network down'));+ const onUpdate = vi.fn();+ renderConfig({ onUpdate });- fireEvent.click(screen.getByRole('button', { name: /Edit settings/i }));- fireEvent.click(screen.getByRole('checkbox', { name: /Dynamic avatar/i }));- fireEvent.click(screen.getByRole('button', { name: /Save settings/i }));+ const scheduledJobs = screen.getByRole('checkbox', { name: /Scheduled agent jobs/i });+ fireEvent.click(scheduledJobs);- await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- expect.objectContaining({ appReviewCooldownMs: 30_000, dynamicAvatar: false }),- { silent: true },- ));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('network down'));+ expect(toast.success).not.toHaveBeenCalled();+ expect(onUpdate).not.toHaveBeenCalled();+ expect(scheduledJobs).not.toBeChecked();+ expect(screen.getByRole('alert')).toHaveTextContent('Change those settings to retry');+ });++ it('serializes rapid changes so an older request cannot finish after the newer value', async () => {+ let resolveFirst;+ api.updateCosConfig+ .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }))+ .mockResolvedValue({ success: true });+ renderConfig();+ await screen.findByText('Waiting for the next wake');++ const scheduledJobs = screen.getByRole('checkbox', { name: /Scheduled agent jobs/i });+ fireEvent.click(scheduledJobs);+ fireEvent.click(scheduledJobs);++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledTimes(1));+ expect(api.updateCosConfig).toHaveBeenNthCalledWith(1, { autonomousJobsEnabled: false }, { silent: true });+ await act(async () => {+ resolveFirst({ success: true });+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledTimes(2));+ });+ expect(api.updateCosConfig).toHaveBeenNthCalledWith(2, { autonomousJobsEnabled: true }, { silent: true });+ await waitFor(() => expect(screen.getByTestId('config-save-status')).toHaveTextContent('All changes saved'));});});@@ -173,13 +183,12 @@ describe('Force Evaluate button', () => {expect(toast.error).not.toHaveBeenCalled();});- it('stays available while the settings editor is open', async () => {+ it('stays available alongside the editable settings', async () => {const onEvaluate = vi.fn();renderConfig({ onEvaluate });await screen.findByText('Waiting for the next wake');- fireEvent.click(screen.getByRole('button', { name: /Edit settings/i }));-+ expect(screen.getByRole('checkbox', { name: /Scheduled agent jobs/i })).toBeInTheDocument();fireEvent.click(screen.getByRole('button', { name: /Force Evaluate/i }));expect(onEvaluate).toHaveBeenCalledTimes(1);});@@ -205,64 +214,22 @@ describe('persistent mind profile', () => {});describe('Default Avatar Style dropdown', () => {- it('shows the saved avatar style as text when not editing', async () => {- renderConfig({ config: { ...config, avatarStyle: 'svg' } });- await screen.findByText('Waiting for the next wake');-- expect(screen.queryByRole('combobox', { name: 'Default avatar' })).not.toBeInTheDocument();- expect(screen.getByText('Digital (SVG)')).toBeInTheDocument();- });-- it('stages dropdown selection locally without triggering immediate save call', async () => {+ it('is immediately editable and saves the selected avatar style', async () => {+ api.updateCosConfig.mockResolvedValue({ success: true });renderConfig({ config: { ...config, avatarStyle: 'svg' } });await screen.findByText('Waiting for the next wake');- fireEvent.click(screen.getByRole('button', { name: /Edit/i }));-const select = screen.getByRole('combobox', { name: 'Default avatar' });expect(select).toBeEnabled();+ expect(select).toHaveValue('svg');fireEvent.change(select, { target: { value: 'cyber' } });+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ { avatarStyle: 'cyber' },+ { silent: true },+ ));expect(select).toHaveValue('cyber');- expect(api.updateCosConfig).not.toHaveBeenCalled();- });-- it('includes staged avatarStyle in updateCosConfig payload on Save click', async () => {- api.updateCosConfig.mockResolvedValue({ success: true });- const onUpdate = vi.fn();- renderConfig({ config: { ...config, avatarStyle: 'svg' }, onUpdate });-- fireEvent.click(screen.getByRole('button', { name: /Edit/i }));-- const select = screen.getByRole('combobox', { name: 'Default avatar' });- fireEvent.change(select, { target: { value: 'cyber' } });-- fireEvent.click(screen.getByRole('button', { name: /Save/i }));-- await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Configuration updated'));- expect(api.updateCosConfig).toHaveBeenCalledWith(- expect.objectContaining({ avatarStyle: 'cyber' }),- { silent: true }- );- expect(screen.getByRole('button', { name: /Edit/i })).toBeInTheDocument();- });-- it('reverts staged avatarStyle dropdown selection when Cancel is clicked', async () => {- renderConfig({ config: { ...config, avatarStyle: 'svg' } });- await screen.findByText('Waiting for the next wake');-- fireEvent.click(screen.getByRole('button', { name: /Edit/i }));-- const select = screen.getByRole('combobox', { name: 'Default avatar' });- fireEvent.change(select, { target: { value: 'cyber' } });- expect(select).toHaveValue('cyber');-- fireEvent.click(screen.getByRole('button', { name: /Cancel/i }));-- expect(screen.getByRole('button', { name: /Edit/i })).toBeInTheDocument();- expect(screen.queryByRole('combobox', { name: 'Default avatar' })).not.toBeInTheDocument();- expect(screen.getByText('Digital (SVG)')).toBeInTheDocument();});});@@ -289,30 +256,25 @@ describe('Rigged avatar records in the Default Avatar dropdown', () => {renderConfig({ config: { ...config, avatarStyle: 'svg' }, riggedAvatars });await screen.findByText('Waiting for the next wake');- fireEvent.click(screen.getByRole('button', { name: /Edit/i }));-const select = screen.getByRole('combobox', { name: 'Default avatar' });const labels = [...select.options].map((option) => option.text);expect(labels).toContain('Digital (SVG)');expect(labels.some((label) => label.includes('Example Dancer') && label.includes('rigged 3D'))).toBe(true);});- it('shows the coverage note when a rigged record is staged', async () => {+ it('shows the coverage note and saves a selected rigged record', async () => {+ api.updateCosConfig.mockResolvedValue({ success: true });renderConfig({ config: { ...config, avatarStyle: 'svg' }, riggedAvatars });await screen.findByText('Waiting for the next wake');- fireEvent.click(screen.getByRole('button', { name: /Edit/i }));-const select = screen.getByRole('combobox', { name: 'Default avatar' });fireEvent.change(select, { target: { value: 'rigged-image3d-1' } });expect(await screen.findByText(/Covered: ideating/)).toBeInTheDocument();expect(screen.getByText(/Other states play Dance/)).toBeInTheDocument();- api.updateCosConfig.mockResolvedValue({ success: true });- fireEvent.click(screen.getByRole('button', { name: /Save/i }));await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- expect.objectContaining({ avatarStyle: 'rigged-image3d-1' }),+ { avatarStyle: 'rigged-image3d-1' },{ silent: true },));});@@ -345,19 +307,60 @@ describe('persistent mind status', () => {});});+describe('domain guardrails and embedding provider autosave', () => {+ it('saves an autonomy mode change immediately', async () => {+ api.updateCosConfig.mockResolvedValue({ success: true });+ renderConfig();+ await screen.findByText('Waiting for the next wake');++ fireEvent.click(within(screen.getByRole('group', { name: 'CoS auto-run mode' })).getByRole('button', { name: 'Off' }));++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ { domainAutonomy: { cos: 'off' } },+ { silent: true },+ ));+ });++ it('saves an embedding provider selection immediately', async () => {+ api.updateCosConfig.mockResolvedValue({ success: true });+ renderConfig();+ await screen.findByText('Waiting for the next wake');++ fireEvent.change(screen.getByRole('combobox', { name: 'Embedding provider' }), { target: { value: 'codex' } });++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ { embeddingProviderId: 'codex', embeddingModel: '' },+ { silent: true },+ ));+ });++ it('saves a budget cap when its number field loses focus', async () => {+ api.updateCosConfig.mockResolvedValue({ success: true });+ renderConfig();+ await screen.findByText('Waiting for the next wake');++ const actionsPerDay = screen.getAllByRole('spinbutton', { name: 'Actions/day' })[0];+ fireEvent.change(actionsPerDay, { target: { value: '5' } });+ fireEvent.blur(actionsPerDay);++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ { domainBudgets: { brain: { maxActionsPerDay: 5 } } },+ { silent: true },+ ));+ });+});+describe('boot startup compatibility', () => {- it('shows alwaysOn as the boot setting and clears the legacy alias when saving it off', async () => {+ it('shows alwaysOn as the boot setting and clears the legacy alias when autosaving it off', async () => {api.updateCosConfig.mockResolvedValue({ success: true });renderConfig({ config: { ...config, alwaysOn: true, autoStart: true } });- fireEvent.click(screen.getByRole('button', { name: /Edit settings/i }));const toggle = screen.getByRole('checkbox', { name: /Start on server boot/i });expect(toggle).toBeChecked();fireEvent.click(toggle);- fireEvent.click(screen.getByRole('button', { name: /Save settings/i }));await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- expect.objectContaining({ alwaysOn: false, autoStart: false }),+ { alwaysOn: false, autoStart: false },{ silent: true },));});