初始化导入 new-api 源码

This commit is contained in:
OpenClaw Task Bot
2026-04-09 22:31:14 +08:00
commit 75bda2e845
994 changed files with 250292 additions and 0 deletions

View File

@@ -0,0 +1,330 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState, useRef } from 'react';
import { Card, Divider, Steps, Form } from '@douyinfe/semi-ui';
import { API, showError, showNotice } from '../../helpers';
import { useTranslation } from 'react-i18next';
import StepNavigation from './components/StepNavigation';
import DatabaseStep from './components/steps/DatabaseStep';
import AdminStep from './components/steps/AdminStep';
import UsageModeStep from './components/steps/UsageModeStep';
import CompleteStep from './components/steps/CompleteStep';
const SetupWizard = () => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [setupStatus, setSetupStatus] = useState({
status: false,
root_init: false,
database_type: '',
});
const [currentStep, setCurrentStep] = useState(0);
const formRef = useRef(null);
const [formData, setFormData] = useState({
username: '',
password: '',
confirmPassword: '',
usageMode: 'external',
});
// 确保默认选中“对外运营模式”,并同步到表单
useEffect(() => {
if (formRef.current) {
formRef.current.setValue('usageMode', 'external');
}
}, []);
// 定义步骤内容
const steps = [
{
title: t('数据库检查'),
description: t('验证数据库连接状态'),
},
{
title: t('管理员账号'),
description: t('设置管理员登录信息'),
},
{
title: t('使用模式'),
description: t('选择系统运行模式'),
},
{
title: t('完成初始化'),
description: t('确认设置并完成初始化'),
},
];
useEffect(() => {
fetchSetupStatus();
}, []);
const fetchSetupStatus = async () => {
try {
const res = await API.get('/api/setup');
const { success, data } = res.data;
if (success) {
setSetupStatus(data);
// If setup is already completed, redirect to home
if (data.status) {
window.location.href = '/';
return;
}
// 设置当前步骤 - 默认从数据库检查开始
setCurrentStep(0);
} else {
showError(t('获取初始化状态失败'));
}
} catch (error) {
console.error('Failed to fetch setup status:', error);
showError(t('获取初始化状态失败'));
}
};
const handleUsageModeChange = (e) => {
const nextMode = e?.target?.value ?? e;
setFormData((prev) => ({ ...prev, usageMode: nextMode }));
// 同步到表单,便于 getValues() 拿到 usageMode
if (formRef.current) {
formRef.current.setValue('usageMode', nextMode);
}
};
const next = () => {
// 验证当前步骤是否可以继续
if (!canProceedToNext()) {
return;
}
const current = currentStep + 1;
setCurrentStep(current);
};
// 验证是否可以继续到下一步
const canProceedToNext = () => {
switch (currentStep) {
case 0: // 数据库检查步骤
return true; // 数据库检查总是可以继续
case 1: // 管理员账号步骤
if (setupStatus.root_init) {
return true; // 如果已经初始化,可以继续
}
// 检查必填字段
if (
!formData.username ||
!formData.password ||
!formData.confirmPassword
) {
showError(t('请填写完整的管理员账号信息'));
return false;
}
if (formData.password !== formData.confirmPassword) {
showError(t('两次输入的密码不一致'));
return false;
}
if (formData.password.length < 8) {
showError(t('密码长度至少为8个字符'));
return false;
}
return true;
case 2: // 使用模式步骤
if (!formData.usageMode) {
showError(t('请选择使用模式'));
return false;
}
return true;
default:
return true;
}
};
const prev = () => {
const current = currentStep - 1;
setCurrentStep(current);
};
const onSubmit = () => {
if (!formRef.current) {
console.error('Form reference is null');
showError(t('表单引用错误,请刷新页面重试'));
return;
}
const values = formRef.current.getValues();
// For root_init=false, validate admin username and password
if (!setupStatus.root_init) {
if (!values.username || !values.username.trim()) {
showError(t('请输入管理员用户名'));
return;
}
if (!values.password || values.password.length < 8) {
showError(t('密码长度至少为8个字符'));
return;
}
if (values.password !== values.confirmPassword) {
showError(t('两次输入的密码不一致'));
return;
}
}
// Prepare submission data
const formValues = { ...values };
const usageMode = values.usageMode;
formValues.SelfUseModeEnabled = usageMode === 'self';
formValues.DemoSiteEnabled = usageMode === 'demo';
// Remove usageMode as it's not needed by the backend
delete formValues.usageMode;
// 提交表单至后端
setLoading(true);
// Submit to backend
API.post('/api/setup', formValues)
.then((res) => {
const { success, message } = res.data;
if (success) {
showNotice(t('系统初始化成功,正在跳转...'));
setTimeout(() => {
window.location.reload();
}, 1500);
} else {
showError(message || t('初始化失败,请重试'));
}
})
.catch((error) => {
console.error('API error:', error);
showError(t('系统初始化失败,请重试'));
setLoading(false);
})
.finally(() => {
setLoading(false);
});
};
// 获取步骤内容
const getStepContent = (step) => {
switch (step) {
case 0:
return <DatabaseStep setupStatus={setupStatus} t={t} />;
case 1:
return (
<AdminStep
setupStatus={setupStatus}
formData={formData}
setFormData={setFormData}
formRef={formRef}
t={t}
/>
);
case 2:
return (
<UsageModeStep
formData={formData}
handleUsageModeChange={handleUsageModeChange}
t={t}
/>
);
case 3:
return (
<CompleteStep setupStatus={setupStatus} formData={formData} t={t} />
);
default:
return null;
}
};
const stepNavigationProps = {
currentStep,
steps,
prev,
next,
onSubmit,
loading,
t,
};
return (
<div className='min-h-screen flex items-center justify-center px-4'>
<div className='w-full max-w-4xl'>
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='mb-4'>
<div className='text-xl font-semibold'>{t('系统初始化')}</div>
<div className='text-xs text-gray-600'>
{t('欢迎使用,请完成以下设置以开始使用系统')}
</div>
</div>
<div className='px-2 py-2'>
<Steps type='basic' current={currentStep}>
{steps.map((item, index) => (
<Steps.Step
key={item.title}
title={
<span className={currentStep === index ? 'shine-text' : ''}>
{item.title}
</span>
}
description={item.description}
/>
))}
</Steps>
</div>
<Divider margin='12px' />
{/* 表单容器 */}
<Form
getFormApi={(formApi) => {
formRef.current = formApi;
}}
initValues={formData}
>
{/* 步骤内容:保持所有字段挂载,仅隐藏非当前步骤 */}
<div className='steps-content'>
{[0, 1, 2, 3].map((idx) => (
<div
key={idx}
style={{ display: currentStep === idx ? 'block' : 'none' }}
>
{React.cloneElement(getStepContent(idx), {
...stepNavigationProps,
renderNavigationButtons: () => (
<StepNavigation {...stepNavigationProps} />
),
})}
</div>
))}
</div>
</Form>
</Card>
</div>
</div>
);
};
export default SetupWizard;

