feat: transition to a fully frontend architecture by removing backend dependencies and updating configuration for local deployment

This commit is contained in:
HouYunFei
2026-06-16 12:56:49 +08:00
parent 8a66524ea7
commit 7f0199da59
36 changed files with 571 additions and 1773 deletions
+308 -191
View File
@@ -1,15 +1,15 @@
"use client";
import { App, Button, Form, Input, Modal, Progress, Segmented, Select } from "antd";
import { Cloud, RefreshCw, Wifi } from "lucide-react";
import { App, Button, Form, Input, Modal, Progress, Segmented, Select, Tabs } from "antd";
import { Cloud, Plus, RefreshCw, Trash2, Wifi } from "lucide-react";
import { useState } from "react";
import { ModelPicker } from "@/components/model-picker";
import { fetchImageModels } from "@/services/api/image";
import { fetchChannelModels } from "@/services/api/image";
import { syncAppDataToWebdav, type AppSyncDomainKey, type AppSyncProgressEvent } from "@/services/app-sync";
import { testWebdavConnection, WEBDAV_MANIFEST_FILE_NAME } from "@/services/webdav-sync";
import { audioFormatOptions, audioVoiceOptions, normalizeAudioSpeedValue } from "@/lib/audio-generation";
import { filterModelsByCapability, useConfigStore, type ModelCapability } from "@/stores/use-config-store";
import { createModelChannel, filterModelsByCapability, modelOptionLabel, modelOptionsFromChannels, normalizeModelOptionValue, useConfigStore, type AiConfig, type ModelCapability, type ModelChannel } from "@/stores/use-config-store";
type ModelGroup = {
capability: ModelCapability;
@@ -54,7 +54,8 @@ function createWebdavDomainProgress(): Record<AppSyncDomainKey, WebdavDomainProg
export function AppConfigModal() {
const { message } = App.useApp();
const [loadingModels, setLoadingModels] = useState(false);
const [activeTab, setActiveTab] = useState("channels");
const [loadingChannelId, setLoadingChannelId] = useState("");
const [testingWebdav, setTestingWebdav] = useState(false);
const [syncingWebdav, setSyncingWebdav] = useState(false);
const [webdavSyncStatus, setWebdavSyncStatus] = useState("");
@@ -67,53 +68,80 @@ export function AppConfigModal() {
const shouldPromptContinue = useConfigStore((state) => state.shouldPromptContinue);
const setConfigDialogOpen = useConfigStore((state) => state.setConfigDialogOpen);
const clearPromptContinue = useConfigStore((state) => state.clearPromptContinue);
const modelOptions = config.models.map((model) => ({ label: model, value: model }));
const modelOptions = config.models.map((model) => ({ label: modelOptionLabel(config, model), value: model }));
const webdavReady = Boolean(webdav.url.trim());
const saveConfig = (nextConfig: AiConfig) => {
(Object.keys(nextConfig) as Array<keyof AiConfig>).forEach((key) => updateConfig(key, nextConfig[key]));
};
const finishConfig = () => {
const ready = config.channels.some((channel) => channel.baseUrl.trim() && channel.apiKey.trim() && channel.models.length);
setConfigDialogOpen(false);
if (!config.baseUrl.trim() || !config.apiKey.trim()) return;
if (!config.imageModel.trim() || !config.videoModel.trim() || !config.textModel.trim()) return;
if (config.channelMode !== "local") updateConfig("channelMode", "local");
if (!ready) return;
message.success(shouldPromptContinue ? "配置已保存,请继续刚才的请求" : "配置已保存");
clearPromptContinue();
};
const refreshModels = async () => {
if (!config.baseUrl.trim() || !config.apiKey.trim()) {
message.error("请先填写 Base URL 和 API Key");
const updateChannels = (channels: ModelChannel[]) => {
const nextConfig = withChannels(config, channels);
saveConfig(nextConfig);
};
const updateChannel = (id: string, patch: Partial<ModelChannel>) => {
updateChannels(config.channels.map((channel) => (channel.id === id ? { ...channel, ...patch, models: patch.models ? uniqueModels(patch.models) : channel.models } : channel)));
};
const addChannel = () => {
updateChannels([...config.channels, createModelChannel({ name: `渠道 ${config.channels.length + 1}` })]);
};
const deleteChannel = (id: string) => {
if (config.channels.length <= 1) {
message.warning("至少保留一个渠道");
return;
}
setLoadingModels(true);
updateChannels(config.channels.filter((channel) => channel.id !== id));
};
const refreshChannelModels = async (channel: ModelChannel) => {
if (!channel.baseUrl.trim() || !channel.apiKey.trim()) {
message.error("请先填写该渠道的 Base URL 和 API Key");
return;
}
setLoadingChannelId(channel.id);
try {
const models = await fetchImageModels(config);
const imageModels = filterModelsByCapability(models, "image");
const videoModels = filterModelsByCapability(models, "video");
const textModels = filterModelsByCapability(models, "text");
const audioModels = filterModelsByCapability(models, "audio");
const nextImageModels = resolveNextCapabilityModels(config.imageModels, imageModels, models);
const nextVideoModels = resolveNextCapabilityModels(config.videoModels, videoModels, models);
const nextTextModels = resolveNextCapabilityModels(config.textModels, textModels, models);
const nextAudioModels = resolveNextCapabilityModels(config.audioModels, audioModels, models);
updateConfig("models", models);
updateConfig("imageModels", nextImageModels);
updateConfig("videoModels", nextVideoModels);
updateConfig("textModels", nextTextModels);
updateConfig("audioModels", nextAudioModels);
if (nextImageModels.length && !nextImageModels.includes(config.imageModel)) updateConfig("imageModel", nextImageModels[0]);
if (nextVideoModels.length && !nextVideoModels.includes(config.videoModel)) updateConfig("videoModel", nextVideoModels[0]);
if (nextTextModels.length && !nextTextModels.includes(config.textModel)) updateConfig("textModel", nextTextModels[0]);
if (nextAudioModels.length && !nextAudioModels.includes(config.audioModel)) updateConfig("audioModel", nextAudioModels[0]);
const models = await fetchChannelModels(channel);
updateChannels(config.channels.map((item) => (item.id === channel.id ? { ...item, models } : item)));
message.success(`${channel.name} 模型列表已更新`);
} catch (error) {
message.error(error instanceof Error ? error.message : "读取模型失败");
} finally {
setLoadingChannelId("");
}
};
const refreshAllModels = async () => {
const runnable = config.channels.filter((channel) => channel.baseUrl.trim() && channel.apiKey.trim());
if (!runnable.length) {
message.error("请先填写至少一个渠道的 Base URL 和 API Key");
return;
}
setLoadingChannelId("all");
try {
const entries = await Promise.all(runnable.map(async (channel) => [channel.id, await fetchChannelModels(channel)] as const));
const modelMap = new Map(entries);
updateChannels(config.channels.map((channel) => (modelMap.has(channel.id) ? { ...channel, models: modelMap.get(channel.id) || [] } : channel)));
message.success("模型列表已更新");
} catch (error) {
message.error(error instanceof Error ? error.message : "读取模型失败");
} finally {
setLoadingModels(false);
setLoadingChannelId("");
}
};
const updateCapabilityModels = (group: ModelGroup, models: string[]) => {
const next = uniqueModels(models);
const next = uniqueModels(models.map((model) => normalizeModelOptionValue(model, config.channels)).filter(Boolean));
updateConfig(group.modelsKey, next);
if (!next.includes(config[group.modelKey])) updateConfig(group.modelKey, next[0] || "");
};
@@ -174,189 +202,255 @@ export function AppConfigModal() {
title={
<div>
<div className="text-lg font-semibold"></div>
<div className="mt-1 text-xs font-normal text-stone-500"></div>
<div className="mt-1 text-xs font-normal text-stone-500"></div>
</div>
}
open={isConfigOpen}
width={960}
width={980}
centered
onCancel={() => setConfigDialogOpen(false)}
styles={{ body: { maxHeight: "72vh", overflowY: "auto", paddingRight: 18 } }}
styles={{ body: { maxHeight: "72vh", overflowY: "auto", paddingRight: 12 } }}
footer={
<Button type="primary" onClick={finishConfig}>
</Button>
}
>
<div className="pt-1">
<Form layout="vertical" requiredMark={false}>
<div className="mb-5 rounded-lg border border-stone-200 p-3 dark:border-stone-800">
<div className="text-sm font-semibold"></div>
<div className="mt-1 text-xs leading-5 text-stone-500">AI OpenAI API Key </div>
</div>
<div className="grid gap-4 md:grid-cols-2">
<Form.Item label="Base URL" className="mb-4">
<Input value={config.baseUrl} onChange={(event) => updateConfig("baseUrl", event.target.value)} />
</Form.Item>
<Form.Item label="API Key" className="mb-4">
<Input.Password value={config.apiKey} onChange={(event) => updateConfig("apiKey", event.target.value)} />
</Form.Item>
</div>
<div className="mb-5 flex items-center justify-between gap-3 rounded-lg border border-stone-200 px-3 py-2 dark:border-stone-800">
<div className="min-w-0">
<div className="text-sm font-medium"></div>
<div className="mt-1 text-xs text-stone-500"> {config.models.length} </div>
</div>
<Button size="small" loading={loadingModels} onClick={() => void refreshModels()}>
</Button>
</div>
<section className="mb-5 rounded-lg border border-stone-200 p-3 dark:border-stone-800">
<div className="mb-3">
<div className="text-sm font-semibold"></div>
<div className="mt-1 text-xs text-stone-500"></div>
</div>
<div className="grid gap-4 md:grid-cols-2">
{modelGroups.map((group) => (
<Form.Item key={group.modelsKey} label={group.optionsLabel} className="mb-0">
<Select
mode="tags"
showSearch
allowClear
maxTagCount="responsive"
placeholder={config.models.length ? `请选择或输入${group.optionsLabel}` : "输入模型名,或先拉取模型列表"}
value={config[group.modelsKey]}
options={modelOptions}
onChange={(models) => updateCapabilityModels(group, models)}
/>
</Form.Item>
))}
</div>
</section>
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
{modelGroups.map((group) => (
<Form.Item key={group.modelKey} label={group.defaultLabel} className="mb-4">
<ModelPicker config={config} value={config[group.modelKey]} onChange={(model) => updateConfig(group.modelKey, model)} capability={group.capability} fullWidth />
</Form.Item>
))}
</div>
<div className="grid gap-4 md:grid-cols-4">
<Form.Item label="画布默认生图张数" extra="新建画布生图和配置节点默认使用,单个节点仍可单独覆盖。" className="mb-4">
<Input
type="number"
min={1}
max={15}
value={config.canvasImageCount}
onChange={(event) => updateConfig("canvasImageCount", event.target.value)}
onBlur={(event) => updateConfig("canvasImageCount", normalizeImageCount(event.target.value))}
/>
</Form.Item>
<Form.Item label="默认音频声音" className="mb-4">
<Select value={config.audioVoice} options={audioVoiceOptions} onChange={(value) => updateConfig("audioVoice", value)} />
</Form.Item>
<Form.Item label="默认音频格式" className="mb-4">
<Select value={config.audioFormat} options={audioFormatOptions} onChange={(value) => updateConfig("audioFormat", value)} />
</Form.Item>
<Form.Item label="默认音频语速" className="mb-4">
<Input
type="number"
min={0.25}
max={4}
step={0.05}
value={config.audioSpeed}
onChange={(event) => updateConfig("audioSpeed", event.target.value)}
onBlur={(event) => updateConfig("audioSpeed", normalizeAudioSpeedValue(event.target.value))}
/>
</Form.Item>
</div>
<Form.Item label="默认音频指令" className="mb-4">
<Input.TextArea rows={2} value={config.audioInstructions} placeholder="例如:自然、温暖、适合旁白。" onChange={(event) => updateConfig("audioInstructions", event.target.value)} />
</Form.Item>
<Form.Item label="系统提示词" className="mb-0">
<Input.TextArea rows={3} value={config.systemPrompt} placeholder="例如:你是一位擅长电影感写实摄影的视觉导演。" onChange={(event) => updateConfig("systemPrompt", event.target.value)} />
</Form.Item>
<section className="mt-5 rounded-lg border border-stone-200 p-3 dark:border-stone-800">
<div className="mb-3 flex flex-wrap items-start justify-between gap-3">
<div>
<div className="flex items-center gap-2 text-sm font-semibold">
<Cloud className="size-4" />
WebDAV
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{
key: "channels",
label: "渠道",
children: (
<Form layout="vertical" requiredMark={false}>
<div className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-stone-200 p-3 dark:border-stone-800">
<div>
<div className="text-sm font-semibold"></div>
<div className="mt-1 text-xs text-stone-500"> Base URLAPI Key </div>
</div>
<div className="flex gap-2">
<Button icon={<RefreshCw className="size-4" />} loading={Boolean(loadingChannelId)} onClick={() => void refreshAllModels()}>
</Button>
<Button type="primary" icon={<Plus className="size-4" />} onClick={addChannel}>
</Button>
</div>
</div>
<div className="mt-1 text-xs text-stone-500"> AI API Key CORS Next.js </div>
</div>
<div className="text-xs text-stone-500">{webdav.lastSyncedAt ? `上次同步 ${formatWebdavTime(webdav.lastSyncedAt)}` : "尚未同步"}</div>
</div>
<div className="grid gap-4 md:grid-cols-2">
<Form.Item label="连接方式" className="mb-4 md:col-span-2">
<Segmented
block
value={webdav.proxyMode}
onChange={(value) => updateWebdavConfig("proxyMode", value as typeof webdav.proxyMode)}
options={[
{ label: "前端直连", value: "direct" },
{ label: "Next.js 转发", value: "nextjs" },
]}
/>
</Form.Item>
<Form.Item label="WebDAV 地址" className="mb-4">
<Input value={webdav.url} placeholder="https://nas.example.com/webdav" onChange={(event) => updateWebdavConfig("url", event.target.value)} />
</Form.Item>
<Form.Item label="远程目录" extra={`会在该目录下分业务目录保存,每个目录包含 ${WEBDAV_MANIFEST_FILE_NAME} 和 files/`} className="mb-4">
<Input value={webdav.directory} placeholder="infinite-canvas" onChange={(event) => updateWebdavConfig("directory", event.target.value)} />
</Form.Item>
<Form.Item label="用户名" className="mb-0">
<Input value={webdav.username} autoComplete="username" onChange={(event) => updateWebdavConfig("username", event.target.value)} />
</Form.Item>
<Form.Item label="密码 / 应用密码" className="mb-0">
<Input.Password value={webdav.password} autoComplete="current-password" onChange={(event) => updateWebdavConfig("password", event.target.value)} />
</Form.Item>
</div>
<div className="mt-4 flex flex-wrap items-center gap-2">
<Button icon={<Wifi className="size-4" />} disabled={!webdavReady || syncingWebdav} loading={testingWebdav} onClick={() => void testWebdav()}>
</Button>
<Button type="primary" icon={<RefreshCw className="size-4" />} disabled={!webdavReady || testingWebdav} loading={syncingWebdav} onClick={() => void syncWebdav()}>
{syncingWebdav ? "同步中" : "立即同步"}
</Button>
{webdavSyncStatus ? <span className="text-xs text-stone-500">{webdavSyncStatus}</span> : null}
</div>
{syncingWebdav || webdavSyncStatus ? (
<div className="mt-3 grid gap-2">
{webdavDomainKeys.map((key) => {
const item = webdavDomainProgress[key];
const count = item.total ? `${item.current || 0}/${item.total}` : "";
return (
<div key={key} className="rounded-md border border-stone-200 px-3 py-2 dark:border-stone-800">
<div className="mb-1 flex min-w-0 items-center justify-between gap-3 text-xs">
<span className="shrink-0 font-medium text-stone-700 dark:text-stone-200">{item.label}</span>
<span className="min-w-0 truncate text-right text-stone-500">
{item.stage}
{count ? ` · ${count}` : ""}
</span>
<div className="space-y-3">
{config.channels.map((channel) => (
<section key={channel.id} className="rounded-lg border border-stone-200 p-3 dark:border-stone-800">
<div className="mb-3 flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="truncate text-sm font-semibold">{channel.name || "未命名渠道"}</div>
<div className="mt-1 text-xs text-stone-500"> {channel.models.length} </div>
</div>
<div className="flex shrink-0 gap-2">
<Button size="small" loading={loadingChannelId === channel.id} onClick={() => void refreshChannelModels(channel)}>
</Button>
<Button size="small" danger icon={<Trash2 className="size-3.5" />} onClick={() => deleteChannel(channel.id)} />
</div>
</div>
<Progress percent={getWebdavProgressPercent(item)} size="small" status={getWebdavProgressStatus(item)} showInfo={false} />
<div className="grid gap-4 md:grid-cols-2">
<Form.Item label="渠道名称" className="mb-0">
<Input value={channel.name} onChange={(event) => updateChannel(channel.id, { name: event.target.value })} />
</Form.Item>
<Form.Item label="Base URL" className="mb-0">
<Input value={channel.baseUrl} onChange={(event) => updateChannel(channel.id, { baseUrl: event.target.value })} />
</Form.Item>
<Form.Item label="API Key" className="mb-0">
<Input.Password value={channel.apiKey} onChange={(event) => updateChannel(channel.id, { apiKey: event.target.value })} />
</Form.Item>
<Form.Item label="模型列表" className="mb-0">
<Select mode="tags" showSearch allowClear maxTagCount="responsive" placeholder="输入模型名,或点击拉取模型" value={channel.models} onChange={(models) => updateChannel(channel.id, { models })} />
</Form.Item>
</div>
</section>
))}
</div>
</Form>
),
},
{
key: "models",
label: "模型",
children: (
<Form layout="vertical" requiredMark={false}>
<div className="mb-4 rounded-lg border border-stone-200 p-3 dark:border-stone-800">
<div className="text-sm font-semibold"></div>
<div className="mt-1 text-xs leading-5 text-stone-500"></div>
</div>
<div className="grid gap-4 md:grid-cols-2">
{modelGroups.map((group) => (
<Form.Item key={group.modelsKey} label={group.optionsLabel} className="mb-0">
<Select
mode="tags"
showSearch
allowClear
maxTagCount="responsive"
placeholder={config.models.length ? `请选择或输入${group.optionsLabel}` : "先到渠道里填写或拉取模型"}
value={config[group.modelsKey]}
options={modelOptions}
onChange={(models) => updateCapabilityModels(group, models)}
/>
</Form.Item>
))}
</div>
<div className="mt-4 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
{modelGroups.map((group) => (
<Form.Item key={group.modelKey} label={group.defaultLabel} className="mb-0">
<ModelPicker config={config} value={config[group.modelKey]} onChange={(model) => updateConfig(group.modelKey, model)} capability={group.capability} fullWidth />
</Form.Item>
))}
</div>
</Form>
),
},
{
key: "preferences",
label: "生成偏好",
children: (
<Form layout="vertical" requiredMark={false}>
<div className="grid gap-4 md:grid-cols-4">
<Form.Item label="画布默认生图张数" extra="新建画布生图和配置节点默认使用,单个节点仍可单独覆盖。" className="mb-4">
<Input
type="number"
min={1}
max={15}
value={config.canvasImageCount}
onChange={(event) => updateConfig("canvasImageCount", event.target.value)}
onBlur={(event) => updateConfig("canvasImageCount", normalizeImageCount(event.target.value))}
/>
</Form.Item>
<Form.Item label="默认音频声音" className="mb-4">
<Select value={config.audioVoice} options={audioVoiceOptions} onChange={(value) => updateConfig("audioVoice", value)} />
</Form.Item>
<Form.Item label="默认音频格式" className="mb-4">
<Select value={config.audioFormat} options={audioFormatOptions} onChange={(value) => updateConfig("audioFormat", value)} />
</Form.Item>
<Form.Item label="默认音频语速" className="mb-4">
<Input
type="number"
min={0.25}
max={4}
step={0.05}
value={config.audioSpeed}
onChange={(event) => updateConfig("audioSpeed", event.target.value)}
onBlur={(event) => updateConfig("audioSpeed", normalizeAudioSpeedValue(event.target.value))}
/>
</Form.Item>
</div>
<Form.Item label="默认音频指令" className="mb-4">
<Input.TextArea rows={2} value={config.audioInstructions} placeholder="例如:自然、温暖、适合旁白。" onChange={(event) => updateConfig("audioInstructions", event.target.value)} />
</Form.Item>
<Form.Item label="系统提示词" className="mb-0">
<Input.TextArea rows={4} value={config.systemPrompt} placeholder="例如:你是一位擅长电影感写实摄影的视觉导演。" onChange={(event) => updateConfig("systemPrompt", event.target.value)} />
</Form.Item>
</Form>
),
},
{
key: "webdav",
label: "WebDAV",
children: (
<Form layout="vertical" requiredMark={false}>
<section className="rounded-lg border border-stone-200 p-3 dark:border-stone-800">
<div className="mb-3 flex flex-wrap items-start justify-between gap-3">
<div>
<div className="flex items-center gap-2 text-sm font-semibold">
<Cloud className="size-4" />
WebDAV
</div>
<div className="mt-1 text-xs text-stone-500"> AI API Key CORS Next.js </div>
</div>
);
})}
</div>
) : null}
</section>
</Form>
</div>
<div className="text-xs text-stone-500">{webdav.lastSyncedAt ? `上次同步 ${formatWebdavTime(webdav.lastSyncedAt)}` : "尚未同步"}</div>
</div>
<div className="grid gap-4 md:grid-cols-2">
<Form.Item label="连接方式" className="mb-4 md:col-span-2">
<Segmented
block
value={webdav.proxyMode}
onChange={(value) => updateWebdavConfig("proxyMode", value as typeof webdav.proxyMode)}
options={[
{ label: "前端直连", value: "direct" },
{ label: "Next.js 转发", value: "nextjs" },
]}
/>
</Form.Item>
<Form.Item label="WebDAV 地址" className="mb-4">
<Input value={webdav.url} placeholder="https://nas.example.com/webdav" onChange={(event) => updateWebdavConfig("url", event.target.value)} />
</Form.Item>
<Form.Item label="远程目录" extra={`会在该目录下分业务目录保存,每个目录包含 ${WEBDAV_MANIFEST_FILE_NAME} 和 files/`} className="mb-4">
<Input value={webdav.directory} placeholder="infinite-canvas" onChange={(event) => updateWebdavConfig("directory", event.target.value)} />
</Form.Item>
<Form.Item label="用户名" className="mb-0">
<Input value={webdav.username} autoComplete="username" onChange={(event) => updateWebdavConfig("username", event.target.value)} />
</Form.Item>
<Form.Item label="密码 / 应用密码" className="mb-0">
<Input.Password value={webdav.password} autoComplete="current-password" onChange={(event) => updateWebdavConfig("password", event.target.value)} />
</Form.Item>
</div>
<div className="mt-4 flex flex-wrap items-center gap-2">
<Button icon={<Wifi className="size-4" />} disabled={!webdavReady || syncingWebdav} loading={testingWebdav} onClick={() => void testWebdav()}>
</Button>
<Button type="primary" icon={<RefreshCw className="size-4" />} disabled={!webdavReady || testingWebdav} loading={syncingWebdav} onClick={() => void syncWebdav()}>
{syncingWebdav ? "同步中" : "立即同步"}
</Button>
{webdavSyncStatus ? <span className="text-xs text-stone-500">{webdavSyncStatus}</span> : null}
</div>
{syncingWebdav || webdavSyncStatus ? <WebdavProgressGrid progress={webdavDomainProgress} /> : null}
</section>
</Form>
),
},
]}
/>
</Modal>
);
}
function normalizeImageCount(value: string) {
return String(Math.max(1, Math.min(15, Math.floor(Math.abs(Number(value)) || 3))));
function withChannels(config: AiConfig, channels: ModelChannel[]): AiConfig {
const models = modelOptionsFromChannels(channels);
const imageModels = keepOrSuggest(config.imageModels, filterModelsByCapability(models, "image"), models);
const videoModels = keepOrSuggest(config.videoModels, filterModelsByCapability(models, "video"), models);
const textModels = keepOrSuggest(config.textModels, filterModelsByCapability(models, "text"), models);
const audioModels = keepOrSuggest(config.audioModels, filterModelsByCapability(models, "audio"), models);
return {
...config,
channels,
models,
baseUrl: channels[0]?.baseUrl || config.baseUrl,
apiKey: channels[0]?.apiKey || config.apiKey,
imageModels,
videoModels,
textModels,
audioModels,
imageModel: normalizeDefaultModel(config.imageModel, imageModels),
videoModel: normalizeDefaultModel(config.videoModel, videoModels),
textModel: normalizeDefaultModel(config.textModel, textModels),
audioModel: normalizeDefaultModel(config.audioModel, audioModels),
};
}
function resolveNextCapabilityModels(current: string[], suggested: string[], allModels: string[]) {
function keepOrSuggest(current: string[], suggested: string[], allModels: string[]) {
const available = new Set(allModels);
const kept = uniqueModels(current).filter((model) => available.has(model));
return kept.length ? kept : suggested;
}
function normalizeDefaultModel(value: string, options: string[]) {
if (options.includes(value)) return value;
return options[0] || value;
}
function normalizeImageCount(value: string) {
return String(Math.max(1, Math.min(15, Math.floor(Math.abs(Number(value)) || 3))));
}
function uniqueModels(models: string[]) {
return Array.from(new Set(models.map((model) => model.trim()).filter(Boolean)));
}
@@ -365,6 +459,29 @@ function formatWebdavTime(value: string) {
return new Date(value).toLocaleString("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
}
function WebdavProgressGrid({ progress }: { progress: Record<AppSyncDomainKey, WebdavDomainProgress> }) {
return (
<div className="mt-3 grid gap-2">
{webdavDomainKeys.map((key) => {
const item = progress[key];
const count = item.total ? `${item.current || 0}/${item.total}` : "";
return (
<div key={key} className="rounded-md border border-stone-200 px-3 py-2 dark:border-stone-800">
<div className="mb-1 flex min-w-0 items-center justify-between gap-3 text-xs">
<span className="shrink-0 font-medium text-stone-700 dark:text-stone-200">{item.label}</span>
<span className="min-w-0 truncate text-right text-stone-500">
{item.stage}
{count ? ` · ${count}` : ""}
</span>
</div>
<Progress percent={getWebdavProgressPercent(item)} size="small" status={getWebdavProgressStatus(item)} showInfo={false} />
</div>
);
})}
</div>
);
}
function getWebdavProgressPercent(item: WebdavDomainProgress) {
if (item.status === "success") return 100;
if (item.total) return Math.min(100, Math.round(((item.current || 0) / item.total) * 100));
+18 -8
View File
@@ -4,19 +4,15 @@ import type { ReactNode } from "react";
import { useEffect, useRef } from "react";
import { App } from "antd";
import { useConfigStore } from "@/stores/use-config-store";
import { createModelChannel, useConfigStore } from "@/stores/use-config-store";
export function ClientRootInit({ children }: { children: ReactNode }) {
const { message } = App.useApp();
const handledConfigParams = useRef(false);
const loadPublicSettings = useConfigStore((state) => state.loadPublicSettings);
const updateConfig = useConfigStore((state) => state.updateConfig);
const config = useConfigStore((state) => state.config);
const openConfigDialog = useConfigStore((state) => state.openConfigDialog);
useEffect(() => {
void loadPublicSettings();
}, [loadPublicSettings]);
useEffect(() => {
if (handledConfigParams.current) return;
const searchParams = new URLSearchParams(window.location.search);
@@ -29,12 +25,26 @@ export function ClientRootInit({ children }: { children: ReactNode }) {
searchParams.delete("apiKey");
searchParams.delete("apikey");
window.history.replaceState(null, "", `${window.location.pathname}${searchParams.size ? `?${searchParams}` : ""}${window.location.hash}`);
updateConfig("channelMode", "local");
const firstChannel = config.channels[0];
updateConfig(
"channels",
firstChannel
? config.channels.map((channel, index) =>
index === 0
? {
...channel,
...(baseUrl ? { baseUrl } : {}),
...(apiKey ? { apiKey } : {}),
}
: channel,
)
: [createModelChannel({ id: "default", name: "默认渠道", baseUrl: baseUrl || undefined, apiKey: apiKey || "" })],
);
if (baseUrl) updateConfig("baseUrl", baseUrl);
if (apiKey) updateConfig("apiKey", apiKey);
openConfigDialog(false);
message.success("已导入本地直连配置");
}, [message, openConfigDialog, updateConfig]);
}, [config.channels, message, openConfigDialog, updateConfig]);
return <>{children}</>;
}
@@ -1,9 +1,7 @@
"use client";
import type { CSSProperties, RefObject } from "react";
import { Avatar, Dropdown } from "antd";
import { BookOpen, Keyboard, LogOut, Settings2 } from "lucide-react";
import type { ItemType } from "antd/es/menu/interface";
import type { CSSProperties } from "react";
import { BookOpen, Keyboard, Settings2 } from "lucide-react";
import { AnimatedThemeToggler } from "@/components/ui/animated-theme-toggler";
import { GitHubLink } from "@/components/layout/github-link";
@@ -13,40 +11,23 @@ import { cn } from "@/lib/utils";
import { canvasThemes } from "@/lib/canvas-theme";
import { useConfigStore } from "@/stores/use-config-store";
import { useThemeStore } from "@/stores/use-theme-store";
import { useUserStore } from "@/stores/use-user-store";
type UserStatusActionsProps = {
showConfig?: boolean;
variant?: "default" | "canvas";
onOpenShortcuts?: () => void;
accountOpen?: boolean;
onAccountOpenChange?: (open: boolean) => void;
accountRef?: RefObject<HTMLDivElement | null>;
getPopupContainer?: (node: HTMLElement) => HTMLElement;
};
export function UserStatusActions({ showConfig = true, variant = "default", onOpenShortcuts, accountOpen, onAccountOpenChange, accountRef, getPopupContainer }: UserStatusActionsProps) {
export function UserStatusActions({ showConfig = true, variant = "default", onOpenShortcuts }: UserStatusActionsProps) {
const theme = useThemeStore((state) => state.theme);
const setTheme = useThemeStore((state) => state.setTheme);
const user = useUserStore((state) => state.user);
const logout = useUserStore((state) => state.clearSession);
const openConfigDialog = useConfigStore((state) => state.openConfigDialog);
const canvasTheme = canvasThemes[theme];
const userName = user?.displayName || user?.username || "";
const avatarUrl = user?.avatarUrl?.trim();
const avatarText = (userName.trim()[0] || "U").toUpperCase();
const naturalIconClass = "inline-flex size-7 shrink-0 items-center justify-center text-stone-600 transition hover:text-stone-950 dark:text-stone-300 dark:hover:text-white [&_svg]:size-4";
const iconStyle: CSSProperties | undefined = variant === "canvas" ? { color: canvasTheme.node.text } : undefined;
const versionStyle = iconStyle;
const gitHubClassName = "size-7 text-base";
const gitHubStyle = iconStyle;
const avatarStyle: CSSProperties | undefined = variant === "canvas" ? { borderColor: canvasTheme.toolbar.border, color: canvasTheme.node.text, background: "transparent" } : undefined;
const menuItems: ItemType[] = [
{ key: "user", disabled: true, label: <span className="font-medium text-current">{userName}</span> },
...(onOpenShortcuts ? [{ key: "shortcuts", icon: <Keyboard className="size-4" />, label: "快捷键", onClick: onOpenShortcuts }] : []),
{ type: "divider" },
{ key: "logout", icon: <LogOut className="size-4" />, label: "清除本地账户", onClick: logout },
];
return (
<div className="inline-flex shrink-0 items-center gap-1">
@@ -61,28 +42,11 @@ export function UserStatusActions({ showConfig = true, variant = "default", onOp
<AnimatedThemeToggler theme={theme} onThemeChange={setTheme} className={naturalIconClass} style={iconStyle} aria-label={theme === "dark" ? "切换到浅色主题" : "切换到深色主题"} title={theme === "dark" ? "切换到浅色主题" : "切换到深色主题"} />
<VersionReleaseModal style={versionStyle} />
<GitHubLink className={cn("bg-transparent hover:bg-transparent dark:hover:bg-transparent", gitHubClassName)} style={gitHubStyle} />
{!user && onOpenShortcuts ? (
{onOpenShortcuts ? (
<button type="button" className={naturalIconClass} style={iconStyle} onClick={onOpenShortcuts} aria-label="快捷键" title="快捷键">
<Keyboard className="size-4" />
</button>
) : null}
{user ? (
<div ref={accountRef}>
<Dropdown open={accountOpen} onOpenChange={onAccountOpenChange} trigger={["click"]} placement="bottomRight" getPopupContainer={getPopupContainer} styles={{ root: { minWidth: 150 } }} menu={{ items: menuItems }}>
<button type="button" className="flex size-7 shrink-0 items-center justify-center rounded-full bg-transparent p-0 text-[0] leading-[0] transition" aria-label="账户菜单">
<Avatar
size={24}
src={avatarUrl ? <img src={avatarUrl} alt={userName} referrerPolicy="no-referrer" /> : undefined}
alt={userName}
className="!flex !items-center !justify-center border border-stone-300 bg-transparent text-[11px] font-semibold text-stone-800 transition hover:border-stone-500 hover:text-stone-950 dark:border-stone-700 dark:text-stone-100 dark:hover:border-stone-400 dark:hover:text-white"
style={avatarStyle}
>
{avatarText}
</Avatar>
</button>
</Dropdown>
</div>
) : null}
</div>
);
}
+9 -9
View File
@@ -5,7 +5,7 @@ import { Cpu } from "lucide-react";
import { Select, SelectContent, SelectItem, SelectTrigger } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { selectableModelsByCapability, type AiConfig, type ModelCapability } from "@/stores/use-config-store";
import { modelOptionLabel, modelOptionName, selectableModelsByCapability, type AiConfig, type ModelCapability } from "@/stores/use-config-store";
type ModelPickerProps = {
config: AiConfig;
@@ -52,10 +52,10 @@ export function ModelPicker({ config, value, onChange, capability, className, fu
)}
onMouseDown={(event) => event.stopPropagation()}
onPointerDown={(event) => event.stopPropagation()}
title={current || placeholder}
title={current ? modelOptionLabel(config, current) : placeholder}
>
<ModelIcon model={current} />
<span className="canvas-model-picker-text min-w-0 flex-1 truncate text-left">{current || placeholder}</span>
<span className="canvas-model-picker-text min-w-0 flex-1 truncate text-left">{current ? modelOptionLabel(config, current) : placeholder}</span>
</SelectTrigger>
<SelectContent
data-canvas-no-zoom
@@ -69,8 +69,8 @@ export function ModelPicker({ config, value, onChange, capability, className, fu
>
{options.length ? (
options.map((model) => (
<SelectItem key={model} value={model} textValue={model}>
<ModelLabel model={model} />
<SelectItem key={model} value={model} textValue={modelOptionLabel(config, model)}>
<ModelLabel config={config} model={model} />
</SelectItem>
))
) : (
@@ -86,20 +86,20 @@ export function ModelPicker({ config, value, onChange, capability, className, fu
function emptyModelLabel(config: AiConfig, capability?: ModelCapability) {
const label = capability === "image" ? "生图" : capability === "video" ? "视频" : capability === "text" ? "文本" : capability === "audio" ? "音频" : "";
if (capability && config.models.length) return "请先在上方配置可选模型";
return config.models.length ? `暂无匹配的${label}模型` : "请先到配置里拉取模型列表";
return config.models.length ? `暂无匹配的${label}模型` : "请先到配置里添加渠道和模型";
}
function ModelLabel({ model }: { model: string }) {
function ModelLabel({ config, model }: { config: AiConfig; model: string }) {
return (
<span className="flex min-w-0 items-center gap-2">
<ModelIcon model={model} />
<span className="truncate">{model}</span>
<span className="truncate">{modelOptionLabel(config, model)}</span>
</span>
);
}
function ModelIcon({ model }: { model: string }) {
const icon = resolveModelIcon(model);
const icon = resolveModelIcon(modelOptionName(model));
return icon ? <img src={icon} alt="" className="size-4 shrink-0 dark:invert" /> : <Cpu className="size-4 shrink-0 opacity-70" />;
}
+2 -2
View File
@@ -6,7 +6,7 @@ import { Switch } from "antd";
import { ImageSettingsTheme } from "@/components/image-settings-panel";
import { boolConfig, isSeedanceFastModel, isSeedanceVideoConfig, normalizeSeedanceDuration, normalizeSeedanceRatio, normalizeSeedanceResolution, seedanceDurationOptions, seedancePixelLabel, seedanceRatioOptions, seedanceResolutionOptions } from "@/lib/seedance-video";
import { type CanvasTheme } from "@/lib/canvas-theme";
import type { AiConfig } from "@/stores/use-config-store";
import { modelOptionName, type AiConfig } from "@/stores/use-config-store";
const resolutionOptions = [
{ value: "720", label: "720p" },
@@ -103,7 +103,7 @@ export function VideoSettingsPanel({ config, onConfigChange, theme, showTitle =
}
function SeedanceVideoSettingsPanel({ config, onConfigChange, theme, showTitle, className }: VideoSettingsPanelProps) {
const model = config.model || config.videoModel;
const model = modelOptionName(config.model || config.videoModel);
const resolution = normalizeSeedanceResolution(config.vquality, model);
const ratio = normalizeSeedanceRatio(config.size);
const duration = normalizeSeedanceDuration(config.videoSeconds);