AccountForm.tsx
12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import { useEffect, useRef, useState, useCallback } from 'react';
import { Modal, Form, Input, Select, InputNumber, AutoComplete, Space, Button, Switch } from 'antd';
import { EyeOutlined, EyeInvisibleOutlined, BulbOutlined } from '@ant-design/icons';
import { useAccountStore } from '../../stores/accountStore';
import { accountService } from '../../services/accountService';
import { useProviderStore } from '../../stores/providerStore';
import type { Account } from '../../types';
interface Props {
open: boolean;
account: Account | null;
onClose: () => void;
}
const SECTION_BADGES = ['01', '02', '03'] as const;
export default function AccountForm({ open, account, onClose }: Props) {
const [form] = Form.useForm();
const { createAccount, updateAccount } = useAccountStore();
const { providers, fetchProviders } = useProviderStore();
const isEdit = !!account;
const [selectedProviderId, setSelectedProviderId] = useState<string | undefined>();
const [submitting, setSubmitting] = useState(false);
const [modelLoading, setModelLoading] = useState(false);
const [dirty, setDirty] = useState(false);
const [decryptedKey, setDecryptedKey] = useState<string | null>(null);
const [showDecryptedKey, setShowDecryptedKey] = useState(false);
const [keyLoading, setKeyLoading] = useState(false);
const firstFieldRef = useRef<HTMLInputElement>(null);
const isInitialMount = useRef(true);
const [thinkingEnabled, setThinkingEnabled] = useState(false);
useEffect(() => {
fetchProviders();
}, [fetchProviders]);
useEffect(() => {
if (open) {
setDirty(false);
setDecryptedKey(null);
setShowDecryptedKey(false);
isInitialMount.current = true;
if (account) {
// 只设置非敏感字段,api_key 留空让用户决定是否修改
const { api_key, ...safeFields } = account;
form.setFieldsValue(safeFields);
setSelectedProviderId(account.provider_id);
setThinkingEnabled(account.extra_config?.thinking_enabled ?? false);
} else {
form.resetFields();
setSelectedProviderId(undefined);
setThinkingEnabled(false);
}
// Auto-focus first field after modal animation
setTimeout(() => firstFieldRef.current?.focus(), 300);
}
}, [open, account, form]);
// Track dirty state
const onFieldsChange = useCallback(() => {
// Skip the initial form population
if (isInitialMount.current) {
isInitialMount.current = false;
return;
}
if (!dirty && form.isFieldsTouched()) {
setDirty(true);
}
}, [dirty, form]);
const handleClose = useCallback(() => {
if (dirty) {
Modal.confirm({
title: '未保存的更改',
content: '当前表单有未保存的修改,确定要关闭吗?',
okText: '关闭',
cancelText: '继续编辑',
onOk: onClose,
});
} else {
onClose();
}
}, [dirty, onClose]);
const handleToggleKeyVisibility = async () => {
if (showDecryptedKey) {
setShowDecryptedKey(false);
return;
}
if (decryptedKey) {
setShowDecryptedKey(true);
return;
}
// Fetch decrypted key from API
if (!account) return;
setKeyLoading(true);
try {
const key = await accountService.getDecryptedKey(account.id);
setDecryptedKey(key);
setShowDecryptedKey(true);
} catch {
Modal.error({ title: '获取失败', content: '无法获取解密后的 API Key,请稍后重试' });
} finally {
setKeyLoading(false);
}
};
const selectedProvider = providers.find((p) => p.id === selectedProviderId);
const modelOptions = selectedProvider?.supported_models?.map((m) => ({
label: m,
value: m,
})) ?? [];
const handleProviderChange = (val: string) => {
setSelectedProviderId(val);
form.setFieldValue('model_name', '');
// Simulate loading for model field when provider changes
setModelLoading(true);
setTimeout(() => setModelLoading(false), 400);
};
const handleOk = async () => {
try {
setSubmitting(true);
const values = await form.validateFields();
// 将思考模式开关合并到 extra_config
const extraConfig = values.extra_config || {};
extraConfig.thinking_enabled = thinkingEnabled;
values.extra_config = extraConfig;
if (isEdit) {
const cleanData: Record<string, unknown> = {};
for (const [k, v] of Object.entries(values)) {
if (v !== undefined && v !== null && v !== '') {
cleanData[k] = v;
}
}
// 确保 extra_config 即使其他字段为空也能提交
if (Object.keys(extraConfig).length === 0) {
delete cleanData.extra_config;
}
await updateAccount(account!.id, cleanData);
} else {
await createAccount(values);
}
onClose();
} catch {
// validation errors shown inline
} finally {
setSubmitting(false);
}
};
return (
<Modal
title={isEdit ? '编辑账号' : '新增账号'}
open={open}
onOk={handleOk}
onCancel={handleClose}
okText="保存"
cancelText="取消"
destroyOnHidden
width={640}
confirmLoading={submitting}
className={dirty ? 'has-dirty-dot' : ''}
footer={(_, { OkBtn, CancelBtn }) => (
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span className="kbd-hint">
按 <kbd>Ctrl</kbd> + <kbd>Enter</kbd> 快速保存
</span>
<div style={{ display: 'flex', gap: 8 }}>
<CancelBtn />
<OkBtn />
</div>
</div>
)}
>
<Form
form={form}
layout="vertical"
style={{ marginTop: 8 }}
onFieldsChange={onFieldsChange}
>
{/* Section 1: 基础信息 */}
<div className="form-section">
<div className="form-section-header">
<span className="section-badge">{SECTION_BADGES[0]}</span>
<h5>基础信息</h5>
<span className="section-hint">选择供应商并命名账号</span>
</div>
<div className="form-field-enter">
<Form.Item
name="provider_id"
label="关联供应商"
rules={[{ required: true, message: '请选择供应商' }]}
>
<Select
showSearch
placeholder="选择供应商"
optionFilterProp="label"
onChange={handleProviderChange}
options={providers.map((p) => ({
label: p.display_name,
value: p.id,
disabled: p.status !== 'active',
}))}
/>
</Form.Item>
</div>
<div className="form-field-enter">
<Form.Item
name="account_name"
label="账号名称"
rules={[
{ required: true, message: '请输入账号名称' },
{ pattern: /^[a-zA-Z0-9_-]+$/, message: '仅支持字母、数字、下划线和连字符' },
]}
extra="建议使用环境前缀,如 dev-main, prod-main"
>
<Input placeholder="例如: dev-main" ref={firstFieldRef} />
</Form.Item>
</div>
<div className="form-field-enter">
<Form.Item
name="code"
label="业务编码"
rules={[
{ required: !isEdit, message: '请输入业务编码' },
{ pattern: /^[a-zA-Z0-9_-]+$/, message: '仅支持字母、数字、下划线和连字符' },
]}
extra="跨环境唯一标识,如 ACCOUNT-QWEN-001,创建后不可修改"
>
<Input placeholder="例如: ACCOUNT-QWEN-001" disabled={isEdit} />
</Form.Item>
</div>
</div>
{/* Section 2: 凭证配置 */}
<div className="form-section">
<div className="form-section-header">
<span className="section-badge">{SECTION_BADGES[1]}</span>
<h5>凭证配置</h5>
<span className="section-hint">API 密钥和接入地址</span>
</div>
<div className="form-field-enter">
<Form.Item
name="api_key"
label="API Key"
rules={isEdit ? [] : [{ required: true, message: '请输入 API Key' }]}
extra={isEdit ? '留空则不修改当前 API Key' : undefined}
>
{isEdit ? (
<Space.Compact style={{ width: '100%' }}>
<Input
placeholder="留空则不修改"
autoComplete="off"
type={showDecryptedKey ? 'text' : 'password'}
value={showDecryptedKey && decryptedKey ? decryptedKey : undefined}
style={{ fontFamily: showDecryptedKey && decryptedKey ? 'monospace' : undefined }}
/>
<Button
icon={showDecryptedKey ? <EyeInvisibleOutlined /> : <EyeOutlined />}
loading={keyLoading}
onClick={handleToggleKeyVisibility}
title={showDecryptedKey ? '隐藏 API Key' : '查看 API Key'}
/>
</Space.Compact>
) : (
<Input.Password
placeholder="输入 API Key"
autoComplete="off"
/>
)}
</Form.Item>
</div>
<div className="form-field-enter">
<Form.Item name="endpoint" label="自定义 Endpoint">
<Input placeholder="可选,覆盖供应商默认 Endpoint URL" />
</Form.Item>
</div>
</div>
{/* Section 3: 模型参数 */}
<div className="form-section">
<div className="form-section-header">
<span className="section-badge">{SECTION_BADGES[2]}</span>
<h5>模型参数</h5>
<span className="section-hint">选择模型并配置调用参数</span>
</div>
<div className="form-field-enter">
<Form.Item
name="model_name"
label="模型名称"
rules={[{ required: true, message: '请选择或输入模型名称' }]}
extra={selectedProvider ? `${selectedProvider.display_name} 支持的模型列表已加载` : '请先选择供应商'}
>
{modelLoading ? (
<div className="field-skeleton" />
) : (
<AutoComplete
placeholder="选择或输入模型名称"
options={modelOptions}
filterOption={(inputValue, option) =>
option!.value.toUpperCase().includes(inputValue.toUpperCase())
}
allowClear
/>
)}
</Form.Item>
</div>
<div className="form-field-enter" style={{ display: 'flex', gap: 12 }}>
<Form.Item name="temperature" label="Temperature" style={{ flex: 1 }}>
<InputNumber min={0} max={2} step={0.1} placeholder="0.7" style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="max_tokens" label="Max Tokens" style={{ flex: 1 }}>
<InputNumber min={1} max={1000000} step={100} placeholder="4096" style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="priority" label="优先级" style={{ flex: 1 }}>
<InputNumber min={0} max={999} placeholder="0" style={{ width: '100%' }} />
</Form.Item>
</div>
<div className="form-field-enter thinking-toggle-row">
<Form.Item label=" " colon={false}>
<Space>
<Switch
checked={thinkingEnabled}
onChange={(checked) => {
setThinkingEnabled(checked);
setDirty(true);
}}
/>
<span className="thinking-toggle-label">
<BulbOutlined /> 思考模式
</span>
<span className="thinking-toggle-hint">
{thinkingEnabled
? '调用模型时注入推理参数(如 reasoning_effort),让模型展示推理过程'
: '模型直接返回最终答案,不展示中间推理过程'}
</span>
</Space>
</Form.Item>
</div>
</div>
</Form>
</Modal>
);
}