Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

test(settings): cover privacy-mode status branches and sandbox input validation

M3gA-Mindaf83cc184eec
diff --git a/app/src/components/settings/panels/__tests__/PrivacyModeSection.status.test.tsx b/app/src/components/settings/panels/__tests__/PrivacyModeSection.status.test.tsx
new file mode 100644
index 0000000000..1cb207f4da
--- /dev/null
+++ b/app/src/components/settings/panels/__tests__/PrivacyModeSection.status.test.tsx
@@ -0,0 +1,168 @@
+/**
+ * PrivacyModeSection — the load/save failure branches, the disabled states and
+ * the auto-clearing "saved" note.
+ *
+ * `PrivacyModeSection.test.tsx` (sibling) covers the three options, the loaded
+ * selection and the no-op re-click. Every failure branch and every transient
+ * status was unexercised, which is what held branch coverage at 70.8%. This
+ * matters more here than on most panels: the control sets the data-egress
+ * posture (#4435), so a save that silently fails leaves the user believing they
+ * are in `local_only` when they are not.
+ *
+ * Separate file rather than an edit to the sibling: three of us are in this
+ * directory.
+ */
+import { act, fireEvent, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { renderWithProviders } from '../../../../test/test-utils';
+import PrivacyModeSection from '../PrivacyModeSection';
+
+const callCoreRpc = vi.fn();
+vi.mock('../../../../services/coreRpcClient', () => ({
+ callCoreRpc: (arg: { method: string; params: unknown }) => callCoreRpc(arg),
+}));
+
+const GET = 'openhuman.config_get_privacy_mode';
+const SET = 'openhuman.config_set_privacy_mode';
+
+/** Load resolves to `mode`; the setter behaviour is supplied per test. */
+function wire(opts: {
+ loadMode?: string;
+ loadError?: unknown;
+ onSet?: (mode?: string) => Promise<unknown>;
+}) {
+ callCoreRpc.mockImplementation((arg: { method: string; params: { mode?: string } }) => {
+ if (arg.method === GET) {
+ return opts.loadError
+ ? Promise.reject(opts.loadError)
+ : Promise.resolve({ result: { mode: opts.loadMode ?? 'standard' } });
+ }
+ if (arg.method === SET) {
+ return opts.onSet
+ ? opts.onSet(arg.params.mode)
+ : Promise.resolve({ result: { mode: arg.params.mode } });
+ }
+ return Promise.reject(new Error(`unexpected method ${arg.method}`));
+ });
+}
+
+const option = (mode: string) => screen.getByTestId(`privacy-mode-option-${mode}`);
+const statusLine = () => document.querySelector('[data-slot="status-line"]') as HTMLElement;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ // The panel logs failures through `console.warn`; keep the run readable while
+ // still proving the branch executed via the rendered status line.
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+describe('PrivacyModeSection — load', () => {
+ it('shows the load failure message and leaves nothing selected', async () => {
+ wire({ loadError: new Error('privacy rpc unavailable') });
+ renderWithProviders(<PrivacyModeSection />);
+
+ expect(await screen.findByText('privacy rpc unavailable')).toBeInTheDocument();
+ // `mode` stays null, so no option may claim to be the current posture.
+ for (const mode of ['local_only', 'standard', 'sensitive']) {
+ expect(option(mode)).not.toBeChecked();
+ }
+ });
+
+ it('stringifies a non-Error load rejection rather than rendering nothing', async () => {
+ wire({ loadError: 'plain string failure' });
+ renderWithProviders(<PrivacyModeSection />);
+
+ expect(await screen.findByText('plain string failure')).toBeInTheDocument();
+ });
+
+ it('disables every option while the current mode is still loading', () => {
+ wire({ onSet: () => new Promise(() => {}) });
+ callCoreRpc.mockImplementation(() => new Promise(() => {}));
+ renderWithProviders(<PrivacyModeSection />);
+
+ for (const mode of ['local_only', 'standard', 'sensitive']) {
+ expect(option(mode)).toBeDisabled();
+ }
+ });
+
+ it('enables the options once the mode has loaded', async () => {
+ wire({ loadMode: 'standard' });
+ renderWithProviders(<PrivacyModeSection />);
+
+ await waitFor(() => expect(option('standard')).toBeChecked());
+ expect(option('local_only')).toBeEnabled();
+ });
+});
+
+describe('PrivacyModeSection — save', () => {
+ it('reports a save failure and keeps the previous selection', async () => {
+ wire({ loadMode: 'standard', onSet: () => Promise.reject(new Error('egress locked')) });
+ renderWithProviders(<PrivacyModeSection />);
+ await waitFor(() => expect(option('standard')).toBeChecked());
+
+ fireEvent.click(option('local_only'));
+
+ expect(await screen.findByText('egress locked')).toBeInTheDocument();
+ // The posture must not appear to have changed when the write failed —
+ // believing you are local-only when you are not is the whole risk here.
+ expect(option('standard')).toBeChecked();
+ expect(option('local_only')).not.toBeChecked();
+ });
+
+ it('adopts the mode the core echoes back, not the one that was clicked', async () => {
+ // The core is authoritative: if it coerces the request, the UI must follow.
+ wire({ loadMode: 'standard', onSet: () => Promise.resolve({ result: { mode: 'sensitive' } }) });
+ renderWithProviders(<PrivacyModeSection />);
+ await waitFor(() => expect(option('standard')).toBeChecked());
+
+ fireEvent.click(option('local_only'));
+
+ await waitFor(() => expect(option('sensitive')).toBeChecked());
+ expect(option('local_only')).not.toBeChecked();
+ });
+
+ it('disables the options while a save is in flight', async () => {
+ let release!: (v: unknown) => void;
+ wire({ loadMode: 'standard', onSet: () => new Promise(resolve => (release = resolve)) });
+ renderWithProviders(<PrivacyModeSection />);
+ await waitFor(() => expect(option('standard')).toBeChecked());
+
+ fireEvent.click(option('local_only'));
+
+ await waitFor(() => expect(option('sensitive')).toBeDisabled());
+ release({ result: { mode: 'local_only' } });
+ await waitFor(() => expect(option('sensitive')).toBeEnabled());
+ });
+
+ it('clears the saved note after the two-second window', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ wire({ loadMode: 'standard' });
+ renderWithProviders(<PrivacyModeSection />);
+ await waitFor(() => expect(option('standard')).toBeChecked());
+
+ fireEvent.click(option('local_only'));
+ await waitFor(() => expect(statusLine()).toHaveTextContent(/saved/i));
+
+ await act(async () => {
+ vi.advanceTimersByTime(2000);
+ });
+ await waitFor(() => expect(statusLine()).toHaveTextContent(''));
+ });
+
+ it('does not call the setter when the already-selected mode is re-chosen', async () => {
+ wire({ loadMode: 'sensitive' });
+ renderWithProviders(<PrivacyModeSection />);
+ await waitFor(() => expect(option('sensitive')).toBeChecked());
+
+ const before = callCoreRpc.mock.calls.filter(c => c[0].method === SET).length;
+ fireEvent.click(option('sensitive'));
+
+ expect(callCoreRpc.mock.calls.filter(c => c[0].method === SET)).toHaveLength(before);
+ });
+});
diff --git a/app/src/components/settings/panels/__tests__/SandboxSettingsPanel.validation.test.tsx b/app/src/components/settings/panels/__tests__/SandboxSettingsPanel.validation.test.tsx
new file mode 100644
index 0000000000..e7e0b3b696
--- /dev/null
+++ b/app/src/components/settings/panels/__tests__/SandboxSettingsPanel.validation.test.tsx
@@ -0,0 +1,205 @@
+/**
+ * SandboxSettingsPanel — the input the blur handlers must REFUSE, the null
+ * limits on load, and the persist sequence guard.
+ *
+ * `SandboxSettingsPanel.test.tsx` (sibling) covers each field's happy path and
+ * the explicit clear-to-null. What it never does is hand a field something
+ * invalid: `handleMemoryBlur` (`SandboxSettingsPanel.tsx:113-123`) and
+ * `handleCpuBlur` (`:125-135`) both drop non-numeric and non-positive input on
+ * the floor, and `handleDockerImageBlur` (`:107-111`) drops a blank image.
+ * Those three guards were entirely unexercised — branch coverage 71.4%.
+ *
+ * The guards matter: a `0` or negative container limit that reached the core
+ * would be a Docker run argument, and a blank image would replace a working one.
+ *
+ * Separate file rather than an edit to the sibling: three of us are in this
+ * directory.
+ */
+import { fireEvent, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { renderWithProviders } from '../../../../test/test-utils';
+import {
+ isTauri,
+ openhumanGetSandboxSettings,
+ openhumanUpdateSandboxSettings,
+ type SandboxSettings,
+} from '../../../../utils/tauriCommands';
+import SandboxSettingsPanel from '../SandboxSettingsPanel';
+
+const sandboxSettings = (overrides: Partial<SandboxSettings> = {}): SandboxSettings => ({
+ enabled: true,
+ backend: 'auto',
+ docker_image: 'alpine:3.20',
+ docker_memory_limit_mb: 512,
+ docker_cpu_limit: 1.0,
+ docker_available: true,
+ detected_backend: 'seatbelt',
+ env_passthrough: ['PATH', 'HOME', 'TERM'],
+ ...overrides,
+});
+
+vi.mock('../../hooks/useSettingsNavigation', () => ({
+ useSettingsNavigation: () => ({
+ navigateBack: vi.fn(),
+ navigateToSettings: vi.fn(),
+ breadcrumbs: [],
+ }),
+}));
+
+vi.mock('../../../../utils/tauriCommands', async () => {
+ const actual = await vi.importActual<typeof import('../../../../utils/tauriCommands')>(
+ '../../../../utils/tauriCommands'
+ );
+ return {
+ ...actual,
+ isTauri: vi.fn(() => true),
+ openhumanGetSandboxSettings: vi.fn(),
+ openhumanUpdateSandboxSettings: vi.fn(),
+ };
+});
+
+const mockGet = vi.mocked(openhumanGetSandboxSettings);
+const mockUpdate = vi.mocked(openhumanUpdateSandboxSettings);
+const mockIsTauri = vi.mocked(isTauri);
+
+async function renderLoaded(overrides: Partial<SandboxSettings> = {}) {
+ mockGet.mockResolvedValue({ result: sandboxSettings(overrides) });
+ renderWithProviders(<SandboxSettingsPanel />);
+ await waitFor(() => expect(mockGet).toHaveBeenCalled());
+}
+
+/** Blur a field after typing `value`, then report what (if anything) persisted. */
+function blurWith(input: HTMLElement, value: string) {
+ fireEvent.change(input, { target: { value } });
+ fireEvent.blur(input);
+}
+
+const memoryInput = () => screen.getByDisplayValue('512');
+const cpuInput = () => screen.getByDisplayValue('1');
+const imageInput = () => screen.getByDisplayValue('alpine:3.20');
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockIsTauri.mockReturnValue(true);
+ mockUpdate.mockResolvedValue(undefined as never);
+});
+
+describe('SandboxSettingsPanel — memory limit validation', () => {
+ // Only values a `type="number"` field can actually hold. Non-numeric text
+ // ('abc', '!!') is unreachable here: jsdom, like a browser, reports an empty
+ // value for it, which lands on the clear-to-null branch instead. The
+ // `!isNaN(parsed)` half of the guard is therefore dead through the UI — see
+ // the note in the bug list.
+ it.each(['0', '-1', '-512'])('refuses to persist %s', async value => {
+ await renderLoaded();
+ blurWith(memoryInput(), value);
+
+ // A moment for any stray async persist to land.
+ await waitFor(() => expect(mockGet).toHaveBeenCalled());
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
+
+ it('persists a positive integer', async () => {
+ await renderLoaded();
+ blurWith(memoryInput(), '2048');
+
+ await waitFor(() => expect(mockUpdate).toHaveBeenCalledWith({ docker_memory_limit_mb: 2048 }));
+ });
+
+ it('persists null when the field is cleared to whitespace', async () => {
+ await renderLoaded();
+ blurWith(memoryInput(), ' ');
+
+ await waitFor(() => expect(mockUpdate).toHaveBeenCalledWith({ docker_memory_limit_mb: null }));
+ });
+});
+
+describe('SandboxSettingsPanel — CPU limit validation', () => {
+ it.each(['0', '-0.5'])('refuses to persist %s', async value => {
+ await renderLoaded();
+ blurWith(cpuInput(), value);
+
+ await waitFor(() => expect(mockGet).toHaveBeenCalled());
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
+
+ it('persists a fractional limit', async () => {
+ await renderLoaded();
+ blurWith(cpuInput(), '0.25');
+
+ await waitFor(() => expect(mockUpdate).toHaveBeenCalledWith({ docker_cpu_limit: 0.25 }));
+ });
+
+ it('persists null when the field is cleared to whitespace', async () => {
+ await renderLoaded();
+ blurWith(cpuInput(), ' ');
+
+ await waitFor(() => expect(mockUpdate).toHaveBeenCalledWith({ docker_cpu_limit: null }));
+ });
+});
+
+describe('SandboxSettingsPanel — docker image validation', () => {
+ it('refuses to persist a blank image, keeping the configured one', async () => {
+ await renderLoaded();
+ blurWith(imageInput(), ' ');
+
+ await waitFor(() => expect(mockGet).toHaveBeenCalled());
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
+
+ it('trims the image before persisting', async () => {
+ await renderLoaded();
+ blurWith(imageInput(), ' ubuntu:24.04 ');
+
+ await waitFor(() => expect(mockUpdate).toHaveBeenCalledWith({ docker_image: 'ubuntu:24.04' }));
+ });
+});
+
+describe('SandboxSettingsPanel — load shape', () => {
+ it('renders empty limit fields when the core reports no limits', async () => {
+ await renderLoaded({ docker_memory_limit_mb: null, docker_cpu_limit: null });
+
+ await waitFor(() => expect(screen.queryByDisplayValue('512')).not.toBeInTheDocument());
+ expect(screen.queryByDisplayValue('1')).not.toBeInTheDocument();
+ });
+
+ it('does not call the core at all off-Tauri', async () => {
+ mockIsTauri.mockReturnValue(false);
+ renderWithProviders(<SandboxSettingsPanel />);
+
+ await waitFor(() => expect(screen.getByText(/desktop app/i)).toBeInTheDocument());
+ expect(mockGet).not.toHaveBeenCalled();
+ });
+});
+
+describe('SandboxSettingsPanel — persist sequence guard', () => {
+ /** Let a settled promise's continuation and the resulting render run. A bare
+ * `waitFor(() => expect(x).not.toBeInTheDocument())` passes on its first
+ * tick, before the rejection is handled, and would hold with the guard gone. */
+ async function flush() {
+ await waitFor(() => expect(mockUpdate).toHaveBeenCalled());
+ await new Promise(resolve => setTimeout(resolve, 0));
+ await new Promise(resolve => setTimeout(resolve, 0));
+ }
+
+ it('drops a stale persist failure that lands after a newer persist', async () => {
+ let rejectFirst!: (e: unknown) => void;
+ mockUpdate.mockReturnValueOnce(
+ new Promise((_res, rej) => {
+ rejectFirst = rej;
+ }) as never
+ );
+ mockUpdate.mockResolvedValueOnce(undefined as never);
+
+ await renderLoaded();
+ blurWith(memoryInput(), '1024');
+ blurWith(cpuInput(), '2');
+ await waitFor(() => expect(mockUpdate).toHaveBeenCalledTimes(2));
+
+ rejectFirst(new Error('stale sandbox failure'));
+ await flush();
+
+ expect(screen.queryByText(/stale sandbox failure/)).not.toBeInTheDocument();
+ });
+});