Xinfan Chen
2026-05-12 143d4e616c3ae50b6bfec6d680aa830a2f7e96bc
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
'use client';
 
import { useEffect, useState } from 'react';
import { CheckCircle, Loader2, Save, Settings, XCircle } from 'lucide-react';
import BrandHeader from '@/components/BrandHeader';
import {
  I2I_PROVIDERS,
  LLM_PROVIDERS,
  T2I_PROVIDERS,
  VIDEO_PROVIDERS,
  VIDEO_RATIOS,
  VLM_PROVIDERS,
  type ProviderGroup,
} from '@/config/models';
 
type ConfigTree = Record<string, any>;
 
type Field = {
  path: string;
  label: string;
  type?: 'text' | 'number' | 'boolean' | 'password' | 'select';
  options?: Array<{ id: string; label: string }> | ProviderGroup[];
};
 
const MODEL_SELECTS = {
  llm: LLM_PROVIDERS,
  vlm: VLM_PROVIDERS,
  image_it2i: I2I_PROVIDERS,
  image_t2i: T2I_PROVIDERS,
  video: VIDEO_PROVIDERS,
  eval: LLM_PROVIDERS,
};
 
const GROUPS: Array<{ title: string; description: string; fields: Field[] }> = [
  {
    title: 'API Server',
    description: '服务启动与调试配置。host / port 保存后需要重启后端完全生效。',
    fields: [
      { path: 'server.host', label: 'host' },
      { path: 'server.port', label: 'port', type: 'number' },
      { path: 'server.debug', label: 'debug', type: 'boolean' },
    ],
  },
  {
    title: 'Common Provider Settings',
    description: '模型调用公共配置和代理设置。',
    fields: [
      { path: 'api_providers.common.print_model_input', label: 'print_model_input', type: 'boolean' },
      { path: 'api_providers.common.proxy', label: 'proxy' },
    ],
  },
  {
    title: 'OpenAI',
    description: 'OpenAI / 兼容 OpenAI 接口配置。',
    fields: [
      { path: 'api_providers.openai.api_key', label: 'api_key', type: 'password' },
      { path: 'api_providers.openai.base_url', label: 'base_url' },
      { path: 'api_providers.openai.enable_proxy', label: 'enable_proxy', type: 'boolean' },
    ],
  },
  {
    title: 'Gemini',
    description: 'Gemini 及兼容接口配置。',
    fields: [
      { path: 'api_providers.gemini.api_key', label: 'api_key', type: 'password' },
      { path: 'api_providers.gemini.base_url', label: 'base_url' },
      { path: 'api_providers.gemini.enable_proxy', label: 'enable_proxy', type: 'boolean' },
    ],
  },
  {
    title: 'DeepSeek',
    description: 'DeepSeek 接口配置。',
    fields: [
      { path: 'api_providers.deepseek.api_key', label: 'api_key', type: 'password' },
      { path: 'api_providers.deepseek.base_url', label: 'base_url' },
      { path: 'api_providers.deepseek.enable_proxy', label: 'enable_proxy', type: 'boolean' },
    ],
  },
  {
    title: 'DashScope',
    description: '通义千问、通义万相等 DashScope 服务配置。',
    fields: [
      { path: 'api_providers.dashscope.api_key', label: 'api_key', type: 'password' },
      { path: 'api_providers.dashscope.base_url', label: 'base_url' },
      { path: 'api_providers.dashscope.enable_proxy', label: 'enable_proxy', type: 'boolean' },
    ],
  },
  {
    title: 'ARK',
    description: 'Seedream / Seedance 使用的火山方舟配置。',
    fields: [
      { path: 'api_providers.ark.api_key', label: 'api_key', type: 'password' },
      { path: 'api_providers.ark.base_url', label: 'base_url' },
      { path: 'api_providers.ark.enable_proxy', label: 'enable_proxy', type: 'boolean' },
    ],
  },
  {
    title: 'Kling',
    description: '可灵视频生成接口配置。',
    fields: [
      { path: 'api_providers.kling.base_url', label: 'base_url' },
      { path: 'api_providers.kling.access_key', label: 'access_key', type: 'password' },
      { path: 'api_providers.kling.secret_key', label: 'secret_key', type: 'password' },
      { path: 'api_providers.kling.enable_proxy', label: 'enable_proxy', type: 'boolean' },
    ],
  },
  {
    title: 'Default Models',
    description: '主流程和 Pipeline 使用的默认模型。',
    fields: [
      { path: 'models.llm', label: 'llm', type: 'select', options: MODEL_SELECTS.llm },
      { path: 'models.vlm', label: 'vlm', type: 'select', options: MODEL_SELECTS.vlm },
      { path: 'models.image_it2i', label: 'image_it2i', type: 'select', options: MODEL_SELECTS.image_it2i },
      { path: 'models.image_t2i', label: 'image_t2i', type: 'select', options: MODEL_SELECTS.image_t2i },
      { path: 'models.video', label: 'video', type: 'select', options: MODEL_SELECTS.video },
      { path: 'models.video_ratio', label: 'video_ratio', type: 'select', options: VIDEO_RATIOS },
      { path: 'models.eval', label: 'eval', type: 'select', options: MODEL_SELECTS.eval },
    ],
  },
];
 