View File

@@ -0,0 +1,71 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Button } from '@douyinfe/semi-ui';
import { IconCheckCircleStroked } from '@douyinfe/semi-icons';
/**
* 步骤导航组件
* 负责渲染上一步、下一步和完成按钮
*/
const StepNavigation = ({
currentStep,
steps,
prev,
next,
onSubmit,
loading,
t,
}) => {
return (
<div className='flex justify-between items-center pt-4'>
{/* 上一步按钮 */}
{currentStep > 0 && (
<Button onClick={prev} className='!rounded-lg'>
{t('上一步')}
</Button>
)}
<div className='flex-1'></div>
{/* 下一步按钮 */}
{currentStep < steps.length - 1 && (
<Button type='primary' onClick={next} className='!rounded-lg'>
{t('下一步')}
</Button>
)}
{/* 完成按钮 */}
{currentStep === steps.length - 1 && (
<Button
type='primary'
onClick={onSubmit}
loading={loading}
className='!rounded-lg'
icon={<IconCheckCircleStroked />}
>
{t('初始化系统')}
</Button>
)}
</div>
);
};
export default StepNavigation;

View File

@@ -0,0 +1,120 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Banner, Form } from '@douyinfe/semi-ui';
import { IconUser, IconLock } from '@douyinfe/semi-icons';
/**
* 管理员账号设置步骤组件
* 提供管理员用户名和密码的设置界面
*/
const AdminStep = ({
setupStatus,
formData,
setFormData,
formRef,
renderNavigationButtons,
t,
}) => {
return (
<>
{setupStatus.root_init ? (
<Banner
type='info'
closeIcon={null}
description={
<div className='flex items-center'>
<span>{t('管理员账号已经初始化过,请继续设置其他参数')}</span>
</div>
}
className='!rounded-lg'
/>
) : (
<>
<Form.Input
field='username'
label={t('用户名')}
placeholder={t('请输入管理员用户名')}
prefix={<IconUser />}
showClear
noLabel={false}
validateStatus='default'
rules={[{ required: true, message: t('请输入管理员用户名') }]}
initValue={formData.username || ''}
onChange={(value) => {
setFormData({ ...formData, username: value });
}}
/>
<Form.Input
field='password'
label={t('密码')}
placeholder={t('请输入管理员密码')}
type='password'
prefix={<IconLock />}
showClear
noLabel={false}
mode='password'
validateStatus='default'
rules={[
{ required: true, message: t('请输入管理员密码') },
{ min: 8, message: t('密码长度至少为8个字符') },
]}
initValue={formData.password || ''}
onChange={(value) => {
setFormData({ ...formData, password: value });
}}
/>
<Form.Input
field='confirmPassword'
label={t('确认密码')}
placeholder={t('请确认管理员密码')}
type='password'
prefix={<IconLock />}
showClear
noLabel={false}
mode='password'
validateStatus='default'
rules={[
{ required: true, message: t('请确认管理员密码') },
{
validator: (rule, value) => {
if (value && formRef.current) {
const password = formRef.current.getValue('password');
if (value !== password) {
return Promise.reject(t('两次输入的密码不一致'));
}
}
return Promise.resolve();
},
},
]}
initValue={formData.confirmPassword || ''}
onChange={(value) => {
setFormData({ ...formData, confirmPassword: value });
}}
/>
</>
)}
{renderNavigationButtons && renderNavigationButtons()}
</>
);
};
export default AdminStep;

