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
fix: gate CoS success toasts + optimistic UI on resolved API calls (#2519)
Adam Eivy33deb1528d9c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex cafbaf7230..439aabe11f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -9,6 +9,7 @@## Fixed+- **[issue-2519] CoS handlers no longer flash a false-success toast after a failed API call.** Several Chief of Staff actions (`handleForceEvaluate` on the CoS page, the Tasks tab "Run Now" button, and the Config tab's Save + autonomy-level change) `.catch`-swallowed the request rejection and then unconditionally toasted success and mutated optimistic UI — so a network/server error still read as "done." Each now awaits inside try/catch and only toasts success / advances state after the request resolves: a failed Save keeps the editor open, and a failed autonomy-level change reverts the optimistic form params. Errors surface via a single `toast.error` (the calls already pass `{ silent: true }`).- **[issue-2510] MidiPianoRoll: clear the stale hover overlay when the transcription data changes.** The piano-roll kept its hovered note/chord identity (objects from the previous parse) when the `data`/`chords` props swapped on a mounted instance, so a re-transcription or Retry while a hover was active and the pointer sat still would keep stroking the old note at coordinates mapped into the new file until the next pointer move or Escape. A `useEffect` now drops the hover identity whenever `data`/`chords` change.- **[issue-2513] Block loopback/metadata hosts in Layered Intelligence custom `http` sources.** `fetchHttpSource` used a bare `fetch` with only an `http(s)` scheme check, so a hand-edited config could point a custom source at `127.0.0.1`, `169.254.169.254`, or `metadata.google.internal` and exfiltrate up to 8KB into the reasoner prompt. It now routes through the shared SSRF-guarded `fetchPublicText` (default posture): loopback, link-local, and cloud-metadata hosts are blocked and redirects are revalidated, while LAN/Tailscale hosts stay intentionally allowed for this single-user tool.- **[issue-2516] Database sync: remove shell interpolation from the dump import.** The active→inactive backend sync built a `bash -c "sed … \"${dumpFile}\" | psql … -U ${pgUser} -d ${pgDb}"` string that interpolated the dump path, port, user, and database name into a shell command — any shell metacharacter in those values (env-derived or surfacing from the export pipeline) was injectable into `psql`. The import now streams the dump through `spawn('psql', argv)` with no shell: the dump is read and piped to psql's stdin, and the pg17-only directives (`\restrict`/`\unrestrict`/`SET transaction_timeout`) the old `sed` stage stripped are filtered in-process. No user- or env-derived value ever reaches a shell string.diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsxindex e5c278d30c..edb3a8a09f 100644--- a/client/src/components/cos/tabs/ConfigTab.jsx+++ b/client/src/components/cos/tabs/ConfigTab.jsx@@ -49,9 +49,10 @@ function AutonomyControl({ config, onLevelChange }) {const currentLevel = detectAutonomyLevel(config);const isCustom = currentLevel === null;- const handleLevelClick = async (level) => {- await onLevelChange(level.params);- toast.success(`Autonomy level set to ${level.label}`);+ const handleLevelClick = (level) => {+ // Success toast is owned by onLevelChange so it only fires once the PUT+ // resolves — a failed level change must not report success.+ onLevelChange(level.params, level.label);};// Get the level to show in preview (hovered or current)@@ -278,11 +279,20 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, simmediateExecution: config?.immediateExecution ?? true});- const handleLevelChange = async (params) => {- const updatedData = { ...formData, ...params };- setFormData(updatedData);- await api.updateCosConfig(params, { silent: true }).catch(err => toast.error(err.message));- onUpdate();+ const handleLevelChange = async (params, label) => {+ // Optimistically reflect the new params, but revert if the PUT fails so the+ // form doesn't lie about the persisted config. Success toast / refresh only+ // fire after the request resolves.+ const previousData = formData;+ setFormData({ ...formData, ...params });+ try {+ await api.updateCosConfig(params, { silent: true });+ if (label) toast.success(`Autonomy level set to ${label}`);+ onUpdate();+ } catch (err) {+ setFormData(previousData);+ toast.error(err.message);+ }};// Today's per-domain usage for the Domain Budgets readout (#711).@@ -322,10 +332,16 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, s};const handleSave = async () => {- await api.updateCosConfig(formData, { silent: true }).catch(err => toast.error(err.message));- toast.success('Configuration updated');- setEditing(false);- onUpdate();+ // Keep the user in edit mode on failure — only close the editor and toast+ // success once the config PUT actually resolves.+ try {+ await api.updateCosConfig(formData, { silent: true });+ toast.success('Configuration updated');+ setEditing(false);+ onUpdate();+ } catch (err) {+ toast.error(err.message);+ }};return (diff --git a/client/src/components/cos/tabs/ConfigTab.test.jsx b/client/src/components/cos/tabs/ConfigTab.test.jsxnew file mode 100644index 0000000000..e534fcee93--- /dev/null+++ b/client/src/components/cos/tabs/ConfigTab.test.jsx@@ -0,0 +1,97 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';++// 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.+const api = vi.hoisted(() => ({+ updateCosConfig: vi.fn(),+ getCosBudgetUsage: vi.fn(),+}));+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));++vi.mock('../../../services/api', () => api);+vi.mock('../../ui/Toast', () => ({ default: toast }));+// The provider/model selector hook fetches providers over the network — stub it+// so the test exercises only the config-save / level-change handlers.+vi.mock('../../../hooks/useProviderModels', () => ({+ default: () => ({+ providers: [],+ availableModels: [],+ setSelectedProviderId: vi.fn(),+ setSelectedModel: vi.fn(),+ selectedProviderId: '',+ selectedModel: '',+ }),+}));++const ConfigTab = (await import('./ConfigTab')).default;++const config = {+ healthCheckIntervalMs: 900000,+ maxConcurrentAgents: 3,+ maxConcurrentAgentsPerProject: 2,+ maxProcessMemoryMb: 2048,+ autoStart: false,+ improvementEnabled: true,+ proactiveMode: true,+ idleReviewEnabled: true,+ immediateExecution: true,+};++beforeEach(() => {+ vi.clearAllMocks();+ api.getCosBudgetUsage.mockResolvedValue({ usage: {} });+});++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();+ render(<ConfigTab config={config} onUpdate={onUpdate} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);++ 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 () => {+ api.updateCosConfig.mockResolvedValue({ success: true });+ const onUpdate = vi.fn();+ render(<ConfigTab config={config} onUpdate={onUpdate} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: /Edit/i }));+ fireEvent.click(screen.getByRole('button', { name: /Save/i }));++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Configuration updated'));+ expect(onUpdate).toHaveBeenCalled();+ // Editor closed — the Edit button is back.+ expect(screen.getByRole('button', { name: /Edit/i })).toBeInTheDocument();+ });+});++describe('ConfigTab handleLevelChange', () => {+ it('does not toast success when the autonomy level change fails', async () => {+ api.updateCosConfig.mockRejectedValue(new Error('boom'));+ render(<ConfigTab config={config} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: 'Standby' }));++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('boom'));+ expect(toast.success).not.toHaveBeenCalled();+ });++ it('toasts the level label only after the change resolves', async () => {+ api.updateCosConfig.mockResolvedValue({ success: true });+ render(<ConfigTab config={config} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: 'Standby' }));++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Autonomy level set to Standby'));+ });+});diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsxindex 4c4485a0c9..5e47ef9288 100644--- a/client/src/components/cos/tabs/TasksTab.jsx+++ b/client/src/components/cos/tabs/TasksTab.jsx@@ -143,8 +143,13 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {<h3 className="text-lg font-semibold text-white">User Tasks (TASKS.md)</h3><buttononClick={async () => {- await api.forceCosEvaluate({ silent: true }).catch(err => toast.error(err.message));- toast.success('Evaluation triggered');+ // Only toast success after the evaluate request resolves.+ try {+ await api.forceCosEvaluate({ silent: true });+ toast.success('Evaluation triggered');+ } catch (err) {+ toast.error(err.message);+ }}}className="flex items-center gap-1 text-sm bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-400 px-3 py-1.5 rounded-lg transition-colors"aria-label="Run tasks now"diff --git a/client/src/components/cos/tabs/TasksTab.test.jsx b/client/src/components/cos/tabs/TasksTab.test.jsxnew file mode 100644index 0000000000..a93e1e09e3--- /dev/null+++ b/client/src/components/cos/tabs/TasksTab.test.jsx@@ -0,0 +1,46 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';++// Regression coverage for #2519 — the "Run Now" evaluate button must only toast+// success after the request resolves.+const api = vi.hoisted(() => ({+ forceCosEvaluate: vi.fn(),+ getCosLearningDurations: vi.fn(),+}));+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));++vi.mock('../../../services/api', () => api);+vi.mock('../../ui/Toast', () => ({ default: toast }));+// TaskAddForm pulls in provider/model plumbing not under test — stub it out.+vi.mock('../TaskAddForm', () => ({ default: () => null }));++const TasksTab = (await import('./TasksTab')).default;++const emptyTasks = { user: { tasks: [] }, cos: { tasks: [] } };++beforeEach(() => {+ vi.clearAllMocks();+ api.getCosLearningDurations.mockResolvedValue(null);+});++describe('TasksTab Run Now', () => {+ it('does not toast success when the evaluate request fails', async () => {+ api.forceCosEvaluate.mockRejectedValue(new Error('offline'));+ render(<TasksTab tasks={emptyTasks} onRefresh={vi.fn()} providers={[]} apps={[]} />);++ fireEvent.click(screen.getByRole('button', { name: /Run tasks now/i }));++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('offline'));+ expect(toast.success).not.toHaveBeenCalled();+ });++ it('toasts success only after the evaluate request resolves', async () => {+ api.forceCosEvaluate.mockResolvedValue({ success: true });+ render(<TasksTab tasks={emptyTasks} onRefresh={vi.fn()} providers={[]} apps={[]} />);++ fireEvent.click(screen.getByRole('button', { name: /Run tasks now/i }));++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Evaluation triggered'));+ expect(toast.error).not.toHaveBeenCalled();+ });+});diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 020a9dfd81..b94e568228 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -328,12 +328,18 @@ export default function ChiefOfStaff() {};const handleForceEvaluate = async () => {- await api.forceCosEvaluate({ silent: true }).catch(err => toast.error(err.message));- toast.success('Evaluation triggered');- setAgentState('thinking');- setStatusMessage("Evaluating tasks...");- setSpeaking(true);- setTimeout(() => setSpeaking(false), 2000);+ // Only announce success / drive the "thinking" state after the request+ // actually resolves — a failed evaluate must not flash a success toast.+ try {+ await api.forceCosEvaluate({ silent: true });+ toast.success('Evaluation triggered');+ setAgentState('thinking');+ setStatusMessage("Evaluating tasks...");+ setSpeaking(true);+ setTimeout(() => setSpeaking(false), 2000);+ } catch (err) {+ toast.error(err.message);+ }};const handleTaskUnblocked = (taskId) => {