🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(desktop): prevent invalid proxy toggle saves (#13850)
Innei35558cbea1c0
diff --git a/src/routes/(main)/settings/proxy/features/ProxyForm.test.tsx b/src/routes/(main)/settings/proxy/features/ProxyForm.test.tsxnew file mode 100644index 00000000000..847dd820e67--- /dev/null+++ b/src/routes/(main)/settings/proxy/features/ProxyForm.test.tsx@@ -0,0 +1,329 @@+/**+ * @vitest-environment happy-dom+ */+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import type { FormInstance } from 'antd';+import type { ComponentProps, ReactNode } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import ProxyForm from './ProxyForm';++interface MockFormValues {+ [key: string]: unknown;+}++const setProxySettingsMock = vi.hoisted(() => vi.fn());+const testProxyConfigMock = vi.hoisted(() => vi.fn());+const toastErrorMock = vi.hoisted(() => vi.fn());+const toastSuccessMock = vi.hoisted(() => vi.fn());++const defaultProxySettings = {+ enableProxy: false,+ proxyBypass: 'localhost, 127.0.0.1, ::1',+ proxyPort: '',+ proxyRequireAuth: false,+ proxyServer: '',+ proxyType: 'http',+} as const;++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++vi.mock('@/services/electron/settings', () => ({+ desktopSettingsService: {+ testProxyConfig: testProxyConfigMock,+ },+}));++vi.mock('@/store/electron', () => ({+ useElectronStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({+ setProxySettings: setProxySettingsMock,+ useGetProxySettings: () => ({+ data: defaultProxySettings,+ isLoading: false,+ }),+ }),+}));++vi.mock('./SaveBar', () => ({+ default: ({+ isDirty,+ isSaving,+ onReset,+ onSave,+ }: {+ isDirty: boolean;+ isSaving: boolean;+ onReset: () => void;+ onSave: () => void;+ }) =>+ isDirty ? (+ <div>+ <button disabled={isSaving} onClick={onReset}>+ proxy.resetButton+ </button>+ <button disabled={isSaving} onClick={onSave}>+ proxy.saveButton+ </button>+ </div>+ ) : null,+}));++vi.mock('@lobehub/ui', async () => {+ const { Form: AntdForm } = await import('antd');++ const GroupedForm = Object.assign(+ ({+ form,+ initialValues,+ items,+ onValuesChange,+ }: {+ form?: FormInstance<MockFormValues>;+ initialValues?: MockFormValues;+ items: Array<{+ children: Array<{+ children: ReactNode;+ label?: ReactNode;+ name?: string;+ rules?: ComponentProps<typeof AntdForm.Item>['rules'];+ valuePropName?: string;+ }>;+ }>;+ onValuesChange?: (changedValues: MockFormValues, values: MockFormValues) => void;+ }) => (+ <AntdForm form={form} initialValues={initialValues} onValuesChange={onValuesChange}>+ {items.map((group, groupIndex) => (+ <div key={groupIndex}>+ {group.children.map((item, itemIndex) =>+ item.name ? (+ <AntdForm.Item+ key={`${groupIndex}-${item.name}-${itemIndex}`}+ label={item.label}+ name={item.name}+ rules={item.rules}+ valuePropName={item.valuePropName}+ >+ {item.children}+ </AntdForm.Item>+ ) : (+ <div key={`${groupIndex}-${itemIndex}`}>+ {item.label ? <div>{item.label}</div> : null}+ {item.children}+ </div>+ ),+ )}+ </div>+ ))}+ </AntdForm>+ ),+ { useForm: AntdForm.useForm },+ );++ return {+ Form: GroupedForm,+ Skeleton: () => <div>loading</div>,+ toast: {+ error: toastErrorMock,+ success: toastSuccessMock,+ },+ };+});++describe('ProxyForm', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ setProxySettingsMock.mockResolvedValue(undefined);+ testProxyConfigMock.mockResolvedValue({ success: true });+ });++ it('keeps enable toggle as an unsaved state when proxy config is incomplete', async () => {+ const user = userEvent.setup({ delay: null });++ render(<ProxyForm />);++ await user.click(screen.getAllByRole('switch')[0]);++ await waitFor(() => {+ expect(setProxySettingsMock).not.toHaveBeenCalled();+ expect(toastErrorMock).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: 'proxy.saveButton' })).toBeInTheDocument();+ });+ });++ it('blocks saving when enabled proxy settings are incomplete', async () => {+ const user = userEvent.setup({ delay: null });++ render(<ProxyForm />);++ await user.click(screen.getAllByRole('switch')[0]);+ await user.click(await screen.findByRole('button', { name: 'proxy.saveButton' }));++ await waitFor(() => {+ expect(setProxySettingsMock).not.toHaveBeenCalled();+ expect(screen.getByText('proxy.validation.serverRequired')).toBeInTheDocument();+ expect(screen.getByText('proxy.validation.portRequired')).toBeInTheDocument();+ });+ });++ it('does not convert form validation failures into a generic test toast', async () => {+ const user = userEvent.setup({ delay: null });++ render(<ProxyForm />);++ await user.click(screen.getAllByRole('switch')[0]);+ await user.click(screen.getByRole('button', { name: 'proxy.testButton' }));++ await waitFor(() => {+ expect(testProxyConfigMock).not.toHaveBeenCalled();+ expect(screen.getByText('proxy.validation.serverRequired')).toBeInTheDocument();+ expect(screen.getByText('proxy.validation.portRequired')).toBeInTheDocument();+ });++ expect(toastErrorMock).not.toHaveBeenCalled();+ });++ it('resets unsaved proxy changes back to persisted settings', async () => {+ const user = userEvent.setup({ delay: null });++ render(<ProxyForm />);++ await user.click(screen.getAllByRole('switch')[0]);+ await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');+ await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');+ await user.click(screen.getByRole('button', { name: 'proxy.resetButton' }));++ await waitFor(() => {+ expect(screen.queryByRole('button', { name: 'proxy.resetButton' })).not.toBeInTheDocument();+ expect(screen.getByRole('textbox', { name: 'proxy.server' })).toHaveValue('');+ expect(screen.getByRole('textbox', { name: 'proxy.port' })).toHaveValue('');+ });+ });++ it('renders auth fields and blocks saving when proxy credentials are missing', async () => {+ const user = userEvent.setup({ delay: null });++ render(<ProxyForm />);++ await user.click(screen.getAllByRole('switch')[0]);+ await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');+ await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');+ await user.click(screen.getAllByRole('switch')[1]);++ expect(screen.getByPlaceholderText('proxy.username_placeholder')).toBeInTheDocument();+ expect(screen.getByPlaceholderText('proxy.password_placeholder')).toBeInTheDocument();++ await user.click(screen.getByRole('button', { name: 'proxy.saveButton' }));++ await waitFor(() => {+ expect(setProxySettingsMock).not.toHaveBeenCalled();+ expect(screen.getByText('proxy.validation.usernameRequired')).toBeInTheDocument();+ expect(screen.getByText('proxy.validation.passwordRequired')).toBeInTheDocument();+ });+ });++ it('blocks saving when the proxy port is outside the valid range', async () => {+ const user = userEvent.setup({ delay: null });++ render(<ProxyForm />);++ await user.click(screen.getAllByRole('switch')[0]);+ await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');+ await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '70000');+ await user.click(screen.getByRole('button', { name: 'proxy.saveButton' }));++ await waitFor(() => {+ expect(setProxySettingsMock).not.toHaveBeenCalled();+ expect(screen.getByText('proxy.validation.portInvalid')).toBeInTheDocument();+ });+ });++ it('saves a valid proxy configuration from the save bar', async () => {+ const user = userEvent.setup({ delay: null });++ render(<ProxyForm />);++ await user.click(screen.getAllByRole('switch')[0]);+ await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');+ await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');+ await user.click(screen.getByRole('button', { name: 'proxy.saveButton' }));++ await waitFor(() => {+ expect(setProxySettingsMock).toHaveBeenCalledWith(+ expect.objectContaining({+ enableProxy: true,+ proxyPort: '7890',+ proxyServer: '127.0.0.1',+ proxyType: 'http',+ }),+ );+ });+ });++ it('reverts the enable switch and shows an error when auto-saving fails', async () => {+ const user = userEvent.setup({ delay: null });++ render(<ProxyForm />);++ await user.click(screen.getAllByRole('switch')[0]);+ await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');+ await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');++ setProxySettingsMock.mockRejectedValueOnce(new Error('boom'));++ await user.click(screen.getAllByRole('switch')[0]);++ await waitFor(() => {+ expect(toastErrorMock).toHaveBeenCalledWith('proxy.saveFailed');+ expect(screen.getAllByRole('switch')[0]).toHaveAttribute('aria-checked', 'true');+ });+ });++ it('tests a valid proxy configuration successfully', async () => {+ const user = userEvent.setup({ delay: null });++ testProxyConfigMock.mockResolvedValue({ responseTime: 42, success: true });++ render(<ProxyForm />);++ await user.click(screen.getAllByRole('switch')[0]);+ await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');+ await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');+ await user.click(screen.getByRole('button', { name: 'proxy.testButton' }));++ await waitFor(() => {+ expect(testProxyConfigMock).toHaveBeenCalledWith(+ expect.objectContaining({+ enableProxy: true,+ proxyPort: '7890',+ proxyServer: '127.0.0.1',+ proxyType: 'http',+ }),+ 'https://www.google.com',+ );+ expect(toastSuccessMock).toHaveBeenCalledWith('proxy.testSuccessWithTime');+ });+ });++ it('surfaces proxy connectivity failures from the test action', async () => {+ const user = userEvent.setup({ delay: null });++ testProxyConfigMock.mockResolvedValue({ message: 'connect ECONNREFUSED', success: false });++ render(<ProxyForm />);++ await user.click(screen.getAllByRole('switch')[0]);+ await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');+ await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');+ await user.click(screen.getByRole('button', { name: 'proxy.testButton' }));++ await waitFor(() => {+ expect(toastErrorMock).toHaveBeenCalledWith('proxy.testFailed: connect ECONNREFUSED');+ });+ });+}, 10000);diff --git a/src/routes/(main)/settings/proxy/features/ProxyForm.tsx b/src/routes/(main)/settings/proxy/features/ProxyForm.tsxindex 432444fd977..d07d6ffa869 100644--- a/src/routes/(main)/settings/proxy/features/ProxyForm.tsx+++ b/src/routes/(main)/settings/proxy/features/ProxyForm.tsx@@ -14,6 +14,41 @@ import { useElectronStore } from '@/store/electron';import SaveBar from './SaveBar';import { useProxyDirty } from './useProxyDirty';+const PROXY_TYPES = ['http', 'https', 'socks5'] as const;+const IP_HOST_REGEX = /^(?:\d{1,3}\.){3}\d{1,3}$/;+const DOMAIN_HOST_REGEX = /^[\dA-Z](?:[\dA-Z-]*[\dA-Z])?(?:\.[\dA-Z](?:[\dA-Z-]*[\dA-Z])?)*$/i;++const isFormValidationError = (+ error: unknown,+): error is {+ errorFields: unknown[];+} => typeof error === 'object' && error !== null && 'errorFields' in error;++const isSupportedProxyType = (value?: string): value is (typeof PROXY_TYPES)[number] =>+ PROXY_TYPES.includes(value as (typeof PROXY_TYPES)[number]);++const isValidProxyHost = (host: string) => IP_HOST_REGEX.test(host) || DOMAIN_HOST_REGEX.test(host);++const isCompleteProxyConfig = (config: Partial<NetworkProxySettings>) => {+ if (!config.enableProxy) return true;+ if (!isSupportedProxyType(config.proxyType)) return false;++ const proxyServer = config.proxyServer?.trim();+ if (!proxyServer || !isValidProxyHost(proxyServer)) return false;++ const proxyPort = config.proxyPort?.trim();+ if (!proxyPort) return false;++ const port = Number.parseInt(proxyPort, 10);+ if (Number.isNaN(port) || port < 1 || port > 65_535) return false;++ if (config.proxyRequireAuth) {+ return Boolean(config.proxyUsername?.trim() && config.proxyPassword?.trim());+ }++ return true;+};+const ProxyForm = () => {const { t } = useTranslation('electron');const [form] = Form.useForm();@@ -40,11 +75,75 @@ const ProxyForm = () => {}}, [form, proxySettings]);+ const validateProxyType = useCallback(+ async (_: unknown, value?: string) => {+ if (!isEnableProxy || isSupportedProxyType(value)) return;++ throw new Error(t('proxy.validation.typeRequired'));+ },+ [isEnableProxy, t],+ );++ const validateProxyServer = useCallback(+ async (_: unknown, value?: string) => {+ if (!isEnableProxy) return;++ const proxyServer = value?.trim();+ if (!proxyServer) {+ throw new Error(t('proxy.validation.serverRequired'));+ }++ if (!isValidProxyHost(proxyServer)) {+ throw new Error(t('proxy.validation.serverInvalid'));+ }+ },+ [isEnableProxy, t],+ );++ const validateProxyPort = useCallback(+ async (_: unknown, value?: string) => {+ if (!isEnableProxy) return;++ const proxyPort = value?.trim();+ if (!proxyPort) {+ throw new Error(t('proxy.validation.portRequired'));+ }++ const port = Number.parseInt(proxyPort, 10);+ if (Number.isNaN(port) || port < 1 || port > 65_535) {+ throw new Error(t('proxy.validation.portInvalid'));+ }+ },+ [isEnableProxy, t],+ );++ const validateProxyUsername = useCallback(+ async (_: unknown, value?: string) => {+ if (!isEnableProxy || !proxyRequireAuth || value?.trim()) return;++ throw new Error(t('proxy.validation.usernameRequired'));+ },+ [isEnableProxy, proxyRequireAuth, t],+ );++ const validateProxyPassword = useCallback(+ async (_: unknown, value?: string) => {+ if (!isEnableProxy || !proxyRequireAuth || value?.trim()) return;++ throw new Error(t('proxy.validation.passwordRequired'));+ },+ [isEnableProxy, proxyRequireAuth, t],+ );+const handleValuesChange = useCallback(- (changed: Partial<NetworkProxySettings>) => {+ (changed: Partial<NetworkProxySettings>, allValues: NetworkProxySettings) => {if ('enableProxy' in changed) {const next = changed.enableProxy;- setProxySettings({ enableProxy: next }).catch((error) => {++ if (next && !isCompleteProxyConfig(allValues)) return;++ const valuesToSave = next ? allValues : { enableProxy: false };+ setProxySettings(valuesToSave).catch((error) => {form.setFieldsValue({ enableProxy: !next });const message = error instanceof Error ? error.message : String(error);toast.error(t('proxy.saveFailed', { error: message }));@@ -87,6 +186,8 @@ const ProxyForm = () => {toast.error(`${t('proxy.testFailed')}: ${result.message ?? ''}`);}} catch (error) {+ if (isFormValidationError(error)) return;+const errorMessage = error instanceof Error ? error.message : 'Unknown error';toast.error(`${t('proxy.testFailed')}: ${errorMessage}`);} finally {@@ -124,18 +225,21 @@ const ProxyForm = () => {label: t('proxy.type'),minWidth: undefined,name: 'proxyType',+ rules: [{ validator: validateProxyType }],},{children: <Input disabled={!isEnableProxy} placeholder="127.0.0.1" />,desc: t('proxy.validation.serverRequired'),label: t('proxy.server'),name: 'proxyServer',+ rules: [{ validator: validateProxyServer }],},{children: <Input disabled={!isEnableProxy} placeholder="7890" style={{ width: 120 }} />,desc: t('proxy.validation.portRequired'),label: t('proxy.port'),name: 'proxyPort',+ rules: [{ validator: validateProxyPort }],},],title: t('proxy.basicSettings'),@@ -158,11 +262,13 @@ const ProxyForm = () => {children: <Input placeholder={t('proxy.username_placeholder')} />,label: t('proxy.username'),name: 'proxyUsername',+ rules: [{ validator: validateProxyUsername }],},{children: <Input.Password placeholder={t('proxy.password_placeholder')} />,label: t('proxy.password'),name: 'proxyPassword',+ rules: [{ validator: validateProxyPassword }],},]: []),diff --git a/src/routes/(main)/settings/proxy/features/SaveBar.tsx b/src/routes/(main)/settings/proxy/features/SaveBar.tsxindex eed92929274..b2546392a51 100644--- a/src/routes/(main)/settings/proxy/features/SaveBar.tsx+++ b/src/routes/(main)/settings/proxy/features/SaveBar.tsx@@ -25,24 +25,27 @@ const styles = createStaticStyles(({ css, cssVar }) => ({padding-block: 6px;padding-inline: 16px 6px;+ border: 1px solid color-mix(in srgb, ${cssVar.colorBorderSecondary} 60%, transparent);border-radius: 999px;font-size: 13px;- color: ${cssVar.colorTextLightSolid};+ color: ${cssVar.colorText};- background: ${cssVar.colorBgSpotlight};- box-shadow:- 0 8px 28px rgb(0 0 0 / 22%),- 0 2px 6px rgb(0 0 0 / 14%);+ background: color-mix(in srgb, ${cssVar.colorBgElevated} 85%, transparent);+ backdrop-filter: blur(16px) saturate(1.2);+ box-shadow: ${cssVar.boxShadowSecondary};`,dot: css`+ flex-shrink: 0;+width: 6px;height: 6px;border-radius: 50%;+background: ${cssVar.colorWarning};`,message: css`- opacity: 0.92;+ color: ${cssVar.colorTextSecondary};`,resetButton: css`height: 28px;@@ -50,30 +53,22 @@ const styles = createStaticStyles(({ css, cssVar }) => ({padding-inline: 12px;border-radius: 999px;- color: rgb(255 255 255 / 85%);+ color: ${cssVar.colorTextSecondary} !important;background: transparent;&:hover {- color: #fff !important;- background: rgb(255 255 255 / 8%) !important;+ color: ${cssVar.colorText} !important;+ background: ${cssVar.colorFillSecondary} !important;}`,saveButton: css`height: 28px;padding-block: 0;padding-inline: 14px;- border: none;border-radius: 999px;font-weight: 500;- color: ${cssVar.colorBgSpotlight} !important;-- background: #fff !important;-- &:hover {- background: rgb(255 255 255 / 92%) !important;- }`,}));diff --git a/src/routes/(main)/settings/proxy/features/useProxyDirty.ts b/src/routes/(main)/settings/proxy/features/useProxyDirty.tsindex 360f9738a60..b1aee4b60ed 100644--- a/src/routes/(main)/settings/proxy/features/useProxyDirty.ts+++ b/src/routes/(main)/settings/proxy/features/useProxyDirty.ts@@ -3,6 +3,7 @@ import { Form as AntdForm, type FormInstance } from 'antd';import { useMemo } from 'react';const WATCH_FIELDS: readonly (keyof NetworkProxySettings)[] = [+ 'enableProxy','proxyType','proxyServer','proxyPort',