View File

@@ -0,0 +1,75 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Avatar, Typography, Descriptions } from '@douyinfe/semi-ui';
import { CheckCircle } from 'lucide-react';
const { Text, Title } = Typography;
/**
* 完成步骤组件
* 显示配置总结和初始化确认界面
*/
const CompleteStep = ({
setupStatus,
formData,
renderNavigationButtons,
t,
}) => {
return (
<div className='text-center'>
<Avatar color='green' className='mx-auto mb-4 shadow-lg'>
<CheckCircle size={24} />
</Avatar>
<Title heading={3} className='mb-2'>
{t('准备完成初始化')}
</Title>
<Text type='secondary' className='mb-6 block'>
{t('请确认以下设置信息,点击"初始化系统"开始配置')}
</Text>
<Descriptions>
<Descriptions.Item itemKey={t('数据库类型')}>
{setupStatus.database_type === 'sqlite'
? 'SQLite'
: setupStatus.database_type === 'mysql'
? 'MySQL'
: 'PostgreSQL'}
</Descriptions.Item>
<Descriptions.Item itemKey={t('管理员账号')}>
{setupStatus.root_init
? t('已初始化')
: formData.username || t('未设置')}
</Descriptions.Item>
<Descriptions.Item itemKey={t('使用模式')}>
{formData.usageMode === 'external'
? t('对外运营模式')
: formData.usageMode === 'self'
? t('自用模式')
: t('演示站点模式')}
</Descriptions.Item>
</Descriptions>
{renderNavigationButtons && renderNavigationButtons()}
</div>
);
};
export default CompleteStep;

View File