function getValue(config: ConfigTree, path: string) {
  return path.split('.').reduce((current, key) => current?.[key], config);
}
 
function setValue(config: ConfigTree, path: string, value: any): ConfigTree {
  const next = structuredClone(config || {});
  const parts = path.split('.');
  let current = next;
  for (const part of parts.slice(0, -1)) {
    current[part] = current[part] || {};
    current = current[part];
  }
  current[parts[parts.length - 1]] = value;
  return next;
}
 
function formatConfigPath(path: string) {
  if (!path) return 'backend/config.yaml';
  const normalized = path.replace(/\\/g, '/');
  const marker = '/aigc-director/aigc-claw/';
  const markerIndex = normalized.lastIndexOf(marker);
  if (markerIndex >= 0) return normalized.slice(markerIndex + marker.length);
  const backendIndex = normalized.lastIndexOf('/backend/config.yaml');
  if (backendIndex >= 0) return normalized.slice(backendIndex + 1);
  return normalized;
}
 
function maskSecret(value: unknown) {
  const text = String(value ?? '');
  if (!text) return '';
  if (text.length <= 10) return '*'.repeat(text.length);
  return `${text.slice(0, 5)}${'*'.repeat(Math.min(12, text.length - 10))}${text.slice(-5)}`;
}
 
function isProviderOptions(options: Field['options']): options is ProviderGroup[] {
  return Array.isArray(options) && options.some(option => 'models' in option);
}
 