@@ -0,0 +1,130 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Banner } from '@douyinfe/semi-ui';
/**
* 数据库检查步骤组件
* 显示当前数据库类型和相关警告信息
*/
const DatabaseStep = ({ setupStatus, renderNavigationButtons, t }) => {
// 检测是否在 Electron 环境中运行
const isElectron =
typeof window !== 'undefined' && window.electron?.isElectron;
return (
<>
{/* 数据库警告 */}
{setupStatus.database_type === 'sqlite' && (
<Banner
type={isElectron ? 'info' : 'warning'}
closeIcon={null}
title={isElectron ? t('本地数据存储') : t('数据库警告')}
description={
isElectron ? (
<div>
<p>
{t(
'您的数据将安全地存储在本地计算机上。所有配置、用户信息和使用记录都会自动保存,关闭应用后不会丢失。',
)}
</p>
{window.electron?.dataDir && (
<p className='mt-2 text-sm opacity-80'>
<strong>{t('数据存储位置:')}</strong>
<br />
<code className='bg-gray-100 dark:bg-gray-800 px-2 py-1 rounded'>
{window.electron.dataDir}
</code>
</p>
)}
<p className='mt-2 text-sm opacity-70'>
💡 {t('提示:如需备份数据,只需复制上述目录即可')}
</p>
</div>
) : (
<div>
<p>
{t(
'您正在使用 SQLite 数据库。如果您在容器环境中运行,请确保已正确设置数据库文件的持久化映射,否则容器重启后所有数据将丢失!',
)}
</p>
<p className='mt-1'>
<strong>
{t(
'建议在生产环境中使用 MySQL 或 PostgreSQL 数据库,或确保 SQLite 数据库文件已映射到宿主机的持久化存储。',
)}
</strong>
</p>
</div>
)
}
className='!rounded-lg'
fullMode={false}
bordered
/>
)}
{/* MySQL数据库提示 */}
{setupStatus.database_type === 'mysql' && (
<Banner
type='success'
closeIcon={null}
title={t('数据库信息')}
description={
<div>
<p>
{t(
'您正在使用 MySQL 数据库。MySQL 是一个可靠的关系型数据库管理系统,适合生产环境使用。',
)}
</p>
</div>
}
className='!rounded-lg'
fullMode={false}
bordered
/>
)}
{/* PostgreSQL数据库提示 */}
{setupStatus.database_type === 'postgres' && (
<Banner
type='success'
closeIcon={null}
title={t('数据库信息')}
description={
<div>
<p>
{t(
'您正在使用 PostgreSQL 数据库。PostgreSQL 是一个功能强大的开源关系型数据库系统,提供了出色的可靠性和数据完整性,适合生产环境使用。',
)}
</p>
</div>
}
className='!rounded-lg'
fullMode={false}
bordered
/>
)}
{renderNavigationButtons && renderNavigationButtons()}
</>
);
};
export default DatabaseStep;

View File

@@ -0,0 +1,71 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { RadioGroup, Radio } from '@douyinfe/semi-ui';
/**
* 使用模式选择步骤组件
* 提供系统使用模式的选择界面
*/
const UsageModeStep = ({
formData,
handleUsageModeChange,
renderNavigationButtons,
t,
}) => {
return (
<>
<RadioGroup
value={formData.usageMode}
onChange={handleUsageModeChange}
type='card'
direction='horizontal'
className='mt-4'
aria-label='使用模式选择'
name='usage-mode-selection'
>
<Radio
value='external'
extra={t('适用于为多个用户提供服务的场景')}
style={{ width: '30%', minWidth: 200 }}
>
{t('对外运营模式')}
</Radio>
<Radio
value='self'
extra={t('适用于个人使用的场景,不需要设置模型价格')}
style={{ width: '30%', minWidth: 200 }}
>
{t('自用模式')}
</Radio>
<Radio
value='demo'
extra={t('适用于展示系统功能的场景,提供基础功能演示')}
style={{ width: '30%', minWidth: 200 }}
>
{t('演示站点模式')}
</Radio>
</RadioGroup>
{renderNavigationButtons && renderNavigationButtons()}
</>
);
};
export default UsageModeStep;

View File

@@ -0,0 +1,29 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 主要组件导出
export { default as SetupWizard } from './SetupWizard';
export { default as StepNavigation } from './components/StepNavigation';
// 步骤组件导出
export { default as DatabaseStep } from './components/steps/DatabaseStep';
export { default as AdminStep } from './components/steps/AdminStep';
export { default as UsageModeStep } from './components/steps/UsageModeStep';
export { default as CompleteStep } from './components/steps/CompleteStep';