export default function SettingsPage() {
  const [config, setConfig] = useState<ConfigTree>({});
  const [path, setPath] = useState('');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  const [secretDrafts, setSecretDrafts] = useState<Record<string, string>>({});
 
  useEffect(() => {
    const load = async () => {
      setLoading(true);
      setError('');
      try {
        const resp = await fetch('/api/config');
        if (!resp.ok) throw new Error('读取配置失败');
        const data = await resp.json();
        setConfig(data.config || {});
        setPath(data.path || '');
        setSecretDrafts({});
      } catch (e: any) {
        setError(e.message || '读取配置失败');
      } finally {
        setLoading(false);
      }
    };
    load();
  }, []);
 
  const updateField = (field: Field, raw: string | boolean) => {
    const value = field.type === 'number' ? Number(raw) || 0 : raw;
    setConfig(current => setValue(current, field.path, value));
  };
 
  const save = async () => {
    setSaving(true);
    setMessage('');
    setError('');
    try {
      const resp = await fetch('/api/config', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ values: config }),
      });
      if (!resp.ok) throw new Error('保存配置失败');
      const data = await resp.json();
      setConfig(data.config || {});
      setPath(data.path || '');
      setSecretDrafts({});
      setMessage('配置已保存');
    } catch (e: any) {
      setError(e.message || '保存配置失败');
    } finally {
      setSaving(false);
    }
  };
 
  const updateSecretField = (field: Field, raw: string) => {
    setSecretDrafts(current => ({ ...current, [field.path]: raw }));
    setConfig(current => setValue(current, field.path, raw));
  };
 
  return (
    <div className="min-h-screen bg-gray-50/50">
      <BrandHeader />
      <main className="w-full max-w-6xl mx-auto px-6 pt-10 pb-12">
        <div className="mb-8 text-center">
          <div className="inline-flex items-center gap-2 mb-3">
            <Settings className="w-7 h-7 text-blue-500" />
            <h1 className="text-2xl font-bold text-gray-800">设置</h1>
          </div>
          <p className="text-sm text-gray-500">
            修改后端配置并保存到 <span className="font-mono">{formatConfigPath(path)}</span>
          </p>
        </div>
 
        {loading ? (
          <div className="h-56 rounded-2xl border border-gray-200 bg-white flex items-center justify-center text-sm text-gray-400">
            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
            正在读取配置
          </div>
        ) : (
          <div className="space-y-5">
            {GROUPS.map(group => (
              <section key={group.title} className="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm">
                <div className="mb-4">
                  <h2 className="text-sm font-semibold text-gray-800">{group.title}</h2>
                  <p className="mt-1 text-xs text-gray-500">{group.description}</p>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {group.fields.map(field => {
                    const value = getValue(config, field.path);
                    return (
                      <label key={field.path} className="flex flex-col gap-1.5 min-w-0">
                        <span className="text-xs font-medium text-gray-500">{field.label}</span>
                        {field.type === 'boolean' ? (
                          <select
                            value={String(Boolean(value))}
                            onChange={event => updateField(field, event.target.value === 'true')}
                            className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 outline-none focus:border-blue-300"
                          >
                            <option value="true">true</option>
                            <option value="false">false</option>
                          </select>
                        ) : field.type === 'select' ? (
                          <select
                            value={String(value ?? '')}
                            onChange={event => updateField(field, event.target.value)}
                            className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 outline-none focus:border-blue-300"
                          >
                            {isProviderOptions(field.options) ? (
                              field.options.map(group => (
                                <optgroup key={group.provider} label={group.label}>
                                  {group.models.map(model => (
                                    <option key={model.id} value={model.id}>{model.label}</option>
                                  ))}
                                </optgroup>
                              ))
                            ) : (
                              (field.options || []).map(option => (
                                <option key={option.id} value={option.id}>{option.label}</option>
                              ))
                            )}
                          </select>
                        ) : field.type === 'password' ? (
                          <input
                            type="text"
                            value={secretDrafts[field.path] ?? maskSecret(value)}
                            onFocus={event => event.currentTarget.select()}
                            onChange={event => updateSecretField(field, event.target.value)}
                            placeholder="输入新密钥覆盖"
                            className="h-10 rounded-lg border border-gray-200 bg-white px-3 font-mono text-sm text-gray-700 outline-none focus:border-blue-300"
                          />
                        ) : (
                          <input
                            type={field.type === 'number' ? 'number' : 'text'}
                            value={String(value ?? '')}
                            onChange={event => updateField(field, event.target.value)}
                            className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 outline-none focus:border-blue-300"
                          />
                        )}
                      </label>
                    );
                  })}
                </div>
              </section>
            ))}
 
            <div className="sticky bottom-4 flex items-center gap-3 rounded-2xl border border-gray-200 bg-white/95 p-3 shadow-lg backdrop-blur">
              {message && (
                <span className="flex items-center gap-1.5 text-sm text-green-600">
                  <CheckCircle className="w-4 h-4" />
                  {message}
                </span>
              )}
              {error && (
                <span className="flex items-center gap-1.5 text-sm text-red-600">
                  <XCircle className="w-4 h-4" />
                  {error}
                </span>
              )}
              <button
                onClick={save}
                disabled={saving}
                className="ml-auto flex items-center gap-2 rounded-xl bg-blue-500 px-5 py-2 text-sm font-medium text-white shadow-sm transition-colors hover:bg-blue-600 disabled:cursor-not-allowed disabled:bg-gray-200"
              >
                {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                保存配置
              </button>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}