mirror of
https://github.com/basketikun/infinite-canvas.git
synced 2026-07-24 15:24:06 +08:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 973d14f4c3 | |||
| f038406070 | |||
| 1b289f6a77 | |||
| 27bd6f004b | |||
| 7893bd72dd | |||
| f7b030e209 | |||
| bce9c2d897 | |||
| b4515ed85f | |||
| 7f0199da59 | |||
| 8a66524ea7 | |||
| 0d90465339 | |||
| d3923e21e0 |
@@ -1,29 +1 @@
|
||||
# 管理员账号,首次启动会自动创建。
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=infinite-canvas
|
||||
|
||||
# JWT 登录密钥和过期时间,正式部署请修改 JWT_SECRET。
|
||||
JWT_SECRET=infinite-canvas
|
||||
JWT_EXPIRE_HOURS=168
|
||||
|
||||
# 后端默认监听 8080,如需本地开发修改端口再取消注释。
|
||||
# Docker 镜像内前端固定监听 3000,避免覆盖前端 PORT。
|
||||
# PORT=8080
|
||||
|
||||
# 公开访问地址,用于把本地上传的 Seedance 参考图/视频暴露给火山方舟拉取。
|
||||
# 线上部署时填写站点根地址,例如:https://your-domain.example.com
|
||||
# PUBLIC_BASE_URL=https://your-domain.example.com
|
||||
|
||||
# 前端开发代理默认使用 http://127.0.0.1:8080,如后端开发端口不同,启动前端时可单独设置 API_BASE_URL。
|
||||
# API_BASE_URL=http://127.0.0.1:8080
|
||||
NEXT_PUBLIC_DOC_URL=https://docs.canvas.best
|
||||
|
||||
# 数据库配置,默认使用本地 SQLite。
|
||||
STORAGE_DRIVER=sqlite
|
||||
# sqlite: DATABASE_DSN=data/infinite-canvas.db
|
||||
# Docker 部署时建议使用绝对路径,避免工作目录变化后写入临时库:DATABASE_DSN=/app/data/infinite-canvas.db
|
||||
# mysql 目标库不存在时会尝试自动创建,账号需有 CREATE 权限。
|
||||
# mysql: DATABASE_DSN=user:password@tcp(127.0.0.1:3306)/infinite_canvas?parseTime=true
|
||||
# postgres 目标库不存在时会尝试自动创建,账号需有 CREATEDB 权限。
|
||||
# postgres: DATABASE_DSN=postgres://user:password@127.0.0.1:5432/infinite_canvas?sslmode=disable
|
||||
DATABASE_DSN=data/infinite-canvas.db
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## v0.4.0 - 2026-06-16
|
||||
|
||||
+ [新增] 新增网页版Agent Loop模式。
|
||||
+ [新增] 支持Vercel一键部署。
|
||||
+ [调整] 移除后端,项目定位为个人画布工具。
|
||||
|
||||
## v0.3.0 - 2026-06-15
|
||||
|
||||
+ [新增] 新增canvas-agent通过codex操作画布。
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# Contributor License Agreement
|
||||
|
||||
This Contributor License Agreement ("Agreement") applies to any code,
|
||||
documentation, design asset, issue text, pull request, patch, or other
|
||||
material ("Contribution") that you submit to the infinite-canvas project
|
||||
("Project").
|
||||
|
||||
By submitting a Contribution, you agree to the terms below.
|
||||
|
||||
## 1. Copyright License
|
||||
|
||||
You keep ownership of your Contributions.
|
||||
|
||||
You grant the Project maintainers, including the repository owner, a
|
||||
perpetual, worldwide, non-exclusive, royalty-free, irrevocable license to use,
|
||||
reproduce, modify, prepare derivative works of, publicly display, publicly
|
||||
perform, sublicense, distribute, commercialize, and otherwise exploit your
|
||||
Contributions as part of the Project and related distributions.
|
||||
|
||||
This license allows the maintainers to publish your Contributions under the
|
||||
Project's open-source license, currently GNU Affero General Public License
|
||||
v3.0, and to use them in commercial, proprietary, privately licensed,
|
||||
source-available, or other versions, services, support offerings, or
|
||||
derivatives related to the Project.
|
||||
|
||||
## 2. Relicensing
|
||||
|
||||
You grant the Project maintainers, including the repository owner, the
|
||||
perpetual, worldwide, irrevocable right to relicense the Project, in whole or
|
||||
in part, under any license terms, whether existing now or created in the
|
||||
future.
|
||||
|
||||
You agree that your Contributions may be incorporated into and distributed as
|
||||
part of versions of the Project released under open-source, source-available,
|
||||
proprietary, commercial, private, dual-license, or other licensing models,
|
||||
without requiring additional permission, notice, approval, or compensation.
|
||||
|
||||
This right includes distribution of the Project as software, hosted services,
|
||||
Software-as-a-Service (SaaS), managed services, commercial offerings, OEM
|
||||
products, embedded products, and any other form of distribution or use.
|
||||
|
||||
## 3. Patent License
|
||||
|
||||
If your Contribution is covered by patents that you own or control, you grant
|
||||
the Project maintainers and recipients of the Project a perpetual, worldwide,
|
||||
non-exclusive, royalty-free, irrevocable patent license to make, use, sell,
|
||||
offer for sale, import, and otherwise run, modify, and distribute your
|
||||
Contribution as part of the Project.
|
||||
|
||||
## 4. Right to Contribute
|
||||
|
||||
You represent that:
|
||||
|
||||
* You have the legal right to submit the Contribution.
|
||||
* The Contribution is your original work, or you have permission to submit it
|
||||
under this Agreement.
|
||||
* Any third-party material included in the Contribution is clearly identified
|
||||
and compatible with the Project's license and this Agreement.
|
||||
* If you submit a Contribution on behalf of an employer or organization, you
|
||||
are authorized to do so.
|
||||
|
||||
## 5. No Obligation
|
||||
|
||||
The maintainers are not required to accept, review, merge, publish, or keep any
|
||||
Contribution. The maintainers may modify, reject, revert, or remove
|
||||
Contributions at their sole discretion.
|
||||
|
||||
## 6. No Warranty
|
||||
|
||||
You provide your Contributions "as is", without warranties or conditions of any
|
||||
kind, express or implied, including warranties of merchantability, fitness for
|
||||
a particular purpose, title, and non-infringement.
|
||||
|
||||
## 7. How This Agreement Is Accepted
|
||||
|
||||
Submitting a pull request, patch, commit, issue attachment, design asset,
|
||||
documentation update, or any other Contribution to this repository constitutes
|
||||
acceptance of this Agreement.
|
||||
|
||||
Maintainers may request explicit confirmation by asking contributors to comment:
|
||||
|
||||
```text
|
||||
I have read and agree to CLA.md.
|
||||
```
|
||||
|
||||
or by requiring acceptance through an automated CLA workflow.
|
||||
|
||||
## 8. Contact
|
||||
|
||||
For questions about this Agreement, contact the maintainers through the
|
||||
repository or email `1844025705@qq.com`.
|
||||
+2
-21
@@ -9,38 +9,19 @@ COPY CHANGELOG.md /app/CHANGELOG.md
|
||||
COPY web ./
|
||||
RUN bun run build
|
||||
|
||||
# 构建 Go 后端入口。
|
||||
FROM golang:1.25-alpine AS api-build
|
||||
|
||||
WORKDIR /app
|
||||
COPY go.mod go.sum ./
|
||||
COPY config ./config
|
||||
COPY handler ./handler
|
||||
COPY middleware ./middleware
|
||||
COPY model ./model
|
||||
COPY repository ./repository
|
||||
COPY router ./router
|
||||
COPY service ./service
|
||||
COPY main.go ./
|
||||
RUN go build -o /server .
|
||||
|
||||
# 运行镜像:Next.js 对外监听 3000,Go 只在容器内部监听 8080。
|
||||
# 运行镜像:只启动 Next.js,AI 请求由浏览器前台直连用户自己的接口。
|
||||
FROM node:22-bookworm-slim
|
||||
|
||||
WORKDIR /app
|
||||
COPY VERSION /app/VERSION
|
||||
COPY CHANGELOG.md /app/CHANGELOG.md
|
||||
COPY --from=api-build /server /app/server
|
||||
COPY --from=web-build /app/web/public /app/web/public
|
||||
COPY --from=web-build /app/web/.next/standalone /app/web
|
||||
COPY --from=web-build /app/web/.next/static /app/web/.next/static
|
||||
ENV NODE_ENV=production
|
||||
ENV HOSTNAME=0.0.0.0
|
||||
ENV PORT=3000
|
||||
ENV PROMPT_DATA_DIR=/app/data/prompts
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
|
||||
RUN mkdir -p /app/data/prompts
|
||||
|
||||
EXPOSE 3000
|
||||
# 先启动内部 Go API,再由 Next.js 提供页面并代理 /api/*。
|
||||
CMD ["sh", "-c", "PORT=8080 /app/server & cd /app/web && PORT=3000 node server.js"]
|
||||
CMD ["sh", "-c", "cd /app/web && PORT=3000 node server.js"]
|
||||
|
||||
@@ -10,9 +10,8 @@
|
||||
<a href="https://github.com/basketikun/infinite-canvas"><img src="https://img.shields.io/github/stars/basketikun/infinite-canvas?style=flat-square&logo=github" alt="GitHub stars"></a>
|
||||
<a href="VERSION"><img src="https://img.shields.io/badge/version-v0.2.0-2563eb?style=flat-square" alt="Version"></a>
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0-f97316?style=flat-square" alt="License"></a>
|
||||
<a href="https://www.docker.com/"><img src="https://img.shields.io/badge/Docker-ready-2496ed?style=flat-square&logo=docker&logoColor=white" alt="Docker ready"></a>
|
||||
<a href="https://vercel.com/"><img src="https://img.shields.io/badge/Vercel-ready-000000?style=flat-square&logo=vercel" alt="Vercel ready"></a>
|
||||
<a href="https://nextjs.org/"><img src="https://img.shields.io/badge/Next.js-16.2-000000?style=flat-square&logo=nextdotjs" alt="Next.js"></a>
|
||||
<a href="https://go.dev/"><img src="https://img.shields.io/badge/Go-1.25-00add8?style=flat-square&logo=go&logoColor=white" alt="Go"></a>
|
||||
</p>
|
||||
|
||||
无限画布是一款面向图片创作的开源工作台。它把画布编排、AI 图片生成、参考图编辑、对话助手、提示词库和素材沉淀放在同一个界面里,适合用来探索视觉方案并连续迭代图片结果。
|
||||
@@ -25,43 +24,43 @@
|
||||
## 核心功能
|
||||
|
||||
- 无限画布:多画布项目、节点拖拽缩放、连线、小地图、撤销重做、导入导出。
|
||||
- AI 创作:支持 OpenAI 兼容接口的文生图、图生图、参考图编辑、文本问答和视频生成;Seedance 2.0 可通过火山方舟 Agent Plan 接入。
|
||||
- AI 创作:浏览器前台直连你配置的 OpenAI 兼容接口,支持文生图、图生图、参考图编辑、文本问答、音频和视频生成;Seedance 2.0 可通过火山方舟 Agent Plan 接入。
|
||||
- 画布助手:围绕选中节点和上游节点对话、生图,并把结果插回画布。
|
||||
- 本地 Agent:通过本机 Canvas Agent 连接 Codex / Claude Code,让 Agent 通过 MCP 操作当前画布。
|
||||
- 提示词库:抓取多个 GitHub 开源项目,按案例整理数百个图片提示词。
|
||||
- 提示词库:Next.js route 抓取多个 GitHub 开源项目,并缓存在运行实例内存中。
|
||||
|
||||
完整功能说明见 [docs/features.md](docs2/features.md)。
|
||||
完整功能说明见 [功能介绍](docs/content/docs/overview/features.mdx)。
|
||||
|
||||
如果你在为担心没有合适的生图API来发愁,可以查看该免费生图项目:[chatgpt2api](https://github.com/basketikun/chatgpt2api)
|
||||
|
||||
## 技术栈
|
||||
|
||||
- 前端:Next.js、React、TypeScript、Tailwind CSS、Ant Design、Zustand、TanStack Query。
|
||||
- 后端:Go、Gin、GORM。
|
||||
- 部署:Docker。
|
||||
- 少量 Next.js Route:第三方提示词内存缓存、WebDAV 可选代理。
|
||||
- 部署:Vercel 或 Docker。
|
||||
|
||||
## 快速开始
|
||||
|
||||
[](https://render.com/deploy?repo=https://github.com/basketikun/infinite-canvas)
|
||||
推荐直接导入仓库到 Vercel,根目录已提供 `vercel.json`,会构建 `web/`。AI API Key、Base URL、画布、素材和生成记录默认保存在浏览器本地。
|
||||
|
||||
```bash
|
||||
git clone git@github.com:basketikun/infinite-canvas.git
|
||||
cd infinite-canvas
|
||||
cp .env.example .env
|
||||
# 修改默认账号密码等信息
|
||||
docker-compose up -d
|
||||
cd web
|
||||
bun install
|
||||
bun run dev
|
||||
```
|
||||
|
||||
本地源码构建运行:
|
||||
Docker 运行:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
docker compose -f docker-compose.local.yml up -d --build
|
||||
docker build -t infinite-canvas .
|
||||
docker run --rm -p 3000:3000 infinite-canvas
|
||||
```
|
||||
|
||||
运行后默认端口3000,可访问 `http://localhost:3000`。
|
||||
|
||||
如需要拉取提示词,可前往:`http://localhost:3000/admin/prompts`
|
||||
首次打开后进入右上角配置,填入自己的 OpenAI 兼容 `Base URL` 和 `API Key`。
|
||||
|
||||
## New API 自动配置
|
||||
|
||||
@@ -89,18 +88,23 @@ https://canvas.best?apiKey={key}&baseUrl={address}
|
||||
<td width="50%"><img src="https://i.ibb.co/bj30FtS5/5.png" alt="5" border="0"></td>
|
||||
<td width="50%"><img src="https://i.ibb.co/hxRvjw51/image.png" alt="image" border="0"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="https://i.ibb.co/jkWsF8q1/image.png" alt="image" border="0"></td>
|
||||
<td width="50%"><img src="https://i.ibb.co/XrnfXHx7/image.png" alt="image" border="0"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 文档
|
||||
|
||||
- [功能介绍](docs2/features.md)
|
||||
- [部署说明](docs2/deployment.md)
|
||||
- [画布节点操作手册](docs2/canvas-node-manual.md)
|
||||
- [画布快捷键](docs2/canvas-shortcuts.md)
|
||||
- [待办事项](docs2/todo.md)
|
||||
- [后端数据库说明](docs2/backend-database.md)
|
||||
- [系统配置数据结构](docs2/system-settings.md)
|
||||
- [接口响应约定](docs2/api-response.md)
|
||||
- [快速开始](docs/content/docs/overview/quick-start.mdx)
|
||||
- [功能介绍](docs/content/docs/overview/features.mdx)
|
||||
- [Render 部署](docs/content/docs/overview/render.mdx)
|
||||
- [Docker 部署](docs/content/docs/overview/docker.mdx)
|
||||
- [画布节点操作手册](docs/content/docs/canvas/canvas-node-manual.mdx)
|
||||
- [画布快捷键](docs/content/docs/canvas/canvas-shortcuts.mdx)
|
||||
- [贡献者协议](CLA.md)
|
||||
- [漏洞提交](SECURITY.md)
|
||||
- [待办事项](docs/content/docs/progress/todo.mdx)
|
||||
- [本地 Canvas Agent](canvas-agent/README.md)
|
||||
|
||||
## 赞助支持
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
infinite-canvas is in active development. Security fixes are accepted for the
|
||||
`main` branch and the latest tagged release. Older versions may be handled on a
|
||||
best-effort basis.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please do not open a public issue with exploit details, credentials, private
|
||||
API keys, proof-of-concept code, or screenshots that reveal sensitive data.
|
||||
|
||||
Preferred reporting channels:
|
||||
|
||||
1. Use GitHub private vulnerability reporting or a GitHub Security Advisory for
|
||||
this repository, if available.
|
||||
2. If a private GitHub report is not available, email `1844025705@qq.com` with
|
||||
the subject `[infinite-canvas security]`.
|
||||
3. If neither private channel is available, open a public issue that asks for a
|
||||
private contact channel and does not include technical exploit details.
|
||||
|
||||
Please include:
|
||||
|
||||
- Affected version, commit, branch, or deployment mode.
|
||||
- Clear reproduction steps.
|
||||
- Impact and attack scenario.
|
||||
- Any relevant logs, screenshots, or proof of concept, with secrets removed.
|
||||
- Whether the issue affects local-only usage, hosted deployments, browser
|
||||
storage, WebDAV sync, AI provider configuration, or API proxy behavior.
|
||||
|
||||
## Scope
|
||||
|
||||
Examples of in-scope reports:
|
||||
|
||||
- Cross-site scripting or token exfiltration in the web app.
|
||||
- Exposure of locally stored API keys or synced canvas data caused by project
|
||||
code.
|
||||
- Unsafe file handling, import/export behavior, or WebDAV proxy behavior.
|
||||
- Authentication, authorization, or access-control flaws in project-managed
|
||||
features.
|
||||
- Supply-chain issues that are exploitable through this repository's shipped
|
||||
code or default configuration.
|
||||
|
||||
Examples that are usually out of scope:
|
||||
|
||||
- Vulnerabilities in third-party AI providers, model APIs, hosting platforms,
|
||||
or browser extensions outside this repository.
|
||||
- Compromise of a user's own API key outside the app.
|
||||
- Denial-of-service reports that require unrealistic traffic volume or physical
|
||||
access to the user's device.
|
||||
- Missing security headers without a demonstrated exploit path.
|
||||
- Social engineering, phishing, spam, or account recovery requests.
|
||||
- Dependency reports without a practical impact on this project.
|
||||
|
||||
## Disclosure
|
||||
|
||||
The maintainers aim to acknowledge valid reports within 7 days and coordinate a
|
||||
fix before public disclosure. Response and fix timelines are best effort for
|
||||
this community project.
|
||||
|
||||
Please allow time for investigation and remediation before publishing details.
|
||||
Credit will be given on request unless you prefer to remain anonymous.
|
||||
|
||||
+38
-14
@@ -53,34 +53,39 @@ export async function startCodexThread(emit: AgentEmit, cwd?: string) {
|
||||
|
||||
export async function resumeCodexThread(emit: AgentEmit, threadId: string, cwd?: string) {
|
||||
codexApp ||= await CodexAppClient.start(emit);
|
||||
await loadCodexThread(emit, threadId, cwd, false);
|
||||
const thread = await codexApp.resumeThread(threadId, cwd);
|
||||
assertThreadWorkspace(thread, cwd);
|
||||
codexThreadId = String(field(thread, "id") || threadId);
|
||||
return { thread, messages: threadMessages(thread) };
|
||||
}
|
||||
|
||||
export async function listCodexThreads(emit: AgentEmit, options: { cwd?: string; all?: boolean; searchTerm?: string; limit?: number }) {
|
||||
export async function listCodexThreads(emit: AgentEmit, options: { cwd: string; searchTerm?: string; limit?: number }) {
|
||||
codexApp ||= await CodexAppClient.start(emit);
|
||||
const result = await codexApp.listThreads({
|
||||
limit: options.limit || 40,
|
||||
sortKey: "updated_at",
|
||||
sortDirection: "desc",
|
||||
sourceKinds: ["cli", "vscode", "appServer", "exec"],
|
||||
...(options.all ? {} : { cwd: options.cwd }),
|
||||
cwd: options.cwd,
|
||||
...(options.searchTerm ? { searchTerm: options.searchTerm } : {}),
|
||||
});
|
||||
const data = Array.isArray(field(result, "data")) ? (field(result, "data") as unknown[]).map(summarizeCodexThread) : [];
|
||||
const data = Array.isArray(field(result, "data")) ? (field(result, "data") as unknown[]).map(summarizeCodexThread).filter((thread) => threadInWorkspace(thread, options.cwd)) : [];
|
||||
return { data, nextCursor: field(result, "nextCursor") || null, backwardsCursor: field(result, "backwardsCursor") || null };
|
||||
}
|
||||
|
||||
export async function readCodexThread(emit: AgentEmit, threadId: string) {
|
||||
codexApp ||= await CodexAppClient.start(emit);
|
||||
const result = await codexApp.readThread(threadId);
|
||||
const thread = field(result, "thread") || {};
|
||||
export async function readCodexThread(emit: AgentEmit, threadId: string, cwd?: string) {
|
||||
const thread = await loadCodexThread(emit, threadId, cwd, true);
|
||||
return { thread: summarizeCodexThread(thread), messages: threadMessages(thread) };
|
||||
}
|
||||
|
||||
export async function archiveCodexThread(emit: AgentEmit, threadId: string) {
|
||||
export async function verifyCodexThreadWorkspace(emit: AgentEmit, threadId: string, cwd: string) {
|
||||
await loadCodexThread(emit, threadId, cwd, false);
|
||||
}
|
||||
|
||||
export async function archiveCodexThread(emit: AgentEmit, threadId: string, cwd?: string) {
|
||||
codexApp ||= await CodexAppClient.start(emit);
|
||||
await loadCodexThread(emit, threadId, cwd, false);
|
||||
await codexApp.archiveThread(threadId);
|
||||
}
|
||||
|
||||
@@ -93,10 +98,11 @@ export function runClaudeTurn(prompt: string, emit: AgentEmit) {
|
||||
|
||||
async function ensureCodexThread(app: CodexAppClient, options: CodexRunOptions) {
|
||||
if (options.threadId) {
|
||||
if (codexThreadId !== options.threadId) {
|
||||
const thread = await app.resumeThread(options.threadId, options.cwd);
|
||||
codexThreadId = String(field(thread, "id") || options.threadId);
|
||||
}
|
||||
const result = await app.readThread(options.threadId, false);
|
||||
assertThreadWorkspace(field(result, "thread") || {}, options.cwd);
|
||||
const thread = await app.resumeThread(options.threadId, options.cwd);
|
||||
assertThreadWorkspace(thread, options.cwd);
|
||||
codexThreadId = String(field(thread, "id") || options.threadId);
|
||||
return codexThreadId;
|
||||
}
|
||||
if (!codexThreadId) {
|
||||
@@ -155,8 +161,8 @@ class CodexAppClient {
|
||||
return this.request("thread/list", params);
|
||||
}
|
||||
|
||||
readThread(threadId: string) {
|
||||
return this.request("thread/read", { threadId, includeTurns: true });
|
||||
readThread(threadId: string, includeTurns = true) {
|
||||
return this.request("thread/read", { threadId, includeTurns });
|
||||
}
|
||||
|
||||
archiveThread(threadId: string) {
|
||||
@@ -291,6 +297,24 @@ function normalizeCodexNotification(method: string, params: Json): AgentEvent |
|
||||
return null;
|
||||
}
|
||||
|
||||
async function loadCodexThread(emit: AgentEmit, threadId: string, cwd: string | undefined, includeTurns: boolean) {
|
||||
codexApp ||= await CodexAppClient.start(emit);
|
||||
const result = await codexApp.readThread(threadId, includeTurns);
|
||||
const thread = field(result, "thread") || {};
|
||||
assertThreadWorkspace(thread, cwd);
|
||||
return thread;
|
||||
}
|
||||
|
||||
function assertThreadWorkspace(thread: unknown, cwd?: string) {
|
||||
if (!cwd || threadInWorkspace(thread, cwd)) return;
|
||||
throw new Error("该 Codex 会话不属于当前画布工作空间");
|
||||
}
|
||||
|
||||
function threadInWorkspace(thread: unknown, cwd: string) {
|
||||
const threadCwd = String(field(thread, "cwd") || "");
|
||||
return Boolean(threadCwd && path.resolve(threadCwd) === path.resolve(cwd));
|
||||
}
|
||||
|
||||
function normalizeItem(item: unknown) {
|
||||
const value = item && typeof item === "object" ? { ...(item as Json) } : {};
|
||||
if (value.type === "agentMessage") value.type = "agent_message";
|
||||
|
||||
@@ -7,7 +7,7 @@ export const DEFAULT_PORT = 17371;
|
||||
export const CONFIG_DIR = path.join(os.homedir(), ".infinite-canvas");
|
||||
export const CONFIG_FILE = path.join(CONFIG_DIR, "canvas-agent.json");
|
||||
export const VERSION = readPackageVersion();
|
||||
export const AGENT_PROMPT = "你正在帮助用户操作 Infinite Canvas 网页画布。需要改动画布时优先使用已配置的 infinite-canvas MCP 工具:先 canvas_get_state 读取当前画布,再根据任务使用 canvas_create_text_node、canvas_generate_text、canvas_generate_image、canvas_generate_video、canvas_generate_audio、canvas_create_generation_flow、canvas_create_config_node、canvas_run_generation、canvas_update_node、canvas_connect_nodes 等通用工具;复杂批量改动再用 canvas_apply_ops。需要生成内容时直接调用对应生成工具,不要绑定特定业务场景。不要模拟鼠标点击,不要要求用户手动复制 JSON。";
|
||||
export const AGENT_PROMPT = "你正在帮助用户操作 Infinite Canvas 网页画布。需要改动画布时优先使用已配置的 infinite-canvas MCP 工具:先 canvas_get_state 读取当前画布,再根据任务使用 canvas_create_text_node、canvas_generate_text、canvas_generate_image、canvas_generate_video、canvas_generate_audio、canvas_create_generation_flow、canvas_create_config_node、canvas_run_generation、canvas_update_node、canvas_connect_nodes 等通用工具;复杂批量改动再用 canvas_apply_ops,删除连线可用 delete_connections。需要生成内容时直接调用对应生成工具,不要绑定特定业务场景。不要模拟鼠标点击,不要要求用户手动复制 JSON。";
|
||||
|
||||
export type CanvasWorkspaceConfig = { workspacePath: string; activeThreadId?: string; pinnedThreadIds?: string[] };
|
||||
export type CanvasAgentConfig = { url: string; token: string; origins?: string[]; canvases?: Record<string, CanvasWorkspaceConfig> };
|
||||
|
||||
@@ -2,7 +2,7 @@ import express, { type NextFunction, type Request, type Response } from "express
|
||||
|
||||
import { DEFAULT_PORT, ensureCanvasWorkspace, loadConfig, saveConfig, updateCanvasWorkspace, type CanvasAgentConfig } from "./config.js";
|
||||
import { CanvasSession } from "./canvas-session.js";
|
||||
import { archiveCodexThread, listCodexThreads, readCodexThread, resumeCodexThread, runClaudeTurn, runCodexTurn, startCodexThread, summarizeCodexThread, withAgentPrompt } from "./agents.js";
|
||||
import { archiveCodexThread, listCodexThreads, readCodexThread, resumeCodexThread, runClaudeTurn, runCodexTurn, startCodexThread, summarizeCodexThread, verifyCodexThreadWorkspace, withAgentPrompt } from "./agents.js";
|
||||
import type { AgentAttachment } from "./types.js";
|
||||
|
||||
export function startHttpServer() {
|
||||
@@ -44,7 +44,7 @@ export function startHttpServer() {
|
||||
});
|
||||
app.get("/agent/codex/threads", route(async (req, res) => {
|
||||
const workspace = ensureCanvasWorkspace(config, String(req.query.canvasId || ""));
|
||||
const result = await listCodexThreads(emit, { cwd: workspace.workspacePath, all: req.query.all === "1", searchTerm: String(req.query.searchTerm || "") });
|
||||
const result = await listCodexThreads(emit, { cwd: workspace.workspacePath, searchTerm: String(req.query.searchTerm || "") });
|
||||
res.json({ ok: true, workspace, ...result });
|
||||
}));
|
||||
app.post("/agent/codex/threads/new", route(async (req, res) => {
|
||||
@@ -55,8 +55,9 @@ export function startHttpServer() {
|
||||
res.json({ ok: true, workspace: { ...workspace, activeThreadId }, thread: summarizeCodexThread(thread), messages: [] });
|
||||
}));
|
||||
app.get("/agent/codex/threads/:threadId", route(async (req, res) => {
|
||||
const workspace = ensureCanvasWorkspace(config, String(req.query.canvasId || ""));
|
||||
const threadId = routeParam(req.params.threadId);
|
||||
res.json({ ok: true, ...(await readCodexThread(emit, threadId)) });
|
||||
res.json({ ok: true, workspace, ...(await readCodexThread(emit, threadId, workspace.workspacePath)) });
|
||||
}));
|
||||
app.post("/agent/codex/threads/:threadId/resume", route(async (req, res) => {
|
||||
const workspace = ensureCanvasWorkspace(config, String(req.body?.canvasId || ""));
|
||||
@@ -68,7 +69,7 @@ export function startHttpServer() {
|
||||
app.post("/agent/codex/threads/:threadId/delete", route(async (req, res) => {
|
||||
const workspace = ensureCanvasWorkspace(config, String(req.body?.canvasId || ""));
|
||||
const threadId = routeParam(req.params.threadId);
|
||||
await archiveCodexThread(emit, threadId);
|
||||
await archiveCodexThread(emit, threadId, workspace.workspacePath);
|
||||
if (workspace.activeThreadId === threadId) updateCanvasWorkspace(config, workspace.canvasId, { activeThreadId: undefined });
|
||||
res.json({ ok: true });
|
||||
}));
|
||||
@@ -81,6 +82,7 @@ export function startHttpServer() {
|
||||
threadId = String((thread as Record<string, unknown>).id || "");
|
||||
updateCanvasWorkspace(config, workspace.canvasId, { activeThreadId: threadId });
|
||||
} else if (threadId !== workspace.activeThreadId) {
|
||||
await verifyCodexThreadWorkspace(emit, threadId, workspace.workspacePath);
|
||||
updateCanvasWorkspace(config, workspace.canvasId, { activeThreadId: threadId });
|
||||
}
|
||||
void runCodexTurn(withAgentPrompt(String(req.body?.prompt || "")), emit, attachments, { threadId, cwd: workspace.workspacePath });
|
||||
|
||||
@@ -37,6 +37,7 @@ export const canvasOpSchema = z.discriminatedUnion("type", [
|
||||
z.object({ type: z.literal("add_node"), nodeType: nodeTypeSchema.optional(), id: z.string().optional(), title: z.string().optional(), x: z.number().optional(), y: z.number().optional(), width: z.number().optional(), height: z.number().optional(), position: positionSchema.optional(), metadata: recordSchema.optional() }).passthrough(),
|
||||
z.object({ type: z.literal("update_node"), id: z.string(), patch: recordSchema.optional(), metadata: recordSchema.optional() }).passthrough(),
|
||||
z.object({ type: z.literal("delete_node"), id: z.string().optional(), ids: z.array(z.string()).optional() }).passthrough(),
|
||||
z.object({ type: z.literal("delete_connections"), id: z.string().optional(), ids: z.array(z.string()).optional(), all: z.boolean().optional() }).passthrough(),
|
||||
z.object({ type: z.literal("connect_nodes"), id: z.string().optional(), fromNodeId: z.string(), toNodeId: z.string() }).passthrough(),
|
||||
z.object({ type: z.literal("set_viewport"), viewport: viewportSchema }).passthrough(),
|
||||
z.object({ type: z.literal("select_nodes"), ids: z.array(z.string()) }).passthrough(),
|
||||
@@ -105,7 +106,7 @@ export const toolDescriptions: Record<ToolName, string> = {
|
||||
canvas_get_state: "读取当前网页画布的节点、连线、选区和视口。",
|
||||
canvas_get_selection: "读取当前网页画布选中的节点。",
|
||||
canvas_export_snapshot: "导出当前画布快照,用于理解布局。",
|
||||
canvas_apply_ops: "批量操作当前网页画布。ops 支持 add_node、update_node、delete_node、connect_nodes、set_viewport、select_nodes、run_generation。",
|
||||
canvas_apply_ops: "批量操作当前网页画布。ops 支持 add_node、update_node、delete_node、delete_connections、connect_nodes、set_viewport、select_nodes、run_generation。",
|
||||
canvas_create_node: "创建任意类型节点:text、image、config、video、audio。适合创建占位图、媒体占位、配置节点或自定义 metadata 节点。",
|
||||
canvas_create_text_node: "在当前画布创建单个文本节点。",
|
||||
canvas_create_text_nodes: "批量创建文本节点,适合生成标题、段落、脚本、说明等内容块。",
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/caarlos0/env/v11"
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Port string `env:"PORT" envDefault:"8080"`
|
||||
AdminUsername string `env:"ADMIN_USERNAME" envDefault:"admin"`
|
||||
AdminPassword string `env:"ADMIN_PASSWORD" envDefault:"infinite-canvas"`
|
||||
JWTSecret string `env:"JWT_SECRET" envDefault:"infinite-canvas"`
|
||||
JWTExpireHours int `env:"JWT_EXPIRE_HOURS" envDefault:"168"`
|
||||
StorageDriver string `env:"STORAGE_DRIVER" envDefault:"sqlite"`
|
||||
DatabaseDSN string `env:"DATABASE_DSN" envDefault:"data/infinite-canvas.db"`
|
||||
PublicBaseURL string `env:"PUBLIC_BASE_URL"`
|
||||
LinuxDoAuthorizeURL string `env:"LINUX_DO_AUTHORIZE_URL" envDefault:"https://connect.linux.do/oauth2/authorize"`
|
||||
LinuxDoTokenURL string `env:"LINUX_DO_TOKEN_URL" envDefault:"https://connect.linux.do/oauth2/token"`
|
||||
LinuxDoUserInfoURL string `env:"LINUX_DO_USERINFO_URL" envDefault:"https://connect.linux.do/api/user"`
|
||||
}
|
||||
|
||||
var Cfg Config
|
||||
|
||||
func Load() error {
|
||||
_ = godotenv.Load()
|
||||
if err := env.Parse(&Cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
normalizeDockerSQLiteDSN("/app/data")
|
||||
if strings.TrimSpace(Cfg.JWTSecret) == "" || Cfg.JWTSecret == "infinite-canvas" {
|
||||
secret, err := randomSecret()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
Cfg.JWTSecret = secret
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeDockerSQLiteDSN(appDataDir string) {
|
||||
driver := strings.ToLower(strings.TrimSpace(Cfg.StorageDriver))
|
||||
if driver != "" && driver != "sqlite" {
|
||||
return
|
||||
}
|
||||
dsn := strings.TrimSpace(Cfg.DatabaseDSN)
|
||||
if dsn == "" || dsn == ":memory:" || strings.HasPrefix(dsn, "file:") {
|
||||
return
|
||||
}
|
||||
pathPart, suffix := dsn, ""
|
||||
if index := strings.Index(dsn, "?"); index >= 0 {
|
||||
pathPart = dsn[:index]
|
||||
suffix = dsn[index:]
|
||||
}
|
||||
if filepath.IsAbs(pathPart) {
|
||||
return
|
||||
}
|
||||
slashPath := filepath.ToSlash(pathPart)
|
||||
if slashPath != "data" && !strings.HasPrefix(slashPath, "data/") {
|
||||
return
|
||||
}
|
||||
if _, err := os.Stat(appDataDir); err != nil {
|
||||
return
|
||||
}
|
||||
Cfg.DatabaseDSN = filepath.Join(filepath.Dir(appDataDir), filepath.FromSlash(slashPath)) + suffix
|
||||
}
|
||||
|
||||
func randomSecret() (string, error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNormalizeDockerSQLiteDSNUsesMountedDataDir(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
appDataDir := filepath.Join(root, "data")
|
||||
if err := os.MkdirAll(appDataDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
Cfg = Config{StorageDriver: "sqlite", DatabaseDSN: "data/infinite-canvas.db?_pragma=busy_timeout(5000)"}
|
||||
|
||||
normalizeDockerSQLiteDSN(appDataDir)
|
||||
|
||||
want := filepath.Join(root, "data", "infinite-canvas.db") + "?_pragma=busy_timeout(5000)"
|
||||
if Cfg.DatabaseDSN != want {
|
||||
t.Fatalf("DatabaseDSN = %q, want %q", Cfg.DatabaseDSN, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeDockerSQLiteDSNLeavesLocalPathWithoutMountedDataDir(t *testing.T) {
|
||||
Cfg = Config{StorageDriver: "sqlite", DatabaseDSN: "data/infinite-canvas.db"}
|
||||
|
||||
normalizeDockerSQLiteDSN(filepath.Join(t.TempDir(), "missing-data"))
|
||||
|
||||
if Cfg.DatabaseDSN != "data/infinite-canvas.db" {
|
||||
t.Fatalf("DatabaseDSN = %q, want relative local path", Cfg.DatabaseDSN)
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,6 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
env_file:
|
||||
- .env
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
ports:
|
||||
- "3000:3000"
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -2,10 +2,6 @@ services:
|
||||
app:
|
||||
image: ghcr.io/basketikun/infinite-canvas:latest
|
||||
container_name: infinite-canvas
|
||||
env_file:
|
||||
- .env
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
ports:
|
||||
- "3000:3000"
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
---
|
||||
title: 接口响应约定
|
||||
description: 业务接口统一响应结构与前端处理约定
|
||||
---
|
||||
|
||||
# 接口响应约定
|
||||
|
||||
后端业务接口统一返回 JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"data": {},
|
||||
"msg": "ok"
|
||||
}
|
||||
```
|
||||
|
||||
- `code`: 业务状态码,`0` 表示成功,非 `0` 表示失败。
|
||||
- `data`: 业务数据。失败时通常为 `null`。
|
||||
- `msg`: 响应消息。成功默认为 `ok`,失败时放错误原因。
|
||||
|
||||
前端请求逻辑以 `code` 判断业务是否成功。当前后端业务失败也会返回 HTTP 200,前端不要只依赖 HTTP 状态码判断结果。
|
||||
|
||||
接口连接失败、服务不可达、返回体不是约定 JSON 时,前端按网络或接口异常处理。
|
||||
@@ -1,200 +0,0 @@
|
||||
---
|
||||
title: 数据库说明
|
||||
description: 当前后端主要数据表与字段说明
|
||||
---
|
||||
|
||||
# 数据库说明
|
||||
|
||||
本文档只记录后端当前已经使用的主要数据表。
|
||||
|
||||
## 数据库
|
||||
|
||||
后端使用 GORM 管理数据库连接和表结构迁移。
|
||||
|
||||
支持的存储驱动:
|
||||
|
||||
- `sqlite`
|
||||
- `mysql`
|
||||
- `postgresql`
|
||||
|
||||
当前启动时执行 `AutoMigrate`,自动维护以下表:
|
||||
|
||||
- `users`
|
||||
- `credit_logs`
|
||||
- `prompts`
|
||||
- `assets`
|
||||
- `settings`
|
||||
|
||||
后续新增表时再同步补充本文档,未实际使用的规划表不提前写入。
|
||||
|
||||
### users
|
||||
|
||||
系统用户表。用户基础信息、角色、算力点余额和第三方登录标识放在该表中。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | string | 主键 |
|
||||
| `username` | string | 用户名,唯一索引 |
|
||||
| `password` | string | 密码哈希 |
|
||||
| `email` | string | 邮箱 |
|
||||
| `display_name` | string | 昵称 |
|
||||
| `avatar_url` | string | 头像地址 |
|
||||
| `role` | string | 角色:`user`、`admin` |
|
||||
| `credits` | number | 算力点余额 |
|
||||
| `aff_code` | string | 用户自己的邀请码,唯一索引 |
|
||||
| `aff_count` | number | 已邀请用户数量,冗余统计字段 |
|
||||
| `inviter_id` | string | 邀请人用户 ID |
|
||||
| `github_id` | string | GitHub 用户 ID |
|
||||
| `linux_do_id` | string | Linux.do 用户 ID |
|
||||
| `wechat_id` | string | 微信用户 ID |
|
||||
| `status` | string | 用户状态:`active`、`ban` |
|
||||
| `last_login_at` | string | 最近登录时间 |
|
||||
| `extra` | json | 扩展信息,第三方资料按平台命名空间保存,如 `linuxDo` |
|
||||
| `created_at` | string | 创建时间 |
|
||||
| `updated_at` | string | 更新时间 |
|
||||
|
||||
### prompts
|
||||
|
||||
提示词表。用于保存公开提示词、内置 GitHub 系统提示词、分类和预览内容。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | string | 主键 |
|
||||
| `title` | string | 标题 |
|
||||
| `cover_url` | string | 封面图 |
|
||||
| `prompt` | string | 提示词内容 |
|
||||
| `tags` | json | 标签列表 |
|
||||
| `category` | string | 分类标识 |
|
||||
| `preview` | text | Markdown 展示内容,可包含文本、图片、视频链接等 |
|
||||
| `created_at` | string | 创建时间 |
|
||||
| `updated_at` | string | 更新时间 |
|
||||
|
||||
`github_url` 仅用于接口返回,不写入数据库。
|
||||
|
||||
### assets
|
||||
|
||||
素材表。当前用于后台素材库。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | string | 主键 |
|
||||
| `title` | string | 标题 |
|
||||
| `type` | string | 素材类型:`text`、`image`、`video` 等 |
|
||||
| `cover_url` | string | 封面图 |
|
||||
| `tags` | json | 标签列表 |
|
||||
| `category` | string | 分类标识 |
|
||||
| `description` | string | 描述 |
|
||||
| `content` | text | 文本或 Markdown 内容 |
|
||||
| `url` | string | 图片、视频等媒体地址 |
|
||||
| `created_at` | string | 创建时间 |
|
||||
| `updated_at` | string | 更新时间 |
|
||||
|
||||
### settings
|
||||
|
||||
系统配置表,只保存两行数据:`public` 放前端可读取的公开配置,`private` 放仅后端和管理员可读取的私有配置,配置值都用 JSON。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `key` | string | 主键:`public`、`private` |
|
||||
| `value` | json | 配置内容 |
|
||||
| `created_at` | string | 创建时间 |
|
||||
| `updated_at` | string | 更新时间 |
|
||||
|
||||
`public.value` 常放前端展示和可公开读取的配置,例如模型列表、登录开关等。
|
||||
`private.value` 常放渠道密钥、登录密钥、后台内部开关等。
|
||||
|
||||
当前系统设置接口会按后端结构体序列化和反序列化已知字段;数据库 JSON 中额外存在的旧字段会被忽略。
|
||||
|
||||
`public.value` 当前字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `modelChannel` | object | 模型渠道公开配置组 |
|
||||
| `auth` | object | 公开登录配置 |
|
||||
|
||||
`modelChannel` 当前字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `availableModels` | string[] | 系统可用模型列表 |
|
||||
| `modelCosts` | object[] | 模型算力点配置 |
|
||||
| `defaultModel` | string | 默认模型 |
|
||||
| `defaultImageModel` | string | 默认图片模型 |
|
||||
| `defaultVideoModel` | string | 默认视频模型 |
|
||||
| `defaultTextModel` | string | 默认文本模型 |
|
||||
| `systemPrompt` | string | 系统提示词 |
|
||||
| `allowCustomChannel` | bool | 是否允许用户自定义渠道,默认允许,关闭后前端只提供走后端渠道的模式 |
|
||||
|
||||
`modelCosts` 每项字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `model` | string | 模型名称 |
|
||||
| `credits` | number | 每次后端模型接口调用前预扣的算力点,未配置默认不扣除 |
|
||||
|
||||
`auth.linuxDo` 当前字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `enabled` | bool | 是否开启 Linux.do 登录 |
|
||||
|
||||
`private.value` 当前字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `channels` | object[] | 模型渠道配置列表 |
|
||||
| `promptSync` | object | GitHub 远程提示词定时同步配置 |
|
||||
| `auth` | object | 私有登录配置 |
|
||||
|
||||
`channels` 每项字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `protocol` | string | 协议,当前支持 `openai` |
|
||||
| `name` | string | 渠道名称 |
|
||||
| `baseUrl` | string | 渠道接口地址 |
|
||||
| `apiKey` | string | 渠道密钥 |
|
||||
| `models` | string[] | 渠道可用模型列表 |
|
||||
| `weight` | number | 渠道权重,同一模型命中多个渠道时按权重随机 |
|
||||
| `enabled` | bool | 是否启用 |
|
||||
| `remark` | string | 备注 |
|
||||
|
||||
`promptSync` 字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `enabled` | bool | 是否开启定时同步,默认开启 |
|
||||
| `cron` | string | Cron 表达式,默认每 5 分钟 |
|
||||
|
||||
`auth.linuxDo` 当前字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `clientId` | string | Linux.do OAuth App Client ID |
|
||||
| `clientSecret` | string | Linux.do OAuth App Client Secret,后台返回时隐藏 |
|
||||
|
||||
后端请求模型时,先按模型名筛选启用且包含该模型的渠道,再按 `weight` 加权随机选择一个渠道。
|
||||
|
||||
### credit_logs
|
||||
|
||||
用户算力点变更流水表。当前记录后台手动调整、模型调用预扣和模型调用失败返还。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | string | 主键 |
|
||||
| `user_id` | string | 关联用户 ID |
|
||||
| `type` | string | 类型:`admin_adjust`、`ai_consume`、`ai_refund` |
|
||||
| `amount` | number | 本次变动数量,增加为正,扣减为负 |
|
||||
| `balance` | number | 变动后的用户算力点余额 |
|
||||
| `related_id` | string | 关联业务 ID,可为空 |
|
||||
| `remark` | string | 备注 |
|
||||
| `extra` | json | 扩展信息 |
|
||||
| `created_at` | string | 创建时间 |
|
||||
|
||||
`type` 当前取值:
|
||||
|
||||
| 值 | 说明 |
|
||||
| --- | --- |
|
||||
| `admin_adjust` | 后台手动调整 |
|
||||
| `ai_consume` | 调用后端模型接口消费 |
|
||||
| `ai_refund` | 后端模型接口调用失败返还 |
|
||||
@@ -1,43 +1,17 @@
|
||||
---
|
||||
title: 本地开发
|
||||
description: 前后端分开启动时的本地开发方式
|
||||
description: 前端优先的本地开发方式
|
||||
---
|
||||
|
||||
# 本地开发
|
||||
|
||||
如果你需要改代码,建议前后端分开启动。
|
||||
当前主应用以 `web/` 前端为主,AI 请求由浏览器前台直连用户自己的 OpenAI 兼容接口。
|
||||
|
||||
## 1. 准备环境变量
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
默认配置下:
|
||||
|
||||
- 后端端口是 `8080`
|
||||
- 前端端口是 `3000`
|
||||
- SQLite 数据库是 `data/infinite-canvas.db`
|
||||
|
||||
## 2. 启动后端
|
||||
|
||||
在仓库根目录执行:
|
||||
|
||||
```bash
|
||||
go run .
|
||||
```
|
||||
|
||||
后端会读取根目录 `.env`,并监听:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8080
|
||||
```
|
||||
|
||||
## 3. 启动前端
|
||||
|
||||
在 `web` 目录执行:
|
||||
## 1. 启动前端
|
||||
|
||||
```bash
|
||||
cd web
|
||||
bun install
|
||||
bun run dev
|
||||
```
|
||||
|
||||
@@ -47,9 +21,11 @@ bun run dev
|
||||
http://localhost:3000
|
||||
```
|
||||
|
||||
开发代理默认转发到 `http://127.0.0.1:8080`。如果你的后端端口不同,启动前设置 `API_BASE_URL`。
|
||||
## 2. 配置模型
|
||||
|
||||
## 4. 启动文档站
|
||||
打开右上角配置弹窗,填写自己的 `Base URL`、`API Key` 和模型名。第三方提示词由 Next.js route 拉取并缓存在运行实例内存中;WebDAV 可选择前端直连或 Next.js 转发。
|
||||
|
||||
## 3. 启动文档站
|
||||
|
||||
如果需要单独调整文档站,在 `docs` 目录执行:
|
||||
|
||||
@@ -60,5 +36,5 @@ bun run dev
|
||||
## 常见场景
|
||||
|
||||
- 改画布、页面和交互:主要看 `web/`
|
||||
- 改接口、业务逻辑和数据库:主要看仓库根目录下的 Go 代码
|
||||
- 改提示词缓存或 WebDAV 代理:主要看 `web/src/app/api/` 和 `web/src/app/webdav-proxy/`
|
||||
- 改文档站内容:主要看 `docs/content/docs/`
|
||||
|
||||
@@ -4,9 +4,6 @@
|
||||
"defaultOpen": true,
|
||||
"pages": [
|
||||
"local-development",
|
||||
"api-response",
|
||||
"system-settings",
|
||||
"backend-database",
|
||||
"canvas-data-structure"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
---
|
||||
title: 系统配置数据结构
|
||||
description: settings 表中 public 和 private 配置结构说明
|
||||
---
|
||||
|
||||
# 系统配置数据结构
|
||||
|
||||
系统配置保存在 `settings` 表中,目前只使用两行:
|
||||
|
||||
| key | 说明 |
|
||||
| --- | --- |
|
||||
| `public` | 公开配置,前端可以读取 |
|
||||
| `private` | 私有配置,只给后端和管理员使用 |
|
||||
|
||||
## public.value
|
||||
|
||||
```json
|
||||
{
|
||||
"modelChannel": {
|
||||
"availableModels": ["gpt-5.5", "gpt-image-2"],
|
||||
"modelCosts": [
|
||||
{ "model": "gpt-5.5", "credits": 1 },
|
||||
{ "model": "gpt-image-2", "credits": 10 }
|
||||
],
|
||||
"defaultModel": "gpt-image-2",
|
||||
"defaultImageModel": "gpt-image-2",
|
||||
"defaultTextModel": "gpt-5.5",
|
||||
"systemPrompt": "",
|
||||
"allowCustomChannel": true
|
||||
},
|
||||
"auth": {
|
||||
"allowRegister": true,
|
||||
"linuxDo": {
|
||||
"enabled": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `modelChannel` | object | 模型渠道公开配置组 |
|
||||
| `auth` | object | 认证相关公开配置 |
|
||||
|
||||
`modelChannel` 字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `availableModels` | string[] | 系统可用模型;保存设置时会自动合并所有已启用私有渠道的模型 |
|
||||
| `modelCosts` | object[] | 模型算力点配置,后端模型接口调用前按模型预扣,上游失败时返还;未配置默认不扣除 |
|
||||
| `defaultModel` | string | 默认模型,从 `availableModels` 中选择;为空或失效时优先选择文本模型 |
|
||||
| `defaultImageModel` | string | 默认图片模型,从 `availableModels` 中选择;为空或失效时优先选择 `seedream`、`image`、`gpt-image` 模型 |
|
||||
| `defaultVideoModel` | string | 默认视频模型,从 `availableModels` 中选择;为空或失效时优先选择 `seedance`、`video` 模型 |
|
||||
| `defaultTextModel` | string | 默认文本模型,从 `availableModels` 中选择;为空或失效时优先选择非图片/视频模型 |
|
||||
| `systemPrompt` | string | 系统提示词 |
|
||||
| `allowCustomChannel` | boolean | 是否允许用户在配置弹窗中切换为本地直连渠道,默认允许 |
|
||||
|
||||
`modelCosts` 每项字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `model` | string | 模型名称 |
|
||||
| `credits` | number | 每次后端模型接口调用前预扣的算力点 |
|
||||
|
||||
用户侧请求模式:
|
||||
|
||||
| 模式 | 说明 |
|
||||
| --- | --- |
|
||||
| 云端渠道 | 使用后端 `/api/v1/*` 代理接口,请求会按模型名匹配 `private.value.channels` 中的可用渠道 |
|
||||
| 本地直连 | 默认可选;`allowCustomChannel` 关闭后不可选,用户在浏览器本地配置 `baseUrl`、`apiKey` 和模型列表后直接请求模型接口 |
|
||||
|
||||
`auth` 字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `allowRegister` | boolean | 是否允许用户注册,默认允许;关闭后注册入口隐藏,注册接口拒绝新用户创建 |
|
||||
| `linuxDo.enabled` | boolean | 是否开启 Linux.do 登录 |
|
||||
|
||||
## private.value
|
||||
|
||||
```json
|
||||
{
|
||||
"channels": [
|
||||
{
|
||||
"protocol": "openai",
|
||||
"name": "默认渠道",
|
||||
"baseUrl": "https://api.example.com",
|
||||
"apiKey": "sk-xxx",
|
||||
"models": ["gpt-5.5", "gpt-image-2"],
|
||||
"weight": 1,
|
||||
"enabled": true,
|
||||
"remark": ""
|
||||
}
|
||||
],
|
||||
"promptSync": {
|
||||
"enabled": true,
|
||||
"cron": "*/5 * * * *"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `channels` | object[] | 模型渠道列表 |
|
||||
| `promptSync` | object | GitHub 远程提示词定时同步配置 |
|
||||
|
||||
`channels` 每项字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `protocol` | string | 协议,当前为 `openai` |
|
||||
| `name` | string | 渠道名称 |
|
||||
| `baseUrl` | string | OpenAI 兼容接口地址 |
|
||||
| `apiKey` | string | 渠道密钥 |
|
||||
| `models` | string[] | 该渠道可用模型 |
|
||||
| `weight` | number | 渠道权重;同一模型有多个可用渠道时按权重随机 |
|
||||
| `enabled` | boolean | 是否启用 |
|
||||
| `remark` | string | 备注 |
|
||||
|
||||
后端调用模型时,会从已启用、已配置 `baseUrl` 和 `apiKey`、且 `models` 包含目标模型的渠道中选择一个。
|
||||
|
||||
`promptSync` 字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `enabled` | boolean | 是否开启定时同步,默认开启 |
|
||||
| `cron` | string | Cron 表达式,默认每 5 分钟 |
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
title: 贡献者协议
|
||||
description: 贡献代码、文档或素材前需要了解的 CLA
|
||||
---
|
||||
|
||||
# 贡献者协议
|
||||
|
||||
Contributor License Agreement,见 [CLA.md](https://github.com/basketikun/infinite-canvas/blob/main/CLA.md)。
|
||||
|
||||
向本仓库提交 Pull Request、补丁、文档、素材或其他贡献,即表示你同意该协议。维护者也可能要求你在 PR 中明确回复:
|
||||
|
||||
```text
|
||||
I have read and agree to CLA.md.
|
||||
```
|
||||
|
||||
## 贡献前请确认
|
||||
|
||||
- 你有权提交相关代码、文档或素材。
|
||||
- 第三方内容已明确标注来源,并且授权方式与本项目兼容。
|
||||
- 提交内容可以随项目以 AGPL-3.0 以及项目相关商业授权方式发布。
|
||||
- 安全漏洞不要通过公开 Issue 直接披露细节,请按[漏洞提交](/docs/support/security)流程处理。
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"defaultOpen": true,
|
||||
"pages": [
|
||||
"license",
|
||||
"cla",
|
||||
"business"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -53,8 +53,8 @@ description: 当前画布节点的主要用途与操作流程
|
||||
- 生成配置节点的视频模式会读取上游文本作为 prompt,读取上游图片作为参考图,读取上游视频作为参考视频,并在输入预览里显示参考视频。
|
||||
- 视频生成接口支持 OpenAI 风格的 `POST /v1/videos`、`GET /v1/videos/{id}` 和 `GET /v1/videos/{id}/content`。
|
||||
- 使用火山方舟 Agent Plan / Seedance 2.0 时,Base URL 配置为 `https://ark.cn-beijing.volces.com/api/plan/v3`,模型名使用 Seedance 2.0 对应模型;系统会改用 `POST /contents/generations/tasks` 创建异步任务,并轮询 `GET /contents/generations/tasks/{id}`。
|
||||
- Agent Plan 专属 `/api/plan/v3` 当前未提供 OpenAI `/models` 模型列表接口,后台不会伪造模型列表;请手动填写 `doubao-seedance-2.0` 或文档列出的其他可用模型。
|
||||
- Seedance 参考视频必须是公网可访问 URL,或由本项目后端在配置 `PUBLIC_BASE_URL` 后上传并暴露的参考素材 URL。本地/内网地址无法被火山服务器拉取。
|
||||
- Agent Plan 专属 `/api/plan/v3` 当前未提供 OpenAI `/models` 模型列表接口,配置弹窗不会伪造模型列表;请手动填写 `doubao-seedance-2.0` 或文档列出的其他可用模型。
|
||||
- Seedance 参考视频更建议使用公网可访问 URL;本地素材由前端读取后传给兼容接口,是否可用取决于具体上游。
|
||||
|
||||
### 推荐流程
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ description: 画布常用鼠标与键盘操作说明
|
||||
|
||||
- 拖入图片文件:上传图片到画布。
|
||||
- 导入图片按钮:从本地选择图片。
|
||||
- 素材库或我的素材:选择素材后插入画布。
|
||||
- 我的素材:选择素材后插入画布。
|
||||
|
||||
## 撤销和重做范围
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ description: 使用 Docker Compose 部署无限画布
|
||||
```bash
|
||||
git clone git@github.com:basketikun/infinite-canvas.git
|
||||
cd infinite-canvas
|
||||
cp .env.example .env
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
@@ -22,19 +21,11 @@ docker compose up -d
|
||||
http://localhost:3000
|
||||
```
|
||||
|
||||
默认管理员账号:
|
||||
|
||||
```text
|
||||
用户名:admin
|
||||
密码:.env 中的 ADMIN_PASSWORD
|
||||
```
|
||||
|
||||
## 本地构建镜像
|
||||
|
||||
如果需要基于当前源码构建镜像:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
docker compose -f docker-compose.local.yml up -d --build
|
||||
```
|
||||
|
||||
@@ -56,14 +47,6 @@ cd docs
|
||||
docker compose -f docker-compose.local.yml up -d --build
|
||||
```
|
||||
|
||||
## 数据目录
|
||||
## 数据说明
|
||||
|
||||
`docker-compose.yml` 会把本地 `./data` 挂载到容器内 `/app/data`,用于保存 SQLite 数据库、提示词数据和上传素材。
|
||||
|
||||
Docker 部署时建议把 `.env` 中的 SQLite 路径设置为:
|
||||
|
||||
```text
|
||||
DATABASE_DSN=/app/data/infinite-canvas.db
|
||||
```
|
||||
|
||||
如果需要让火山方舟拉取本地上传的 Seedance 参考素材,还需要把 `PUBLIC_BASE_URL` 设置为公网可访问的站点地址。
|
||||
当前主应用镜像只启动 Next.js。画布、我的素材、生成记录和 AI API Key 默认保存在浏览器本地;第三方提示词由 Next.js route 拉取后缓存在运行实例内存里,不需要额外挂载数据目录。
|
||||
|
||||
@@ -30,7 +30,7 @@ description: 当前项目已实现的主要功能
|
||||
|
||||
目前画布中有三类节点:
|
||||
|
||||
- 图片节点:展示上传图片、生成图片或素材库图片。
|
||||
- 图片节点:展示上传图片、生成图片或我的素材图片。
|
||||
- 文本节点:保存提示词、说明文案、AI 文字回答等文本内容。
|
||||
- 生成配置节点:汇总上游文本和图片,统一配置模型、比例、数量后批量生成图片或文本。
|
||||
|
||||
@@ -57,16 +57,13 @@ description: 当前项目已实现的主要功能
|
||||
|
||||
## AI 生成
|
||||
|
||||
项目支持两种 AI 调用方式:
|
||||
|
||||
- 本地直连:前端使用本地配置的 Base URL、API Key 和 Model 直接请求 OpenAI 兼容接口。
|
||||
- 后台渠道:前端请求本项目后端 `/api/v1/*` 代理接口,后端按模型选择管理后台配置的渠道。
|
||||
项目默认使用前台直连:前端使用浏览器本地配置的 Base URL、API Key 和 Model 直接请求 OpenAI 兼容接口,不再通过项目服务端转发 AI 请求。
|
||||
|
||||
OpenAI 兼容图像和文本能力继续复用现有接口:
|
||||
|
||||
- `/v1/images/generations`:文生图。
|
||||
- `/v1/images/edits`:图生图/参考图编辑。
|
||||
- `/v1/chat/completions`:文本问答和带图问答。
|
||||
- `/v1/responses`:文本问答、带图问答和在线 Agent 工具调用。
|
||||
- `/v1/models`:读取模型列表;火山方舟 Agent Plan 专属 `/api/plan/v3` 当前未提供 OpenAI `/models` 模型列表接口,需要手动填写模型名。
|
||||
|
||||
视频能力支持两类接口:
|
||||
@@ -76,7 +73,7 @@ OpenAI 兼容图像和文本能力继续复用现有接口:
|
||||
|
||||
Base URL 如果已经以 `/v1`、`/api/v3` 或 `/api/plan/v3` 结尾,系统不会再追加 `/v1`。因此 cpa 反代或火山方舟 Agent Plan 可以继续通过现有 Base URL + API Key + Model 方式配置,不需要新增火山生图 Provider。
|
||||
|
||||
后台“拉取模型列表”会尝试真实请求 OpenAI `/models`,不会为 Agent Plan 伪造模型结果。如果火山方舟 Agent Plan 返回 404,请手动增加 `doubao-seedance-2.0` 或文档列出的其他模型名。
|
||||
配置弹窗里的“拉取模型列表”会尝试真实请求 OpenAI `/models`,不会为 Agent Plan 伪造模型结果。如果火山方舟 Agent Plan 返回 404,请手动增加 `doubao-seedance-2.0` 或文档列出的其他模型名。
|
||||
|
||||
可配置项:
|
||||
|
||||
@@ -91,7 +88,7 @@ Base URL 如果已经以 `/v1`、`/api/v3` 或 `/api/plan/v3` 结尾,系统不
|
||||
|
||||
普通图片/文本节点可以直接输入提示词生成结果。生成配置节点可以读取上游节点内容,并按节点自己的配置批量生成多个图片或文本结果。生成配置节点支持预览当前提示词和参考图输入,并调整输入顺序。
|
||||
|
||||
视频生成可从文本节点读取 prompt,从图片节点读取参考图,从视频节点读取参考视频,从音频节点读取参考音频。Seedance 2.0 支持最多 9 张参考图、3 个参考视频、3 个参考音频;分辨率支持 `480p`、`720p`、`1080p`(fast 模型不支持 `1080p`),比例支持 `16:9`、`4:3`、`1:1`、`3:4`、`9:16`、`21:9`、`adaptive`,时长支持 4-15 秒或智能时长。生成成功后会把视频插入画布为视频节点并使用原生播放器预览。Seedance 参考视频和参考音频需要公网可访问 URL;本地上传素材会先通过 `/api/v1/media/references` 保存到服务端,再由 `PUBLIC_BASE_URL` 生成可供火山服务器拉取的公开链接。
|
||||
视频生成可从文本节点读取 prompt,从图片节点读取参考图,从视频节点读取参考视频,从音频节点读取参考音频。Seedance 2.0 支持最多 9 张参考图、3 个参考视频、3 个参考音频;分辨率支持 `480p`、`720p`、`1080p`(fast 模型不支持 `1080p`),比例支持 `16:9`、`4:3`、`1:1`、`3:4`、`9:16`、`21:9`、`adaptive`,时长支持 4-15 秒或智能时长。生成成功后会把视频插入画布为视频节点并使用原生播放器预览。参考视频和参考音频优先使用公网可访问 URL;本地素材会以前端可读取的数据传给兼容接口,是否支持取决于具体上游。
|
||||
|
||||
## 画布助手
|
||||
|
||||
@@ -121,15 +118,14 @@ Base URL 如果已经以 `/v1`、`/api/v3` 或 `/api/plan/v3` 结尾,系统不
|
||||
- 复制提示词。
|
||||
- 把提示词加入“我的素材”。
|
||||
|
||||
后台提示词管理支持:
|
||||
提示词管理支持:
|
||||
|
||||
- 查询提示词。
|
||||
- 新增、编辑、删除提示词。
|
||||
- 按分组和标签筛选。
|
||||
- 查看远程提示词源。
|
||||
- 同步内置远程提示词源。
|
||||
- 触发读取内置远程提示词源。
|
||||
|
||||
当前内置远程源包括多个 GPT Image / GPT-4o / Nano Banana Pro 相关提示词仓库。
|
||||
当前内置远程源包括多个 GPT Image / GPT-4o / Nano Banana Pro 相关提示词仓库,由 Next.js route 拉取并缓存在当前运行实例内存中。
|
||||
|
||||
## 素材
|
||||
|
||||
@@ -143,49 +139,19 @@ Base URL 如果已经以 `/v1`、`/api/v3` 或 `/api/plan/v3` 结尾,系统不
|
||||
- 分页浏览。
|
||||
- 复制文本素材。
|
||||
- 下载图片素材。
|
||||
- 从提示词库、画布节点和服务器素材库加入素材。
|
||||
- 从提示词库和画布节点加入素材。
|
||||
- 在画布中插入素材。
|
||||
|
||||
“素材库”是服务器素材库,支持:
|
||||
## 配置和同步
|
||||
|
||||
- 按标题搜索。
|
||||
- 按类型筛选。
|
||||
- 按标签筛选。
|
||||
- 查看素材详情。
|
||||
- 复制文本或图片链接。
|
||||
- 加入“我的素材”。
|
||||
- 在画布中插入素材。
|
||||
|
||||
后台素材库管理支持:
|
||||
|
||||
- 查询素材。
|
||||
- 新增、编辑、删除素材。
|
||||
- 按类型和标签筛选。
|
||||
|
||||
## 账号和后台
|
||||
|
||||
- 注册功能暂时关闭。
|
||||
- 仅允许管理员账号登录。
|
||||
- 支持 JWT 会话。
|
||||
- `/api/auth/me` 可读取当前用户,未登录时返回访客用户。
|
||||
- 首次启动时可根据环境变量创建默认管理员。
|
||||
- 管理员后台目前包含提示词管理和素材库管理。
|
||||
- 后端已有用户管理接口,但前端暂未实现用户管理页面。
|
||||
|
||||
## 后端能力
|
||||
|
||||
- Gin 提供 API 服务。
|
||||
- Docker 运行时由 Next.js 提供页面入口,`/api/*` 请求代理到内部 Go 服务。
|
||||
- GORM 管理数据库连接和自动迁移。
|
||||
- 支持 SQLite、MySQL、PostgreSQL。
|
||||
- 数据库保存用户、提示词分组、提示词和服务器素材。
|
||||
- 业务接口统一返回 `{ code, data, msg }`。
|
||||
- 当前版本不需要账号登录,也不再提供后台管理页面。
|
||||
- 配置与用户偏好弹窗支持多个 OpenAI 兼容渠道、默认模型、生成偏好和 WebDAV 同步设置。
|
||||
- 第三方提示词和 WebDAV 可使用少量 Next.js route,AI 接口不经过项目后端代理。
|
||||
|
||||
## 当前限制
|
||||
|
||||
- 画布项目和“我的素材”目前只保存在浏览器本地,不会随账号同步。
|
||||
- 本地直连模式下,AI API Key 保存在浏览器本地,并由浏览器直接请求配置的 OpenAI 兼容接口;只适合本地或个人使用,公网多人使用不安全。公网部署推荐使用后台渠道,把真实密钥保存在服务端配置中。
|
||||
- 服务器素材库目前主要保存 URL 或文本,暂未提供文件上传接口。
|
||||
- Seedance 本地参考图/视频上传依赖 `PUBLIC_BASE_URL`,如果服务部署在 localhost、内网或不可被火山访问的地址,火山无法拉取参考素材。
|
||||
- AI API Key 保存在浏览器本地,并由浏览器直接请求配置的 OpenAI 兼容接口;只适合个人或可信环境使用。
|
||||
- Seedance 本地参考视频/音频更建议使用公网可访问 URL;上游是否接受前端传入的本地数据取决于具体兼容接口。
|
||||
- Seedance 返回远程视频 URL 时,前端会尽量下载为本地 Blob 持久化;如果因 CORS 或网络限制无法下载,会保留远程 URL,后续是否可播放取决于上游 URL 的有效期。
|
||||
- 画布更适合桌面端使用,移动端触控体验还未系统完善。
|
||||
|
||||
@@ -5,15 +5,20 @@ description: 用最少步骤把无限画布跑起来
|
||||
|
||||
# 快速开始
|
||||
|
||||
如果你只是想先把项目跑起来,优先使用 Docker。
|
||||
如果你只是想先把项目跑起来,优先部署或启动 `web/` 前端。
|
||||
|
||||
## Docker 启动
|
||||
## Vercel 部署
|
||||
|
||||
在 Vercel 中导入仓库即可,根目录 `vercel.json` 会构建 `web/`。当前版本的 AI 请求由浏览器前台直连用户自己的 OpenAI 兼容地址,不需要额外配置服务端。
|
||||
|
||||
## 本地启动
|
||||
|
||||
```bash
|
||||
git clone git@github.com:basketikun/infinite-canvas.git
|
||||
cd infinite-canvas
|
||||
cp .env.example .env
|
||||
docker compose up -d
|
||||
cd web
|
||||
bun install
|
||||
bun run dev
|
||||
```
|
||||
|
||||
启动后访问:
|
||||
@@ -22,29 +27,22 @@ docker compose up -d
|
||||
http://localhost:3000
|
||||
```
|
||||
|
||||
默认管理员账号:
|
||||
## Docker 启动
|
||||
|
||||
```text
|
||||
用户名:admin
|
||||
密码:.env 中的 ADMIN_PASSWORD
|
||||
```
|
||||
|
||||
## 本地构建镜像启动
|
||||
|
||||
如果你需要基于当前源码本地构建镜像:
|
||||
如果你需要基于当前源码构建镜像:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
docker compose -f docker-compose.local.yml up -d --build
|
||||
docker build -t infinite-canvas .
|
||||
docker run --rm -p 3000:3000 infinite-canvas
|
||||
```
|
||||
|
||||
## 首次使用建议
|
||||
|
||||
- 先打开右上角配置弹窗,填入自己的 `Base URL`、`API Key` 和模型名。
|
||||
- 如果使用后台渠道模式,再去管理后台补充系统模型与渠道配置。
|
||||
- 如果需要提示词仓库内容,可进入 `/admin/prompts` 拉取或同步。
|
||||
- 如果需要提示词仓库内容,打开 `/prompts` 会通过 Next.js route 拉取并缓存在内存中。
|
||||
- 如果需要跨设备同步画布、素材和生成记录,可在配置弹窗中填写 WebDAV。
|
||||
|
||||
## 说明
|
||||
|
||||
- 当前画布项目和“我的素材”主要保存在浏览器本地,不支持云同步。
|
||||
- 本地直连模式下,AI API Key 保存在浏览器本地,并由前端直接请求 OpenAI 兼容接口。
|
||||
- 当前画布项目和“我的素材”主要保存在浏览器本地,WebDAV 同步需要用户自行配置。
|
||||
- AI API Key 保存在浏览器本地,并由前端直接请求 OpenAI 兼容接口。
|
||||
|
||||
@@ -13,7 +13,7 @@ description: 使用 Render 部署无限画布
|
||||
|
||||
1. 点击 `Deploy to Render`。
|
||||
2. 登录 Render,并按页面提示连接 GitHub。
|
||||
3. 填写 `ADMIN_PASSWORD`,然后点击确认部署。
|
||||
3. 确认部署。
|
||||
|
||||
部署完成后,打开 Render 分配的 `.onrender.com` 域名即可访问。
|
||||
|
||||
@@ -22,17 +22,7 @@ description: 使用 Render 部署无限画布
|
||||
默认使用 Render 免费 Web Service:
|
||||
|
||||
- 空闲约 15 分钟后会休眠,下次访问会自动唤醒。
|
||||
- 免费版本地文件不是持久化存储,SQLite 数据可能在重启、重新部署后丢失。
|
||||
- 当前主应用数据默认保存在浏览器本地;第三方提示词缓存会随 Render 实例重启而清空,下次访问会重新拉取。
|
||||
- 适合体验和演示,不适合长期保存正式数据。
|
||||
|
||||
如果要长期使用,建议升级 Render 付费实例并挂载 Persistent Disk,或改用 PostgreSQL。
|
||||
|
||||
## 管理员账号
|
||||
|
||||
默认管理员用户名:
|
||||
|
||||
```text
|
||||
admin
|
||||
```
|
||||
|
||||
管理员密码是在 Render 部署页面里填写的 `ADMIN_PASSWORD`。
|
||||
长期使用建议优先部署到 Vercel,或自行配置 WebDAV 同步浏览器本地数据。
|
||||
|
||||
@@ -50,7 +50,7 @@ canvas-agent/
|
||||
|
||||
原因:
|
||||
|
||||
- 这是用户本机运行的 Node 服务,不属于线上 Go 后端,也不属于纯前端页面。
|
||||
- 这是用户本机运行的 Node 服务,不属于线上服务端,也不属于纯前端页面。
|
||||
- 后续可以发布成 npm 包,用户通过 `npx` 或全局安装启动。
|
||||
- Codex SDK、Codex MCP、Claude SDK 都更适合在本地 Node 进程中接入。
|
||||
- HTTP 路由使用 Express,MCP 协议层使用官方 `@modelcontextprotocol/sdk`,工具入参使用 `zod`,避免手写协议和松散 JSON。
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,8 +1,9 @@
|
||||
{
|
||||
"title": "赞助支持",
|
||||
"title": "支持与安全",
|
||||
"root": true,
|
||||
"defaultOpen": true,
|
||||
"pages": [
|
||||
"security",
|
||||
"donate",
|
||||
"sponsor"
|
||||
]
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
title: 漏洞提交
|
||||
description: 安全漏洞提交和负责任披露说明
|
||||
---
|
||||
|
||||
# 漏洞提交
|
||||
|
||||
安全策略英文原文见 [SECURITY.md](https://github.com/basketikun/infinite-canvas/blob/main/SECURITY.md)。
|
||||
|
||||
请不要在公开 Issue 中直接发布漏洞细节、可利用代码、私密 API Key、截图中的敏感信息或真实用户数据。
|
||||
|
||||
## 提交流程
|
||||
|
||||
优先使用 GitHub 的私密漏洞报告或 Security Advisory。如果仓库没有开启对应入口,请发送邮件至 [1844025705@qq.com](mailto:1844025705@qq.com),邮件标题建议使用:
|
||||
|
||||
```text
|
||||
[infinite-canvas security]
|
||||
```
|
||||
|
||||
如果暂时无法使用私密渠道,可以先开一个公开 Issue 请求维护者提供私密联系方式,但不要在 Issue 中写入漏洞细节。
|
||||
|
||||
## 建议提供的信息
|
||||
|
||||
- 受影响的版本、提交、分支或部署方式。
|
||||
- 清晰的复现步骤。
|
||||
- 漏洞影响、攻击场景和触发条件。
|
||||
- 已脱敏的日志、截图或 PoC。
|
||||
- 是否涉及浏览器本地存储、API Key、WebDAV 同步、AI 渠道配置或代理接口。
|
||||
|
||||
## 范围说明
|
||||
|
||||
项目会优先处理由本仓库代码或默认配置导致的 XSS、敏感信息泄露、文件处理、导入导出、WebDAV 代理、权限控制和供应链风险。
|
||||
|
||||
第三方模型服务、托管平台、浏览器插件、用户自行泄露的 API Key、没有实际利用路径的安全头建议、纯社工钓鱼或账号找回问题通常不属于本项目漏洞范围。
|
||||
|
||||
+6
-8
@@ -13,22 +13,20 @@
|
||||
- [画布节点操作手册](/docs/canvas/canvas-node-manual)
|
||||
- [画布快捷键](/docs/canvas/canvas-shortcuts)
|
||||
|
||||
## 开发文档
|
||||
## 开发与数据
|
||||
|
||||
- [本地开发](/docs/backend/local-development)
|
||||
- [接口响应约定](/docs/backend/api-response)
|
||||
- [系统配置数据结构](/docs/backend/system-settings)
|
||||
- [后端数据库说明](/docs/backend/backend-database)
|
||||
- [画布数据结构](/docs/backend/canvas-data-structure)
|
||||
|
||||
## 商务合作
|
||||
|
||||
- [开源协议](/docs/business/license)
|
||||
- [贡献者协议](/docs/business/cla)
|
||||
- [商务合作](/docs/business/business)
|
||||
|
||||
## 赞助支持
|
||||
## 支持与安全
|
||||
|
||||
- [文档](/docs/support/docs)
|
||||
- [漏洞提交](/docs/support/security)
|
||||
- [打赏支持](/docs/support/donate)
|
||||
- [广告赞助](/docs/support/sponsor)
|
||||
|
||||
@@ -40,5 +38,5 @@
|
||||
|
||||
## 说明
|
||||
|
||||
- 当前画布项目和“我的素材”主要保存在浏览器本地,不支持云同步。
|
||||
- 本地直连模式下,AI API Key 保存在浏览器本地,并由前端直接请求 OpenAI 兼容接口。
|
||||
- 当前画布项目和“我的素材”主要保存在浏览器本地,跨设备可自行配置 WebDAV 同步。
|
||||
- AI API Key 保存在浏览器本地,并由前端直接请求 OpenAI 兼容接口。
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
module github.com/basketikun/infinite-canvas
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/caarlos0/env/v11 v11.3.1
|
||||
github.com/gin-gonic/gin v1.11.0
|
||||
github.com/glebarez/sqlite v1.11.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/go-sql-driver/mysql v1.8.1
|
||||
github.com/jackc/pgx/v5 v5.6.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
golang.org/x/crypto v0.48.0
|
||||
gorm.io/driver/mysql v1.6.0
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
gorm.io/gorm v1.31.1
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/bytedance/sonic v1.14.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/glebarez/go-sqlite v1.21.2 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.27.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/goccy/go-yaml v1.18.0 // indirect
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/quic-go/qpack v0.5.1 // indirect
|
||||
github.com/quic-go/quic-go v0.54.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||
go.uber.org/mock v0.5.0 // indirect
|
||||
golang.org/x/arch v0.20.0 // indirect
|
||||
golang.org/x/mod v0.33.0 // indirect
|
||||
golang.org/x/net v0.50.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
golang.org/x/tools v0.42.0 // indirect
|
||||
google.golang.org/protobuf v1.36.9 // indirect
|
||||
modernc.org/libc v1.22.5 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.5.0 // indirect
|
||||
modernc.org/sqlite v1.23.1 // indirect
|
||||
)
|
||||
@@ -1,140 +0,0 @@
|
||||
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
||||
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
|
||||
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
|
||||
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
|
||||
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
|
||||
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
|
||||
github.com/caarlos0/env/v11 v11.3.1 h1:cArPWC15hWmEt+gWk7YBi7lEXTXCvpaSdCiZE2X5mCA=
|
||||
github.com/caarlos0/env/v11 v11.3.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
|
||||
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
||||
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
|
||||
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
|
||||
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
|
||||
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
|
||||
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
|
||||
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
|
||||
github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
||||
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
|
||||
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
|
||||
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
||||
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
|
||||
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
||||
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
|
||||
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
||||
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
|
||||
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
|
||||
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
|
||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
|
||||
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
|
||||
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
|
||||
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
|
||||
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
|
||||
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
|
||||
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
|
||||
modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM=
|
||||
modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=
|
||||
@@ -1,74 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/basketikun/infinite-canvas/service"
|
||||
)
|
||||
|
||||
type adminSyncRequest struct {
|
||||
Category string `json:"category"`
|
||||
}
|
||||
|
||||
type adminBatchDeleteRequest struct {
|
||||
IDs []string `json:"ids"`
|
||||
}
|
||||
|
||||
func AdminPromptCategories(w http.ResponseWriter, r *http.Request) {
|
||||
OK(w, service.ListPromptCategories())
|
||||
}
|
||||
|
||||
func AdminPrompts(w http.ResponseWriter, r *http.Request) {
|
||||
result, err := service.ListPrompts(parseQuery(r))
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, result)
|
||||
}
|
||||
|
||||
func AdminSavePrompt(w http.ResponseWriter, r *http.Request) {
|
||||
var item model.Prompt
|
||||
_ = json.NewDecoder(r.Body).Decode(&item)
|
||||
result, err := service.SavePrompt(item)
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, result)
|
||||
}
|
||||
|
||||
func AdminDeletePrompt(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if err := service.DeletePrompt(id); err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, true)
|
||||
}
|
||||
|
||||
func AdminDeletePrompts(w http.ResponseWriter, r *http.Request) {
|
||||
var request adminBatchDeleteRequest
|
||||
_ = json.NewDecoder(r.Body).Decode(&request)
|
||||
if err := service.DeletePrompts(request.IDs); err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, true)
|
||||
}
|
||||
|
||||
func AdminSyncPromptCategories(w http.ResponseWriter, r *http.Request) {
|
||||
var request adminSyncRequest
|
||||
_ = json.NewDecoder(r.Body).Decode(&request)
|
||||
log.Printf("sync prompt category start category=%s", request.Category)
|
||||
categories, err := service.SyncPromptCategory(request.Category)
|
||||
if err != nil {
|
||||
log.Printf("sync prompt category failed category=%s err=%v", request.Category, err)
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
log.Printf("sync prompt category done category=%s", request.Category)
|
||||
OK(w, categories)
|
||||
}
|
||||
-311
@@ -1,311 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/service"
|
||||
)
|
||||
|
||||
func AIImagesGenerations(w http.ResponseWriter, r *http.Request) {
|
||||
proxyAIRequest(w, r, "/images/generations")
|
||||
}
|
||||
|
||||
func AIImagesEdits(w http.ResponseWriter, r *http.Request) {
|
||||
proxyAIRequest(w, r, "/images/edits")
|
||||
}
|
||||
|
||||
func AIChatCompletions(w http.ResponseWriter, r *http.Request) {
|
||||
proxyAIRequest(w, r, "/chat/completions")
|
||||
}
|
||||
|
||||
func AIAudioSpeech(w http.ResponseWriter, r *http.Request) {
|
||||
proxyAIRequest(w, r, "/audio/speech")
|
||||
}
|
||||
|
||||
func AIVideos(w http.ResponseWriter, r *http.Request) {
|
||||
proxyAIRequest(w, r, "/videos")
|
||||
}
|
||||
|
||||
func AIVideo(w http.ResponseWriter, r *http.Request, id string) {
|
||||
proxyAIGetRequest(w, r, "/videos/"+id)
|
||||
}
|
||||
|
||||
func AIVideoContent(w http.ResponseWriter, r *http.Request, id string) {
|
||||
proxyAIGetRequest(w, r, "/videos/"+id+"/content")
|
||||
}
|
||||
|
||||
func proxyAIGetRequest(w http.ResponseWriter, r *http.Request, path string) {
|
||||
modelName := r.URL.Query().Get("model")
|
||||
if strings.TrimSpace(modelName) == "" {
|
||||
modelName = "grok-imagine-video"
|
||||
}
|
||||
channel, err := service.SelectModelChannel(modelName)
|
||||
if err != nil {
|
||||
log.Printf("AI proxy select channel failed: model=%s err=%v", modelName, err)
|
||||
Fail(w, "AI 接口请求失败")
|
||||
return
|
||||
}
|
||||
path = resolveAIProxyPath(channel.BaseURL, modelName, path)
|
||||
request, err := http.NewRequest(http.MethodGet, service.BuildModelChannelURL(channel, path), nil)
|
||||
if err != nil {
|
||||
Fail(w, "AI 接口请求失败")
|
||||
return
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+channel.APIKey)
|
||||
copyAIResponse(w, request, nil)
|
||||
}
|
||||
|
||||
func proxyAIRequest(w http.ResponseWriter, r *http.Request, path string) {
|
||||
body, contentType, modelName, err := readAIRequest(r)
|
||||
if err != nil {
|
||||
log.Printf("AI proxy request read failed: %v", err)
|
||||
Fail(w, "AI 接口请求失败")
|
||||
return
|
||||
}
|
||||
user, ok := service.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
Fail(w, "未登录或权限不足")
|
||||
return
|
||||
}
|
||||
credits, err := service.ModelCost(modelName)
|
||||
if err != nil {
|
||||
log.Printf("AI proxy read model cost failed: model=%s err=%v", modelName, err)
|
||||
Fail(w, "AI 接口请求失败")
|
||||
return
|
||||
}
|
||||
credits *= readAIRequestCount(body, contentType)
|
||||
channel, err := service.SelectModelChannel(modelName)
|
||||
if err != nil {
|
||||
log.Printf("AI proxy select channel failed: model=%s err=%v", modelName, err)
|
||||
Fail(w, "AI 接口请求失败")
|
||||
return
|
||||
}
|
||||
path = resolveAIProxyPath(channel.BaseURL, modelName, path)
|
||||
request, err := http.NewRequest(http.MethodPost, service.BuildModelChannelURL(channel, path), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
log.Printf("AI proxy build request failed: url=%s err=%v", service.BuildModelChannelURL(channel, path), err)
|
||||
Fail(w, "AI 接口请求失败")
|
||||
return
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+channel.APIKey)
|
||||
if contentType != "" {
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
if err := service.ConsumeUserCredits(user.ID, modelName, credits, path); err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
copyAIResponse(w, request, func() {
|
||||
if err := service.RefundUserCredits(user.ID, modelName, credits, path); err != nil {
|
||||
log.Printf("AI proxy refund credits failed: user=%s model=%s credits=%d err=%v", user.ID, modelName, credits, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func copyAIResponse(w http.ResponseWriter, request *http.Request, onFailure func()) {
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
log.Printf("AI proxy request failed: url=%s err=%v", request.URL.String(), err)
|
||||
if onFailure != nil {
|
||||
onFailure()
|
||||
}
|
||||
Fail(w, "AI 接口请求失败")
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode >= http.StatusBadRequest {
|
||||
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
||||
log.Printf("AI upstream error: url=%s status=%d", request.URL.String(), response.StatusCode)
|
||||
if onFailure != nil {
|
||||
onFailure()
|
||||
}
|
||||
Fail(w, aiUpstreamStatusMessage(response.StatusCode, body))
|
||||
return
|
||||
}
|
||||
|
||||
for key, values := range response.Header {
|
||||
if strings.EqualFold(key, "Content-Length") {
|
||||
continue
|
||||
}
|
||||
for _, value := range values {
|
||||
w.Header().Add(key, value)
|
||||
}
|
||||
}
|
||||
w.WriteHeader(response.StatusCode)
|
||||
_, _ = io.Copy(w, response.Body)
|
||||
}
|
||||
|
||||
func readAIRequest(r *http.Request) ([]byte, string, string, error) {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, "", "", err
|
||||
}
|
||||
modelName := ""
|
||||
if strings.HasPrefix(contentType, "multipart/form-data") {
|
||||
modelName = readMultipartModel(body, contentType)
|
||||
} else {
|
||||
var payload struct {
|
||||
Model string `json:"model"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &payload)
|
||||
modelName = payload.Model
|
||||
}
|
||||
if strings.TrimSpace(modelName) == "" {
|
||||
return nil, "", "", errMissingModel
|
||||
}
|
||||
return body, contentType, modelName, nil
|
||||
}
|
||||
|
||||
func readMultipartModel(body []byte, contentType string) string {
|
||||
_, params, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
reader := multipart.NewReader(bytes.NewReader(body), params["boundary"])
|
||||
form, err := reader.ReadForm(32 << 20)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer form.RemoveAll()
|
||||
if values := form.Value["model"]; len(values) > 0 {
|
||||
return values[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func readAIRequestCount(body []byte, contentType string) int {
|
||||
count := 1
|
||||
if strings.HasPrefix(contentType, "multipart/form-data") {
|
||||
_, params, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
return count
|
||||
}
|
||||
form, err := multipart.NewReader(bytes.NewReader(body), params["boundary"]).ReadForm(32 << 20)
|
||||
if err != nil {
|
||||
return count
|
||||
}
|
||||
defer form.RemoveAll()
|
||||
if values := form.Value["n"]; len(values) > 0 {
|
||||
_, _ = fmt.Sscan(values[0], &count)
|
||||
}
|
||||
} else {
|
||||
var payload struct {
|
||||
N int `json:"n"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &payload)
|
||||
count = payload.N
|
||||
}
|
||||
if count < 1 {
|
||||
return 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
var errMissingModel = &aiError{"缺少模型名称"}
|
||||
|
||||
func resolveAIProxyPath(baseURL string, modelName string, path string) string {
|
||||
if !isArkSeedanceVideo(baseURL, modelName) {
|
||||
return path
|
||||
}
|
||||
if path == "/videos" {
|
||||
return "/contents/generations/tasks"
|
||||
}
|
||||
if strings.HasPrefix(path, "/videos/") && !strings.HasSuffix(path, "/content") {
|
||||
return "/contents/generations/tasks/" + strings.TrimPrefix(path, "/videos/")
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func isArkSeedanceVideo(baseURL string, modelName string) bool {
|
||||
base := strings.ToLower(baseURL)
|
||||
model := strings.ToLower(modelName)
|
||||
return strings.Contains(model, "seedance") || strings.Contains(model, "doubao-seedance") || strings.Contains(base, "/api/plan/v3")
|
||||
}
|
||||
|
||||
func aiStatusMessage(statusCode int) string {
|
||||
switch statusCode {
|
||||
case http.StatusUnauthorized, http.StatusForbidden:
|
||||
return "AI 接口鉴权失败,请检查 API Key、套餐权限或模型权限"
|
||||
case http.StatusTooManyRequests:
|
||||
return "AI 接口限流或额度不足,请稍后重试或检查额度"
|
||||
default:
|
||||
return "AI 接口请求失败"
|
||||
}
|
||||
}
|
||||
|
||||
func aiUpstreamStatusMessage(statusCode int, body []byte) string {
|
||||
base := aiStatusMessage(statusCode)
|
||||
detail := aiUpstreamErrorDetail(body)
|
||||
if detail == "" {
|
||||
return base
|
||||
}
|
||||
return base + ":" + detail
|
||||
}
|
||||
|
||||
func aiUpstreamErrorDetail(body []byte) string {
|
||||
text := strings.TrimSpace(string(body))
|
||||
if text == "" {
|
||||
return ""
|
||||
}
|
||||
var payload struct {
|
||||
Msg string `json:"msg"`
|
||||
Message string `json:"message"`
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &payload); err == nil {
|
||||
if payload.Error.Message != "" {
|
||||
if detail := friendlyUpstreamError(payload.Error.Code, payload.Error.Message); detail != "" {
|
||||
return safeUpstreamText(detail)
|
||||
}
|
||||
if payload.Error.Code != "" {
|
||||
return safeUpstreamText(payload.Error.Code + " " + payload.Error.Message)
|
||||
}
|
||||
return safeUpstreamText(payload.Error.Message)
|
||||
}
|
||||
if payload.Msg != "" {
|
||||
return safeUpstreamText(payload.Msg)
|
||||
}
|
||||
if payload.Message != "" {
|
||||
return safeUpstreamText(payload.Message)
|
||||
}
|
||||
}
|
||||
return safeUpstreamText(text)
|
||||
}
|
||||
|
||||
func friendlyUpstreamError(code string, message string) string {
|
||||
lowerCode := strings.ToLower(strings.TrimSpace(code))
|
||||
if strings.Contains(lowerCode, "inputvideosensitivecontentdetected") || strings.Contains(lowerCode, "privacyinformation") {
|
||||
return strings.TrimSpace(code + " 参考视频疑似包含真人或隐私信息,火山方舟拒绝使用普通 URL 作为真人视频参考;请改用不含真人的视频、官方允许的模型产物,或已授权的 asset:// 素材。原始错误:" + message)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func safeUpstreamText(text string) string {
|
||||
text = strings.Join(strings.Fields(strings.TrimSpace(text)), " ")
|
||||
runes := []rune(text)
|
||||
if len(runes) > 300 {
|
||||
return string(runes[:300]) + "..."
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
type aiError struct {
|
||||
message string
|
||||
}
|
||||
|
||||
func (err *aiError) Error() string {
|
||||
return err.message
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAIUpstreamErrorDetail(t *testing.T) {
|
||||
got := aiUpstreamErrorDetail([]byte(`{"error":{"code":"InvalidParameter","message":"reference video fps is invalid"}}`))
|
||||
if got != "InvalidParameter reference video fps is invalid" {
|
||||
t.Fatalf("detail = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAIUpstreamErrorDetailExplainsSensitiveVideo(t *testing.T) {
|
||||
got := aiUpstreamErrorDetail([]byte(`{"error":{"code":"InputVideoSensitiveContentDetected.PrivacyInformation","message":"The request failed because the input video may contain real person."}}`))
|
||||
if !strings.Contains(got, "参考视频疑似包含真人") || !strings.Contains(got, "asset://") {
|
||||
t.Fatalf("detail = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeUpstreamTextTruncates(t *testing.T) {
|
||||
got := safeUpstreamText(strings.Repeat("错", 320))
|
||||
if len([]rune(got)) != 303 {
|
||||
t.Fatalf("truncated rune length = %d", len([]rune(got)))
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/basketikun/infinite-canvas/service"
|
||||
)
|
||||
|
||||
func Assets(w http.ResponseWriter, r *http.Request) {
|
||||
result, err := service.ListAssets(parseQuery(r))
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, result)
|
||||
}
|
||||
|
||||
func AdminAssets(w http.ResponseWriter, r *http.Request) {
|
||||
result, err := service.ListAssets(parseQuery(r))
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, result)
|
||||
}
|
||||
|
||||
func AdminSaveAsset(w http.ResponseWriter, r *http.Request) {
|
||||
var item model.Asset
|
||||
_ = json.NewDecoder(r.Body).Decode(&item)
|
||||
result, err := service.SaveAsset(item)
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, result)
|
||||
}
|
||||
|
||||
func AdminDeleteAsset(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if err := service.DeleteAsset(id); err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, true)
|
||||
}
|
||||
-186
@@ -1,186 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/basketikun/infinite-canvas/service"
|
||||
)
|
||||
|
||||
type loginRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type registerRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type saveUserRequest struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Role model.UserRole `json:"role"`
|
||||
Status model.UserStatus `json:"status"`
|
||||
}
|
||||
|
||||
type adjustUserCreditsRequest struct {
|
||||
Credits int `json:"credits"`
|
||||
}
|
||||
|
||||
func Register(w http.ResponseWriter, r *http.Request) {
|
||||
var request registerRequest
|
||||
_ = json.NewDecoder(r.Body).Decode(&request)
|
||||
session, err := service.Register(request.Username, request.Password)
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, session)
|
||||
}
|
||||
|
||||
func Login(w http.ResponseWriter, r *http.Request) {
|
||||
var request loginRequest
|
||||
_ = json.NewDecoder(r.Body).Decode(&request)
|
||||
session, err := service.Login(request.Username, request.Password)
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, session)
|
||||
}
|
||||
|
||||
func LinuxDoAuthorize(w http.ResponseWriter, r *http.Request) {
|
||||
authURL, err := service.LinuxDoAuthorizeURL(r, r.URL.Query().Get("redirect"))
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, authURL, http.StatusFound)
|
||||
}
|
||||
|
||||
func LinuxDoCallback(w http.ResponseWriter, r *http.Request) {
|
||||
session, redirect, err := service.LoginWithLinuxDo(r, r.URL.Query().Get("code"), r.URL.Query().Get("state"))
|
||||
if err != nil {
|
||||
http.Redirect(w, r, loginRedirect(r, redirect, "", err.Error()), http.StatusFound)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, loginRedirect(r, redirect, session.Token, ""), http.StatusFound)
|
||||
}
|
||||
|
||||
func AdminLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var request loginRequest
|
||||
_ = json.NewDecoder(r.Body).Decode(&request)
|
||||
session, err := service.Login(request.Username, request.Password)
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
if session.User.Role != model.UserRoleAdmin {
|
||||
Fail(w, "需要管理员权限")
|
||||
return
|
||||
}
|
||||
OK(w, session)
|
||||
}
|
||||
|
||||
func CurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
if user, ok := service.UserFromContext(r.Context()); ok {
|
||||
OK(w, user)
|
||||
return
|
||||
}
|
||||
OK(w, service.GuestUser())
|
||||
}
|
||||
|
||||
func AdminUsers(w http.ResponseWriter, r *http.Request) {
|
||||
users, err := service.ListUsers(parseQuery(r))
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, users)
|
||||
}
|
||||
|
||||
func AdminSaveUser(w http.ResponseWriter, r *http.Request) {
|
||||
var request saveUserRequest
|
||||
_ = json.NewDecoder(r.Body).Decode(&request)
|
||||
user, err := service.SaveUser(model.User{
|
||||
ID: request.ID,
|
||||
Username: request.Username,
|
||||
Email: request.Email,
|
||||
DisplayName: request.DisplayName,
|
||||
Role: request.Role,
|
||||
Status: request.Status,
|
||||
}, request.Password)
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, user)
|
||||
}
|
||||
|
||||
func AdminAdjustUserCredits(w http.ResponseWriter, r *http.Request, id string) {
|
||||
var request adjustUserCreditsRequest
|
||||
_ = json.NewDecoder(r.Body).Decode(&request)
|
||||
user, err := service.AdjustUserCredits(id, request.Credits)
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, user)
|
||||
}
|
||||
|
||||
func AdminCreditLogs(w http.ResponseWriter, r *http.Request) {
|
||||
logs, err := service.ListCreditLogs(parseQuery(r))
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, logs)
|
||||
}
|
||||
|
||||
func AdminSaveCreditLog(w http.ResponseWriter, r *http.Request) {
|
||||
var log model.CreditLog
|
||||
_ = json.NewDecoder(r.Body).Decode(&log)
|
||||
result, err := service.SaveCreditLog(log)
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, result)
|
||||
}
|
||||
|
||||
func AdminDeleteCreditLog(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if err := service.DeleteCreditLog(id); err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, true)
|
||||
}
|
||||
|
||||
func loginRedirect(r *http.Request, redirect string, token string, message string) string {
|
||||
values := url.Values{}
|
||||
if strings.TrimSpace(token) != "" {
|
||||
values.Set("token", token)
|
||||
}
|
||||
if strings.TrimSpace(message) != "" {
|
||||
values.Set("error", message)
|
||||
}
|
||||
if strings.TrimSpace(redirect) != "" {
|
||||
values.Set("redirect", redirect)
|
||||
}
|
||||
return service.RequestOrigin(r) + "/login?" + values.Encode()
|
||||
}
|
||||
|
||||
func AdminDeleteUser(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if err := service.DeleteUser(id); err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, true)
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/config"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
referenceMediaMaxBytes = 80 << 20
|
||||
referenceImageMaxBytes = 30 << 20
|
||||
referenceVideoMaxBytes = 50 << 20
|
||||
referenceAudioMaxBytes = 15 << 20
|
||||
referenceImageAllowedText = "jpeg/png/webp/bmp/gif/heic/heif 图片"
|
||||
referenceVideoAllowedText = "mp4/mov 视频"
|
||||
referenceAudioAllowedText = "mp3/wav 音频"
|
||||
referenceMediaAllowedText = referenceImageAllowedText + "、" + referenceVideoAllowedText + "或" + referenceAudioAllowedText
|
||||
)
|
||||
|
||||
type referenceMediaUploadResult struct {
|
||||
ID string `json:"id"`
|
||||
URL string `json:"url"`
|
||||
MimeType string `json:"mimeType"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
}
|
||||
|
||||
func UploadReferenceMedia(w http.ResponseWriter, r *http.Request) {
|
||||
publicBaseURL := strings.TrimRight(strings.TrimSpace(config.Cfg.PublicBaseURL), "/")
|
||||
if publicBaseURL == "" {
|
||||
Fail(w, "未配置 PUBLIC_BASE_URL,无法把本地参考素材提供给火山方舟访问")
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, referenceMediaMaxBytes+1)
|
||||
if err := r.ParseMultipartForm(referenceMediaMaxBytes); err != nil {
|
||||
Fail(w, "参考素材过大或上传格式不正确")
|
||||
return
|
||||
}
|
||||
if r.MultipartForm != nil {
|
||||
defer r.MultipartForm.RemoveAll()
|
||||
}
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
Fail(w, "请上传参考图片或视频")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
mimeType, ext, ok := normalizeReferenceMediaType(header.Header.Get("Content-Type"), filepath.Ext(header.Filename))
|
||||
if !ok {
|
||||
Fail(w, "参考素材格式不支持,请使用 "+referenceMediaAllowedText)
|
||||
return
|
||||
}
|
||||
if err := os.MkdirAll(referenceMediaDir(), 0o755); err != nil {
|
||||
Fail(w, "参考素材保存失败")
|
||||
return
|
||||
}
|
||||
id := uuid.NewString() + ext
|
||||
targetPath := filepath.Join(referenceMediaDir(), id)
|
||||
target, err := os.OpenFile(targetPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
|
||||
if err != nil {
|
||||
Fail(w, "参考素材保存失败")
|
||||
return
|
||||
}
|
||||
bytes, copyErr := io.Copy(target, file)
|
||||
closeErr := target.Close()
|
||||
if copyErr != nil || closeErr != nil {
|
||||
_ = os.Remove(targetPath)
|
||||
Fail(w, "参考素材保存失败")
|
||||
return
|
||||
}
|
||||
if bytes <= 0 {
|
||||
_ = os.Remove(targetPath)
|
||||
Fail(w, "参考素材为空")
|
||||
return
|
||||
}
|
||||
if limit := referenceMediaTypeMaxBytes(mimeType); limit > 0 && bytes > limit {
|
||||
_ = os.Remove(targetPath)
|
||||
Fail(w, referenceMediaSizeMessage(mimeType))
|
||||
return
|
||||
}
|
||||
OK(w, referenceMediaUploadResult{
|
||||
ID: id,
|
||||
URL: fmt.Sprintf("%s/api/media/references/%s", publicBaseURL, id),
|
||||
MimeType: mimeType,
|
||||
Bytes: bytes,
|
||||
})
|
||||
}
|
||||
|
||||
func ReferenceMedia(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if id == "" || id != filepath.Base(id) || strings.Contains(id, "..") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
path := filepath.Join(referenceMediaDir(), id)
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
info, err := file.Stat()
|
||||
if err != nil || info.IsDir() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if mimeType := mimeTypeByReferenceMediaExt(filepath.Ext(id)); mimeType != "" {
|
||||
w.Header().Set("Content-Type", mimeType)
|
||||
}
|
||||
w.Header().Set("Cache-Control", "public, max-age=86400")
|
||||
http.ServeContent(w, r, id, info.ModTime(), file)
|
||||
}
|
||||
|
||||
func referenceMediaDir() string {
|
||||
return filepath.Join(referenceDataDir(), "reference-media")
|
||||
}
|
||||
|
||||
func referenceDataDir() string {
|
||||
driver := strings.ToLower(strings.TrimSpace(config.Cfg.StorageDriver))
|
||||
dsn := strings.TrimSpace(config.Cfg.DatabaseDSN)
|
||||
if (driver == "" || driver == "sqlite") && dsn != "" && dsn != ":memory:" && !strings.HasPrefix(dsn, "file:") {
|
||||
pathPart := dsn
|
||||
if index := strings.Index(dsn, "?"); index >= 0 {
|
||||
pathPart = dsn[:index]
|
||||
}
|
||||
if filepath.IsAbs(pathPart) {
|
||||
return filepath.Dir(pathPart)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat("/app/data"); err == nil {
|
||||
return "/app/data"
|
||||
}
|
||||
return "data"
|
||||
}
|
||||
|
||||
func normalizeReferenceMediaType(contentType string, ext string) (string, string, bool) {
|
||||
contentType = strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))
|
||||
ext = strings.ToLower(strings.TrimSpace(ext))
|
||||
if contentType == "" || contentType == "application/octet-stream" {
|
||||
contentType = mimeTypeByReferenceMediaExt(ext)
|
||||
}
|
||||
if fixedExt := referenceMediaExtByMimeType(contentType); fixedExt != "" {
|
||||
return contentType, fixedExt, true
|
||||
}
|
||||
if mimeType := mimeTypeByReferenceMediaExt(ext); mimeType != "" {
|
||||
return mimeType, ext, true
|
||||
}
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
func referenceMediaExtByMimeType(mimeType string) string {
|
||||
switch strings.ToLower(mimeType) {
|
||||
case "image/jpeg", "image/jpg":
|
||||
return ".jpg"
|
||||
case "image/png":
|
||||
return ".png"
|
||||
case "image/webp":
|
||||
return ".webp"
|
||||
case "image/bmp":
|
||||
return ".bmp"
|
||||
case "image/gif":
|
||||
return ".gif"
|
||||
case "image/heic":
|
||||
return ".heic"
|
||||
case "image/heif":
|
||||
return ".heif"
|
||||
case "video/mp4":
|
||||
return ".mp4"
|
||||
case "video/quicktime", "video/mov":
|
||||
return ".mov"
|
||||
case "audio/mpeg", "audio/mp3":
|
||||
return ".mp3"
|
||||
case "audio/wav", "audio/x-wav", "audio/wave":
|
||||
return ".wav"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func mimeTypeByReferenceMediaExt(ext string) string {
|
||||
switch strings.ToLower(ext) {
|
||||
case ".jpg", ".jpeg":
|
||||
return "image/jpeg"
|
||||
case ".png":
|
||||
return "image/png"
|
||||
case ".webp":
|
||||
return "image/webp"
|
||||
case ".bmp":
|
||||
return "image/bmp"
|
||||
case ".gif":
|
||||
return "image/gif"
|
||||
case ".heic":
|
||||
return "image/heic"
|
||||
case ".heif":
|
||||
return "image/heif"
|
||||
case ".mp4":
|
||||
return "video/mp4"
|
||||
case ".mov":
|
||||
return "video/quicktime"
|
||||
case ".mp3":
|
||||
return "audio/mpeg"
|
||||
case ".wav":
|
||||
return "audio/wav"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func referenceMediaTypeMaxBytes(mimeType string) int64 {
|
||||
if strings.HasPrefix(mimeType, "image/") {
|
||||
return referenceImageMaxBytes
|
||||
}
|
||||
if strings.HasPrefix(mimeType, "video/") {
|
||||
return referenceVideoMaxBytes
|
||||
}
|
||||
if strings.HasPrefix(mimeType, "audio/") {
|
||||
return referenceAudioMaxBytes
|
||||
}
|
||||
return referenceMediaMaxBytes
|
||||
}
|
||||
|
||||
func referenceMediaSizeMessage(mimeType string) string {
|
||||
if strings.HasPrefix(mimeType, "image/") {
|
||||
return "参考图片超过大小限制,请使用 30MB 以内的图片"
|
||||
}
|
||||
if strings.HasPrefix(mimeType, "video/") {
|
||||
return "参考视频超过大小限制,请使用 50MB 以内的 mp4/mov 视频"
|
||||
}
|
||||
if strings.HasPrefix(mimeType, "audio/") {
|
||||
return "参考音频超过大小限制,请使用 15MB 以内的 mp3/wav 音频"
|
||||
}
|
||||
return "参考素材超过大小限制"
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/config"
|
||||
)
|
||||
|
||||
func TestNormalizeReferenceMediaTypeSupportsAudio(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
contentType string
|
||||
ext string
|
||||
wantMime string
|
||||
wantExt string
|
||||
}{
|
||||
{name: "mp3 mime", contentType: "audio/mpeg", ext: ".bin", wantMime: "audio/mpeg", wantExt: ".mp3"},
|
||||
{name: "wav ext fallback", contentType: "application/octet-stream", ext: ".wav", wantMime: "audio/wav", wantExt: ".wav"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mimeType, ext, ok := normalizeReferenceMediaType(tt.contentType, tt.ext)
|
||||
if !ok {
|
||||
t.Fatal("expected media type to be accepted")
|
||||
}
|
||||
if mimeType != tt.wantMime || ext != tt.wantExt {
|
||||
t.Fatalf("got (%q, %q), want (%q, %q)", mimeType, ext, tt.wantMime, tt.wantExt)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferenceMediaTypeMaxBytes(t *testing.T) {
|
||||
if got := referenceMediaTypeMaxBytes("audio/mpeg"); got != referenceAudioMaxBytes {
|
||||
t.Fatalf("audio max bytes = %d, want %d", got, referenceAudioMaxBytes)
|
||||
}
|
||||
if got := referenceMediaTypeMaxBytes("video/mp4"); got != referenceVideoMaxBytes {
|
||||
t.Fatalf("video max bytes = %d, want %d", got, referenceVideoMaxBytes)
|
||||
}
|
||||
if got := referenceMediaTypeMaxBytes("image/png"); got != referenceImageMaxBytes {
|
||||
t.Fatalf("image max bytes = %d, want %d", got, referenceImageMaxBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferenceMediaDirUsesAbsoluteSQLiteDataDir(t *testing.T) {
|
||||
previous := config.Cfg
|
||||
t.Cleanup(func() { config.Cfg = previous })
|
||||
root := t.TempDir()
|
||||
config.Cfg = config.Config{StorageDriver: "sqlite", DatabaseDSN: filepath.Join(root, "infinite-canvas.db")}
|
||||
|
||||
if got := referenceMediaDir(); got != filepath.Join(root, "reference-media") {
|
||||
t.Fatalf("referenceMediaDir = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/service"
|
||||
)
|
||||
|
||||
func Prompts(w http.ResponseWriter, r *http.Request) {
|
||||
result, err := service.ListPrompts(parseQuery(r))
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, result)
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
)
|
||||
|
||||
type response struct {
|
||||
Code int `json:"code"`
|
||||
Data any `json:"data"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
func OK(w http.ResponseWriter, data any) {
|
||||
writeJSON(w, response{Code: 0, Data: data, Msg: "ok"})
|
||||
}
|
||||
|
||||
func Fail(w http.ResponseWriter, msg string) {
|
||||
writeJSON(w, response{Code: 1, Data: nil, Msg: msg})
|
||||
}
|
||||
|
||||
func FailError(w http.ResponseWriter, err error) {
|
||||
log.Printf("request failed: %v", err)
|
||||
if safe, ok := err.(interface{ SafeMessage() string }); ok {
|
||||
Fail(w, safe.SafeMessage())
|
||||
return
|
||||
}
|
||||
Fail(w, "操作失败")
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func parseQuery(r *http.Request) model.Query {
|
||||
q := r.URL.Query()
|
||||
page, _ := strconv.Atoi(q.Get("page"))
|
||||
pageSize, _ := strconv.Atoi(q.Get("pageSize"))
|
||||
return model.Query{
|
||||
Keyword: q.Get("keyword"),
|
||||
Tags: q["tag"],
|
||||
Category: q.Get("category"),
|
||||
Type: q.Get("type"),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/basketikun/infinite-canvas/service"
|
||||
)
|
||||
|
||||
type adminChannelActionRequest struct {
|
||||
Index *int `json:"index"`
|
||||
Channel model.ModelChannel `json:"channel"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
|
||||
func Settings(w http.ResponseWriter, r *http.Request) {
|
||||
settings, err := service.PublicSettings()
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, settings)
|
||||
}
|
||||
|
||||
func AdminSettings(w http.ResponseWriter, r *http.Request) {
|
||||
settings, err := service.AdminSettings()
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, settings)
|
||||
}
|
||||
|
||||
func AdminSaveSettings(w http.ResponseWriter, r *http.Request) {
|
||||
var settings model.Settings
|
||||
_ = json.NewDecoder(r.Body).Decode(&settings)
|
||||
result, err := service.SaveSettings(settings)
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, result)
|
||||
}
|
||||
|
||||
func AdminChannelModels(w http.ResponseWriter, r *http.Request) {
|
||||
var request adminChannelActionRequest
|
||||
_ = json.NewDecoder(r.Body).Decode(&request)
|
||||
models, err := service.AdminChannelModels(request.Index, request.Channel)
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, models)
|
||||
}
|
||||
|
||||
func AdminTestChannelModel(w http.ResponseWriter, r *http.Request) {
|
||||
var request adminChannelActionRequest
|
||||
_ = json.NewDecoder(r.Body).Decode(&request)
|
||||
result, err := service.AdminTestChannelModel(request.Index, request.Channel, request.Model)
|
||||
if err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
}
|
||||
OK(w, result)
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/config"
|
||||
"github.com/basketikun/infinite-canvas/router"
|
||||
"github.com/basketikun/infinite-canvas/service"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := config.Load(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := service.EnsureDefaultAdmin(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
service.StartPromptSyncScheduler()
|
||||
log.Fatal(router.New().Run(":" + config.Cfg.Port))
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/handler"
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/basketikun/infinite-canvas/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func AdminAuth(c *gin.Context) {
|
||||
user, ok := authUser(c)
|
||||
if !ok || user.Role != model.UserRoleAdmin {
|
||||
handler.Fail(c.Writer, "未登录或权限不足")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Request = c.Request.WithContext(service.WithUser(c.Request.Context(), user))
|
||||
c.Next()
|
||||
}
|
||||
|
||||
func UserAuth(c *gin.Context) {
|
||||
user, ok := authUser(c)
|
||||
if !ok || user.Role == model.UserRoleGuest {
|
||||
handler.Fail(c.Writer, "未登录或权限不足")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Request = c.Request.WithContext(service.WithUser(c.Request.Context(), user))
|
||||
c.Next()
|
||||
}
|
||||
|
||||
func OptionalAuth(c *gin.Context) {
|
||||
if user, ok := authUser(c); ok {
|
||||
c.Request = c.Request.WithContext(service.WithUser(c.Request.Context(), user))
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
|
||||
func NotFoundJSON(c *gin.Context) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 1, "data": nil, "msg": "接口不存在"})
|
||||
}
|
||||
|
||||
func authUser(c *gin.Context) (model.AuthUser, bool) {
|
||||
token := strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer ")
|
||||
if strings.TrimSpace(token) == "" {
|
||||
return model.AuthUser{}, false
|
||||
}
|
||||
return service.CurrentAuthUser(token)
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package model
|
||||
|
||||
type AssetType string
|
||||
|
||||
const (
|
||||
AssetTypeText AssetType = "text"
|
||||
AssetTypeImage AssetType = "image"
|
||||
)
|
||||
|
||||
// Asset 素材记录。
|
||||
type Asset struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
Title string `json:"title"`
|
||||
Type AssetType `json:"type"`
|
||||
CoverURL string `json:"coverUrl"`
|
||||
Tags []string `json:"tags" gorm:"serializer:json"`
|
||||
Category string `json:"category"`
|
||||
Description string `json:"description"`
|
||||
Content string `json:"content,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// AssetList 素材分页结果。
|
||||
type AssetList struct {
|
||||
Items []Asset `json:"items"`
|
||||
Tags []string `json:"tags"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package model
|
||||
|
||||
// Prompt 提示词记录。
|
||||
type Prompt struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
Title string `json:"title"`
|
||||
CoverURL string `json:"coverUrl"`
|
||||
Prompt string `json:"prompt"`
|
||||
Tags []string `json:"tags" gorm:"serializer:json"`
|
||||
Category string `json:"category" gorm:"index"`
|
||||
GithubURL string `json:"githubUrl" gorm:"-"`
|
||||
Preview string `json:"preview"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// PromptList 提示词分页结果。
|
||||
type PromptList struct {
|
||||
Items []Prompt `json:"items"`
|
||||
Tags []string `json:"tags"`
|
||||
Categories []string `json:"categories"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// PromptCategory 提示词分类。
|
||||
type PromptCategory struct {
|
||||
Category string `json:"category" gorm:"primaryKey"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
GithubURL string `json:"githubUrl"`
|
||||
Remote bool `json:"remote"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package model
|
||||
|
||||
const MaxPageSize = 500
|
||||
|
||||
// Query 列表筛选和分页参数。
|
||||
type Query struct {
|
||||
Keyword string
|
||||
Tags []string
|
||||
Category string
|
||||
Type string
|
||||
Page int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
func (q *Query) Normalize() {
|
||||
if q.Page < 1 {
|
||||
q.Page = 1
|
||||
}
|
||||
if q.PageSize < 1 {
|
||||
q.PageSize = 20
|
||||
}
|
||||
if q.PageSize > MaxPageSize {
|
||||
q.PageSize = MaxPageSize
|
||||
}
|
||||
}
|
||||
|
||||
func (q *Query) Offset() int {
|
||||
return (q.Page - 1) * q.PageSize
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package model
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type SettingKey string
|
||||
|
||||
const (
|
||||
SettingKeyPublic SettingKey = "public"
|
||||
SettingKeyPrivate SettingKey = "private"
|
||||
)
|
||||
|
||||
// ModelChannel 模型渠道配置。
|
||||
type ModelChannel struct {
|
||||
Protocol string `json:"protocol"`
|
||||
Name string `json:"name"`
|
||||
BaseURL string `json:"baseUrl"`
|
||||
APIKey string `json:"apiKey"`
|
||||
Models []string `json:"models"`
|
||||
Weight int `json:"weight"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
|
||||
// ModelCost 模型算力点配置。
|
||||
type ModelCost struct {
|
||||
Model string `json:"model"`
|
||||
Credits int `json:"credits"`
|
||||
}
|
||||
|
||||
// PublicModelChannelSetting 公开模型渠道配置。
|
||||
type PublicModelChannelSetting struct {
|
||||
AvailableModels []string `json:"availableModels"`
|
||||
ModelCosts []ModelCost `json:"modelCosts"`
|
||||
DefaultModel string `json:"defaultModel"`
|
||||
DefaultImageModel string `json:"defaultImageModel"`
|
||||
DefaultVideoModel string `json:"defaultVideoModel"`
|
||||
DefaultTextModel string `json:"defaultTextModel"`
|
||||
SystemPrompt string `json:"systemPrompt"`
|
||||
AllowCustomChannel *bool `json:"allowCustomChannel"`
|
||||
}
|
||||
|
||||
// PublicSetting 公开配置。
|
||||
type PublicSetting struct {
|
||||
ModelChannel PublicModelChannelSetting `json:"modelChannel"`
|
||||
Auth PublicAuthSetting `json:"auth"`
|
||||
}
|
||||
|
||||
type PublicAuthSetting struct {
|
||||
AllowRegister *bool `json:"allowRegister"`
|
||||
LinuxDo PublicLinuxDoAuthSetting `json:"linuxDo"`
|
||||
}
|
||||
|
||||
type PublicLinuxDoAuthSetting struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// PrivateSetting 私有配置。
|
||||
type PrivateSetting struct {
|
||||
Channels []ModelChannel `json:"channels"`
|
||||
PromptSync PromptSyncSetting `json:"promptSync"`
|
||||
Auth PrivateAuthSetting `json:"auth"`
|
||||
}
|
||||
|
||||
// PromptSyncSetting 提示词定时同步配置。
|
||||
type PromptSyncSetting struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
Cron string `json:"cron"`
|
||||
}
|
||||
|
||||
type PrivateAuthSetting struct {
|
||||
LinuxDo PrivateLinuxDoAuthSetting `json:"linuxDo"`
|
||||
}
|
||||
|
||||
type PrivateLinuxDoAuthSetting struct {
|
||||
ClientID string `json:"clientId"`
|
||||
ClientSecret string `json:"clientSecret"`
|
||||
}
|
||||
|
||||
// Setting 系统配置。
|
||||
type Setting struct {
|
||||
Key SettingKey `json:"key" gorm:"primaryKey"`
|
||||
Value json.RawMessage `json:"value" gorm:"serializer:json"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// Settings 系统公开和私有配置。
|
||||
type Settings struct {
|
||||
Public PublicSetting `json:"public"`
|
||||
Private PrivateSetting `json:"private"`
|
||||
}
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
package model
|
||||
|
||||
type UserRole string
|
||||
|
||||
const (
|
||||
UserRoleGuest UserRole = "guest"
|
||||
UserRoleUser UserRole = "user"
|
||||
UserRoleAdmin UserRole = "admin"
|
||||
)
|
||||
|
||||
type UserStatus string
|
||||
|
||||
const (
|
||||
UserStatusActive UserStatus = "active"
|
||||
UserStatusBan UserStatus = "ban"
|
||||
)
|
||||
|
||||
// User 系统用户。
|
||||
type User struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
Username string `json:"username" gorm:"uniqueIndex"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"displayName"`
|
||||
AvatarURL string `json:"avatarUrl"`
|
||||
Role UserRole `json:"role"`
|
||||
Credits int `json:"credits"`
|
||||
AffCode string `json:"affCode" gorm:"uniqueIndex"`
|
||||
AffCount int `json:"affCount"`
|
||||
InviterID string `json:"inviterId"`
|
||||
GithubID string `json:"githubId"`
|
||||
LinuxDoID string `json:"linuxDoId" gorm:"index"`
|
||||
WechatID string `json:"wechatId"`
|
||||
Status UserStatus `json:"status"`
|
||||
LastLoginAt string `json:"lastLoginAt"`
|
||||
Extra string `json:"extra" gorm:"type:text"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// UserList 用户分页结果。
|
||||
type UserList struct {
|
||||
Items []User `json:"items"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// AuthUser 用户公开信息。
|
||||
type AuthUser struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"displayName"`
|
||||
AvatarURL string `json:"avatarUrl"`
|
||||
Role UserRole `json:"role"`
|
||||
Credits int `json:"credits"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// AuthSession 登录会话信息。
|
||||
type AuthSession struct {
|
||||
Token string `json:"token"`
|
||||
User AuthUser `json:"user"`
|
||||
}
|
||||
|
||||
func PublicUser(user User) AuthUser {
|
||||
return AuthUser{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
AvatarURL: user.AvatarURL,
|
||||
Role: user.Role,
|
||||
Credits: user.Credits,
|
||||
CreatedAt: user.CreatedAt,
|
||||
UpdatedAt: user.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
type CreditLogType string
|
||||
|
||||
const (
|
||||
CreditLogTypeAdminAdjust CreditLogType = "admin_adjust"
|
||||
CreditLogTypeAIConsume CreditLogType = "ai_consume"
|
||||
CreditLogTypeAIRefund CreditLogType = "ai_refund"
|
||||
)
|
||||
|
||||
// CreditLog 用户算力点变更流水。
|
||||
type CreditLog struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
UserID string `json:"userId" gorm:"index"`
|
||||
Type CreditLogType `json:"type"`
|
||||
Amount int `json:"amount"`
|
||||
Balance int `json:"balance"`
|
||||
RelatedID string `json:"relatedId"`
|
||||
Remark string `json:"remark"`
|
||||
Extra string `json:"extra" gorm:"type:text"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
}
|
||||
|
||||
type CreditLogList struct {
|
||||
Items []CreditLog `json:"items"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
+1
-13
@@ -4,19 +4,7 @@ services:
|
||||
runtime: docker
|
||||
plan: free
|
||||
autoDeployTrigger: off
|
||||
healthCheckPath: /api/health
|
||||
healthCheckPath: /
|
||||
envVars:
|
||||
- key: ADMIN_USERNAME
|
||||
value: admin
|
||||
- key: ADMIN_PASSWORD
|
||||
sync: false
|
||||
- key: JWT_SECRET
|
||||
generateValue: true
|
||||
- key: JWT_EXPIRE_HOURS
|
||||
value: 168
|
||||
- key: PORT
|
||||
value: 3000
|
||||
- key: STORAGE_DRIVER
|
||||
value: sqlite
|
||||
- key: DATABASE_DSN
|
||||
value: data/infinite-canvas.db
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ListAssets 按查询条件返回素材分页列表。
|
||||
func ListAssets(q model.Query) ([]model.Asset, int64, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
q.Normalize()
|
||||
tx := applyAssetFilters(db.Model(&model.Asset{}), q)
|
||||
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
var items []model.Asset
|
||||
err = tx.Order("updated_at desc").Offset(q.Offset()).Limit(q.PageSize).Find(&items).Error
|
||||
return items, total, err
|
||||
}
|
||||
|
||||
// ListAssetTags 返回当前素材查询条件下的全部标签。
|
||||
func ListAssetTags(q model.Query) ([]string, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q.Normalize()
|
||||
q.Tags = nil
|
||||
tx := applyAssetFilters(db.Model(&model.Asset{}), q)
|
||||
|
||||
var items []model.Asset
|
||||
if err := tx.Select("tags").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return assetTagsFromItems(items), nil
|
||||
}
|
||||
|
||||
// SaveAsset 保存素材,并在更新时保留原创建时间。
|
||||
func SaveAsset(item model.Asset) (model.Asset, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return item, err
|
||||
}
|
||||
if saved, ok, err := findAsset(db, item.ID); err != nil {
|
||||
return item, err
|
||||
} else if ok && item.CreatedAt == "" {
|
||||
item.CreatedAt = saved.CreatedAt
|
||||
}
|
||||
return item, db.Save(&item).Error
|
||||
}
|
||||
|
||||
// DeleteAsset 删除指定素材。
|
||||
func DeleteAsset(id string) error {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Delete(&model.Asset{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// applyAssetFilters 应用素材列表的搜索条件。
|
||||
func applyAssetFilters(tx *gorm.DB, q model.Query) *gorm.DB {
|
||||
if q.Keyword != "" {
|
||||
like := "%" + q.Keyword + "%"
|
||||
tx = tx.Where("title LIKE ? OR description LIKE ? OR content LIKE ?", like, like, like)
|
||||
}
|
||||
if isActiveAssetOption(q.Type) {
|
||||
tx = tx.Where("type = ?", q.Type)
|
||||
}
|
||||
return applyAssetTagsFilter(tx, q.Tags)
|
||||
}
|
||||
|
||||
// findAsset 根据 ID 查询素材。
|
||||
func findAsset(db *gorm.DB, id string) (model.Asset, bool, error) {
|
||||
item := model.Asset{}
|
||||
err := db.Where("id = ?", id).First(&item).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return model.Asset{}, false, nil
|
||||
}
|
||||
return item, err == nil, err
|
||||
}
|
||||
|
||||
// applyAssetTagsFilter 应用 JSON 标签条件。
|
||||
func applyAssetTagsFilter(tx *gorm.DB, tags []string) *gorm.DB {
|
||||
if len(tags) == 0 {
|
||||
return tx
|
||||
}
|
||||
condition := tx.Session(&gorm.Session{NewDB: true})
|
||||
for _, tag := range tags {
|
||||
condition = condition.Or(assetJSONTagsContains(tx), tag)
|
||||
}
|
||||
return tx.Where(condition)
|
||||
}
|
||||
|
||||
func assetTagsFromItems(items []model.Asset) []string {
|
||||
seen := map[string]bool{}
|
||||
tags := []string{}
|
||||
for _, item := range items {
|
||||
for _, tag := range item.Tags {
|
||||
if tag != "" && !seen[tag] {
|
||||
seen[tag] = true
|
||||
tags = append(tags, tag)
|
||||
}
|
||||
}
|
||||
}
|
||||
return tags
|
||||
}
|
||||
|
||||
// assetJSONTagsContains 返回素材 tags 的 JSON 包含条件。
|
||||
func assetJSONTagsContains(tx *gorm.DB) string {
|
||||
switch tx.Dialector.Name() {
|
||||
case "mysql":
|
||||
return "JSON_CONTAINS(tags, JSON_QUOTE(?))"
|
||||
case "postgres":
|
||||
return "jsonb_exists(tags::jsonb, ?)"
|
||||
default:
|
||||
return "EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)"
|
||||
}
|
||||
}
|
||||
|
||||
// isActiveAssetOption 判断素材筛选项有效状态。
|
||||
func isActiveAssetOption(value string) bool {
|
||||
return value != "" && value != "全部" && value != "all"
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/config"
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/glebarez/sqlite"
|
||||
mysqldriver "github.com/go-sql-driver/mysql"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
gormmysql "gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var promptCategories = []model.PromptCategory{
|
||||
{Category: "system", Name: "系统", Description: "系统提示词分类"},
|
||||
{Category: "gpt-image-2-prompts", Name: "GPT Image 2 Prompts", Description: "EvoLinkAI 的 GPT Image 2 案例提示词分类", GithubURL: "https://github.com/EvoLinkAI/awesome-gpt-image-2-API-and-Prompts", Remote: true},
|
||||
{Category: "awesome-gpt-image", Name: "Awesome GPT Image", Description: "ZeroLu 的中文 GPT Image 提示词分类", GithubURL: "https://github.com/ZeroLu/awesome-gpt-image", Remote: true},
|
||||
{Category: "awesome-gpt4o-image-prompts", Name: "Awesome GPT4o Image Prompts", Description: "ImgEdify 的 GPT-4o 图像提示词分类", GithubURL: "https://github.com/ImgEdify/Awesome-GPT4o-Image-Prompts", Remote: true},
|
||||
{Category: "youmind-gpt-image-2", Name: "YouMind GPT Image 2", Description: "YouMind OpenLab 的 GPT Image 2 中文提示词分类", GithubURL: "https://github.com/YouMind-OpenLab/awesome-gpt-image-2", Remote: true},
|
||||
{Category: "youmind-nano-banana-pro", Name: "YouMind Nano Banana Pro", Description: "YouMind OpenLab 的 Nano Banana Pro 中文提示词分类", GithubURL: "https://github.com/YouMind-OpenLab/awesome-nano-banana-pro-prompts", Remote: true},
|
||||
{Category: "davidwu-gpt-image2-prompts", Name: "awesome-gpt-image2-prompts", Description: "davidwuw0811-boop 整理的 GPT Image 2 提示词分类", GithubURL: "https://github.com/davidwuw0811-boop/awesome-gpt-image2-prompts", Remote: true},
|
||||
}
|
||||
|
||||
var (
|
||||
db *gorm.DB
|
||||
dbOnce sync.Once
|
||||
dbErr error
|
||||
)
|
||||
|
||||
// DB 初始化并返回全局数据库连接。
|
||||
func DB() (*gorm.DB, error) {
|
||||
dbOnce.Do(func() {
|
||||
driver := strings.ToLower(strings.TrimSpace(config.Cfg.StorageDriver))
|
||||
if driver == "" {
|
||||
driver = "sqlite"
|
||||
}
|
||||
dsn := config.Cfg.DatabaseDSN
|
||||
if driver == "sqlite" && dsn != ":memory:" {
|
||||
_ = os.MkdirAll(filepath.Dir(dsn), 0755)
|
||||
}
|
||||
if isPostgresDriver(driver) {
|
||||
dbErr = ensurePostgresDatabase(dsn)
|
||||
if dbErr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if driver == "mysql" {
|
||||
dbErr = ensureMySQLDatabase(dsn)
|
||||
if dbErr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
db, dbErr = gorm.Open(dialector(driver, dsn), &gorm.Config{})
|
||||
if dbErr != nil {
|
||||
return
|
||||
}
|
||||
dbErr = db.AutoMigrate(
|
||||
&model.User{},
|
||||
&model.CreditLog{},
|
||||
&model.Prompt{},
|
||||
&model.Asset{},
|
||||
&model.Setting{},
|
||||
)
|
||||
})
|
||||
return db, dbErr
|
||||
}
|
||||
|
||||
func dialector(driver string, dsn string) gorm.Dialector {
|
||||
switch driver {
|
||||
case "mysql":
|
||||
return gormmysql.Open(dsn)
|
||||
case "postgres", "postgresql":
|
||||
return postgres.Open(dsn)
|
||||
default:
|
||||
return sqlite.Open(dsn)
|
||||
}
|
||||
}
|
||||
|
||||
func isPostgresDriver(driver string) bool {
|
||||
return driver == "postgres" || driver == "postgresql"
|
||||
}
|
||||
|
||||
func ensureMySQLDatabase(dsn string) error {
|
||||
cfg, err := mysqldriver.ParseDSN(dsn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target := strings.TrimSpace(cfg.DBName)
|
||||
if target == "" {
|
||||
return nil
|
||||
}
|
||||
ctx := context.Background()
|
||||
targetDB, err := sql.Open("mysql", dsn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = targetDB.PingContext(ctx)
|
||||
_ = targetDB.Close()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !isMySQLError(err, 1049) {
|
||||
return err
|
||||
}
|
||||
|
||||
maintenance := cfg.Clone()
|
||||
maintenance.DBName = ""
|
||||
serverDB, err := sql.Open("mysql", maintenance.FormatDSN())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer serverDB.Close()
|
||||
|
||||
_, err = serverDB.ExecContext(ctx, "CREATE DATABASE "+quoteMySQLIdentifier(target)+" CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
|
||||
if isMySQLError(err, 1007) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func ensurePostgresDatabase(dsn string) error {
|
||||
cfg, err := pgx.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target := strings.TrimSpace(cfg.Database)
|
||||
if target == "" {
|
||||
return nil
|
||||
}
|
||||
ctx := context.Background()
|
||||
conn, err := pgx.ConnectConfig(ctx, cfg)
|
||||
if err == nil {
|
||||
_ = conn.Close(ctx)
|
||||
return nil
|
||||
}
|
||||
if !isPostgresError(err, "3D000") {
|
||||
return err
|
||||
}
|
||||
|
||||
maintenance := cfg.Copy()
|
||||
maintenance.Database = "postgres"
|
||||
if strings.EqualFold(target, "postgres") {
|
||||
maintenance.Database = "template1"
|
||||
}
|
||||
conn, err = pgx.ConnectConfig(ctx, maintenance)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close(ctx)
|
||||
|
||||
_, err = conn.Exec(ctx, "CREATE DATABASE "+pgx.Identifier{target}.Sanitize(), pgx.QueryExecModeExec)
|
||||
if isPostgresError(err, "42P04") {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func isMySQLError(err error, number uint16) bool {
|
||||
var mysqlErr *mysqldriver.MySQLError
|
||||
return errors.As(err, &mysqlErr) && mysqlErr.Number == number
|
||||
}
|
||||
|
||||
func isPostgresError(err error, code string) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == code
|
||||
}
|
||||
|
||||
func quoteMySQLIdentifier(name string) string {
|
||||
return "`" + strings.ReplaceAll(name, "`", "``") + "`"
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// PromptCategories 返回内置提示词分类的副本。
|
||||
func PromptCategories() []model.PromptCategory {
|
||||
result := make([]model.PromptCategory, len(promptCategories))
|
||||
copy(result, promptCategories)
|
||||
return result
|
||||
}
|
||||
|
||||
// PromptCategoryByCode 根据分类编码查找内置提示词分类。
|
||||
func PromptCategoryByCode(category string) (model.PromptCategory, bool) {
|
||||
for _, item := range promptCategories {
|
||||
if item.Category == category {
|
||||
return item, true
|
||||
}
|
||||
}
|
||||
return model.PromptCategory{}, false
|
||||
}
|
||||
|
||||
// ListPromptCategories 返回内置提示词分类。
|
||||
func ListPromptCategories() ([]model.PromptCategory, error) {
|
||||
return PromptCategories(), nil
|
||||
}
|
||||
|
||||
// ListPrompts 按查询条件返回提示词分页列表。
|
||||
func ListPrompts(q model.Query) ([]model.Prompt, int64, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
q.Normalize()
|
||||
tx := applyPromptFilters(db.Model(&model.Prompt{}), q)
|
||||
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
var items []model.Prompt
|
||||
if err := tx.Order("updated_at desc").Offset(q.Offset()).Limit(q.PageSize).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
categories, _ := ListPromptCategories()
|
||||
githubURLs := map[string]string{}
|
||||
for _, item := range categories {
|
||||
githubURLs[item.Category] = item.GithubURL
|
||||
}
|
||||
for i := range items {
|
||||
items[i].GithubURL = githubURLs[items[i].Category]
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
// ListPromptTags 返回当前提示词查询条件下的全部标签。
|
||||
func ListPromptTags(q model.Query) ([]string, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q.Normalize()
|
||||
q.Tags = nil
|
||||
tx := applyPromptFilters(db.Model(&model.Prompt{}), q)
|
||||
|
||||
var items []model.Prompt
|
||||
if err := tx.Select("tags").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return promptTagsFromItems(items), nil
|
||||
}
|
||||
|
||||
// SavePrompt 保存提示词,并在更新时保留原创建时间。
|
||||
func SavePrompt(item model.Prompt) (model.Prompt, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return item, err
|
||||
}
|
||||
if saved, ok, err := findPrompt(db, item.ID); err != nil {
|
||||
return item, err
|
||||
} else if ok && item.CreatedAt == "" {
|
||||
item.CreatedAt = saved.CreatedAt
|
||||
}
|
||||
item.GithubURL = ""
|
||||
return item, db.Save(&item).Error
|
||||
}
|
||||
|
||||
// DeletePrompt 删除指定提示词。
|
||||
func DeletePrompt(id string) error {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Delete(&model.Prompt{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// DeletePrompts 批量删除提示词。
|
||||
func DeletePrompts(ids []string) error {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Delete(&model.Prompt{}, "id IN ?", ids).Error
|
||||
}
|
||||
|
||||
// ReplacePromptCategory 用远程同步结果替换整个提示词分类。
|
||||
func ReplacePromptCategory(category model.PromptCategory, items []model.Prompt) error {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Where("category = ?", category.Category).Delete(&model.Prompt{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
for i := range items {
|
||||
items[i].Category = category.Category
|
||||
items[i].GithubURL = ""
|
||||
}
|
||||
return tx.Create(&items).Error
|
||||
})
|
||||
}
|
||||
|
||||
// applyPromptFilters 应用提示词列表的搜索条件。
|
||||
func applyPromptFilters(tx *gorm.DB, q model.Query) *gorm.DB {
|
||||
if q.Keyword != "" {
|
||||
like := "%" + q.Keyword + "%"
|
||||
tx = tx.Where("title LIKE ? OR prompt LIKE ?", like, like)
|
||||
}
|
||||
if isActivePromptOption(q.Category) {
|
||||
tx = tx.Where("category = ?", q.Category)
|
||||
}
|
||||
return applyPromptTagsFilter(tx, q.Tags)
|
||||
}
|
||||
|
||||
// findPrompt 根据 ID 查询提示词。
|
||||
func findPrompt(db *gorm.DB, id string) (model.Prompt, bool, error) {
|
||||
item := model.Prompt{}
|
||||
err := db.Where("id = ?", id).First(&item).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return model.Prompt{}, false, nil
|
||||
}
|
||||
return item, err == nil, err
|
||||
}
|
||||
|
||||
// applyPromptTagsFilter 应用 JSON 标签条件。
|
||||
func applyPromptTagsFilter(tx *gorm.DB, tags []string) *gorm.DB {
|
||||
if len(tags) == 0 {
|
||||
return tx
|
||||
}
|
||||
condition := tx.Session(&gorm.Session{NewDB: true})
|
||||
for _, tag := range tags {
|
||||
condition = condition.Or(promptJSONTagsContains(tx), tag)
|
||||
}
|
||||
return tx.Where(condition)
|
||||
}
|
||||
|
||||
func promptTagsFromItems(items []model.Prompt) []string {
|
||||
seen := map[string]bool{}
|
||||
tags := []string{}
|
||||
for _, item := range items {
|
||||
for _, tag := range item.Tags {
|
||||
if tag != "" && !seen[tag] {
|
||||
seen[tag] = true
|
||||
tags = append(tags, tag)
|
||||
}
|
||||
}
|
||||
}
|
||||
return tags
|
||||
}
|
||||
|
||||
// promptJSONTagsContains 返回提示词 tags 的 JSON 包含条件。
|
||||
func promptJSONTagsContains(tx *gorm.DB) string {
|
||||
switch tx.Dialector.Name() {
|
||||
case "mysql":
|
||||
return "JSON_CONTAINS(tags, JSON_QUOTE(?))"
|
||||
case "postgres":
|
||||
return "jsonb_exists(tags::jsonb, ?)"
|
||||
default:
|
||||
return "EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)"
|
||||
}
|
||||
}
|
||||
|
||||
// isActivePromptOption 判断提示词筛选项有效状态。
|
||||
func isActivePromptOption(value string) bool {
|
||||
return value != "" && value != "全部" && value != "all"
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// GetSettings 返回 public 和 private 两行配置。
|
||||
func GetSettings() (model.Settings, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return model.Settings{}, err
|
||||
}
|
||||
var items []model.Setting
|
||||
if err := db.Find(&items).Error; err != nil {
|
||||
return model.Settings{}, err
|
||||
}
|
||||
result := model.Settings{}
|
||||
for _, item := range items {
|
||||
if item.Key == model.SettingKeyPrivate {
|
||||
_ = json.Unmarshal(item.Value, &result.Private)
|
||||
} else if item.Key == model.SettingKeyPublic {
|
||||
_ = json.Unmarshal(item.Value, &result.Public)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SaveSettings 保存 public 和 private 两行配置。
|
||||
func SaveSettings(settings model.Settings, now string) (model.Settings, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return settings, err
|
||||
}
|
||||
publicValue, _ := json.Marshal(settings.Public)
|
||||
privateValue, _ := json.Marshal(settings.Private)
|
||||
items := []model.Setting{
|
||||
{Key: model.SettingKeyPublic, Value: publicValue, CreatedAt: now, UpdatedAt: now},
|
||||
{Key: model.SettingKeyPrivate, Value: privateValue, CreatedAt: now, UpdatedAt: now},
|
||||
}
|
||||
err = db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "key"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"value", "updated_at"}),
|
||||
}).Create(&items).Error
|
||||
return settings, err
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ListUsers 分页查询用户。
|
||||
func ListUsers(q model.Query) ([]model.User, int64, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
q.Normalize()
|
||||
tx := db.Model(&model.User{})
|
||||
if keyword := strings.TrimSpace(q.Keyword); keyword != "" {
|
||||
like := "%" + keyword + "%"
|
||||
tx = tx.Where("username LIKE ? OR display_name LIKE ? OR email LIKE ? OR linux_do_id LIKE ?", like, like, like, like)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
var users []model.User
|
||||
err = tx.Order("created_at desc").Offset(q.Offset()).Limit(q.PageSize).Find(&users).Error
|
||||
return users, total, err
|
||||
}
|
||||
|
||||
// CountUsers 返回用户总数。
|
||||
func CountUsers() (int64, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var total int64
|
||||
return total, db.Model(&model.User{}).Count(&total).Error
|
||||
}
|
||||
|
||||
// HasAdmin 判断系统中是否存在管理员。
|
||||
func HasAdmin() (bool, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var total int64
|
||||
err = db.Model(&model.User{}).Where("role = ?", model.UserRoleAdmin).Count(&total).Error
|
||||
return total > 0, err
|
||||
}
|
||||
|
||||
// GetUserByID 根据 ID 查询用户。
|
||||
func GetUserByID(id string) (model.User, bool, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
return findUser(db, "id = ?", id)
|
||||
}
|
||||
|
||||
// GetUserByUsername 根据用户名查询用户。
|
||||
func GetUserByUsername(username string) (model.User, bool, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
return findUser(db, "username = ?", username)
|
||||
}
|
||||
|
||||
// SaveUser 保存用户信息。
|
||||
func SaveUser(user model.User) (model.User, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
return user, db.Save(&user).Error
|
||||
}
|
||||
|
||||
func ConsumeUserCredits(id string, credits int, now string) (model.User, bool, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
if credits <= 0 {
|
||||
user, ok, err := GetUserByID(id)
|
||||
return user, ok, err
|
||||
}
|
||||
tx := db.Model(&model.User{}).Where("id = ? AND credits >= ?", id, credits).Updates(map[string]any{
|
||||
"credits": gorm.Expr("credits - ?", credits),
|
||||
"updated_at": now,
|
||||
})
|
||||
if tx.Error != nil {
|
||||
return model.User{}, false, tx.Error
|
||||
}
|
||||
user, ok, err := GetUserByID(id)
|
||||
return user, ok && tx.RowsAffected > 0, err
|
||||
}
|
||||
|
||||
func RefundUserCredits(id string, credits int, now string) (model.User, bool, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
if credits <= 0 {
|
||||
user, ok, err := GetUserByID(id)
|
||||
return user, ok, err
|
||||
}
|
||||
tx := db.Model(&model.User{}).Where("id = ?", id).Updates(map[string]any{
|
||||
"credits": gorm.Expr("credits + ?", credits),
|
||||
"updated_at": now,
|
||||
})
|
||||
if tx.Error != nil {
|
||||
return model.User{}, false, tx.Error
|
||||
}
|
||||
user, ok, err := GetUserByID(id)
|
||||
return user, ok && tx.RowsAffected > 0, err
|
||||
}
|
||||
|
||||
// SaveCreditLog 保存算力点变更流水。
|
||||
func SaveCreditLog(log model.CreditLog) (model.CreditLog, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return log, err
|
||||
}
|
||||
return log, db.Save(&log).Error
|
||||
}
|
||||
|
||||
func ListCreditLogs(q model.Query) ([]model.CreditLog, int64, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
q.Normalize()
|
||||
tx := db.Model(&model.CreditLog{})
|
||||
if keyword := strings.TrimSpace(q.Keyword); keyword != "" {
|
||||
like := "%" + keyword + "%"
|
||||
tx = tx.Where("user_id LIKE ? OR type LIKE ? OR remark LIKE ? OR related_id LIKE ?", like, like, like, like)
|
||||
}
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var logs []model.CreditLog
|
||||
err = tx.Order("created_at desc").Offset(q.Offset()).Limit(q.PageSize).Find(&logs).Error
|
||||
return logs, total, err
|
||||
}
|
||||
|
||||
func DeleteCreditLog(id string) error {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Delete(&model.CreditLog{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// DeleteUser 删除指定用户。
|
||||
func DeleteUser(id string) error {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Delete(&model.User{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// GetUserByLinuxDoID 根据 Linux.do ID 查询用户。
|
||||
func GetUserByLinuxDoID(id string) (model.User, bool, error) {
|
||||
db, err := DB()
|
||||
if err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
return findUser(db, "linux_do_id = ?", id)
|
||||
}
|
||||
|
||||
// findUser 查询单个用户,并将未命中转换为 ok=false。
|
||||
func findUser(db *gorm.DB, query string, args ...any) (model.User, bool, error) {
|
||||
user := model.User{}
|
||||
err := db.Where(query, args...).First(&user).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return model.User{}, false, nil
|
||||
}
|
||||
return user, err == nil, err
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/handler"
|
||||
"github.com/basketikun/infinite-canvas/middleware"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func New() *gin.Engine {
|
||||
router := gin.Default()
|
||||
router.RedirectTrailingSlash = false
|
||||
_ = router.SetTrustedProxies(nil)
|
||||
api := router.Group("/api")
|
||||
api.GET("/health", func(c *gin.Context) {
|
||||
c.String(http.StatusOK, "ok")
|
||||
})
|
||||
api.POST("/auth/register", gin.WrapF(handler.Register))
|
||||
api.POST("/auth/login", gin.WrapF(handler.Login))
|
||||
api.GET("/auth/linux-do/authorize", gin.WrapF(handler.LinuxDoAuthorize))
|
||||
api.GET("/auth/linux-do/callback", gin.WrapF(handler.LinuxDoCallback))
|
||||
api.GET("/auth/me", middleware.OptionalAuth, gin.WrapF(handler.CurrentUser))
|
||||
api.GET("/settings", gin.WrapF(handler.Settings))
|
||||
api.GET("/media/references/:id", func(c *gin.Context) {
|
||||
handler.ReferenceMedia(c.Writer, c.Request, c.Param("id"))
|
||||
})
|
||||
api.HEAD("/media/references/:id", func(c *gin.Context) {
|
||||
handler.ReferenceMedia(c.Writer, c.Request, c.Param("id"))
|
||||
})
|
||||
v1 := api.Group("/v1", middleware.UserAuth)
|
||||
v1.POST("/images/generations", gin.WrapF(handler.AIImagesGenerations))
|
||||
v1.POST("/images/edits", gin.WrapF(handler.AIImagesEdits))
|
||||
v1.POST("/chat/completions", gin.WrapF(handler.AIChatCompletions))
|
||||
v1.POST("/audio/speech", gin.WrapF(handler.AIAudioSpeech))
|
||||
v1.POST("/videos", gin.WrapF(handler.AIVideos))
|
||||
v1.POST("/media/references", gin.WrapF(handler.UploadReferenceMedia))
|
||||
v1.GET("/videos/:id", func(c *gin.Context) {
|
||||
handler.AIVideo(c.Writer, c.Request, c.Param("id"))
|
||||
})
|
||||
v1.GET("/videos/:id/content", func(c *gin.Context) {
|
||||
handler.AIVideoContent(c.Writer, c.Request, c.Param("id"))
|
||||
})
|
||||
api.GET("/prompts", middleware.OptionalAuth, gin.WrapF(handler.Prompts))
|
||||
api.GET("/assets", middleware.OptionalAuth, gin.WrapF(handler.Assets))
|
||||
api.POST("/admin/login", gin.WrapF(handler.AdminLogin))
|
||||
|
||||
admin := api.Group("/admin", middleware.AdminAuth)
|
||||
admin.GET("/users", gin.WrapF(handler.AdminUsers))
|
||||
admin.POST("/users", gin.WrapF(handler.AdminSaveUser))
|
||||
admin.POST("/users/:id/credits", func(c *gin.Context) {
|
||||
handler.AdminAdjustUserCredits(c.Writer, c.Request, c.Param("id"))
|
||||
})
|
||||
admin.DELETE("/users/:id", func(c *gin.Context) {
|
||||
handler.AdminDeleteUser(c.Writer, c.Request, c.Param("id"))
|
||||
})
|
||||
admin.GET("/credit-logs", gin.WrapF(handler.AdminCreditLogs))
|
||||
admin.POST("/credit-logs", gin.WrapF(handler.AdminSaveCreditLog))
|
||||
admin.DELETE("/credit-logs/:id", func(c *gin.Context) {
|
||||
handler.AdminDeleteCreditLog(c.Writer, c.Request, c.Param("id"))
|
||||
})
|
||||
admin.GET("/settings", gin.WrapF(handler.AdminSettings))
|
||||
admin.POST("/settings", gin.WrapF(handler.AdminSaveSettings))
|
||||
admin.POST("/settings/channel-models", gin.WrapF(handler.AdminChannelModels))
|
||||
admin.POST("/settings/channel-test", gin.WrapF(handler.AdminTestChannelModel))
|
||||
admin.GET("/prompt-categories", gin.WrapF(handler.AdminPromptCategories))
|
||||
admin.POST("/prompt-categories/sync", gin.WrapF(handler.AdminSyncPromptCategories))
|
||||
admin.GET("/prompts", gin.WrapF(handler.AdminPrompts))
|
||||
admin.POST("/prompts", gin.WrapF(handler.AdminSavePrompt))
|
||||
admin.POST("/prompts/batch-delete", gin.WrapF(handler.AdminDeletePrompts))
|
||||
admin.DELETE("/prompts/:id", func(c *gin.Context) {
|
||||
handler.AdminDeletePrompt(c.Writer, c.Request, c.Param("id"))
|
||||
})
|
||||
admin.GET("/assets", gin.WrapF(handler.AdminAssets))
|
||||
admin.POST("/assets", gin.WrapF(handler.AdminSaveAsset))
|
||||
admin.DELETE("/assets/:id", func(c *gin.Context) {
|
||||
handler.AdminDeleteAsset(c.Writer, c.Request, c.Param("id"))
|
||||
})
|
||||
|
||||
router.NoRoute(middleware.NotFoundJSON)
|
||||
|
||||
return router
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/basketikun/infinite-canvas/repository"
|
||||
)
|
||||
|
||||
func ListAssets(q model.Query) (model.AssetList, error) {
|
||||
items, total, err := repository.ListAssets(q)
|
||||
if err != nil {
|
||||
return model.AssetList{}, err
|
||||
}
|
||||
tags, err := repository.ListAssetTags(q)
|
||||
if err != nil {
|
||||
return model.AssetList{}, err
|
||||
}
|
||||
return model.AssetList{Items: items, Tags: tags, Total: int(total)}, nil
|
||||
}
|
||||
|
||||
func SaveAsset(item model.Asset) (model.Asset, error) {
|
||||
now := time.Now().Format(time.RFC3339)
|
||||
if item.Type == "" {
|
||||
item.Type = model.AssetTypeText
|
||||
}
|
||||
if item.ID == "" {
|
||||
item.ID = newID("asset")
|
||||
item.CreatedAt = now
|
||||
}
|
||||
item.UpdatedAt = now
|
||||
if item.CoverURL == "" {
|
||||
item.CoverURL = assetCoverURL(item)
|
||||
}
|
||||
return repository.SaveAsset(item)
|
||||
}
|
||||
|
||||
func DeleteAsset(id string) error {
|
||||
return repository.DeleteAsset(id)
|
||||
}
|
||||
|
||||
func assetCoverURL(item model.Asset) string {
|
||||
if item.CoverURL != "" {
|
||||
return item.CoverURL
|
||||
}
|
||||
if item.Type == model.AssetTypeImage {
|
||||
return item.URL
|
||||
}
|
||||
return ""
|
||||
}
|
||||
-590
@@ -1,590 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/config"
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/basketikun/infinite-canvas/repository"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type TokenClaims struct {
|
||||
UserID string `json:"userId"`
|
||||
Username string `json:"username"`
|
||||
Role model.UserRole `json:"role"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
type userExtra struct {
|
||||
LinuxDo any `json:"linuxDo,omitempty"`
|
||||
}
|
||||
|
||||
func EnsureDefaultAdmin() error {
|
||||
if strings.TrimSpace(config.Cfg.AdminUsername) == "" || strings.TrimSpace(config.Cfg.AdminPassword) == "" {
|
||||
return nil
|
||||
}
|
||||
WarnDefaultSecurityConfig()
|
||||
hasAdmin, err := repository.HasAdmin()
|
||||
if err != nil || hasAdmin {
|
||||
return err
|
||||
}
|
||||
hash, err := hashPassword(config.Cfg.AdminPassword)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = repository.SaveUser(model.User{
|
||||
ID: newID("user"),
|
||||
Username: strings.TrimSpace(config.Cfg.AdminUsername),
|
||||
Password: hash,
|
||||
Role: model.UserRoleAdmin,
|
||||
AffCode: newAffCode(),
|
||||
Status: model.UserStatusActive,
|
||||
CreatedAt: now(),
|
||||
UpdatedAt: now(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func Register(username string, password string) (model.AuthSession, error) {
|
||||
settings, err := repository.GetSettings()
|
||||
if err != nil {
|
||||
return model.AuthSession{}, err
|
||||
}
|
||||
normalizedSettings := normalizeSettings(settings)
|
||||
if normalizedSettings.Public.Auth.AllowRegister != nil && !*normalizedSettings.Public.Auth.AllowRegister {
|
||||
return model.AuthSession{}, safeMessageError{message: "当前未开放注册"}
|
||||
}
|
||||
username = strings.TrimSpace(username)
|
||||
if strings.ContainsAny(username, " \t\r\n") {
|
||||
return model.AuthSession{}, safeMessageError{message: "用户名不能包含空格"}
|
||||
}
|
||||
if username == "" || password == "" {
|
||||
return model.AuthSession{}, safeMessageError{message: "用户名和密码不能为空"}
|
||||
}
|
||||
if _, ok, err := repository.GetUserByUsername(username); err != nil || ok {
|
||||
if err != nil {
|
||||
return model.AuthSession{}, err
|
||||
}
|
||||
return model.AuthSession{}, safeMessageError{message: "用户名已存在"}
|
||||
}
|
||||
hash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return model.AuthSession{}, err
|
||||
}
|
||||
user, err := repository.SaveUser(model.User{
|
||||
ID: newID("user"),
|
||||
Username: username,
|
||||
Password: hash,
|
||||
Role: model.UserRoleUser,
|
||||
AffCode: newAffCode(),
|
||||
Status: model.UserStatusActive,
|
||||
CreatedAt: now(),
|
||||
UpdatedAt: now(),
|
||||
})
|
||||
if err != nil {
|
||||
return model.AuthSession{}, err
|
||||
}
|
||||
return newSession(user)
|
||||
}
|
||||
|
||||
func Login(username string, password string) (model.AuthSession, error) {
|
||||
user, ok, err := repository.GetUserByUsername(strings.TrimSpace(username))
|
||||
if err != nil {
|
||||
return model.AuthSession{}, err
|
||||
}
|
||||
if !ok || bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) != nil {
|
||||
return model.AuthSession{}, safeMessageError{message: "用户名或密码错误"}
|
||||
}
|
||||
if user.Status == model.UserStatusBan {
|
||||
return model.AuthSession{}, safeMessageError{message: "账号已被禁用"}
|
||||
}
|
||||
normalizeUserDefaults(&user)
|
||||
user.LastLoginAt = now()
|
||||
user.UpdatedAt = now()
|
||||
user, err = repository.SaveUser(user)
|
||||
if err != nil {
|
||||
return model.AuthSession{}, err
|
||||
}
|
||||
return newSession(user)
|
||||
}
|
||||
|
||||
func LinuxDoAuthorizeURL(r *http.Request, redirect string) (string, error) {
|
||||
settings, err := repository.GetSettings()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
settings = normalizeSettings(settings)
|
||||
linuxDo := settings.Private.Auth.LinuxDo
|
||||
if !settings.Public.Auth.LinuxDo.Enabled {
|
||||
return "", safeMessageError{message: "Linux.do 登录未开启"}
|
||||
}
|
||||
if strings.TrimSpace(linuxDo.ClientID) == "" || strings.TrimSpace(linuxDo.ClientSecret) == "" {
|
||||
return "", safeMessageError{message: "Linux.do 登录未配置"}
|
||||
}
|
||||
values := url.Values{}
|
||||
values.Set("client_id", linuxDo.ClientID)
|
||||
values.Set("redirect_uri", linuxDoRedirectURI(r))
|
||||
values.Set("response_type", "code")
|
||||
values.Set("scope", "read")
|
||||
values.Set("state", base64.RawURLEncoding.EncodeToString([]byte(redirect)))
|
||||
return config.Cfg.LinuxDoAuthorizeURL + "?" + values.Encode(), nil
|
||||
}
|
||||
|
||||
func LoginWithLinuxDo(r *http.Request, code string, state string) (model.AuthSession, string, error) {
|
||||
redirect := decodeState(state)
|
||||
settings, err := repository.GetSettings()
|
||||
if err != nil {
|
||||
return model.AuthSession{}, redirect, err
|
||||
}
|
||||
settings = normalizeSettings(settings)
|
||||
linuxDo := settings.Private.Auth.LinuxDo
|
||||
if !settings.Public.Auth.LinuxDo.Enabled {
|
||||
return model.AuthSession{}, redirect, safeMessageError{message: "Linux.do 登录未开启"}
|
||||
}
|
||||
token, err := linuxDoAccessToken(r, code, linuxDo)
|
||||
if err != nil {
|
||||
return model.AuthSession{}, redirect, err
|
||||
}
|
||||
profile, err := linuxDoProfile(token)
|
||||
if err != nil {
|
||||
return model.AuthSession{}, redirect, err
|
||||
}
|
||||
linuxDoID := fmt.Sprint(profile.ID)
|
||||
if strings.TrimSpace(linuxDoID) == "" || linuxDoID == "0" {
|
||||
return model.AuthSession{}, redirect, safeMessageError{message: "Linux.do 用户信息无效"}
|
||||
}
|
||||
user, ok, err := repository.GetUserByLinuxDoID(linuxDoID)
|
||||
if err != nil {
|
||||
return model.AuthSession{}, redirect, err
|
||||
}
|
||||
if !ok {
|
||||
if settings.Public.Auth.AllowRegister != nil && !*settings.Public.Auth.AllowRegister {
|
||||
return model.AuthSession{}, redirect, safeMessageError{message: "当前未开放注册"}
|
||||
}
|
||||
user = model.User{
|
||||
ID: newID("user"),
|
||||
Username: linuxDoUsername(profile.Username, linuxDoID),
|
||||
DisplayName: strings.TrimSpace(profile.Name),
|
||||
AvatarURL: linuxDoAvatar(profile.AvatarTemplate),
|
||||
Role: model.UserRoleUser,
|
||||
AffCode: newAffCode(),
|
||||
LinuxDoID: linuxDoID,
|
||||
Status: model.UserStatusActive,
|
||||
CreatedAt: now(),
|
||||
}
|
||||
} else if user.Status == model.UserStatusBan {
|
||||
return model.AuthSession{}, redirect, safeMessageError{message: "账号已被禁用"}
|
||||
}
|
||||
user.DisplayName = firstNonEmpty(profile.Name, user.DisplayName)
|
||||
user.AvatarURL = firstNonEmpty(linuxDoAvatar(profile.AvatarTemplate), user.AvatarURL)
|
||||
user.LastLoginAt = now()
|
||||
user.UpdatedAt = now()
|
||||
extra, _ := json.Marshal(userExtra{LinuxDo: profile})
|
||||
user.Extra = string(extra)
|
||||
user, err = repository.SaveUser(user)
|
||||
if err != nil {
|
||||
return model.AuthSession{}, redirect, err
|
||||
}
|
||||
session, err := newSession(user)
|
||||
return session, redirect, err
|
||||
}
|
||||
|
||||
func ParseToken(tokenText string) (TokenClaims, error) {
|
||||
claims := TokenClaims{}
|
||||
token, err := jwt.ParseWithClaims(tokenText, &claims, func(token *jwt.Token) (any, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("登录状态无效")
|
||||
}
|
||||
return []byte(config.Cfg.JWTSecret), nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
return TokenClaims{}, errors.New("登录状态无效")
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func CurrentAuthUser(tokenText string) (model.AuthUser, bool) {
|
||||
claims, err := ParseToken(tokenText)
|
||||
if err != nil {
|
||||
return model.AuthUser{}, false
|
||||
}
|
||||
user, ok, err := repository.GetUserByID(claims.UserID)
|
||||
if err != nil || !ok {
|
||||
return model.AuthUser{}, false
|
||||
}
|
||||
if user.Status == model.UserStatusBan {
|
||||
return model.AuthUser{}, false
|
||||
}
|
||||
return model.PublicUser(user), true
|
||||
}
|
||||
|
||||
func ListUsers(q model.Query) (model.UserList, error) {
|
||||
users, total, err := repository.ListUsers(q)
|
||||
if err != nil {
|
||||
return model.UserList{}, err
|
||||
}
|
||||
for i := range users {
|
||||
users[i].Password = ""
|
||||
normalizeUserDefaults(&users[i])
|
||||
}
|
||||
return model.UserList{Items: users, Total: int(total)}, nil
|
||||
}
|
||||
|
||||
func SaveUser(user model.User, password string) (model.User, error) {
|
||||
user.Username = strings.TrimSpace(user.Username)
|
||||
if strings.ContainsAny(user.Username, " \t\r\n") {
|
||||
return user, safeMessageError{message: "用户名不能包含空格"}
|
||||
}
|
||||
if user.Username == "" {
|
||||
return user, safeMessageError{message: "用户名不能为空"}
|
||||
}
|
||||
if user.Role == "" || user.Role == model.UserRoleGuest {
|
||||
user.Role = model.UserRoleUser
|
||||
}
|
||||
if user.Status == "" {
|
||||
user.Status = model.UserStatusActive
|
||||
}
|
||||
if saved, ok, err := repository.GetUserByUsername(user.Username); err != nil {
|
||||
return user, err
|
||||
} else if ok && saved.ID != user.ID {
|
||||
return user, safeMessageError{message: "用户名已存在"}
|
||||
}
|
||||
isCreate := user.ID == ""
|
||||
if isCreate {
|
||||
user.ID = newID("user")
|
||||
user.AffCode = newAffCode()
|
||||
user.CreatedAt = now()
|
||||
} else if saved, ok, err := repository.GetUserByID(user.ID); err != nil {
|
||||
return user, err
|
||||
} else if ok {
|
||||
user.CreatedAt = saved.CreatedAt
|
||||
user.Password = saved.Password
|
||||
user.AvatarURL = saved.AvatarURL
|
||||
user.Credits = saved.Credits
|
||||
user.Extra = saved.Extra
|
||||
if user.AffCode == "" {
|
||||
user.AffCode = saved.AffCode
|
||||
}
|
||||
if user.AffCode == "" {
|
||||
user.AffCode = newAffCode()
|
||||
}
|
||||
if user.LinuxDoID == "" {
|
||||
user.LinuxDoID = saved.LinuxDoID
|
||||
}
|
||||
user.LastLoginAt = saved.LastLoginAt
|
||||
}
|
||||
if password != "" {
|
||||
hash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
user.Password = hash
|
||||
}
|
||||
if isCreate && user.Password == "" {
|
||||
return user, safeMessageError{message: "密码不能为空"}
|
||||
}
|
||||
user.UpdatedAt = now()
|
||||
user, err := repository.SaveUser(user)
|
||||
user.Password = ""
|
||||
return user, err
|
||||
}
|
||||
|
||||
func AdjustUserCredits(id string, credits int) (model.User, error) {
|
||||
user, ok, err := repository.GetUserByID(id)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
return user, safeMessageError{message: "用户不存在"}
|
||||
}
|
||||
oldCredits := user.Credits
|
||||
user.Credits = credits
|
||||
user.UpdatedAt = now()
|
||||
user, err = repository.SaveUser(user)
|
||||
if err == nil && oldCredits != credits {
|
||||
_, err = repository.SaveCreditLog(model.CreditLog{
|
||||
ID: newID("credit"),
|
||||
UserID: user.ID,
|
||||
Type: model.CreditLogTypeAdminAdjust,
|
||||
Amount: credits - oldCredits,
|
||||
Balance: credits,
|
||||
Remark: "后台手动调整",
|
||||
CreatedAt: now(),
|
||||
})
|
||||
}
|
||||
user.Password = ""
|
||||
return user, err
|
||||
}
|
||||
|
||||
func ConsumeUserCredits(userID string, modelName string, credits int, path string) error {
|
||||
if credits <= 0 {
|
||||
return nil
|
||||
}
|
||||
user, ok, err := repository.ConsumeUserCredits(userID, credits, now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return safeMessageError{message: "算力点不足"}
|
||||
}
|
||||
extra, _ := json.Marshal(map[string]string{"model": modelName, "path": path})
|
||||
_, err = repository.SaveCreditLog(model.CreditLog{
|
||||
ID: newID("credit"),
|
||||
UserID: userID,
|
||||
Type: model.CreditLogTypeAIConsume,
|
||||
Amount: -credits,
|
||||
Balance: user.Credits,
|
||||
Remark: "调用模型 " + modelName,
|
||||
Extra: string(extra),
|
||||
CreatedAt: now(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func RefundUserCredits(userID string, modelName string, credits int, path string) error {
|
||||
if credits <= 0 {
|
||||
return nil
|
||||
}
|
||||
user, ok, err := repository.RefundUserCredits(userID, credits, now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return safeMessageError{message: "用户不存在"}
|
||||
}
|
||||
extra, _ := json.Marshal(map[string]string{"model": modelName, "path": path})
|
||||
_, err = repository.SaveCreditLog(model.CreditLog{
|
||||
ID: newID("credit"),
|
||||
UserID: userID,
|
||||
Type: model.CreditLogTypeAIRefund,
|
||||
Amount: credits,
|
||||
Balance: user.Credits,
|
||||
Remark: "模型调用失败返还 " + modelName,
|
||||
Extra: string(extra),
|
||||
CreatedAt: now(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func ListCreditLogs(q model.Query) (model.CreditLogList, error) {
|
||||
logs, total, err := repository.ListCreditLogs(q)
|
||||
if err != nil {
|
||||
return model.CreditLogList{}, err
|
||||
}
|
||||
return model.CreditLogList{Items: logs, Total: int(total)}, nil
|
||||
}
|
||||
|
||||
func SaveCreditLog(log model.CreditLog) (model.CreditLog, error) {
|
||||
if log.ID == "" {
|
||||
log.ID = newID("credit")
|
||||
log.CreatedAt = now()
|
||||
}
|
||||
return repository.SaveCreditLog(log)
|
||||
}
|
||||
|
||||
func DeleteCreditLog(id string) error {
|
||||
return repository.DeleteCreditLog(id)
|
||||
}
|
||||
|
||||
func DeleteUser(id string) error {
|
||||
return repository.DeleteUser(id)
|
||||
}
|
||||
|
||||
func GuestUser() model.AuthUser {
|
||||
return model.AuthUser{ID: "", Username: "guest", Role: model.UserRoleGuest}
|
||||
}
|
||||
|
||||
func newSession(user model.User) (model.AuthSession, error) {
|
||||
token, err := newToken(user)
|
||||
if err != nil {
|
||||
return model.AuthSession{}, err
|
||||
}
|
||||
return model.AuthSession{Token: token, User: model.PublicUser(user)}, nil
|
||||
}
|
||||
|
||||
func newToken(user model.User) (string, error) {
|
||||
expireHours := config.Cfg.JWTExpireHours
|
||||
if expireHours <= 0 {
|
||||
expireHours = 168
|
||||
}
|
||||
claims := TokenClaims{
|
||||
UserID: user.ID,
|
||||
Username: user.Username,
|
||||
Role: user.Role,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(expireHours) * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
Subject: user.ID,
|
||||
},
|
||||
}
|
||||
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(config.Cfg.JWTSecret))
|
||||
}
|
||||
|
||||
func hashPassword(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
return string(hash), err
|
||||
}
|
||||
|
||||
func now() string {
|
||||
return time.Now().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func newID(prefix string) string {
|
||||
return prefix + "-" + uuid.NewString()
|
||||
}
|
||||
|
||||
func newAffCode() string {
|
||||
return strings.ToUpper(strings.ReplaceAll(uuid.NewString()[:8], "-", ""))
|
||||
}
|
||||
|
||||
func normalizeUserDefaults(user *model.User) {
|
||||
if user.Status == "" {
|
||||
user.Status = model.UserStatusActive
|
||||
}
|
||||
if user.AffCode == "" {
|
||||
user.AffCode = newAffCode()
|
||||
}
|
||||
}
|
||||
|
||||
type linuxDoTokenResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
}
|
||||
|
||||
type linuxDoUserResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Name string `json:"name"`
|
||||
AvatarTemplate string `json:"avatar_template"`
|
||||
}
|
||||
|
||||
func linuxDoAccessToken(r *http.Request, code string, setting model.PrivateLinuxDoAuthSetting) (string, error) {
|
||||
values := url.Values{}
|
||||
values.Set("client_id", setting.ClientID)
|
||||
values.Set("client_secret", setting.ClientSecret)
|
||||
values.Set("grant_type", "authorization_code")
|
||||
values.Set("code", code)
|
||||
values.Set("redirect_uri", linuxDoRedirectURI(r))
|
||||
req, _ := http.NewRequest(http.MethodPost, config.Cfg.LinuxDoTokenURL, strings.NewReader(values.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
var payload linuxDoTokenResponse
|
||||
if err := doLinuxDoJSON(req, &payload); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if strings.TrimSpace(payload.AccessToken) == "" {
|
||||
return "", safeMessageError{message: "Linux.do 登录失败"}
|
||||
}
|
||||
return payload.AccessToken, nil
|
||||
}
|
||||
|
||||
func linuxDoRedirectURI(r *http.Request) string {
|
||||
return RequestOrigin(r) + "/api/auth/linux-do/callback"
|
||||
}
|
||||
|
||||
func linuxDoProfile(token string) (linuxDoUserResponse, error) {
|
||||
req, _ := http.NewRequest(http.MethodGet, config.Cfg.LinuxDoUserInfoURL, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
var payload linuxDoUserResponse
|
||||
err := doLinuxDoJSON(req, &payload)
|
||||
return payload, err
|
||||
}
|
||||
|
||||
func doLinuxDoJSON(req *http.Request, payload any) error {
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return safeMessageError{message: "Linux.do 登录失败"}
|
||||
}
|
||||
return json.NewDecoder(bytes.NewReader(body)).Decode(payload)
|
||||
}
|
||||
|
||||
func linuxDoUsername(username string, id string) string {
|
||||
base := strings.TrimSpace(username)
|
||||
if base == "" {
|
||||
base = "linuxdo-" + id
|
||||
}
|
||||
if _, ok, err := repository.GetUserByUsername(base); err != nil || !ok {
|
||||
return base
|
||||
}
|
||||
return base + "-" + id
|
||||
}
|
||||
|
||||
func linuxDoAvatar(template string) string {
|
||||
if strings.TrimSpace(template) == "" {
|
||||
return ""
|
||||
}
|
||||
if strings.HasPrefix(template, "//") {
|
||||
template = "https:" + template
|
||||
}
|
||||
if strings.HasPrefix(template, "/") {
|
||||
template = "https://linux.do" + template
|
||||
}
|
||||
return strings.ReplaceAll(template, "{size}", "120")
|
||||
}
|
||||
|
||||
func decodeState(state string) string {
|
||||
data, err := base64.RawURLEncoding.DecodeString(state)
|
||||
if err != nil {
|
||||
return "/"
|
||||
}
|
||||
return safeRedirectPath(string(data))
|
||||
}
|
||||
|
||||
// safeRedirectPath 仅放行站内相对路径,拦截开放重定向。浏览器会忽略 URL 中的
|
||||
// Tab/换行/回车,并把 //host 或 /\host 解析为协议相对的跨站地址,因此先剥离这些
|
||||
// 控制字符,再拒绝 // 与 /\ 前缀。
|
||||
func safeRedirectPath(redirect string) string {
|
||||
cleaned := strings.Map(func(r rune) rune {
|
||||
if r == '\t' || r == '\n' || r == '\r' {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, redirect)
|
||||
if !strings.HasPrefix(cleaned, "/") || strings.HasPrefix(cleaned, "//") || strings.HasPrefix(cleaned, "/\\") {
|
||||
return "/"
|
||||
}
|
||||
return cleaned
|
||||
}
|
||||
|
||||
func RequestOrigin(r *http.Request) string {
|
||||
host := strings.TrimSpace(r.Header.Get("X-Forwarded-Host"))
|
||||
if host == "" {
|
||||
host = r.Host
|
||||
}
|
||||
proto := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto"))
|
||||
if proto == "" {
|
||||
proto = "http"
|
||||
}
|
||||
return proto + "://" + host
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func WarnDefaultSecurityConfig() {
|
||||
if config.Cfg.AdminUsername == "admin" && config.Cfg.AdminPassword == "infinite-canvas" {
|
||||
log.Println("WARNING: using default admin credentials, please set ADMIN_USERNAME and ADMIN_PASSWORD to safer values before deployment")
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSafeRedirectPath(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"/": "/",
|
||||
"/canvas/abc": "/canvas/abc",
|
||||
"/login?redirect=/x": "/login?redirect=/x",
|
||||
"": "/",
|
||||
"//evil.com": "/",
|
||||
"/\\evil.com": "/",
|
||||
"https://evil.com": "/",
|
||||
"http://evil.com": "/",
|
||||
"javascript:alert(1)": "/",
|
||||
"evil.com": "/",
|
||||
"/\t/evil.com": "/", // browsers strip the tab → //evil.com
|
||||
"/normal\tpath": "/normalpath",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := safeRedirectPath(in); got != want {
|
||||
t.Errorf("safeRedirectPath(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeStateRejectsOpenRedirect(t *testing.T) {
|
||||
for _, in := range []string{"//evil.com", "/\\evil.com", "https://evil.com"} {
|
||||
state := base64.RawURLEncoding.EncodeToString([]byte(in))
|
||||
if got := decodeState(state); got != "/" {
|
||||
t.Errorf("decodeState(state(%q)) = %q, want \"/\"", in, got)
|
||||
}
|
||||
}
|
||||
state := base64.RawURLEncoding.EncodeToString([]byte("/canvas/1"))
|
||||
if got := decodeState(state); got != "/canvas/1" {
|
||||
t.Errorf("decodeState(state(/canvas/1)) = %q, want /canvas/1", got)
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
)
|
||||
|
||||
type userContextKey struct{}
|
||||
|
||||
func WithUser(ctx context.Context, user model.AuthUser) context.Context {
|
||||
return context.WithValue(ctx, userContextKey{}, user)
|
||||
}
|
||||
|
||||
func UserFromContext(ctx context.Context) (model.AuthUser, bool) {
|
||||
user, ok := ctx.Value(userContextKey{}).(model.AuthUser)
|
||||
return user, ok
|
||||
}
|
||||
@@ -1,349 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/basketikun/infinite-canvas/repository"
|
||||
)
|
||||
|
||||
const (
|
||||
gptImage2RawBase = "https://raw.githubusercontent.com/EvoLinkAI/awesome-gpt-image-2-API-and-Prompts/main"
|
||||
awesomeGptImageRawBase = "https://raw.githubusercontent.com/ZeroLu/awesome-gpt-image/main"
|
||||
awesomeGpt4oImagePromptsBase = "https://raw.githubusercontent.com/ImgEdify/Awesome-GPT4o-Image-Prompts/main"
|
||||
youMindGptImage2RawBase = "https://raw.githubusercontent.com/YouMind-OpenLab/awesome-gpt-image-2/main"
|
||||
youMindNanoBananaProRawBase = "https://raw.githubusercontent.com/YouMind-OpenLab/awesome-nano-banana-pro-prompts/main"
|
||||
davidWuGptImage2RawBase = "https://raw.githubusercontent.com/davidwuw0811-boop/awesome-gpt-image2-prompts/main"
|
||||
)
|
||||
|
||||
var gptImage2CaseFiles = []string{"README.md", "cases/ad-creative.md", "cases/character.md", "cases/comparison.md", "cases/ecommerce.md", "cases/portrait.md", "cases/poster.md", "cases/ui.md"}
|
||||
|
||||
type gptImage2Data struct {
|
||||
Records []struct {
|
||||
Title string `json:"title"`
|
||||
TweetURL string `json:"tweet_url"`
|
||||
ImageDir string `json:"image_dir"`
|
||||
Category string `json:"category"`
|
||||
AddedAt string `json:"added_at"`
|
||||
} `json:"records"`
|
||||
}
|
||||
|
||||
type davidWuGptImage2Prompt struct {
|
||||
ID int `json:"id"`
|
||||
TitleEN string `json:"title_en"`
|
||||
TitleCN string `json:"title_cn"`
|
||||
Category string `json:"category"`
|
||||
CategoryCN string `json:"category_cn"`
|
||||
Prompt string `json:"prompt"`
|
||||
Note string `json:"note"`
|
||||
Author string `json:"author"`
|
||||
Source string `json:"source"`
|
||||
NeedsRef bool `json:"needs_ref"`
|
||||
Image string `json:"image"`
|
||||
}
|
||||
|
||||
func SyncPromptCategory(category string) ([]model.PromptCategory, error) {
|
||||
for _, item := range repository.PromptCategories() {
|
||||
if item.Category != category {
|
||||
continue
|
||||
}
|
||||
items, err := buildPromptCategory(item.Category)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := repository.ReplacePromptCategory(item, items); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return repository.ListPromptCategories()
|
||||
}
|
||||
return nil, errors.New("未知提示词分类")
|
||||
}
|
||||
|
||||
func buildPromptCategory(category string) ([]model.Prompt, error) {
|
||||
switch category {
|
||||
case "gpt-image-2-prompts":
|
||||
return buildGptImage2Prompts()
|
||||
case "awesome-gpt-image":
|
||||
return buildAwesomeGptImagePrompts()
|
||||
case "awesome-gpt4o-image-prompts":
|
||||
return buildAwesomeGpt4oImagePrompts()
|
||||
case "youmind-gpt-image-2":
|
||||
return buildYouMindGptImage2Prompts()
|
||||
case "youmind-nano-banana-pro":
|
||||
return buildYouMindNanoBananaProPrompts()
|
||||
case "davidwu-gpt-image2-prompts":
|
||||
return buildDavidWuGptImage2Prompts()
|
||||
}
|
||||
return nil, errors.New("未知提示词分类")
|
||||
}
|
||||
|
||||
func fetchText(baseURL, file string) (string, error) {
|
||||
request, _ := http.NewRequest(http.MethodGet, baseURL+"/"+file, nil)
|
||||
client := http.Client{Timeout: 30 * time.Second}
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return "", errors.New(file + " 拉取失败")
|
||||
}
|
||||
data, err := io.ReadAll(response.Body)
|
||||
return string(data), err
|
||||
}
|
||||
|
||||
func buildGptImage2Prompts() ([]model.Prompt, error) {
|
||||
cases := map[string]string{}
|
||||
raw, err := fetchText(gptImage2RawBase, "data/ingested_tweets.json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data := gptImage2Data{}
|
||||
if err := json.Unmarshal([]byte(raw), &data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range gptImage2CaseFiles {
|
||||
markdown, err := fetchText(gptImage2RawBase, file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
collectGptImage2Cases(cases, markdown)
|
||||
}
|
||||
items := []model.Prompt{}
|
||||
for _, item := range data.Records {
|
||||
prompt := cases[item.TweetURL]
|
||||
if prompt == "" {
|
||||
continue
|
||||
}
|
||||
image := gptImage2RawBase + "/" + item.ImageDir + "/output.jpg"
|
||||
items = append(items, model.Prompt{ID: "gpt-image-2-prompts-" + leftPad(len(items)+1), Title: item.Title, CoverURL: image, Prompt: prompt, Tags: tagsFromCategory(item.Category), CreatedAt: item.AddedAt, UpdatedAt: item.AddedAt, Preview: markdownPreview([]string{image})})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func collectGptImage2Cases(cases map[string]string, markdown string) {
|
||||
re := regexp.MustCompile("(?s)### Case \\d+: \\[[^\\]]+\\]\\(([^)]+)\\).*?\\*\\*Prompt:\\*\\*\\s*\\r?\\n\\s*```[\\w-]*\\r?\\n(.*?)\\r?\\n```")
|
||||
for _, match := range re.FindAllStringSubmatch(markdown, -1) {
|
||||
cases[match[1]] = strings.TrimSpace(match[2])
|
||||
}
|
||||
}
|
||||
|
||||
func buildAwesomeGptImagePrompts() ([]model.Prompt, error) {
|
||||
markdown, err := fetchText(awesomeGptImageRawBase, "README.zh-CN.md")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := []model.Prompt{}
|
||||
for _, section := range splitBeforeHeading(markdown, "## ") {
|
||||
tags := tagsFromHeading(firstMatch(section, `(?m)^##\s+(.+)$`))
|
||||
for _, block := range splitBeforeHeading(section, "### ") {
|
||||
title := strings.TrimSpace(regexp.MustCompile(`\[([^\]]+)]\([^)]+\)`).ReplaceAllString(firstMatch(block, `(?m)^###\s+(.+)$`), "$1"))
|
||||
prompt := strings.TrimSpace(firstMatch(block, "(?s)\\*\\*提示词:\\*\\*\\s*\\r?\\n\\s*```[\\w-]*\\r?\\n(.*?)\\r?\\n```"))
|
||||
if title == "" || prompt == "" {
|
||||
continue
|
||||
}
|
||||
images := extractMarkdownImages(awesomeGptImageRawBase, block)
|
||||
cover := ""
|
||||
if len(images) > 0 {
|
||||
cover = images[0]
|
||||
}
|
||||
items = append(items, model.Prompt{ID: "awesome-gpt-image-" + leftPad(len(items)+1), Title: title, CoverURL: cover, Prompt: prompt, Tags: tags, Preview: markdownPreview(images)})
|
||||
}
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func buildAwesomeGpt4oImagePrompts() ([]model.Prompt, error) {
|
||||
markdown, err := fetchText(awesomeGpt4oImagePromptsBase, "README.zh-CN.md")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := []model.Prompt{}
|
||||
for _, block := range splitBeforeHeading(markdown, "### ") {
|
||||
title := strings.TrimSpace(firstMatch(block, `(?m)^###\s+(.+)$`))
|
||||
prompt := strings.TrimSpace(firstMatch(block, "(?s)- \\*\\*提示词文本:\\*\\*\\s*`(.*?)`"))
|
||||
if title == "" || prompt == "" {
|
||||
continue
|
||||
}
|
||||
images := extractMarkdownImages(awesomeGpt4oImagePromptsBase, block)
|
||||
cover := ""
|
||||
if len(images) > 0 {
|
||||
cover = images[0]
|
||||
}
|
||||
items = append(items, model.Prompt{ID: "awesome-gpt4o-image-prompts-" + leftPad(len(items)+1), Title: title, CoverURL: cover, Prompt: prompt, Tags: []string{"gpt4o"}, Preview: markdownPreview(images)})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func buildYouMindGptImage2Prompts() ([]model.Prompt, error) {
|
||||
return buildYouMindPrompts(youMindGptImage2RawBase, "youmind-gpt-image-2", "gpt-image-2")
|
||||
}
|
||||
|
||||
func buildYouMindNanoBananaProPrompts() ([]model.Prompt, error) {
|
||||
return buildYouMindPrompts(youMindNanoBananaProRawBase, "youmind-nano-banana-pro", "nano-banana-pro")
|
||||
}
|
||||
|
||||
func buildDavidWuGptImage2Prompts() ([]model.Prompt, error) {
|
||||
raw, err := fetchText(davidWuGptImage2RawBase, "prompts.json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data := []davidWuGptImage2Prompt{}
|
||||
if err := json.Unmarshal([]byte(raw), &data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := []model.Prompt{}
|
||||
for _, item := range data {
|
||||
title := strings.TrimSpace(item.TitleCN)
|
||||
if title == "" {
|
||||
title = strings.TrimSpace(item.TitleEN)
|
||||
}
|
||||
prompt := strings.TrimSpace(item.Prompt)
|
||||
if title == "" || prompt == "" {
|
||||
continue
|
||||
}
|
||||
image := absoluteImage(davidWuGptImage2RawBase, item.Image)
|
||||
items = append(items, model.Prompt{ID: "davidwu-gpt-image2-prompts-" + leftPad(item.ID), Title: title, CoverURL: image, Prompt: prompt, Tags: davidWuGptImage2Tags(item), Preview: davidWuGptImage2Preview(item, image)})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func buildYouMindPrompts(baseURL, idPrefix, modelTag string) ([]model.Prompt, error) {
|
||||
markdown, err := fetchText(baseURL, "README_zh.md")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := []model.Prompt{}
|
||||
for _, block := range splitBeforeHeading(markdown, "### ") {
|
||||
title := strings.TrimSpace(firstMatch(block, `(?m)^###\s+No\.\s*\d+:\s*(.+)$`))
|
||||
prompt := strings.TrimSpace(firstMatch(block, "(?s)#### .*?提示词\\s*\\r?\\n\\s*```[\\w-]*\\r?\\n(.*?)\\r?\\n```"))
|
||||
if title == "" || prompt == "" {
|
||||
continue
|
||||
}
|
||||
images := extractMarkdownImages(baseURL, block)
|
||||
cover := ""
|
||||
if len(images) > 0 {
|
||||
cover = images[0]
|
||||
}
|
||||
items = append(items, model.Prompt{ID: idPrefix + "-" + leftPad(len(items)+1), Title: title, CoverURL: cover, Prompt: prompt, Tags: youMindTags(title, modelTag), Preview: markdownPreview(images)})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func splitBeforeHeading(markdown string, prefix string) []string {
|
||||
blocks := []string{}
|
||||
lines := strings.Split(markdown, "\n")
|
||||
current := []string{}
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(line, prefix) && len(current) > 0 {
|
||||
blocks = append(blocks, strings.Join(current, "\n"))
|
||||
current = []string{}
|
||||
}
|
||||
current = append(current, line)
|
||||
}
|
||||
return append(blocks, strings.Join(current, "\n"))
|
||||
}
|
||||
|
||||
func firstMatch(value string, pattern string) string {
|
||||
match := regexp.MustCompile(pattern).FindStringSubmatch(value)
|
||||
if len(match) > 1 {
|
||||
return match[1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func tagsFromCategory(category string) []string {
|
||||
return splitTags(regexp.MustCompile(`(?i)\s+Cases$`).ReplaceAllString(category, ""), `\s*(&|and)\s*`)
|
||||
}
|
||||
|
||||
func tagsFromHeading(heading string) []string {
|
||||
return splitTags(regexp.MustCompile(`[^\p{L}\p{N}/&、与 ]`).ReplaceAllString(heading, ""), `\s*(/|&|、|与)\s*`)
|
||||
}
|
||||
|
||||
func youMindTags(title, modelTag string) []string {
|
||||
tags := []string{modelTag}
|
||||
parts := strings.SplitN(title, " - ", 2)
|
||||
if len(parts) > 1 {
|
||||
tags = append(tags, tagsFromHeading(parts[0])...)
|
||||
}
|
||||
return tags
|
||||
}
|
||||
|
||||
func davidWuGptImage2Tags(item davidWuGptImage2Prompt) []string {
|
||||
tags := splitTags(strings.Join([]string{item.CategoryCN, item.Category, item.Author, item.Source}, "/"), `/`)
|
||||
if item.NeedsRef {
|
||||
tags = append(tags, "需要参考图")
|
||||
}
|
||||
return tags
|
||||
}
|
||||
|
||||
func davidWuGptImage2Preview(item davidWuGptImage2Prompt, image string) string {
|
||||
lines := []string{}
|
||||
if item.TitleEN != "" {
|
||||
lines = append(lines, item.TitleEN)
|
||||
}
|
||||
if item.Note != "" {
|
||||
lines = append(lines, item.Note)
|
||||
}
|
||||
if image != "" {
|
||||
lines = append(lines, "")
|
||||
}
|
||||
return strings.Join(lines, "\n\n")
|
||||
}
|
||||
|
||||
func splitTags(value string, pattern string) []string {
|
||||
tags := []string{}
|
||||
for _, tag := range regexp.MustCompile(pattern).Split(value, -1) {
|
||||
if tag = strings.ToLower(strings.TrimSpace(tag)); tag != "" {
|
||||
tags = append(tags, tag)
|
||||
}
|
||||
}
|
||||
return tags
|
||||
}
|
||||
|
||||
func markdownPreview(images []string) string {
|
||||
lines := []string{}
|
||||
for _, image := range images {
|
||||
if image != "" {
|
||||
lines = append(lines, "")
|
||||
}
|
||||
}
|
||||
return strings.Join(lines, "\n\n")
|
||||
}
|
||||
|
||||
func extractMarkdownImages(baseURL string, block string) []string {
|
||||
seen := map[string]bool{}
|
||||
images := []string{}
|
||||
for _, pattern := range []string{`<img[^>]+src="([^"]+)"`, `!\[[^\]]*]\(([^)]+)\)`} {
|
||||
for _, match := range regexp.MustCompile(pattern).FindAllStringSubmatch(block, -1) {
|
||||
image := absoluteImage(baseURL, match[1])
|
||||
if image != "" && !seen[image] {
|
||||
seen[image] = true
|
||||
images = append(images, image)
|
||||
}
|
||||
}
|
||||
}
|
||||
return images
|
||||
}
|
||||
|
||||
func absoluteImage(baseURL, image string) string {
|
||||
if image == "" || strings.HasPrefix(image, "http://") || strings.HasPrefix(image, "https://") {
|
||||
return image
|
||||
}
|
||||
return baseURL + "/" + strings.TrimLeft(strings.TrimPrefix(image, "."), "/")
|
||||
}
|
||||
|
||||
func leftPad(value int) string {
|
||||
if value >= 1000 {
|
||||
return strconv.Itoa(value)
|
||||
}
|
||||
text := "000" + strconv.Itoa(value)
|
||||
return text[len(text)-3:]
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/basketikun/infinite-canvas/repository"
|
||||
"github.com/robfig/cron/v3"
|
||||
)
|
||||
|
||||
const defaultPromptSyncCron = "*/5 * * * *"
|
||||
|
||||
var (
|
||||
promptSyncCron *cron.Cron
|
||||
promptSyncOnce sync.Once
|
||||
promptSyncMu sync.Mutex
|
||||
)
|
||||
|
||||
func StartPromptSyncScheduler() {
|
||||
promptSyncOnce.Do(func() {
|
||||
promptSyncCron = cron.New()
|
||||
promptSyncCron.Start()
|
||||
})
|
||||
RefreshPromptSyncScheduler()
|
||||
}
|
||||
|
||||
func RefreshPromptSyncScheduler() {
|
||||
promptSyncMu.Lock()
|
||||
defer promptSyncMu.Unlock()
|
||||
if promptSyncCron == nil {
|
||||
return
|
||||
}
|
||||
for _, entry := range promptSyncCron.Entries() {
|
||||
promptSyncCron.Remove(entry.ID)
|
||||
}
|
||||
settings, err := repository.GetSettings()
|
||||
if err != nil {
|
||||
log.Printf("load prompt sync setting failed err=%v", err)
|
||||
return
|
||||
}
|
||||
setting := normalizePromptSyncSetting(settings.Private.PromptSync)
|
||||
if setting.Enabled == nil || !*setting.Enabled {
|
||||
return
|
||||
}
|
||||
if _, err := promptSyncCron.AddFunc(setting.Cron, SyncRemotePromptCategories); err != nil {
|
||||
log.Printf("add prompt sync cron failed cron=%s err=%v", setting.Cron, err)
|
||||
}
|
||||
}
|
||||
|
||||
func SyncRemotePromptCategories() {
|
||||
for _, category := range repository.PromptCategories() {
|
||||
if !category.Remote {
|
||||
continue
|
||||
}
|
||||
log.Printf("scheduled prompt sync start category=%s", category.Category)
|
||||
if _, err := SyncPromptCategory(category.Category); err != nil {
|
||||
log.Printf("scheduled prompt sync failed category=%s err=%v", category.Category, err)
|
||||
continue
|
||||
}
|
||||
log.Printf("scheduled prompt sync done category=%s", category.Category)
|
||||
}
|
||||
}
|
||||
|
||||
func normalizePromptSyncSetting(setting model.PromptSyncSetting) model.PromptSyncSetting {
|
||||
if setting.Cron == "" {
|
||||
setting.Cron = defaultPromptSyncCron
|
||||
}
|
||||
if setting.Enabled == nil {
|
||||
enabled := true
|
||||
setting.Enabled = &enabled
|
||||
}
|
||||
return setting
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/basketikun/infinite-canvas/repository"
|
||||
)
|
||||
|
||||
func ListPrompts(q model.Query) (model.PromptList, error) {
|
||||
items, total, err := repository.ListPrompts(q)
|
||||
if err != nil {
|
||||
return model.PromptList{}, err
|
||||
}
|
||||
tags, err := repository.ListPromptTags(q)
|
||||
if err != nil {
|
||||
return model.PromptList{}, err
|
||||
}
|
||||
categories := promptCategoryCodes(ListPromptCategories())
|
||||
return model.PromptList{Items: items, Tags: tags, Categories: categories, Total: int(total)}, nil
|
||||
}
|
||||
|
||||
func ListPromptCategories() []model.PromptCategory {
|
||||
categories, _ := repository.ListPromptCategories()
|
||||
return categories
|
||||
}
|
||||
|
||||
func SavePrompt(item model.Prompt) (model.Prompt, error) {
|
||||
now := time.Now().Format(time.RFC3339)
|
||||
if item.Category == "" {
|
||||
item.Category = repository.PromptCategories()[0].Category
|
||||
}
|
||||
if item.ID == "" {
|
||||
item.ID = newID(item.Category)
|
||||
item.CreatedAt = now
|
||||
}
|
||||
item.UpdatedAt = now
|
||||
category, ok := repository.PromptCategoryByCode(item.Category)
|
||||
if !ok {
|
||||
category = repository.PromptCategories()[0]
|
||||
item.Category = category.Category
|
||||
}
|
||||
item.GithubURL = ""
|
||||
return repository.SavePrompt(item)
|
||||
}
|
||||
|
||||
func DeletePrompt(id string) error {
|
||||
return repository.DeletePrompt(id)
|
||||
}
|
||||
|
||||
func DeletePrompts(ids []string) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
return repository.DeletePrompts(ids)
|
||||
}
|
||||
|
||||
func promptCategoryCodes(items []model.PromptCategory) []string {
|
||||
codes := []string{}
|
||||
for _, item := range items {
|
||||
if item.Category != "" {
|
||||
codes = append(codes, item.Category)
|
||||
}
|
||||
}
|
||||
return codes
|
||||
}
|
||||
@@ -1,488 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
"github.com/basketikun/infinite-canvas/repository"
|
||||
)
|
||||
|
||||
var adminModelHTTPClient = &http.Client{Timeout: 30 * time.Second}
|
||||
|
||||
func PublicSettings() (model.PublicSetting, error) {
|
||||
settings, err := repository.GetSettings()
|
||||
return normalizeSettings(settings).Public, err
|
||||
}
|
||||
|
||||
func AdminSettings() (model.Settings, error) {
|
||||
settings, err := repository.GetSettings()
|
||||
return hidePrivateAPIKeys(normalizeSettings(settings)), err
|
||||
}
|
||||
|
||||
func SaveSettings(settings model.Settings) (model.Settings, error) {
|
||||
saved, err := repository.GetSettings()
|
||||
if err != nil {
|
||||
return model.Settings{}, err
|
||||
}
|
||||
settings = normalizeSettings(settings)
|
||||
keepPrivateAPIKeys(&settings, normalizeSettings(saved))
|
||||
keepPrivateAuthSecrets(&settings, normalizeSettings(saved))
|
||||
result, err := repository.SaveSettings(settings, now())
|
||||
if err == nil {
|
||||
RefreshPromptSyncScheduler()
|
||||
}
|
||||
return hidePrivateAPIKeys(result), err
|
||||
}
|
||||
|
||||
func AdminChannelModels(index *int, channel model.ModelChannel) ([]string, error) {
|
||||
resolved, err := resolveAdminChannel(index, channel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return fetchAdminChannelModels(resolved)
|
||||
}
|
||||
|
||||
func AdminTestChannelModel(index *int, channel model.ModelChannel, modelName string) (string, error) {
|
||||
resolved, err := resolveAdminChannel(index, channel)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if isArkAgentPlanChannel(resolved) || isSeedanceModelName(modelName) {
|
||||
return testArkSeedanceChannelModel(resolved, modelName)
|
||||
}
|
||||
return testAdminChannelModel(resolved, modelName)
|
||||
}
|
||||
|
||||
func normalizeSettings(settings model.Settings) model.Settings {
|
||||
settings.Private = normalizePrivateSetting(settings.Private)
|
||||
settings.Public = normalizePublicSettingWithChannels(settings.Public, settings.Private.Channels)
|
||||
return settings
|
||||
}
|
||||
|
||||
func normalizePublicSetting(setting model.PublicSetting) model.PublicSetting {
|
||||
return normalizePublicSettingWithChannels(setting, nil)
|
||||
}
|
||||
|
||||
func normalizePublicSettingWithChannels(setting model.PublicSetting, channels []model.ModelChannel) model.PublicSetting {
|
||||
if setting.ModelChannel.AvailableModels == nil {
|
||||
setting.ModelChannel.AvailableModels = []string{}
|
||||
}
|
||||
if setting.ModelChannel.ModelCosts == nil {
|
||||
setting.ModelChannel.ModelCosts = []model.ModelCost{}
|
||||
}
|
||||
for i := range setting.ModelChannel.ModelCosts {
|
||||
setting.ModelChannel.ModelCosts[i].Model = strings.TrimSpace(setting.ModelChannel.ModelCosts[i].Model)
|
||||
if setting.ModelChannel.ModelCosts[i].Credits < 0 {
|
||||
setting.ModelChannel.ModelCosts[i].Credits = 0
|
||||
}
|
||||
}
|
||||
if setting.ModelChannel.AllowCustomChannel == nil {
|
||||
enabled := true
|
||||
setting.ModelChannel.AllowCustomChannel = &enabled
|
||||
}
|
||||
if setting.Auth.AllowRegister == nil {
|
||||
enabled := true
|
||||
setting.Auth.AllowRegister = &enabled
|
||||
}
|
||||
enabledModels := enabledChannelModels(channels)
|
||||
if len(enabledModels) > 0 {
|
||||
setting.ModelChannel.AvailableModels = enabledModels
|
||||
} else {
|
||||
setting.ModelChannel.AvailableModels = uniqueModelNames(setting.ModelChannel.AvailableModels)
|
||||
}
|
||||
setting.ModelChannel.DefaultTextModel = repairDefaultModel(setting.ModelChannel.DefaultTextModel, setting.ModelChannel.AvailableModels, isTextModelName)
|
||||
setting.ModelChannel.DefaultImageModel = repairDefaultModel(setting.ModelChannel.DefaultImageModel, setting.ModelChannel.AvailableModels, isImageModelName)
|
||||
setting.ModelChannel.DefaultVideoModel = repairDefaultModel(setting.ModelChannel.DefaultVideoModel, setting.ModelChannel.AvailableModels, isVideoModelName)
|
||||
setting.ModelChannel.DefaultModel = repairDefaultModel(setting.ModelChannel.DefaultModel, setting.ModelChannel.AvailableModels, isTextModelName)
|
||||
return setting
|
||||
}
|
||||
|
||||
func ModelCost(modelName string) (int, error) {
|
||||
settings, err := repository.GetSettings()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
modelName = strings.TrimSpace(modelName)
|
||||
for _, item := range normalizePublicSetting(settings.Public).ModelChannel.ModelCosts {
|
||||
if item.Model == modelName {
|
||||
return item.Credits, nil
|
||||
}
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func normalizePrivateSetting(setting model.PrivateSetting) model.PrivateSetting {
|
||||
if setting.Channels == nil {
|
||||
setting.Channels = []model.ModelChannel{}
|
||||
}
|
||||
setting.PromptSync = normalizePromptSyncSetting(setting.PromptSync)
|
||||
for i := range setting.Channels {
|
||||
if setting.Channels[i].Protocol == "" {
|
||||
setting.Channels[i].Protocol = "openai"
|
||||
}
|
||||
if setting.Channels[i].Models == nil {
|
||||
setting.Channels[i].Models = []string{}
|
||||
}
|
||||
if setting.Channels[i].Weight <= 0 {
|
||||
setting.Channels[i].Weight = 1
|
||||
}
|
||||
}
|
||||
return setting
|
||||
}
|
||||
|
||||
func hidePrivateAPIKeys(settings model.Settings) model.Settings {
|
||||
for i := range settings.Private.Channels {
|
||||
settings.Private.Channels[i].APIKey = ""
|
||||
}
|
||||
settings.Private.Auth.LinuxDo.ClientSecret = ""
|
||||
return settings
|
||||
}
|
||||
|
||||
func keepPrivateAPIKeys(settings *model.Settings, saved model.Settings) {
|
||||
for i := range settings.Private.Channels {
|
||||
if strings.TrimSpace(settings.Private.Channels[i].APIKey) != "" {
|
||||
continue
|
||||
}
|
||||
if channel, ok := findSavedChannel(settings.Private.Channels[i], saved.Private.Channels, i); ok {
|
||||
settings.Private.Channels[i].APIKey = channel.APIKey
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func keepPrivateAuthSecrets(settings *model.Settings, saved model.Settings) {
|
||||
if strings.TrimSpace(settings.Private.Auth.LinuxDo.ClientSecret) == "" {
|
||||
settings.Private.Auth.LinuxDo.ClientSecret = saved.Private.Auth.LinuxDo.ClientSecret
|
||||
}
|
||||
}
|
||||
|
||||
func findSavedChannel(channel model.ModelChannel, saved []model.ModelChannel, index int) (model.ModelChannel, bool) {
|
||||
for _, item := range saved {
|
||||
if item.Name == channel.Name && item.BaseURL == channel.BaseURL {
|
||||
return item, true
|
||||
}
|
||||
}
|
||||
if index < len(saved) {
|
||||
return saved[index], true
|
||||
}
|
||||
return model.ModelChannel{}, false
|
||||
}
|
||||
|
||||
func SelectModelChannel(modelName string) (model.ModelChannel, error) {
|
||||
settings, err := repository.GetSettings()
|
||||
if err != nil {
|
||||
return model.ModelChannel{}, err
|
||||
}
|
||||
channels := modelChannelsForModel(normalizePrivateSetting(settings.Private).Channels, modelName)
|
||||
if len(channels) == 0 {
|
||||
return model.ModelChannel{}, errors.New("没有可用模型渠道")
|
||||
}
|
||||
total := 0
|
||||
for _, channel := range channels {
|
||||
total += channel.Weight
|
||||
}
|
||||
hit := rand.Intn(total)
|
||||
for _, channel := range channels {
|
||||
hit -= channel.Weight
|
||||
if hit < 0 {
|
||||
return channel, nil
|
||||
}
|
||||
}
|
||||
return channels[0], nil
|
||||
}
|
||||
|
||||
func BuildModelChannelURL(channel model.ModelChannel, path string) string {
|
||||
baseURL := normalizeModelChannelBaseURL(channel.BaseURL)
|
||||
lowerBaseURL := strings.ToLower(baseURL)
|
||||
if !strings.HasSuffix(lowerBaseURL, "/v1") && !strings.HasSuffix(lowerBaseURL, "/api/v3") && !strings.HasSuffix(lowerBaseURL, "/api/plan/v3") {
|
||||
baseURL += "/v1"
|
||||
}
|
||||
return baseURL + path
|
||||
}
|
||||
|
||||
func normalizeModelChannelBaseURL(baseURL string) string {
|
||||
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
||||
parsed, err := url.Parse(baseURL)
|
||||
if err == nil && parsed.Scheme != "" && parsed.Host != "" {
|
||||
path := strings.TrimRight(parsed.Path, "/")
|
||||
lowerPath := strings.ToLower(path)
|
||||
if index := strings.Index(lowerPath, "/api/plan/v3"); index >= 0 {
|
||||
end := index + len("/api/plan/v3")
|
||||
if len(lowerPath) == end || lowerPath[end] == '/' {
|
||||
parsed.Path = path[:end]
|
||||
parsed.RawPath = ""
|
||||
parsed.RawQuery = ""
|
||||
parsed.Fragment = ""
|
||||
return strings.TrimRight(parsed.String(), "/")
|
||||
}
|
||||
}
|
||||
}
|
||||
return baseURL
|
||||
}
|
||||
|
||||
func isArkAgentPlanChannel(channel model.ModelChannel) bool {
|
||||
baseURL := strings.ToLower(normalizeModelChannelBaseURL(channel.BaseURL))
|
||||
return strings.HasSuffix(baseURL, "/api/plan/v3")
|
||||
}
|
||||
|
||||
func isSeedanceModelName(modelName string) bool {
|
||||
modelName = strings.ToLower(strings.TrimSpace(modelName))
|
||||
return strings.Contains(modelName, "seedance") || strings.Contains(modelName, "doubao-seedance")
|
||||
}
|
||||
|
||||
func enabledChannelModels(channels []model.ModelChannel) []string {
|
||||
models := []string{}
|
||||
for _, channel := range channels {
|
||||
if !channel.Enabled {
|
||||
continue
|
||||
}
|
||||
models = append(models, channel.Models...)
|
||||
}
|
||||
return uniqueModelNames(models)
|
||||
}
|
||||
|
||||
func uniqueModelNames(models []string) []string {
|
||||
result := []string{}
|
||||
seen := map[string]bool{}
|
||||
for _, item := range models {
|
||||
name := strings.TrimSpace(item)
|
||||
if name == "" || seen[name] {
|
||||
continue
|
||||
}
|
||||
seen[name] = true
|
||||
result = append(result, name)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func repairDefaultModel(current string, models []string, preferred func(string) bool) string {
|
||||
current = strings.TrimSpace(current)
|
||||
for _, item := range models {
|
||||
if item == current {
|
||||
return current
|
||||
}
|
||||
}
|
||||
for _, item := range models {
|
||||
if preferred(item) {
|
||||
return item
|
||||
}
|
||||
}
|
||||
if len(models) > 0 {
|
||||
return models[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func isVideoModelName(modelName string) bool {
|
||||
name := strings.ToLower(strings.TrimSpace(modelName))
|
||||
return strings.Contains(name, "seedance") || strings.Contains(name, "video")
|
||||
}
|
||||
|
||||
func isImageModelName(modelName string) bool {
|
||||
name := strings.ToLower(strings.TrimSpace(modelName))
|
||||
return strings.Contains(name, "seedream") || strings.Contains(name, "gpt-image") || strings.Contains(name, "image")
|
||||
}
|
||||
|
||||
func isTextModelName(modelName string) bool {
|
||||
return !isImageModelName(modelName) && !isVideoModelName(modelName)
|
||||
}
|
||||
|
||||
func normalizeModelChannel(channel model.ModelChannel) model.ModelChannel {
|
||||
if channel.Protocol == "" {
|
||||
channel.Protocol = "openai"
|
||||
}
|
||||
if channel.Models == nil {
|
||||
channel.Models = []string{}
|
||||
}
|
||||
if channel.Weight <= 0 {
|
||||
channel.Weight = 1
|
||||
}
|
||||
return channel
|
||||
}
|
||||
|
||||
func resolveAdminChannel(index *int, channel model.ModelChannel) (model.ModelChannel, error) {
|
||||
resolved := normalizeModelChannel(channel)
|
||||
if strings.TrimSpace(resolved.APIKey) == "" {
|
||||
settings, err := repository.GetSettings()
|
||||
if err != nil {
|
||||
return model.ModelChannel{}, err
|
||||
}
|
||||
saved := normalizePrivateSetting(settings.Private).Channels
|
||||
if index != nil && *index >= 0 && *index < len(saved) {
|
||||
if resolved.APIKey == "" {
|
||||
resolved.APIKey = saved[*index].APIKey
|
||||
}
|
||||
if resolved.BaseURL == "" {
|
||||
resolved.BaseURL = saved[*index].BaseURL
|
||||
}
|
||||
if resolved.Name == "" {
|
||||
resolved.Name = saved[*index].Name
|
||||
}
|
||||
}
|
||||
if resolved.APIKey == "" {
|
||||
if savedChannel, ok := findSavedChannel(resolved, saved, -1); ok {
|
||||
resolved.APIKey = savedChannel.APIKey
|
||||
}
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(resolved.BaseURL) == "" {
|
||||
return model.ModelChannel{}, safeMessageError{message: "缺少接口地址"}
|
||||
}
|
||||
if strings.TrimSpace(resolved.APIKey) == "" {
|
||||
return model.ModelChannel{}, safeMessageError{message: "缺少 API Key"}
|
||||
}
|
||||
return resolved, nil
|
||||
}
|
||||
|
||||
func fetchAdminChannelModels(channel model.ModelChannel) ([]string, error) {
|
||||
request, err := http.NewRequest(http.MethodGet, BuildModelChannelURL(channel, "/models"), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+channel.APIKey)
|
||||
response, err := adminModelHTTPClient.Do(request)
|
||||
if err != nil {
|
||||
return nil, safeMessageError{message: "读取模型失败:上游接口无响应或网络不可达"}
|
||||
}
|
||||
defer response.Body.Close()
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
if response.StatusCode >= http.StatusBadRequest {
|
||||
if response.StatusCode == http.StatusNotFound && isArkAgentPlanChannel(channel) {
|
||||
return nil, safeMessageError{message: "火山方舟 Agent Plan 未提供 OpenAI /models 模型列表接口,请手动填写模型名称,例如 doubao-seedance-2.0。"}
|
||||
}
|
||||
return nil, readAdminChannelError(body, response.StatusCode, "读取模型失败")
|
||||
}
|
||||
var payload struct {
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &payload)
|
||||
result := make([]string, 0, len(payload.Data))
|
||||
for _, item := range payload.Data {
|
||||
if strings.TrimSpace(item.ID) != "" {
|
||||
result = append(result, item.ID)
|
||||
}
|
||||
}
|
||||
sort.Strings(result)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func testAdminChannelModel(channel model.ModelChannel, modelName string) (string, error) {
|
||||
if strings.TrimSpace(modelName) == "" {
|
||||
return "", errors.New("缺少模型名称")
|
||||
}
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"model": modelName,
|
||||
"messages": []map[string]string{{
|
||||
"role": "user",
|
||||
"content": "hi",
|
||||
}},
|
||||
})
|
||||
request, err := http.NewRequest(http.MethodPost, BuildModelChannelURL(channel, "/chat/completions"), strings.NewReader(string(body)))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+channel.APIKey)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response, err := adminModelHTTPClient.Do(request)
|
||||
if err != nil {
|
||||
return "", safeMessageError{message: "测试失败:上游接口无响应或网络不可达"}
|
||||
}
|
||||
defer response.Body.Close()
|
||||
responseBody, _ := io.ReadAll(response.Body)
|
||||
if response.StatusCode >= http.StatusBadRequest {
|
||||
return "", readAdminChannelError(responseBody, response.StatusCode, "测试失败")
|
||||
}
|
||||
var payload struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
}
|
||||
_ = json.Unmarshal(responseBody, &payload)
|
||||
if len(payload.Choices) > 0 && strings.TrimSpace(payload.Choices[0].Message.Content) != "" {
|
||||
return payload.Choices[0].Message.Content, nil
|
||||
}
|
||||
return "ok", nil
|
||||
}
|
||||
|
||||
func testArkSeedanceChannelModel(channel model.ModelChannel, modelName string) (string, error) {
|
||||
if strings.TrimSpace(modelName) == "" {
|
||||
return "", errors.New("缺少模型名称")
|
||||
}
|
||||
if strings.TrimSpace(channel.BaseURL) == "" {
|
||||
return "", safeMessageError{message: "缺少接口地址"}
|
||||
}
|
||||
if strings.TrimSpace(channel.APIKey) == "" {
|
||||
return "", safeMessageError{message: "缺少 API Key"}
|
||||
}
|
||||
if !isArkAgentPlanChannel(channel) {
|
||||
return "Seedance 视频模型不会发送 /chat/completions 文本测试。已检查 Base URL、API Key 和模型名非空;未调用视频生成接口,因此未验证套餐额度或模型权限。", nil
|
||||
}
|
||||
return "Agent Plan / Seedance 视频模型配置格式已通过。后台测试不会调用视频生成接口,因此未验证 API Key、套餐额度或模型权限;请在画布中使用视频生成验证。", nil
|
||||
}
|
||||
|
||||
func readAdminChannelError(body []byte, statusCode int, fallback string) error {
|
||||
var payload struct {
|
||||
Error *struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
if len(body) > 0 && json.Unmarshal(body, &payload) == nil {
|
||||
if payload.Error != nil && strings.TrimSpace(payload.Error.Message) != "" {
|
||||
return safeMessageError{message: payload.Error.Message}
|
||||
}
|
||||
if strings.TrimSpace(payload.Msg) != "" {
|
||||
return safeMessageError{message: payload.Msg}
|
||||
}
|
||||
}
|
||||
if statusCode == http.StatusUnauthorized || statusCode == http.StatusForbidden {
|
||||
return safeMessageError{message: fmt.Sprintf("上游接口鉴权失败(%d),请检查 API Key、套餐权限或模型权限", statusCode)}
|
||||
}
|
||||
if statusCode == http.StatusTooManyRequests {
|
||||
return safeMessageError{message: "上游接口限流或额度不足(429),请稍后重试或检查额度"}
|
||||
}
|
||||
if statusCode > 0 {
|
||||
return safeMessageError{message: fmt.Sprintf("%s:%d", fallback, statusCode)}
|
||||
}
|
||||
return safeMessageError{message: fallback}
|
||||
}
|
||||
|
||||
type safeMessageError struct {
|
||||
message string
|
||||
}
|
||||
|
||||
func (err safeMessageError) Error() string {
|
||||
return err.message
|
||||
}
|
||||
|
||||
func (err safeMessageError) SafeMessage() string {
|
||||
return err.message
|
||||
}
|
||||
|
||||
func modelChannelsForModel(channels []model.ModelChannel, modelName string) []model.ModelChannel {
|
||||
result := []model.ModelChannel{}
|
||||
for _, channel := range channels {
|
||||
if !channel.Enabled || channel.BaseURL == "" || channel.APIKey == "" {
|
||||
continue
|
||||
}
|
||||
for _, item := range channel.Models {
|
||||
if strings.TrimSpace(item) == modelName {
|
||||
result = append(result, channel)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/basketikun/infinite-canvas/model"
|
||||
)
|
||||
|
||||
func TestFetchAdminChannelModelsParsesOpenAIModels(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/models" {
|
||||
t.Fatalf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"z-model"},{"id":"a-model"},{"id":""}]}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
models, err := fetchAdminChannelModels(model.ModelChannel{
|
||||
BaseURL: server.URL,
|
||||
APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("fetchAdminChannelModels returned error: %v", err)
|
||||
}
|
||||
if want := []string{"a-model", "z-model"}; !reflect.DeepEqual(models, want) {
|
||||
t.Fatalf("models = %#v, want %#v", models, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchAdminChannelModelsReportsArkPlanModelsUnsupported(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/plan/v3/models" {
|
||||
t.Fatalf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, err := fetchAdminChannelModels(model.ModelChannel{
|
||||
BaseURL: server.URL + "/api/plan/v3/contents/generations/tasks",
|
||||
APIKey: "test-key",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected unsupported /models error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "Agent Plan 未提供 OpenAI /models") {
|
||||
t.Fatalf("error = %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildModelChannelURLNormalizesArkPlanTaskPath(t *testing.T) {
|
||||
got := BuildModelChannelURL(model.ModelChannel{BaseURL: "https://ark.cn-beijing.volces.com/api/plan/v3/contents/generations/tasks?debug=1"}, "/models")
|
||||
want := "https://ark.cn-beijing.volces.com/api/plan/v3/models"
|
||||
if got != want {
|
||||
t.Fatalf("BuildModelChannelURL = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeSettingsPublishesEnabledChannelModelsAndRepairsDefaults(t *testing.T) {
|
||||
settings := normalizeSettings(model.Settings{
|
||||
Public: model.PublicSetting{
|
||||
ModelChannel: model.PublicModelChannelSetting{
|
||||
AvailableModels: []string{"grok-imagine-video", "disabled-model"},
|
||||
DefaultModel: "grok-imagine-video",
|
||||
DefaultTextModel: "missing-text",
|
||||
DefaultImageModel: "missing-image",
|
||||
DefaultVideoModel: "missing-video",
|
||||
},
|
||||
},
|
||||
Private: model.PrivateSetting{
|
||||
Channels: []model.ModelChannel{
|
||||
{Enabled: true, Models: []string{"gpt-5.5", "doubao-seedream-5.0-lite", "doubao-seedance-2.0-fast", "gpt-5.5"}},
|
||||
{Enabled: false, Models: []string{"disabled-model"}},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
channel := settings.Public.ModelChannel
|
||||
wantModels := []string{"gpt-5.5", "doubao-seedream-5.0-lite", "doubao-seedance-2.0-fast"}
|
||||
if !reflect.DeepEqual(channel.AvailableModels, wantModels) {
|
||||
t.Fatalf("available models = %#v, want %#v", channel.AvailableModels, wantModels)
|
||||
}
|
||||
if channel.DefaultModel != "gpt-5.5" {
|
||||
t.Fatalf("default model = %q, want text model", channel.DefaultModel)
|
||||
}
|
||||
if channel.DefaultTextModel != "gpt-5.5" {
|
||||
t.Fatalf("default text model = %q, want text model", channel.DefaultTextModel)
|
||||
}
|
||||
if channel.DefaultImageModel != "doubao-seedream-5.0-lite" {
|
||||
t.Fatalf("default image model = %q, want seedream", channel.DefaultImageModel)
|
||||
}
|
||||
if channel.DefaultVideoModel != "doubao-seedance-2.0-fast" {
|
||||
t.Fatalf("default video model = %q, want seedance", channel.DefaultVideoModel)
|
||||
}
|
||||
}
|
||||
@@ -1,271 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { CopyOutlined, DeleteOutlined, EditOutlined, EyeOutlined, PlusOutlined, ReloadOutlined, SearchOutlined } from "@ant-design/icons";
|
||||
import { ProTable, type ProColumns } from "@ant-design/pro-components";
|
||||
import { Button, Card, Col, Flex, Form, Image, Input, Modal, Row, Select, Space, Tag, Tooltip, Typography } from "antd";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { useCopyText } from "@/hooks/use-copy-text";
|
||||
import type { AdminAsset } from "@/services/api/admin";
|
||||
import { useAdminAssets } from "./use-admin-assets";
|
||||
|
||||
type AssetFormValues = Partial<AdminAsset> & { tagText?: string };
|
||||
|
||||
const typeOptions = [
|
||||
{ label: "全部类型", value: "" },
|
||||
{ label: "文本", value: "text" },
|
||||
{ label: "图片", value: "image" },
|
||||
];
|
||||
|
||||
const editTypeOptions = typeOptions.slice(1);
|
||||
|
||||
export default function AdminAssetsPage() {
|
||||
const { assets, tags, keyword, kind, tag, page, pageSize, total, isLoading, searchAssets, changeKind, changeTag, changePage, changePageSize, resetFilters, refreshAssets, saveAsset: saveAdminAsset, deleteAsset } = useAdminAssets();
|
||||
const copyText = useCopyText();
|
||||
const [form] = Form.useForm<AssetFormValues>();
|
||||
const [keywordText, setKeywordText] = useState(keyword);
|
||||
const [editingAsset, setEditingAsset] = useState<Partial<AdminAsset> | null>(null);
|
||||
const [detailAsset, setDetailAsset] = useState<AdminAsset | null>(null);
|
||||
const [deletingAsset, setDeletingAsset] = useState<AdminAsset | null>(null);
|
||||
const formType = Form.useWatch("type", form) || editingAsset?.type || "text";
|
||||
const tagOptions = tags.map((item) => ({ label: item, value: item }));
|
||||
|
||||
useEffect(() => {
|
||||
if (editingAsset) form.setFieldsValue({ ...editingAsset, tagText: editingAsset.tags?.join(", ") || "" });
|
||||
}, [editingAsset, form]);
|
||||
|
||||
useEffect(() => setKeywordText(keyword), [keyword]);
|
||||
|
||||
const saveAsset = async () => {
|
||||
const value = await form.validateFields();
|
||||
const nextType = value.type || "text";
|
||||
await saveAdminAsset({
|
||||
...editingAsset,
|
||||
...value,
|
||||
type: nextType,
|
||||
coverUrl: value.coverUrl || (nextType === "image" ? value.url : ""),
|
||||
tags: (value.tagText || "")
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean),
|
||||
});
|
||||
setEditingAsset(null);
|
||||
};
|
||||
|
||||
const columns: ProColumns<AdminAsset>[] = [
|
||||
{
|
||||
title: "封面",
|
||||
dataIndex: "coverUrl",
|
||||
width: 88,
|
||||
render: (_, item) => <Image src={item.coverUrl || item.url || "/logo.svg"} alt={item.title} width={56} height={42} style={{ objectFit: "cover", borderRadius: 6 }} preview={{ mask: "放大" }} fallback="/logo.svg" />,
|
||||
},
|
||||
{
|
||||
title: "标题",
|
||||
dataIndex: "title",
|
||||
width: 260,
|
||||
render: (_, item) => (
|
||||
<Typography.Link strong ellipsis style={{ maxWidth: 260, display: "block" }} onClick={() => setDetailAsset(item)}>
|
||||
{item.title}
|
||||
</Typography.Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "类型",
|
||||
dataIndex: "type",
|
||||
width: 84,
|
||||
render: (_, item) => <Tag>{item.type === "image" ? "图片" : "文本"}</Tag>,
|
||||
},
|
||||
{
|
||||
title: "标签",
|
||||
dataIndex: "tags",
|
||||
width: 180,
|
||||
render: (_, item) => (
|
||||
<Space size={[4, 4]} wrap>
|
||||
{(item.tags || []).slice(0, 3).map((tag) => (
|
||||
<Tag key={tag}>{tag}</Tag>
|
||||
))}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "分类",
|
||||
dataIndex: "category",
|
||||
width: 120,
|
||||
render: (_, item) => <Typography.Text type="secondary">{item.category || "未标注"}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
key: "actions",
|
||||
width: 112,
|
||||
align: "right",
|
||||
render: (_, item) => (
|
||||
<Space size={4}>
|
||||
<Tooltip title="详情">
|
||||
<Button type="text" size="small" icon={<EyeOutlined />} onClick={() => setDetailAsset(item)} />
|
||||
</Tooltip>
|
||||
<Tooltip title="编辑">
|
||||
<Button type="text" size="small" icon={<EditOutlined />} onClick={() => setEditingAsset(item)} />
|
||||
</Tooltip>
|
||||
<Tooltip title="删除">
|
||||
<Button danger type="text" size="small" icon={<DeleteOutlined />} onClick={() => setDeletingAsset(item)} />
|
||||
</Tooltip>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<main style={{ padding: 24 }}>
|
||||
<Flex vertical gap={16}>
|
||||
<Card variant="borderless">
|
||||
<Form layout="vertical">
|
||||
<Row gutter={16} align="bottom">
|
||||
<Col flex="360px">
|
||||
<Form.Item label="关键词">
|
||||
<Input.Search value={keywordText} placeholder="搜索标题、内容或标签" allowClear enterButton={<SearchOutlined />} onSearch={() => searchAssets(keywordText)} onChange={(event) => setKeywordText(event.target.value)} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col flex="180px">
|
||||
<Form.Item label="类型">
|
||||
<Select value={kind} onChange={changeKind} options={typeOptions} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col flex="220px">
|
||||
<Form.Item label="标签">
|
||||
<Select mode="multiple" allowClear maxTagCount="responsive" value={tag} onChange={changeTag} options={tagOptions} placeholder="全部标签" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col flex="none">
|
||||
<Form.Item>
|
||||
<Space>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setKeywordText("");
|
||||
resetFilters();
|
||||
}}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
<Button type="primary" icon={<ReloadOutlined />} onClick={() => searchAssets(keywordText)}>
|
||||
查询
|
||||
</Button>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Form>
|
||||
</Card>
|
||||
<ProTable<AdminAsset>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={assets}
|
||||
loading={isLoading}
|
||||
search={false}
|
||||
defaultSize="middle"
|
||||
tableLayout="fixed"
|
||||
cardProps={{ variant: "borderless" }}
|
||||
headerTitle={
|
||||
<Space>
|
||||
<Typography.Text strong>素材列表</Typography.Text>
|
||||
<Tag>{total} 条</Tag>
|
||||
</Space>
|
||||
}
|
||||
options={{ density: true, setting: true, reload: () => void refreshAssets() }}
|
||||
toolBarRender={() => [
|
||||
<Button key="add" type="primary" icon={<PlusOutlined />} onClick={() => setEditingAsset({ type: "text", tags: [] })}>
|
||||
新增
|
||||
</Button>,
|
||||
]}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [10, 20, 50, 100],
|
||||
showTotal: (value) => `共 ${value} 条`,
|
||||
onChange: (nextPage, nextPageSize) => (nextPageSize !== pageSize ? changePageSize(nextPageSize) : changePage(nextPage)),
|
||||
}}
|
||||
/>
|
||||
</Flex>
|
||||
|
||||
<Modal title={editingAsset?.id ? "编辑素材" : "新增素材"} open={Boolean(editingAsset)} width={760} onCancel={() => setEditingAsset(null)} onOk={() => void saveAsset()} okText="保存" cancelText="取消" destroyOnHidden>
|
||||
<Form form={form} layout="vertical" requiredMark={false}>
|
||||
<Form.Item name="type" label="类型" rules={[{ required: true, message: "请选择类型" }]}>
|
||||
<Select options={editTypeOptions} />
|
||||
</Form.Item>
|
||||
<Form.Item name="title" label="标题" rules={[{ required: true, message: "请输入标题" }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="coverUrl" label="封面 URL">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="tagText" label="标签,用逗号分隔">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="category" label="分类">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="描述">
|
||||
<Input.TextArea rows={3} />
|
||||
</Form.Item>
|
||||
{formType === "image" ? (
|
||||
<Form.Item name="url" label="图片 URL" rules={[{ required: true, message: "请输入图片 URL" }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
) : (
|
||||
<Form.Item name="content" label="文本内容" rules={[{ required: true, message: "请输入文本内容" }]}>
|
||||
<Input.TextArea rows={6} />
|
||||
</Form.Item>
|
||||
)}
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal title="素材详情" open={Boolean(detailAsset)} width={760} onCancel={() => setDetailAsset(null)} footer={<Button onClick={() => setDetailAsset(null)}>关闭</Button>}>
|
||||
{detailAsset ? (
|
||||
<Flex vertical gap={14}>
|
||||
<Flex gap={14} align="start">
|
||||
<Image src={detailAsset.coverUrl || detailAsset.url || "/logo.svg"} alt={detailAsset.title} width={116} height={84} style={{ objectFit: "cover", borderRadius: 8 }} preview={{ mask: "放大" }} fallback="/logo.svg" />
|
||||
<Flex vertical gap={8} style={{ minWidth: 0 }}>
|
||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
||||
{detailAsset.title}
|
||||
</Typography.Title>
|
||||
<Space wrap>
|
||||
<Tag>{detailAsset.type === "image" ? "图片" : "文本"}</Tag>
|
||||
{detailAsset.category ? <Tag>{detailAsset.category}</Tag> : null}
|
||||
{(detailAsset.tags || []).map((tag) => (
|
||||
<Tag key={tag}>{tag}</Tag>
|
||||
))}
|
||||
</Space>
|
||||
</Flex>
|
||||
</Flex>
|
||||
{detailAsset.description ? (
|
||||
<Typography.Paragraph type="secondary" style={{ margin: 0 }}>
|
||||
{detailAsset.description}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
<Input.TextArea value={detailAsset.type === "image" ? detailAsset.url || detailAsset.coverUrl : detailAsset.content} rows={7} readOnly />
|
||||
<Button icon={<CopyOutlined />} onClick={() => copyText(detailAsset.type === "image" ? detailAsset.url || detailAsset.coverUrl : detailAsset.content)}>
|
||||
复制内容
|
||||
</Button>
|
||||
</Flex>
|
||||
) : null}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="删除素材"
|
||||
open={Boolean(deletingAsset)}
|
||||
onCancel={() => setDeletingAsset(null)}
|
||||
onOk={async () => {
|
||||
if (!deletingAsset) return;
|
||||
await deleteAsset(deletingAsset.id);
|
||||
setDeletingAsset(null);
|
||||
}}
|
||||
okText="删除"
|
||||
okButtonProps={{ danger: true }}
|
||||
cancelText="取消"
|
||||
>
|
||||
确定删除「{deletingAsset?.title}」吗?删除后会从服务器素材库中移除。
|
||||
</Modal>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { App } from "antd";
|
||||
|
||||
import { deleteAdminAsset, fetchAdminAssets, saveAdminAsset, type AdminAsset } from "@/services/api/admin";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
|
||||
const defaultPageSize = 10;
|
||||
|
||||
export function useAdminAssets() {
|
||||
const { message } = App.useApp();
|
||||
const queryClient = useQueryClient();
|
||||
const token = useUserStore((state) => state.token);
|
||||
const clearSession = useUserStore((state) => state.clearSession);
|
||||
const [keyword, setKeyword] = useState("");
|
||||
const [type, setType] = useState("");
|
||||
const [tag, setTag] = useState<string[]>([]);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ["admin", "assets", token, keyword, type, tag, page, pageSize],
|
||||
queryFn: () => fetchAdminAssets(token, { keyword, type, tag, page, pageSize }),
|
||||
enabled: Boolean(token),
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (asset: Partial<AdminAsset>) => saveAdminAsset(token, asset),
|
||||
onSuccess: async (_, asset) => {
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "assets"] });
|
||||
message.success(asset.id ? "素材已保存" : "素材已新增");
|
||||
},
|
||||
onError: (error) => {
|
||||
message.error(error instanceof Error ? error.message : "保存失败");
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deleteAdminAsset(token, id),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "assets"] });
|
||||
message.success("素材已删除");
|
||||
},
|
||||
onError: (error) => {
|
||||
message.error(error instanceof Error ? error.message : "删除失败");
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (query.isError) {
|
||||
const errorMessage = query.error instanceof Error ? query.error.message : "读取素材失败";
|
||||
message.error(errorMessage);
|
||||
if (errorMessage.includes("未登录") || errorMessage.includes("权限不足") || errorMessage.includes("登录状态无效")) clearSession();
|
||||
}
|
||||
}, [clearSession, message, query.error, query.isError]);
|
||||
|
||||
const updateFilters = (next: Partial<{ keyword: string; type: string; tag: string[]; page: number; pageSize: number }>) => {
|
||||
const queryState = { keyword, type, tag, page, pageSize, ...next };
|
||||
if (next.keyword !== undefined || next.type !== undefined || next.tag !== undefined || next.pageSize !== undefined) queryState.page = 1;
|
||||
setKeyword(queryState.keyword);
|
||||
setType(queryState.type);
|
||||
setTag(queryState.tag);
|
||||
setPage(queryState.page);
|
||||
setPageSize(queryState.pageSize);
|
||||
};
|
||||
|
||||
const data = query.data;
|
||||
|
||||
return {
|
||||
assets: data?.items || [],
|
||||
tags: data?.tags || [],
|
||||
keyword,
|
||||
kind: type,
|
||||
tag,
|
||||
page,
|
||||
pageSize,
|
||||
total: data?.total || 0,
|
||||
isLoading: query.isFetching || saveMutation.isPending || deleteMutation.isPending,
|
||||
searchAssets: (value = keyword) => updateFilters({ keyword: value }),
|
||||
changeKind: (value: string) => updateFilters({ type: value, tag: [] }),
|
||||
changeTag: (value: string[]) => updateFilters({ tag: value }),
|
||||
changePage: (value: number) => updateFilters({ page: value }),
|
||||
changePageSize: (value: number) => updateFilters({ pageSize: value }),
|
||||
resetFilters: () => updateFilters({ keyword: "", type: "", tag: [], page: 1, pageSize: defaultPageSize }),
|
||||
refreshAssets: () => query.refetch(),
|
||||
saveAsset: (asset: Partial<AdminAsset>) => saveMutation.mutateAsync(asset),
|
||||
deleteAsset: (id: string) => deleteMutation.mutateAsync(id),
|
||||
};
|
||||
}
|
||||
@@ -1,221 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { DeleteOutlined, EditOutlined, PlusOutlined, ReloadOutlined, SearchOutlined } from "@ant-design/icons";
|
||||
import { ProTable, type ProColumns } from "@ant-design/pro-components";
|
||||
import { Button, Card, Col, Form, Input, InputNumber, Modal, Row, Space, Tag, Tooltip, Typography } from "antd";
|
||||
import dayjs from "dayjs";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import type { AdminCreditLog } from "@/services/api/admin";
|
||||
import { useAdminCreditLogs } from "./use-admin-credit-logs";
|
||||
|
||||
type CreditLogFormValues = Partial<AdminCreditLog>;
|
||||
|
||||
const creditLogTypeLabels: Record<string, string> = {
|
||||
admin_adjust: "后台调整",
|
||||
ai_consume: "模型消费",
|
||||
ai_refund: "失败返还",
|
||||
};
|
||||
|
||||
export default function AdminCreditLogsPage() {
|
||||
const { logs, keyword, page, pageSize, total, isLoading, searchLogs, changePage, changePageSize, resetFilters, refreshLogs, saveLog: saveAdminLog, deleteLog } = useAdminCreditLogs();
|
||||
const [form] = Form.useForm<CreditLogFormValues>();
|
||||
const [keywordText, setKeywordText] = useState(keyword);
|
||||
const [editingLog, setEditingLog] = useState<Partial<AdminCreditLog> | null>(null);
|
||||
const [deletingLog, setDeletingLog] = useState<AdminCreditLog | null>(null);
|
||||
|
||||
useEffect(() => setKeywordText(keyword), [keyword]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editingLog) form.setFieldsValue({ type: "admin_adjust", amount: 0, balance: 0, ...editingLog });
|
||||
}, [editingLog, form]);
|
||||
|
||||
const saveLog = async () => {
|
||||
const value = await form.validateFields();
|
||||
await saveAdminLog({ ...editingLog, ...value });
|
||||
setEditingLog(null);
|
||||
};
|
||||
|
||||
const columns: ProColumns<AdminCreditLog>[] = [
|
||||
{
|
||||
title: "用户 ID",
|
||||
dataIndex: "userId",
|
||||
width: 220,
|
||||
render: (_, item) => <Typography.Text copyable>{item.userId}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: "类型",
|
||||
dataIndex: "type",
|
||||
width: 140,
|
||||
render: (_, item) => <Tag>{creditLogTypeLabels[item.type] || item.type || "-"}</Tag>,
|
||||
},
|
||||
{
|
||||
title: "变动",
|
||||
dataIndex: "amount",
|
||||
width: 100,
|
||||
render: (_, item) => <Typography.Text type={item.amount >= 0 ? "success" : "danger"}>{item.amount}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: "余额",
|
||||
dataIndex: "balance",
|
||||
width: 100,
|
||||
},
|
||||
{
|
||||
title: "备注",
|
||||
dataIndex: "remark",
|
||||
ellipsis: true,
|
||||
render: (_, item) => <Typography.Text type="secondary">{item.remark || "-"}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: "创建时间",
|
||||
dataIndex: "createdAt",
|
||||
width: 180,
|
||||
render: (_, item) => <Typography.Text type="secondary">{item.createdAt ? dayjs(item.createdAt).format("YYYY-MM-DD HH:mm:ss") : "-"}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
key: "actions",
|
||||
width: 96,
|
||||
align: "right",
|
||||
render: (_, item) => (
|
||||
<Space size={4}>
|
||||
<Tooltip title="编辑">
|
||||
<Button type="text" size="small" icon={<EditOutlined />} onClick={() => setEditingLog(item)} />
|
||||
</Tooltip>
|
||||
<Tooltip title="删除">
|
||||
<Button danger type="text" size="small" icon={<DeleteOutlined />} onClick={() => setDeletingLog(item)} />
|
||||
</Tooltip>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<main style={{ padding: 24 }}>
|
||||
<Space direction="vertical" size={16} style={{ width: "100%" }}>
|
||||
<Card variant="borderless">
|
||||
<Form layout="vertical">
|
||||
<Row gutter={16} align="bottom">
|
||||
<Col flex="360px">
|
||||
<Form.Item label="关键词">
|
||||
<Input.Search value={keywordText} placeholder="搜索用户 ID、类型、备注或关联 ID" allowClear enterButton={<SearchOutlined />} onSearch={() => searchLogs(keywordText)} onChange={(event) => setKeywordText(event.target.value)} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col flex="none">
|
||||
<Form.Item>
|
||||
<Space>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setKeywordText("");
|
||||
resetFilters();
|
||||
}}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
<Button type="primary" icon={<ReloadOutlined />} onClick={() => searchLogs(keywordText)}>
|
||||
查询
|
||||
</Button>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Form>
|
||||
</Card>
|
||||
<ProTable<AdminCreditLog>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={logs}
|
||||
loading={isLoading}
|
||||
search={false}
|
||||
defaultSize="middle"
|
||||
tableLayout="fixed"
|
||||
cardProps={{ variant: "borderless" }}
|
||||
headerTitle={
|
||||
<Space>
|
||||
<Typography.Text strong>算力点日志</Typography.Text>
|
||||
<Tag>{total} 条</Tag>
|
||||
</Space>
|
||||
}
|
||||
options={{ density: true, setting: true, reload: () => void refreshLogs() }}
|
||||
toolBarRender={() => [
|
||||
<Button key="add" type="primary" icon={<PlusOutlined />} onClick={() => setEditingLog({ type: "admin_adjust", amount: 0, balance: 0 })}>
|
||||
新增
|
||||
</Button>,
|
||||
]}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [10, 20, 50, 100],
|
||||
showTotal: (value) => `共 ${value} 条`,
|
||||
onChange: (nextPage, nextPageSize) => (nextPageSize !== pageSize ? changePageSize(nextPageSize) : changePage(nextPage)),
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
|
||||
<Modal title={editingLog?.id ? "编辑日志" : "新增日志"} open={Boolean(editingLog)} width={680} onCancel={() => setEditingLog(null)} onOk={() => void saveLog()} okText="保存" cancelText="取消" destroyOnHidden>
|
||||
<Form form={form} layout="vertical" requiredMark={false}>
|
||||
<Row gutter={14}>
|
||||
<Col span={12}>
|
||||
<Form.Item name="userId" label="用户 ID" rules={[{ required: true, message: "请输入用户 ID" }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="type" label="类型" rules={[{ required: true, message: "请输入类型" }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="amount" label="变动数量" rules={[{ required: true, message: "请输入变动数量" }]}>
|
||||
<InputNumber precision={0} style={{ width: "100%" }} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="balance" label="变动后余额" rules={[{ required: true, message: "请输入变动后余额" }]}>
|
||||
<InputNumber min={0} precision={0} style={{ width: "100%" }} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="relatedId" label="关联 ID">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="createdAt" label="创建时间">
|
||||
<Input placeholder="不填则新增时自动生成" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={24}>
|
||||
<Form.Item name="remark" label="备注">
|
||||
<Input.TextArea rows={3} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={24}>
|
||||
<Form.Item name="extra" label="扩展信息">
|
||||
<Input.TextArea rows={3} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="删除日志"
|
||||
open={Boolean(deletingLog)}
|
||||
onCancel={() => setDeletingLog(null)}
|
||||
onOk={async () => {
|
||||
if (!deletingLog) return;
|
||||
await deleteLog(deletingLog.id);
|
||||
setDeletingLog(null);
|
||||
}}
|
||||
okText="删除"
|
||||
okButtonProps={{ danger: true }}
|
||||
cancelText="取消"
|
||||
>
|
||||
确定删除这条算力点日志吗?
|
||||
</Modal>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { App } from "antd";
|
||||
|
||||
import { deleteAdminCreditLog, fetchAdminCreditLogs, saveAdminCreditLog, type AdminCreditLog } from "@/services/api/admin";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
|
||||
const defaultPageSize = 10;
|
||||
|
||||
export function useAdminCreditLogs() {
|
||||
const { message } = App.useApp();
|
||||
const queryClient = useQueryClient();
|
||||
const token = useUserStore((state) => state.token);
|
||||
const clearSession = useUserStore((state) => state.clearSession);
|
||||
const [keyword, setKeyword] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ["admin", "credit-logs", token, keyword, page, pageSize],
|
||||
queryFn: () => fetchAdminCreditLogs(token, { keyword, page, pageSize }),
|
||||
enabled: Boolean(token),
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (log: Partial<AdminCreditLog>) => saveAdminCreditLog(token, log),
|
||||
onSuccess: async (_, log) => {
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "credit-logs"] });
|
||||
message.success(log.id ? "日志已保存" : "日志已新增");
|
||||
},
|
||||
onError: (error) => message.error(error instanceof Error ? error.message : "保存失败"),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deleteAdminCreditLog(token, id),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "credit-logs"] });
|
||||
message.success("日志已删除");
|
||||
},
|
||||
onError: (error) => message.error(error instanceof Error ? error.message : "删除失败"),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (query.isError) {
|
||||
const errorMessage = query.error instanceof Error ? query.error.message : "读取日志失败";
|
||||
message.error(errorMessage);
|
||||
if (errorMessage.includes("未登录") || errorMessage.includes("权限不足") || errorMessage.includes("登录状态无效")) clearSession();
|
||||
}
|
||||
}, [clearSession, message, query.error, query.isError]);
|
||||
|
||||
const updateFilters = (next: Partial<{ keyword: string; page: number; pageSize: number }>) => {
|
||||
const queryState = { keyword, page, pageSize, ...next };
|
||||
if (next.keyword !== undefined || next.pageSize !== undefined) queryState.page = 1;
|
||||
setKeyword(queryState.keyword);
|
||||
setPage(queryState.page);
|
||||
setPageSize(queryState.pageSize);
|
||||
};
|
||||
|
||||
const data = query.data;
|
||||
|
||||
return {
|
||||
logs: data?.items || [],
|
||||
keyword,
|
||||
page,
|
||||
pageSize,
|
||||
total: data?.total || 0,
|
||||
isLoading: query.isFetching || saveMutation.isPending || deleteMutation.isPending,
|
||||
searchLogs: (value = keyword) => updateFilters({ keyword: value }),
|
||||
changePage: (value: number) => updateFilters({ page: value }),
|
||||
changePageSize: (value: number) => updateFilters({ pageSize: value }),
|
||||
resetFilters: () => updateFilters({ keyword: "", page: 1, pageSize: defaultPageSize }),
|
||||
refreshLogs: () => query.refetch(),
|
||||
saveLog: (log: Partial<AdminCreditLog>) => saveMutation.mutateAsync(log),
|
||||
deleteLog: (id: string) => deleteMutation.mutateAsync(id),
|
||||
};
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { FileTextOutlined, HomeOutlined, LogoutOutlined, PictureOutlined, SettingOutlined, TransactionOutlined, UserOutlined } from "@ant-design/icons";
|
||||
import { Button, Flex, Layout, Menu, Typography, theme } from "antd";
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import type { ReactNode } from "react";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { UserStatusActions } from "@/components/layout/user-status-actions";
|
||||
import { adminLayoutStyle } from "@/lib/app-theme";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
|
||||
const adminMenus = [
|
||||
{ key: "/admin/users", icon: <UserOutlined />, label: "用户管理" },
|
||||
{ key: "/admin/credit-logs", icon: <TransactionOutlined />, label: "算力点日志" },
|
||||
{ key: "/admin/prompts", icon: <FileTextOutlined />, label: "提示词管理" },
|
||||
{ key: "/admin/assets", icon: <PictureOutlined />, label: "素材库" },
|
||||
{ key: "/admin/settings", icon: <SettingOutlined />, label: "系统设置" },
|
||||
];
|
||||
|
||||
export default function AdminLayout({ children }: { children: ReactNode }) {
|
||||
const { token: antToken } = theme.useToken();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const token = useUserStore((state) => state.token);
|
||||
const user = useUserStore((state) => state.user);
|
||||
const isReady = useUserStore((state) => state.isReady);
|
||||
const logout = useUserStore((state) => state.clearSession);
|
||||
const activeKey = pathname.startsWith("/admin/settings")
|
||||
? "/admin/settings"
|
||||
: pathname.startsWith("/admin/assets")
|
||||
? "/admin/assets"
|
||||
: pathname.startsWith("/admin/prompts")
|
||||
? "/admin/prompts"
|
||||
: pathname.startsWith("/admin/credit-logs")
|
||||
? "/admin/credit-logs"
|
||||
: pathname.startsWith("/admin/users")
|
||||
? "/admin/users"
|
||||
: "";
|
||||
const pageTitle = pathname.startsWith("/admin/settings") ? "系统设置" : pathname.startsWith("/admin/assets") ? "素材库管理" : pathname.startsWith("/admin/prompts") ? "提示词管理" : pathname.startsWith("/admin/credit-logs") ? "算力点日志" : "用户管理";
|
||||
|
||||
useEffect(() => {
|
||||
if (!isReady) return;
|
||||
if (!token) {
|
||||
router.replace("/login?redirect=/admin");
|
||||
return;
|
||||
}
|
||||
if (user?.role !== "admin") {
|
||||
router.replace("/");
|
||||
}
|
||||
}, [isReady, router, token, user?.role]);
|
||||
|
||||
if (!isReady || !token || user?.role !== "admin") {
|
||||
return (
|
||||
<div style={{ display: "flex", minHeight: "100vh", alignItems: "center", justifyContent: "center", background: antToken.colorBgLayout }}>
|
||||
<span />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout hasSider style={{ height: "100vh", overflow: "hidden", background: antToken.colorBgLayout }}>
|
||||
<Layout.Sider width={adminLayoutStyle.siderWidth} style={{ height: "100vh", overflow: "hidden", background: antToken.colorBgContainer, borderRight: `1px solid ${antToken.colorBorder}` }}>
|
||||
<Flex align="center" gap={12} style={{ height: adminLayoutStyle.brandHeight, padding: "0 20px", borderBottom: `1px solid ${antToken.colorBorderSecondary}` }}>
|
||||
<span aria-hidden style={{ display: "inline-block", width: 30, height: 30, background: antToken.colorText, WebkitMask: "url(/logo.svg) center / contain no-repeat", mask: "url(/logo.svg) center / contain no-repeat" }} />
|
||||
<Typography.Text strong style={{ fontSize: 18, letterSpacing: 0 }}>
|
||||
无限画布
|
||||
</Typography.Text>
|
||||
</Flex>
|
||||
<Menu
|
||||
mode="inline"
|
||||
selectedKeys={[activeKey]}
|
||||
style={adminLayoutStyle.menu}
|
||||
items={adminMenus.map((item) => ({
|
||||
...item,
|
||||
label: (
|
||||
<Link href={item.key} style={{ color: "inherit" }}>
|
||||
{item.label}
|
||||
</Link>
|
||||
),
|
||||
style: adminLayoutStyle.menuItem,
|
||||
}))}
|
||||
/>
|
||||
<Flex vertical gap={8} style={{ position: "absolute", bottom: 0, insetInline: 0, padding: 12, borderTop: `1px solid ${antToken.colorBorder}`, background: antToken.colorBgContainer }}>
|
||||
<Button block icon={<HomeOutlined />} href="/canvas" target="_blank" rel="noreferrer">
|
||||
前往画布
|
||||
</Button>
|
||||
<Button block icon={<LogoutOutlined />} onClick={logout}>
|
||||
退出登录
|
||||
</Button>
|
||||
</Flex>
|
||||
</Layout.Sider>
|
||||
<Layout style={{ background: antToken.colorBgLayout }}>
|
||||
<Layout.Header
|
||||
style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: adminLayoutStyle.headerHeight, padding: "0 24px", background: antToken.colorBgContainer, borderBottom: `1px solid ${antToken.colorBorder}` }}
|
||||
>
|
||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
||||
{pageTitle}
|
||||
</Typography.Title>
|
||||
<Flex align="center" gap={4}>
|
||||
<UserStatusActions showConfig={false} />
|
||||
</Flex>
|
||||
</Layout.Header>
|
||||
<Layout.Content style={{ minHeight: 0, overflow: "auto" }}>{children}</Layout.Content>
|
||||
</Layout>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default function AdminPage() {
|
||||
redirect("/admin/users");
|
||||
}
|
||||
@@ -1,347 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { CopyOutlined, DeleteOutlined, EditOutlined, ExportOutlined, EyeOutlined, PlusOutlined, ReloadOutlined, SearchOutlined, SyncOutlined } from "@ant-design/icons";
|
||||
import { ProTable, type ProColumns } from "@ant-design/pro-components";
|
||||
import { Button, Card, Col, Flex, Form, Image, Input, Modal, Row, Select, Space, Table, Tag, Tooltip, Typography } from "antd";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { useCopyText } from "@/hooks/use-copy-text";
|
||||
import type { Prompt } from "@/services/api/prompts";
|
||||
import { useAdminPrompts } from "./use-admin-prompts";
|
||||
|
||||
export default function AdminPromptsPage() {
|
||||
const {
|
||||
categories,
|
||||
prompts,
|
||||
tags,
|
||||
keyword,
|
||||
category,
|
||||
tag,
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
isLoading,
|
||||
isSyncing,
|
||||
searchPrompts,
|
||||
changeCategory,
|
||||
changeTag,
|
||||
changePage,
|
||||
changePageSize,
|
||||
resetFilters,
|
||||
refreshPrompts,
|
||||
syncCategory,
|
||||
savePrompt: saveAdminPrompt,
|
||||
deletePrompt,
|
||||
deletePrompts,
|
||||
} = useAdminPrompts();
|
||||
const copyText = useCopyText();
|
||||
const [form] = Form.useForm<Partial<Prompt> & { tagText?: string }>();
|
||||
const [keywordText, setKeywordText] = useState(keyword);
|
||||
const [editingPrompt, setEditingPrompt] = useState<Partial<Prompt> | null>(null);
|
||||
const [detailPrompt, setDetailPrompt] = useState<Prompt | null>(null);
|
||||
const [deletingPrompt, setDeletingPrompt] = useState<Prompt | null>(null);
|
||||
const [selectedPromptIds, setSelectedPromptIds] = useState<string[]>([]);
|
||||
const [isBatchDeleteOpen, setIsBatchDeleteOpen] = useState(false);
|
||||
const [isSyncOpen, setIsSyncOpen] = useState(false);
|
||||
const defaultCategory = categories[0]?.category || "";
|
||||
const categoryName = (category: string) => categories.find((item) => item.category === category)?.name || category;
|
||||
const categoryOptions = [{ label: "全部分类", value: "" }, ...categories.map((item) => ({ label: item.name, value: item.category }))];
|
||||
const tagOptions = tags.map((item) => ({ label: item, value: item }));
|
||||
|
||||
useEffect(() => {
|
||||
if (editingPrompt) form.setFieldsValue({ ...editingPrompt, tagText: editingPrompt.tags?.join(", ") || "" });
|
||||
}, [editingPrompt, form]);
|
||||
|
||||
useEffect(() => setKeywordText(keyword), [keyword]);
|
||||
|
||||
const savePrompt = async () => {
|
||||
const value = await form.validateFields();
|
||||
await saveAdminPrompt({
|
||||
...editingPrompt,
|
||||
...value,
|
||||
category: value.category || defaultCategory,
|
||||
tags: (value.tagText || "")
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean),
|
||||
});
|
||||
setEditingPrompt(null);
|
||||
};
|
||||
|
||||
const batchDeletePrompts = async () => {
|
||||
await deletePrompts(selectedPromptIds);
|
||||
setSelectedPromptIds([]);
|
||||
setIsBatchDeleteOpen(false);
|
||||
};
|
||||
|
||||
const columns: ProColumns<Prompt>[] = [
|
||||
{
|
||||
title: "封面",
|
||||
dataIndex: "coverUrl",
|
||||
width: 88,
|
||||
render: (_, item) => <Image src={item.coverUrl || "/logo.svg"} alt={item.title} width={56} height={42} style={{ objectFit: "cover", borderRadius: 6 }} preview={{ mask: "放大" }} fallback="/logo.svg" />,
|
||||
},
|
||||
{
|
||||
title: "标题",
|
||||
dataIndex: "title",
|
||||
width: 260,
|
||||
render: (_, item) => (
|
||||
<Typography.Link strong ellipsis style={{ maxWidth: 260, display: "block" }} onClick={() => setDetailPrompt(item)}>
|
||||
{item.title}
|
||||
</Typography.Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "分类",
|
||||
dataIndex: "category",
|
||||
width: 150,
|
||||
render: (_, item) => <Typography.Text type="secondary">{categoryName(item.category)}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: "标签",
|
||||
dataIndex: "tags",
|
||||
width: 180,
|
||||
render: (_, item) => (
|
||||
<Space size={[4, 4]} wrap>
|
||||
{(item.tags || []).slice(0, 3).map((tag) => (
|
||||
<Tag key={tag}>{tag}</Tag>
|
||||
))}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
key: "actions",
|
||||
width: 112,
|
||||
align: "right",
|
||||
render: (_, item) => (
|
||||
<Space size={4}>
|
||||
<Tooltip title="详情">
|
||||
<Button type="text" size="small" icon={<EyeOutlined />} onClick={() => setDetailPrompt(item)} />
|
||||
</Tooltip>
|
||||
<Tooltip title="编辑">
|
||||
<Button type="text" size="small" icon={<EditOutlined />} onClick={() => setEditingPrompt(item)} />
|
||||
</Tooltip>
|
||||
<Tooltip title="删除">
|
||||
<Button danger type="text" size="small" icon={<DeleteOutlined />} onClick={() => setDeletingPrompt(item)} />
|
||||
</Tooltip>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<main style={{ padding: 24 }}>
|
||||
<Flex vertical gap={16}>
|
||||
<Card variant="borderless">
|
||||
<Form layout="vertical">
|
||||
<Row gutter={16} align="bottom">
|
||||
<Col flex="360px">
|
||||
<Form.Item label="关键词">
|
||||
<Input.Search value={keywordText} placeholder="搜索标题或提示词" allowClear enterButton={<SearchOutlined />} onSearch={() => searchPrompts(keywordText)} onChange={(event) => setKeywordText(event.target.value)} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col flex="220px">
|
||||
<Form.Item label="分组">
|
||||
<Select value={category} onChange={changeCategory} options={categoryOptions} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col flex="220px">
|
||||
<Form.Item label="标签">
|
||||
<Select mode="multiple" allowClear maxTagCount="responsive" value={tag} onChange={changeTag} options={tagOptions} placeholder="全部标签" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col flex="none">
|
||||
<Form.Item>
|
||||
<Space>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setKeywordText("");
|
||||
resetFilters();
|
||||
}}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
<Button type="primary" icon={<ReloadOutlined />} onClick={() => searchPrompts(keywordText)}>
|
||||
查询
|
||||
</Button>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Form>
|
||||
</Card>
|
||||
<ProTable<Prompt>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={prompts}
|
||||
loading={isLoading}
|
||||
search={false}
|
||||
defaultSize="middle"
|
||||
tableLayout="fixed"
|
||||
cardProps={{ variant: "borderless" }}
|
||||
headerTitle={
|
||||
<Space>
|
||||
<Typography.Text strong>提示词列表</Typography.Text>
|
||||
<Tag>{total} 条</Tag>
|
||||
</Space>
|
||||
}
|
||||
options={{ density: true, setting: true, reload: () => void refreshPrompts() }}
|
||||
rowSelection={{ selectedRowKeys: selectedPromptIds, onChange: (keys) => setSelectedPromptIds(keys.map(String)) }}
|
||||
toolBarRender={() => [
|
||||
<Button key="batch-delete" danger icon={<DeleteOutlined />} disabled={!selectedPromptIds.length} onClick={() => setIsBatchDeleteOpen(true)}>
|
||||
批量删除{selectedPromptIds.length ? ` ${selectedPromptIds.length}` : ""}
|
||||
</Button>,
|
||||
<Button key="sync" icon={<SyncOutlined />} onClick={() => setIsSyncOpen(true)}>
|
||||
同步
|
||||
</Button>,
|
||||
<Button key="add" type="primary" icon={<PlusOutlined />} onClick={() => setEditingPrompt({ category: defaultCategory, tags: [] })}>
|
||||
新增
|
||||
</Button>,
|
||||
]}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [10, 20, 50, 100],
|
||||
showTotal: (value) => `共 ${value} 条`,
|
||||
onChange: (nextPage, nextPageSize) => (nextPageSize !== pageSize ? changePageSize(nextPageSize) : changePage(nextPage)),
|
||||
}}
|
||||
/>
|
||||
</Flex>
|
||||
|
||||
<Modal title={editingPrompt?.id ? "编辑提示词" : "新增提示词"} open={Boolean(editingPrompt)} width={720} onCancel={() => setEditingPrompt(null)} onOk={() => void savePrompt()} okText="保存" cancelText="取消" destroyOnHidden>
|
||||
<Form form={form} layout="vertical" requiredMark={false}>
|
||||
<Form.Item name="title" label="标题" rules={[{ required: true, message: "请输入标题" }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="category" label="分类">
|
||||
<Select options={categories.map((item) => ({ label: item.name, value: item.category }))} />
|
||||
</Form.Item>
|
||||
<Form.Item name="coverUrl" label="封面 URL">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="tagText" label="标签,用逗号分隔">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="prompt" label="提示词" rules={[{ required: true, message: "请输入提示词" }]}>
|
||||
<Input.TextArea rows={6} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal title="提示词详情" open={Boolean(detailPrompt)} width={760} onCancel={() => setDetailPrompt(null)} footer={<Button onClick={() => setDetailPrompt(null)}>关闭</Button>}>
|
||||
{detailPrompt ? (
|
||||
<Flex vertical gap={14}>
|
||||
<Flex gap={14} align="start">
|
||||
<Image src={detailPrompt.coverUrl || "/logo.svg"} alt={detailPrompt.title} width={116} height={84} style={{ objectFit: "cover", borderRadius: 8 }} preview={{ mask: "放大" }} fallback="/logo.svg" />
|
||||
<Flex vertical gap={8} style={{ minWidth: 0 }}>
|
||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
||||
{detailPrompt.title}
|
||||
</Typography.Title>
|
||||
<Space wrap>
|
||||
<Tag>{categoryName(detailPrompt.category)}</Tag>
|
||||
{(detailPrompt.tags || []).map((tag) => (
|
||||
<Tag key={tag}>{tag}</Tag>
|
||||
))}
|
||||
</Space>
|
||||
</Flex>
|
||||
</Flex>
|
||||
{detailPrompt.preview ? (
|
||||
<Typography.Paragraph type="secondary" style={{ margin: 0 }}>
|
||||
{detailPrompt.preview}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
<Input.TextArea value={detailPrompt.prompt} rows={8} readOnly />
|
||||
<Space>
|
||||
<Button icon={<CopyOutlined />} onClick={() => copyText(detailPrompt.prompt)}>
|
||||
复制提示词
|
||||
</Button>
|
||||
{detailPrompt.githubUrl ? (
|
||||
<Button icon={<ExportOutlined />} href={detailPrompt.githubUrl} target="_blank">
|
||||
远程源
|
||||
</Button>
|
||||
) : null}
|
||||
</Space>
|
||||
</Flex>
|
||||
) : null}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="同步远程提示词源"
|
||||
open={isSyncOpen}
|
||||
width={640}
|
||||
onCancel={() => !isSyncing && setIsSyncOpen(false)}
|
||||
mask={{ closable: !isSyncing }}
|
||||
footer={
|
||||
<Button disabled={isSyncing} onClick={() => setIsSyncOpen(false)}>
|
||||
取消
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Table
|
||||
rowKey="category"
|
||||
dataSource={categories.filter((item) => item.remote)}
|
||||
pagination={false}
|
||||
columns={[
|
||||
{
|
||||
title: "远程源",
|
||||
dataIndex: "name",
|
||||
render: (_, item) => (
|
||||
<Flex align="center" gap={8}>
|
||||
{item.name}
|
||||
{item.githubUrl ? (
|
||||
<Typography.Link href={item.githubUrl} target="_blank">
|
||||
<ExportOutlined />
|
||||
</Typography.Link>
|
||||
) : null}
|
||||
</Flex>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "",
|
||||
key: "sync",
|
||||
width: 96,
|
||||
align: "right",
|
||||
render: (_, item) => (
|
||||
<Button
|
||||
type="primary"
|
||||
loading={isSyncing}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await syncCategory(item.category);
|
||||
setIsSyncOpen(false);
|
||||
} catch {}
|
||||
}}
|
||||
>
|
||||
同步
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="删除提示词"
|
||||
open={Boolean(deletingPrompt)}
|
||||
onCancel={() => setDeletingPrompt(null)}
|
||||
onOk={async () => {
|
||||
if (!deletingPrompt) return;
|
||||
await deletePrompt(deletingPrompt.id);
|
||||
setDeletingPrompt(null);
|
||||
}}
|
||||
okText="删除"
|
||||
okButtonProps={{ danger: true }}
|
||||
cancelText="取消"
|
||||
>
|
||||
确定删除「{deletingPrompt?.title}」吗?删除后会从当前分类中删除。
|
||||
</Modal>
|
||||
|
||||
<Modal title="批量删除提示词" open={isBatchDeleteOpen} onCancel={() => setIsBatchDeleteOpen(false)} onOk={() => void batchDeletePrompts()} okText="删除" okButtonProps={{ danger: true }} cancelText="取消">
|
||||
确定删除已选中的 {selectedPromptIds.length} 条提示词吗?删除后会从当前分类中删除。
|
||||
</Modal>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { App } from "antd";
|
||||
|
||||
import { deleteAdminPrompt, deleteAdminPrompts, fetchAdminPrompts, fetchAdminPromptCategories, saveAdminPrompt, syncAdminPromptCategory, type AdminPromptCategory } from "@/services/api/admin";
|
||||
import type { Prompt } from "@/services/api/prompts";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
|
||||
const defaultPageSize = 10;
|
||||
|
||||
export function useAdminPrompts() {
|
||||
const { message } = App.useApp();
|
||||
const queryClient = useQueryClient();
|
||||
const token = useUserStore((state) => state.token);
|
||||
const clearSession = useUserStore((state) => state.clearSession);
|
||||
const [keyword, setKeyword] = useState("");
|
||||
const [category, setCategory] = useState("");
|
||||
const [tag, setTag] = useState<string[]>([]);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize);
|
||||
|
||||
const categoriesQuery = useQuery({
|
||||
queryKey: ["admin", "prompt-categories", token],
|
||||
queryFn: () => fetchAdminPromptCategories(token),
|
||||
enabled: Boolean(token),
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const promptsQuery = useQuery({
|
||||
queryKey: ["admin", "prompts", token, keyword, category, tag, page, pageSize],
|
||||
queryFn: () => fetchAdminPrompts(token, { keyword, category, tag, page, pageSize }),
|
||||
enabled: Boolean(token),
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const syncMutation = useMutation({
|
||||
mutationFn: (category: string) => syncAdminPromptCategory(token, category),
|
||||
onSuccess: async (categories) => {
|
||||
queryClient.setQueryData<AdminPromptCategory[]>(["admin", "prompt-categories", token], categories);
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "prompts"] });
|
||||
message.success("远程提示词源已同步");
|
||||
},
|
||||
onError: (error) => {
|
||||
message.error(error instanceof Error ? error.message : "同步失败");
|
||||
},
|
||||
});
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (prompt: Partial<Prompt>) => saveAdminPrompt(token, prompt),
|
||||
onSuccess: async (_, prompt) => {
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "prompt-categories"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "prompts"] });
|
||||
message.success(prompt.id ? "提示词已保存" : "提示词已新增");
|
||||
},
|
||||
onError: (error) => {
|
||||
message.error(error instanceof Error ? error.message : "保存失败");
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deleteAdminPrompt(token, id),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "prompt-categories"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "prompts"] });
|
||||
message.success("提示词已删除");
|
||||
},
|
||||
onError: (error) => {
|
||||
message.error(error instanceof Error ? error.message : "删除失败");
|
||||
},
|
||||
});
|
||||
|
||||
const batchDeleteMutation = useMutation({
|
||||
mutationFn: (ids: string[]) => deleteAdminPrompts(token, ids),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "prompt-categories"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "prompts"] });
|
||||
message.success("提示词已批量删除");
|
||||
},
|
||||
onError: (error) => {
|
||||
message.error(error instanceof Error ? error.message : "批量删除失败");
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const error = categoriesQuery.error || promptsQuery.error;
|
||||
if (!error) return;
|
||||
const errorMessage = error instanceof Error ? error.message : "读取提示词失败";
|
||||
message.error(errorMessage);
|
||||
if (errorMessage.includes("未登录") || errorMessage.includes("权限不足") || errorMessage.includes("登录状态无效")) clearSession();
|
||||
}, [categoriesQuery.error, clearSession, message, promptsQuery.error]);
|
||||
|
||||
const updateFilters = (next: Partial<{ keyword: string; category: string; tag: string[]; page: number; pageSize: number }>) => {
|
||||
const queryState = { keyword, category, tag, page, pageSize, ...next };
|
||||
if (next.keyword !== undefined || next.category !== undefined || next.tag !== undefined || next.pageSize !== undefined) queryState.page = 1;
|
||||
setKeyword(queryState.keyword);
|
||||
setCategory(queryState.category);
|
||||
setTag(queryState.tag);
|
||||
setPage(queryState.page);
|
||||
setPageSize(queryState.pageSize);
|
||||
};
|
||||
|
||||
const data = promptsQuery.data;
|
||||
|
||||
return {
|
||||
categories: categoriesQuery.data || [],
|
||||
prompts: data?.items || [],
|
||||
tags: data?.tags || [],
|
||||
keyword,
|
||||
category,
|
||||
tag,
|
||||
page,
|
||||
pageSize,
|
||||
total: data?.total || 0,
|
||||
isLoading: categoriesQuery.isFetching || promptsQuery.isFetching || saveMutation.isPending || deleteMutation.isPending || batchDeleteMutation.isPending,
|
||||
isSyncing: syncMutation.isPending,
|
||||
syncCategory: (category: string) => syncMutation.mutateAsync(category),
|
||||
searchPrompts: (value = keyword) => updateFilters({ keyword: value }),
|
||||
changeCategory: (value: string) => updateFilters({ category: value, tag: [] }),
|
||||
changeTag: (value: string[]) => updateFilters({ tag: value }),
|
||||
changePage: (value: number) => updateFilters({ page: value }),
|
||||
changePageSize: (value: number) => updateFilters({ pageSize: value }),
|
||||
resetFilters: () => updateFilters({ keyword: "", category: "", tag: [], page: 1, pageSize: defaultPageSize }),
|
||||
refreshPrompts: async () => {
|
||||
await categoriesQuery.refetch();
|
||||
await promptsQuery.refetch();
|
||||
},
|
||||
savePrompt: (prompt: Partial<Prompt>) => saveMutation.mutateAsync(prompt),
|
||||
deletePrompt: (id: string) => deleteMutation.mutateAsync(id),
|
||||
deletePrompts: (ids: string[]) => batchDeleteMutation.mutateAsync(ids),
|
||||
};
|
||||
}
|
||||
@@ -1,980 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { CheckCircleOutlined, DeleteOutlined, FormatPainterOutlined, LoadingOutlined, PlusOutlined, ReloadOutlined, SaveOutlined } from "@ant-design/icons";
|
||||
import { json } from "@codemirror/lang-json";
|
||||
import { App, Button, Card, Checkbox, Col, Drawer, Flex, Form, Input, InputNumber, Modal, Row, Segmented, Select, Space, Switch, Table, Tabs, Tag, Typography } from "antd";
|
||||
import dynamic from "next/dynamic";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { EditorView } from "@uiw/react-codemirror";
|
||||
|
||||
import { fetchAdminSettings, fetchChannelModels, saveAdminSettings, testChannelModel, type AdminModelChannel, type AdminModelCost, type AdminSettings } from "@/services/api/admin";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
|
||||
const CodeMirror = dynamic(() => import("@uiw/react-codemirror"), { ssr: false });
|
||||
const jsonEditorTheme = EditorView.theme({
|
||||
"&": { backgroundColor: "var(--ant-color-bg-container)", color: "var(--ant-color-text)" },
|
||||
".cm-content": { caretColor: "var(--ant-color-text)", padding: "12px 0" },
|
||||
".cm-line": { padding: "0 18px" },
|
||||
".cm-gutters": { backgroundColor: "var(--ant-color-fill-quaternary)", borderRight: "1px solid var(--ant-color-border)", color: "var(--ant-color-text-tertiary)" },
|
||||
".cm-activeLine": { backgroundColor: "var(--ant-color-fill-quaternary)" },
|
||||
".cm-activeLineGutter": { backgroundColor: "var(--ant-color-fill-quaternary)", color: "var(--ant-color-text)" },
|
||||
".cm-cursor": { borderLeftColor: "var(--ant-color-text)" },
|
||||
".cm-selectionBackground, &.cm-focused .cm-selectionBackground": { backgroundColor: "var(--ant-control-item-bg-active)" },
|
||||
".cm-foldPlaceholder": { backgroundColor: "var(--ant-color-fill-quaternary)", border: "1px solid var(--ant-color-border)", color: "var(--ant-color-text-tertiary)" },
|
||||
"&.cm-focused": { outline: "none" },
|
||||
});
|
||||
|
||||
const emptySettings: AdminSettings = {
|
||||
public: {
|
||||
modelChannel: {
|
||||
availableModels: [],
|
||||
modelCosts: [],
|
||||
defaultModel: "",
|
||||
defaultImageModel: "",
|
||||
defaultVideoModel: "",
|
||||
defaultTextModel: "",
|
||||
systemPrompt: "",
|
||||
allowCustomChannel: true,
|
||||
},
|
||||
auth: { allowRegister: true, linuxDo: { enabled: false } },
|
||||
},
|
||||
private: { channels: [], promptSync: { enabled: true, cron: "*/5 * * * *" }, auth: { linuxDo: { clientId: "", clientSecret: "" } } },
|
||||
};
|
||||
const emptyChannel: AdminModelChannel = { protocol: "openai", name: "", baseUrl: "", apiKey: "", models: [], weight: 1, enabled: true, remark: "" };
|
||||
|
||||
type SettingsTabKey = "public" | "private";
|
||||
type EditorMode = "visual" | "json";
|
||||
type ModelSelectTabKey = "new" | "current";
|
||||
|
||||
export default function AdminSettingsPage() {
|
||||
const token = useUserStore((state) => state.token);
|
||||
const { message } = App.useApp();
|
||||
const [form] = Form.useForm<AdminSettings>();
|
||||
const [activeTab, setActiveTab] = useState<SettingsTabKey>("public");
|
||||
const [editorMode, setEditorMode] = useState<Record<SettingsTabKey, EditorMode>>({ public: "visual", private: "visual" });
|
||||
const [jsonText, setJsonText] = useState<Record<SettingsTabKey, string>>({ public: "", private: "" });
|
||||
const [channels, setChannels] = useState<AdminModelChannel[]>([]);
|
||||
const [channelForm] = Form.useForm<AdminModelChannel>();
|
||||
const [editingChannelIndex, setEditingChannelIndex] = useState<number | null>(null);
|
||||
const [isChannelDrawerOpen, setIsChannelDrawerOpen] = useState(false);
|
||||
const [testChannelIndex, setTestChannelIndex] = useState<number | null>(null);
|
||||
const [testKeyword, setTestKeyword] = useState("");
|
||||
const [selectedTestModels, setSelectedTestModels] = useState<string[]>([]);
|
||||
const [testingModels, setTestingModels] = useState<string[]>([]);
|
||||
const [testResults, setTestResults] = useState<Record<string, { status: "success" | "error"; duration?: string; message: string }>>({});
|
||||
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
|
||||
const [modelSelectSource, setModelSelectSource] = useState<string[]>([]);
|
||||
const [modelSelectExisting, setModelSelectExisting] = useState<string[]>([]);
|
||||
const [modelSelectSelected, setModelSelectSelected] = useState<string[]>([]);
|
||||
const [modelSelectKeyword, setModelSelectKeyword] = useState("");
|
||||
const [modelSelectNewModel, setModelSelectNewModel] = useState("");
|
||||
const [modelSelectTab, setModelSelectTab] = useState<ModelSelectTabKey>("new");
|
||||
const [isFetchingChannelModels, setIsFetchingChannelModels] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [modelCosts, setModelCosts] = useState<AdminModelCost[]>([]);
|
||||
const [knownModels, setKnownModels] = useState<string[]>([]);
|
||||
const publicModels = Form.useWatch(["public", "modelChannel", "availableModels"], form) || [];
|
||||
const channelModels = useMemo(() => collectChannelModels(channels), [channels]);
|
||||
const channelTableData = useMemo(() => channels.map((channel, index) => ({ ...channel, _index: index, _rowKey: `${index}-${channel.name}-${channel.baseUrl}` })), [channels]);
|
||||
const activeMode = editorMode[activeTab];
|
||||
const activeJsonText = jsonText[activeTab];
|
||||
const jsonError = activeMode === "json" ? getJsonError(activeJsonText) : "";
|
||||
const modelSelectGroups = useMemo(() => buildModelSelectGroups(modelSelectSource, modelSelectExisting), [modelSelectSource, modelSelectExisting]);
|
||||
const activeModelSelectModels = useMemo(() => {
|
||||
const keyword = modelSelectKeyword.trim().toLowerCase();
|
||||
return modelSelectGroups[modelSelectTab].filter((model) => model.toLowerCase().includes(keyword));
|
||||
}, [modelSelectGroups, modelSelectKeyword, modelSelectTab]);
|
||||
const activeSelectedCount = activeModelSelectModels.filter((model) => modelSelectSelected.includes(model)).length;
|
||||
|
||||
const loadSettings = async () => {
|
||||
if (!token) return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const data = normalizeSettings(await fetchAdminSettings(token));
|
||||
form.setFieldsValue(data);
|
||||
setChannels(data.private.channels);
|
||||
setModelCosts(data.public.modelChannel.modelCosts);
|
||||
setKnownModels(collectKnownModels(data));
|
||||
setJsonText({
|
||||
public: JSON.stringify(data.public, null, 2),
|
||||
private: JSON.stringify(data.private, null, 2),
|
||||
});
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : "读取设置失败");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void loadSettings();
|
||||
}, [token]);
|
||||
|
||||
const changeTab = (nextTab: SettingsTabKey) => {
|
||||
setActiveTab(nextTab);
|
||||
};
|
||||
|
||||
const saveSettings = async () => {
|
||||
if (!token) return;
|
||||
const values = await collectSettings(form, editorMode, jsonText, message);
|
||||
if (!values) {
|
||||
return;
|
||||
}
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const saved = normalizeSettings(await saveAdminSettings(token, values));
|
||||
const merged = mergeChannelApiKeys(values.private.channels, saved);
|
||||
form.setFieldsValue(merged);
|
||||
setChannels(merged.private.channels);
|
||||
setModelCosts(merged.public.modelChannel.modelCosts);
|
||||
rememberKnownModels(merged);
|
||||
setJsonText({
|
||||
public: JSON.stringify(merged.public, null, 2),
|
||||
private: JSON.stringify(merged.private, null, 2),
|
||||
});
|
||||
message.success("已保存");
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : "保存失败");
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleMode = (tab: SettingsTabKey, nextMode: EditorMode) => {
|
||||
if (nextMode === "json") {
|
||||
setJsonText((current) => ({
|
||||
...current,
|
||||
[tab]: JSON.stringify(tab === "public" ? normalizePublicSetting(form.getFieldValue(["public"]) as Partial<AdminSettings["public"]>) : normalizePrivateSetting(form.getFieldValue(["private"]) as Partial<AdminSettings["private"]>), null, 2),
|
||||
}));
|
||||
setEditorMode((current) => ({ ...current, [tab]: nextMode }));
|
||||
return;
|
||||
}
|
||||
const parsed = parseTabJson(tab, jsonText[tab]);
|
||||
if (!parsed) {
|
||||
message.error("JSON 格式不正确");
|
||||
return;
|
||||
}
|
||||
form.setFieldsValue({ [tab]: parsed } as Partial<AdminSettings>);
|
||||
if (tab === "private") setChannels((parsed as AdminSettings["private"]).channels);
|
||||
if (tab === "public") setModelCosts((parsed as AdminSettings["public"]).modelChannel.modelCosts);
|
||||
rememberKnownModels({ ...normalizeSettings(form.getFieldsValue(true) as AdminSettings), [tab]: parsed });
|
||||
setEditorMode((current) => ({ ...current, [tab]: nextMode }));
|
||||
};
|
||||
|
||||
const formatJson = (tab: SettingsTabKey) => {
|
||||
const parsed = parseTabJson(tab, jsonText[tab]);
|
||||
if (!parsed) {
|
||||
message.error("JSON 格式不正确");
|
||||
return;
|
||||
}
|
||||
if (tab === "public") setModelCosts((parsed as AdminSettings["public"]).modelChannel.modelCosts);
|
||||
setJsonText((current) => ({
|
||||
...current,
|
||||
[tab]: JSON.stringify(parsed, null, 2),
|
||||
}));
|
||||
};
|
||||
|
||||
const openChannelDrawer = (index: number | null) => {
|
||||
setEditingChannelIndex(index);
|
||||
setIsChannelDrawerOpen(true);
|
||||
const channel = index === null ? emptyChannel : normalizeChannel(channels[index]);
|
||||
channelForm.setFieldsValue(channel);
|
||||
rememberModels(channel.models);
|
||||
};
|
||||
|
||||
const closeChannelDrawer = () => {
|
||||
setIsChannelDrawerOpen(false);
|
||||
setEditingChannelIndex(null);
|
||||
channelForm.resetFields();
|
||||
};
|
||||
|
||||
const saveChannel = async () => {
|
||||
const channel = normalizeChannel(await channelForm.validateFields());
|
||||
rememberModels(channel.models);
|
||||
const nextChannels = [...channels];
|
||||
if (editingChannelIndex === null) nextChannels.push(channel);
|
||||
else nextChannels[editingChannelIndex] = channel;
|
||||
await persistChannels(nextChannels);
|
||||
closeChannelDrawer();
|
||||
};
|
||||
|
||||
const fetchChannelModelList = async () => {
|
||||
if (!token) return;
|
||||
const channel = channelForm.getFieldsValue();
|
||||
if (!channel?.baseUrl) {
|
||||
message.warning("请先填写接口地址");
|
||||
return;
|
||||
}
|
||||
if (editingChannelIndex === null && !channel?.apiKey) {
|
||||
message.warning("请先填写 API Key");
|
||||
return;
|
||||
}
|
||||
setIsFetchingChannelModels(true);
|
||||
try {
|
||||
const channelModels = await fetchChannelModels(token, { index: editingChannelIndex ?? undefined, channel: normalizeChannel(channel) });
|
||||
const current = isModelSelectorOpen ? uniqueModels(modelSelectSelected) : uniqueModels(channelForm.getFieldValue("models") || []);
|
||||
rememberModels(channelModels);
|
||||
if (!channelModels.length) {
|
||||
message.warning("上游未返回模型列表,请手动输入模型名称");
|
||||
return;
|
||||
}
|
||||
setModelSelectExisting(current);
|
||||
setModelSelectSource(uniqueModels(channelModels));
|
||||
setModelSelectSelected(uniqueModels([...current, ...channelModels]));
|
||||
setModelSelectKeyword("");
|
||||
setModelSelectNewModel("");
|
||||
setModelSelectTab("new");
|
||||
setIsModelSelectorOpen(true);
|
||||
message.success(`已获取 ${channelModels.length} 个模型,请选择后确认`);
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : "读取模型失败");
|
||||
} finally {
|
||||
setIsFetchingChannelModels(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openChannelModelSelector = (sourceModels?: string[]) => {
|
||||
const current = uniqueModels(channelForm.getFieldValue("models") || []);
|
||||
const source = uniqueModels(sourceModels !== undefined ? sourceModels : [...knownModels, ...current]);
|
||||
setModelSelectExisting(current);
|
||||
setModelSelectSource(source);
|
||||
setModelSelectSelected(sourceModels ? uniqueModels([...current, ...source]) : current);
|
||||
setModelSelectKeyword("");
|
||||
setModelSelectNewModel("");
|
||||
setModelSelectTab(sourceModels ? "new" : "current");
|
||||
setIsModelSelectorOpen(true);
|
||||
};
|
||||
|
||||
const closeChannelModelSelector = () => {
|
||||
setIsModelSelectorOpen(false);
|
||||
setModelSelectKeyword("");
|
||||
setModelSelectNewModel("");
|
||||
};
|
||||
|
||||
const confirmChannelModelSelector = () => {
|
||||
const models = uniqueModels(modelSelectSelected);
|
||||
channelForm.setFieldValue("models", models);
|
||||
rememberModels(models);
|
||||
closeChannelModelSelector();
|
||||
};
|
||||
|
||||
const toggleSelectedModel = (model: string, checked: boolean) => {
|
||||
setModelSelectSelected((current) => (checked ? uniqueModels([...current, model]) : current.filter((item) => item !== model)));
|
||||
};
|
||||
|
||||
const selectActiveModels = () => {
|
||||
setModelSelectSelected((current) => uniqueModels([...current, ...activeModelSelectModels]));
|
||||
};
|
||||
|
||||
const clearActiveModels = () => {
|
||||
const active = new Set(activeModelSelectModels);
|
||||
setModelSelectSelected((current) => current.filter((model) => !active.has(model)));
|
||||
};
|
||||
|
||||
const addModelInSelector = () => {
|
||||
const model = modelSelectNewModel.trim();
|
||||
if (!model) return;
|
||||
setModelSelectExisting((current) => uniqueModels([...current, model]));
|
||||
setModelSelectSelected((current) => uniqueModels([...current, model]));
|
||||
setModelSelectNewModel("");
|
||||
setModelSelectTab("current");
|
||||
};
|
||||
|
||||
function rememberModels(models: string[]) {
|
||||
setKnownModels((current) => uniqueModels([...current, ...models]));
|
||||
}
|
||||
|
||||
function rememberKnownModels(settings: AdminSettings) {
|
||||
rememberModels(collectKnownModels(settings));
|
||||
}
|
||||
|
||||
const openTestDialog = (index: number) => {
|
||||
const channel = normalizeChannel(channels[index]);
|
||||
if (!channel.baseUrl || channel.models.length === 0) {
|
||||
message.warning("请先填写接口地址和至少一个模型");
|
||||
return;
|
||||
}
|
||||
setTestChannelIndex(index);
|
||||
setTestKeyword("");
|
||||
setSelectedTestModels([]);
|
||||
setTestingModels([]);
|
||||
setTestResults({});
|
||||
};
|
||||
|
||||
const closeTestDialog = () => {
|
||||
setTestChannelIndex(null);
|
||||
setTestKeyword("");
|
||||
setSelectedTestModels([]);
|
||||
setTestingModels([]);
|
||||
setTestResults({});
|
||||
};
|
||||
|
||||
const testModelOnline = async (model: string) => {
|
||||
if (testChannelIndex === null) return;
|
||||
if (!token) return;
|
||||
const channel = normalizeChannel(channels[testChannelIndex]);
|
||||
setTestingModels((current) => [...current, model]);
|
||||
try {
|
||||
const startedAt = performance.now();
|
||||
const result = await testChannelModel(token, { index: testChannelIndex, channel, model });
|
||||
setTestResults((current) => ({ ...current, [model]: { status: "success", duration: `${((performance.now() - startedAt) / 1000).toFixed(2)}s`, message: result } }));
|
||||
} catch (error) {
|
||||
setTestResults((current) => ({ ...current, [model]: { status: "error", message: error instanceof Error ? error.message : "测试失败" } }));
|
||||
} finally {
|
||||
setTestingModels((current) => current.filter((item) => item !== model));
|
||||
}
|
||||
};
|
||||
|
||||
const batchTestModels = async () => {
|
||||
for (const model of selectedTestModels) {
|
||||
await testModelOnline(model);
|
||||
}
|
||||
};
|
||||
|
||||
const testChannel = testChannelIndex === null ? null : normalizeChannel(channels[testChannelIndex]);
|
||||
const testModels = (testChannel?.models || []).filter((model) => model.toLowerCase().includes(testKeyword.trim().toLowerCase()));
|
||||
|
||||
async function persistChannels(nextChannels: AdminModelChannel[]) {
|
||||
if (!token) return;
|
||||
const values = normalizeSettings(form.getFieldsValue(true) as AdminSettings);
|
||||
const nextChannelModels = collectChannelModels(nextChannels);
|
||||
const nextSettings = normalizeSettings({
|
||||
...values,
|
||||
public: { ...values.public, modelChannel: { ...values.public.modelChannel, availableModels: nextChannelModels } },
|
||||
private: { ...values.private, channels: nextChannels },
|
||||
});
|
||||
const saved = normalizeSettings(await saveAdminSettings(token, nextSettings));
|
||||
const merged = mergeChannelApiKeys(nextChannels, saved);
|
||||
setChannels(merged.private.channels);
|
||||
setModelCosts(merged.public.modelChannel.modelCosts);
|
||||
rememberKnownModels(merged);
|
||||
form.setFieldsValue(merged);
|
||||
setJsonText({
|
||||
public: JSON.stringify(merged.public, null, 2),
|
||||
private: JSON.stringify(merged.private, null, 2),
|
||||
});
|
||||
message.success("已保存");
|
||||
}
|
||||
|
||||
return (
|
||||
<main style={{ padding: 24 }}>
|
||||
<Flex vertical gap={16}>
|
||||
<Card variant="borderless">
|
||||
<Flex justify="space-between" align="center" gap={16} wrap>
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
onChange={(key) => changeTab(key as SettingsTabKey)}
|
||||
items={[
|
||||
{ key: "public", label: "公开配置(对外暴露)" },
|
||||
{ key: "private", label: "私有配置(不会对外暴露)" },
|
||||
]}
|
||||
/>
|
||||
<Space>
|
||||
<Button icon={<ReloadOutlined />} loading={isLoading} onClick={() => void loadSettings()}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button type="primary" icon={<SaveOutlined />} loading={isSaving} onClick={() => void saveSettings()}>
|
||||
保存设置
|
||||
</Button>
|
||||
</Space>
|
||||
</Flex>
|
||||
</Card>
|
||||
|
||||
<Card variant="borderless">
|
||||
<Flex justify="space-between" align="center" gap={16} wrap style={{ marginBottom: 16 }}>
|
||||
<Segmented
|
||||
value={activeMode}
|
||||
onChange={(value) => toggleMode(activeTab, value as EditorMode)}
|
||||
options={[
|
||||
{ label: "可视化编辑", value: "visual" },
|
||||
{ label: "手动编辑 JSON", value: "json" },
|
||||
]}
|
||||
/>
|
||||
{activeMode === "json" ? (
|
||||
<Space>
|
||||
{jsonError ? (
|
||||
<Tag color="error">{jsonError}</Tag>
|
||||
) : (
|
||||
<Tag color="success" icon={<CheckCircleOutlined />}>
|
||||
JSON 格式正确
|
||||
</Tag>
|
||||
)}
|
||||
<Button icon={<FormatPainterOutlined />} onClick={() => formatJson(activeTab)}>
|
||||
格式化
|
||||
</Button>
|
||||
</Space>
|
||||
) : (
|
||||
<Typography.Text type="secondary">{activeTab === "public" ? "这些配置会暴露给前端读取" : "这些配置只会在后台保存"}</Typography.Text>
|
||||
)}
|
||||
</Flex>
|
||||
|
||||
{activeTab === "public" ? (
|
||||
activeMode === "visual" ? (
|
||||
<Form form={form} layout="vertical" initialValues={emptySettings} requiredMark={false}>
|
||||
<Row gutter={16}>
|
||||
<Col span={24}>
|
||||
<Form.Item name={["public", "modelChannel", "availableModels"]} label="系统可用模型(请先在私有配置里配置渠道)" extra="保存设置时会自动合并所有已启用私有渠道的模型,前台模型下拉会读取这里的公开列表">
|
||||
<Select mode="multiple" placeholder="请选择系统可用模型" options={channelModels.map((item) => ({ label: item, value: item }))} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={6}>
|
||||
<Form.Item name={["public", "modelChannel", "defaultModel"]} label="默认模型">
|
||||
<Select showSearch allowClear options={publicModels.map((item) => ({ label: item, value: item }))} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={6}>
|
||||
<Form.Item name={["public", "modelChannel", "defaultImageModel"]} label="默认图片模型">
|
||||
<Select showSearch allowClear options={publicModels.map((item) => ({ label: item, value: item }))} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={6}>
|
||||
<Form.Item name={["public", "modelChannel", "defaultVideoModel"]} label="默认视频模型">
|
||||
<Select showSearch allowClear options={publicModels.map((item) => ({ label: item, value: item }))} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={6}>
|
||||
<Form.Item name={["public", "modelChannel", "defaultTextModel"]} label="默认文本模型">
|
||||
<Select showSearch allowClear options={publicModels.map((item) => ({ label: item, value: item }))} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={24}>
|
||||
<Form.Item name={["public", "modelChannel", "systemPrompt"]} label="系统提示词">
|
||||
<Input.TextArea rows={4} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={24}>
|
||||
<Form.Item name={["public", "modelChannel", "allowCustomChannel"]} label="是否允许用户自定义渠道" extra="开启后,前端可提供走后端渠道和用户自定义 baseUrl 直连两种模式" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={24}>
|
||||
<Form.Item name={["public", "auth", "allowRegister"]} label="是否允许用户注册" extra="关闭后隐藏注册入口,注册接口也会拒绝新用户创建" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={24}>
|
||||
<Typography.Title level={5}>模型算力点</Typography.Title>
|
||||
<Table
|
||||
rowKey="model"
|
||||
pagination={false}
|
||||
size="small"
|
||||
dataSource={publicModels.map((model) => ({ model, credits: modelCostCredits(modelCosts, model) }))}
|
||||
columns={[
|
||||
{ title: "模型", dataIndex: "model" },
|
||||
{
|
||||
title: "每次调用扣除",
|
||||
dataIndex: "credits",
|
||||
width: 220,
|
||||
render: (_, item) => (
|
||||
<InputNumber
|
||||
min={0}
|
||||
step={1}
|
||||
precision={0}
|
||||
className="!w-full"
|
||||
value={item.credits}
|
||||
addonAfter="点"
|
||||
onChange={(value) => setModelCost(form, setModelCosts, item.model, Number(value) || 0)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
</Form>
|
||||
) : (
|
||||
<div style={{ overflow: "hidden", border: "1px solid var(--ant-color-border)", borderRadius: 6 }}>
|
||||
<CodeMirror
|
||||
value={activeJsonText}
|
||||
height="520px"
|
||||
extensions={[json(), jsonEditorTheme]}
|
||||
basicSetup={{ foldGutter: true, lineNumbers: true, highlightActiveLine: true, highlightActiveLineGutter: true }}
|
||||
theme="none"
|
||||
onChange={(value) => setJsonText((current) => ({ ...current, public: value }))}
|
||||
style={{ fontSize: 13 }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
) : activeMode === "visual" ? (
|
||||
<Form form={form} layout="vertical" initialValues={emptySettings} requiredMark={false}>
|
||||
<Flex vertical gap={12}>
|
||||
<Card
|
||||
size="small"
|
||||
title={
|
||||
<Space>
|
||||
<img src="/icons/linuxdo.svg" alt="" width={18} height={18} />
|
||||
Linux.do 登录
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Flex vertical gap={14}>
|
||||
<Typography.Text type="secondary">
|
||||
本项目接口回调地址是 /api/auth/linux-do/callback,请在 Linux.do 应用后台自行拼接站点前缀。
|
||||
<Typography.Link href="https://connect.linux.do" target="_blank" rel="noreferrer">
|
||||
点击此处管理你的 LinuxDO OAuth App
|
||||
</Typography.Link>
|
||||
</Typography.Text>
|
||||
<Row gutter={16}>
|
||||
<Col xs={24} md={6}>
|
||||
<Form.Item name={["public", "auth", "linuxDo", "enabled"]} label="开启 Linux.do 登录" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={9}>
|
||||
<Form.Item name={["private", "auth", "linuxDo", "clientId"]} label="Linux.do Client ID">
|
||||
<Input placeholder="输入 Linux.do OAuth App 的 ID" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={9}>
|
||||
<Form.Item name={["private", "auth", "linuxDo", "clientSecret"]} label="Linux.do Client Secret">
|
||||
<Input.Password placeholder="留空则沿用已保存的密钥" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Flex>
|
||||
</Card>
|
||||
<Card size="small" title="提示词定时同步">
|
||||
<Row gutter={16} align="middle">
|
||||
<Col xs={24} md={8}>
|
||||
<Form.Item name={["private", "promptSync", "enabled"]} label="开启定时同步" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={16}>
|
||||
<Form.Item name={["private", "promptSync", "cron"]} label="Cron 表达式" extra="默认每 5 分钟同步内置 GitHub 远程提示词源">
|
||||
<Input placeholder="*/5 * * * *" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => openChannelDrawer(null)}>
|
||||
新增渠道
|
||||
</Button>
|
||||
<Table
|
||||
rowKey="_rowKey"
|
||||
pagination={false}
|
||||
dataSource={channelTableData}
|
||||
columns={[
|
||||
{ title: "名称", dataIndex: "name", render: (value) => value || "未命名渠道" },
|
||||
{ title: "协议", dataIndex: "protocol", width: 96, render: (value) => <Tag>{value || "openai"}</Tag> },
|
||||
{ title: "状态", dataIndex: "enabled", width: 96, render: (value) => <Tag color={value ? "success" : "default"}>{value ? "已启用" : "已停用"}</Tag> },
|
||||
{
|
||||
title: "模型",
|
||||
dataIndex: "models",
|
||||
render: (value: string[]) => (
|
||||
<Typography.Text ellipsis style={{ maxWidth: 360 }}>
|
||||
{modelSummary(value || [])}
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
{ title: "权重", dataIndex: "weight", width: 88 },
|
||||
{
|
||||
title: "操作",
|
||||
key: "actions",
|
||||
width: 220,
|
||||
align: "right",
|
||||
render: (_, item) => (
|
||||
<Space size={4}>
|
||||
<Button size="small" onClick={() => openTestDialog(item._index)}>
|
||||
测试
|
||||
</Button>
|
||||
<Button size="small" onClick={() => openChannelDrawer(item._index)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
icon={<DeleteOutlined />}
|
||||
onClick={() => {
|
||||
const nextChannels = [...channels];
|
||||
nextChannels.splice(item._index, 1);
|
||||
void persistChannels(nextChannels);
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Flex>
|
||||
</Form>
|
||||
) : (
|
||||
<div style={{ overflow: "hidden", border: "1px solid var(--ant-color-border)", borderRadius: 6 }}>
|
||||
<CodeMirror
|
||||
value={activeJsonText}
|
||||
height="520px"
|
||||
extensions={[json(), jsonEditorTheme]}
|
||||
basicSetup={{ foldGutter: true, lineNumbers: true, highlightActiveLine: true, highlightActiveLineGutter: true }}
|
||||
theme="none"
|
||||
onChange={(value) => setJsonText((current) => ({ ...current, private: value }))}
|
||||
style={{ fontSize: 13 }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
<Drawer
|
||||
title={editingChannelIndex === null ? "新增渠道" : "编辑渠道"}
|
||||
open={isChannelDrawerOpen}
|
||||
size={560}
|
||||
onClose={closeChannelDrawer}
|
||||
extra={
|
||||
<Space>
|
||||
<Button onClick={closeChannelDrawer}>取消</Button>
|
||||
<Button type="primary" onClick={() => void saveChannel()}>
|
||||
保存
|
||||
</Button>
|
||||
</Space>
|
||||
}
|
||||
destroyOnHidden
|
||||
>
|
||||
<Form form={channelForm} layout="vertical" requiredMark={false} initialValues={emptyChannel}>
|
||||
<Row gutter={16}>
|
||||
<Col span={12}>
|
||||
<Form.Item name="name" label="渠道名称" rules={[{ required: true, message: "请输入渠道名称" }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="protocol" label="协议">
|
||||
<Select options={[{ label: "OpenAI", value: "openai" }]} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="weight" label="权重">
|
||||
<InputNumber min={1} step={1} className="!w-full" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="enabled" label="启用" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={24}>
|
||||
<Form.Item name="baseUrl" label="接口地址" rules={[{ required: true, message: "请输入接口地址" }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={24}>
|
||||
<Form.Item name="apiKey" label="API Key" rules={editingChannelIndex === null ? [{ required: true, message: "请输入 API Key" }] : []}>
|
||||
<Input.Password placeholder={editingChannelIndex === null ? "" : "留空则沿用已保存的 API Key"} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={24}>
|
||||
<Form.Item label="渠道可用模型">
|
||||
<Space.Compact style={{ width: "100%" }}>
|
||||
<Form.Item name="models" noStyle>
|
||||
<Select mode="tags" maxTagCount="responsive" tokenSeparators={[",", "\n"]} options={knownModels.map((model) => ({ label: model, value: model }))} />
|
||||
</Form.Item>
|
||||
<Button onClick={() => openChannelModelSelector()}>选择模型</Button>
|
||||
</Space.Compact>
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={24}>
|
||||
<Form.Item name="remark" label="备注">
|
||||
<Input.TextArea rows={3} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Form>
|
||||
</Drawer>
|
||||
<Modal
|
||||
title={
|
||||
<Space size={12}>
|
||||
选择渠道模型
|
||||
<Typography.Text type="secondary">
|
||||
已选择 {modelSelectSelected.length} / {uniqueModels([...modelSelectSource, ...modelSelectExisting]).length}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
}
|
||||
open={isModelSelectorOpen}
|
||||
width={960}
|
||||
onCancel={closeChannelModelSelector}
|
||||
footer={
|
||||
<Space>
|
||||
<Button onClick={closeChannelModelSelector}>取消</Button>
|
||||
<Button type="primary" onClick={confirmChannelModelSelector}>
|
||||
确定
|
||||
</Button>
|
||||
</Space>
|
||||
}
|
||||
destroyOnHidden
|
||||
>
|
||||
<Flex vertical gap={14}>
|
||||
<Flex gap={12} wrap>
|
||||
<Input.Search placeholder="搜索模型" allowClear value={modelSelectKeyword} onChange={(event) => setModelSelectKeyword(event.target.value)} style={{ flex: "1 1 260px" }} />
|
||||
<Space.Compact style={{ flex: "1 1 320px" }}>
|
||||
<Input value={modelSelectNewModel} placeholder="输入模型名称" onChange={(event) => setModelSelectNewModel(event.target.value)} onPressEnter={addModelInSelector} />
|
||||
<Button onClick={addModelInSelector}>增加模型</Button>
|
||||
<Button icon={<ReloadOutlined />} loading={isFetchingChannelModels} onClick={() => void fetchChannelModelList()}>
|
||||
拉取模型列表
|
||||
</Button>
|
||||
</Space.Compact>
|
||||
</Flex>
|
||||
<Typography.Text type="secondary">如果上游不提供 OpenAI /models 模型列表接口,请在这里手动增加模型名称。</Typography.Text>
|
||||
<Tabs
|
||||
activeKey={modelSelectTab}
|
||||
onChange={(key) => setModelSelectTab(key as ModelSelectTabKey)}
|
||||
items={[
|
||||
{ key: "new", label: `新获取的模型 (${modelSelectGroups.new.length})` },
|
||||
{ key: "current", label: `已有的模型 (${modelSelectGroups.current.length})` },
|
||||
]}
|
||||
/>
|
||||
<Flex justify="space-between" align="center" gap={12} wrap>
|
||||
<Typography.Text type="secondary">
|
||||
当前列表已选择 {activeSelectedCount} / {activeModelSelectModels.length}
|
||||
</Typography.Text>
|
||||
<Space size={8}>
|
||||
<Button size="small" disabled={!activeModelSelectModels.length || activeSelectedCount === activeModelSelectModels.length} onClick={selectActiveModels}>
|
||||
全选当前列表
|
||||
</Button>
|
||||
<Button size="small" disabled={!activeSelectedCount} onClick={clearActiveModels}>
|
||||
取消当前列表
|
||||
</Button>
|
||||
</Space>
|
||||
</Flex>
|
||||
<div style={{ maxHeight: 420, overflowY: "auto", borderTop: "1px solid var(--ant-color-border-secondary)", paddingTop: 12 }}>
|
||||
{activeModelSelectModels.length ? (
|
||||
<div style={{ display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))", columnGap: 24, rowGap: 12 }}>
|
||||
{activeModelSelectModels.map((model) => (
|
||||
<Checkbox key={model} checked={modelSelectSelected.includes(model)} onChange={(event) => toggleSelectedModel(model, event.target.checked)}>
|
||||
<Typography.Text style={{ wordBreak: "break-all" }}>{model}</Typography.Text>
|
||||
</Checkbox>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ padding: "48px 0", textAlign: "center" }}>
|
||||
<Typography.Text type="secondary">没有匹配的模型</Typography.Text>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Flex>
|
||||
</Modal>
|
||||
<Modal
|
||||
title={
|
||||
<Space>
|
||||
{testChannel?.name || "渠道"} 渠道的模型测试<Typography.Text type="secondary">共 {testChannel?.models.length || 0} 个模型</Typography.Text>
|
||||
</Space>
|
||||
}
|
||||
open={testChannelIndex !== null}
|
||||
width={920}
|
||||
onCancel={closeTestDialog}
|
||||
footer={
|
||||
<Space>
|
||||
<Button onClick={closeTestDialog}>取消</Button>
|
||||
<Button type="primary" disabled={!selectedTestModels.length || testingModels.length > 0} onClick={() => void batchTestModels()}>
|
||||
批量测试 {selectedTestModels.length} 个模型
|
||||
</Button>
|
||||
</Space>
|
||||
}
|
||||
destroyOnHidden
|
||||
>
|
||||
<Flex vertical gap={12}>
|
||||
<Typography.Text type="secondary">普通文本模型会发送一条 hi;Agent Plan / Seedance 视频模型只做配置格式检查,不会发起视频生成,也不代表模型权限已验证。</Typography.Text>
|
||||
<Input.Search placeholder="搜索模型..." allowClear value={testKeyword} onChange={(event) => setTestKeyword(event.target.value)} />
|
||||
<Table
|
||||
rowKey="model"
|
||||
pagination={false}
|
||||
scroll={{ y: 420 }}
|
||||
dataSource={testModels.map((model) => ({ model }))}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedTestModels,
|
||||
onChange: (keys) => setSelectedTestModels(keys.map(String)),
|
||||
}}
|
||||
columns={[
|
||||
{ title: "模型名称", dataIndex: "model", render: (value) => <Typography.Text strong>{value}</Typography.Text> },
|
||||
{
|
||||
title: "状态",
|
||||
dataIndex: "model",
|
||||
width: 260,
|
||||
render: (value) => {
|
||||
if (testingModels.includes(value)) return <Tag icon={<LoadingOutlined className="animate-spin" />}>测试中</Tag>;
|
||||
const result = testResults[value];
|
||||
if (!result) return <Tag>未开始</Tag>;
|
||||
return result.status === "success" ? (
|
||||
<Space size={6} wrap>
|
||||
<Tag color="success">成功</Tag>
|
||||
<Typography.Text type="secondary">请求时长: {result.duration}</Typography.Text>
|
||||
</Space>
|
||||
) : (
|
||||
<Typography.Text type="danger">{result.message}</Typography.Text>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
key: "actions",
|
||||
width: 120,
|
||||
align: "right",
|
||||
render: (_, item) => (
|
||||
<Button size="small" loading={testingModels.includes(item.model)} onClick={() => void testModelOnline(item.model)}>
|
||||
测试
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Flex>
|
||||
</Modal>
|
||||
</Flex>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeSettings(settings: Partial<AdminSettings> = {}): AdminSettings {
|
||||
const privateSetting = normalizePrivateSetting(settings.private);
|
||||
return {
|
||||
public: {
|
||||
...normalizePublicSetting(settings.public),
|
||||
},
|
||||
private: privateSetting,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePublicSetting(setting: Partial<AdminSettings["public"]> = {}): AdminSettings["public"] {
|
||||
return {
|
||||
...emptySettings.public,
|
||||
modelChannel: {
|
||||
...emptySettings.public.modelChannel,
|
||||
...(setting.modelChannel || {}),
|
||||
availableModels: setting.modelChannel?.availableModels || [],
|
||||
modelCosts: normalizeModelCosts(setting.modelChannel?.modelCosts || []),
|
||||
},
|
||||
auth: {
|
||||
allowRegister: setting.auth?.allowRegister !== false,
|
||||
linuxDo: {
|
||||
enabled: setting.auth?.linuxDo?.enabled === true,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeModelCosts(items: Partial<AdminSettings["public"]["modelChannel"]["modelCosts"][number]>[]) {
|
||||
return items.filter((item) => item.model).map((item) => ({ model: item.model || "", credits: Math.max(0, Number(item.credits) || 0) }));
|
||||
}
|
||||
|
||||
function normalizePrivateSetting(setting: Partial<AdminSettings["private"]> = {}): AdminSettings["private"] {
|
||||
return {
|
||||
channels: (setting.channels || []).map(normalizeChannel),
|
||||
promptSync: {
|
||||
enabled: setting.promptSync?.enabled !== false,
|
||||
cron: setting.promptSync?.cron || "*/5 * * * *",
|
||||
},
|
||||
auth: {
|
||||
linuxDo: {
|
||||
clientId: setting.auth?.linuxDo?.clientId || "",
|
||||
clientSecret: setting.auth?.linuxDo?.clientSecret || "",
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeChannel(item: Partial<AdminModelChannel> = {}): AdminModelChannel {
|
||||
return {
|
||||
protocol: "openai",
|
||||
name: item.name || "",
|
||||
baseUrl: item.baseUrl || "",
|
||||
apiKey: item.apiKey || "",
|
||||
models: item.models || [],
|
||||
weight: Math.max(1, Number(item.weight) || 1),
|
||||
enabled: item.enabled !== false,
|
||||
remark: item.remark || "",
|
||||
};
|
||||
}
|
||||
|
||||
function modelCostCredits(items: AdminSettings["public"]["modelChannel"]["modelCosts"], model: string) {
|
||||
return items.find((item) => item.model === model)?.credits || 0;
|
||||
}
|
||||
|
||||
function setModelCost(form: any, setModelCosts: (items: AdminModelCost[]) => void, model: string, credits: number) {
|
||||
const current = (form.getFieldValue(["public", "modelChannel", "modelCosts"]) || []) as AdminSettings["public"]["modelChannel"]["modelCosts"];
|
||||
const next = current.filter((item) => item.model !== model);
|
||||
next.push({ model, credits: Math.max(0, credits) });
|
||||
form.setFieldValue(["public", "modelChannel", "modelCosts"], next);
|
||||
setModelCosts(next);
|
||||
}
|
||||
|
||||
function mergeChannelApiKeys(currentChannels: AdminModelChannel[], saved: AdminSettings): AdminSettings {
|
||||
const channels = saved.private.channels.map((item, index) => ({
|
||||
...item,
|
||||
apiKey: currentChannels[index]?.apiKey || item.apiKey,
|
||||
}));
|
||||
return {
|
||||
public: saved.public,
|
||||
private: { ...saved.private, channels },
|
||||
};
|
||||
}
|
||||
|
||||
function collectChannelModels(channels: AdminModelChannel[]) {
|
||||
return uniqueModels(channels.filter((channel) => channel.enabled).flatMap((channel) => channel.models || []));
|
||||
}
|
||||
|
||||
function collectKnownModels(settings: AdminSettings) {
|
||||
return uniqueModels([
|
||||
...(settings.public.modelChannel.availableModels || []),
|
||||
...(settings.public.modelChannel.modelCosts || []).map((item) => item.model),
|
||||
...settings.private.channels.flatMap((channel) => channel.models || []),
|
||||
]);
|
||||
}
|
||||
|
||||
function buildModelSelectGroups(sourceModels: string[], existingModels: string[]): Record<ModelSelectTabKey, string[]> {
|
||||
const source = uniqueModels(sourceModels);
|
||||
const existing = uniqueModels(existingModels);
|
||||
const existingSet = new Set(existing);
|
||||
return {
|
||||
new: source.filter((model) => !existingSet.has(model)),
|
||||
current: existing,
|
||||
};
|
||||
}
|
||||
|
||||
function uniqueModels(models: string[]) {
|
||||
return Array.from(new Set(models.filter(Boolean)));
|
||||
}
|
||||
|
||||
function modelSummary(models: string[]) {
|
||||
if (!models.length) return "未配置模型";
|
||||
const preview = models.slice(0, 3).join(", ");
|
||||
return models.length > 3 ? `${models.length} 个模型:${preview}...` : preview;
|
||||
}
|
||||
|
||||
function parseTabJson(tab: "public", value: string): AdminSettings["public"] | null;
|
||||
function parseTabJson(tab: "private", value: string): AdminSettings["private"] | null;
|
||||
function parseTabJson(tab: SettingsTabKey, value: string): AdminSettings[SettingsTabKey] | null;
|
||||
function parseTabJson(tab: SettingsTabKey, value: string): AdminSettings[SettingsTabKey] | null {
|
||||
try {
|
||||
return tab === "public" ? normalizePublicSetting(JSON.parse(value) as Partial<AdminSettings["public"]>) : normalizePrivateSetting(JSON.parse(value) as Partial<AdminSettings["private"]>);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function collectSettings(form: any, editorMode: Record<SettingsTabKey, EditorMode>, jsonText: Record<SettingsTabKey, string>, message: { error: (value: string) => void }) {
|
||||
const values = normalizeSettings(form.getFieldsValue(true) as AdminSettings);
|
||||
if (editorMode.public === "json") {
|
||||
const publicSetting = parseTabJson("public", jsonText.public);
|
||||
if (!publicSetting) {
|
||||
message.error("公开配置 JSON 格式不正确");
|
||||
return null;
|
||||
}
|
||||
values.public = publicSetting;
|
||||
}
|
||||
if (editorMode.private === "json") {
|
||||
const privateSetting = parseTabJson("private", jsonText.private);
|
||||
if (!privateSetting) {
|
||||
message.error("私有配置 JSON 格式不正确");
|
||||
return null;
|
||||
}
|
||||
values.private = privateSetting;
|
||||
}
|
||||
values.public.modelChannel.availableModels = collectChannelModels(values.private.channels);
|
||||
return normalizeSettings(values);
|
||||
}
|
||||
|
||||
function getJsonError(value: string) {
|
||||
try {
|
||||
JSON.parse(value);
|
||||
return "";
|
||||
} catch (error) {
|
||||
return error instanceof Error ? error.message : "JSON 格式不正确";
|
||||
}
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { DeleteOutlined, EditOutlined, PlusOutlined, ReloadOutlined, SearchOutlined } from "@ant-design/icons";
|
||||
import { ProTable, type ProColumns } from "@ant-design/pro-components";
|
||||
import { Avatar, Button, Card, Col, Divider, Flex, Form, Input, InputNumber, Modal, Row, Select, Space, Tag, Tooltip, Typography } from "antd";
|
||||
import dayjs from "dayjs";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import type { AdminUser } from "@/services/api/admin";
|
||||
import { useAdminUsers } from "./use-admin-users";
|
||||
|
||||
type UserFormValues = Partial<AdminUser> & { password?: string };
|
||||
|
||||
const roleOptions = [
|
||||
{ label: "普通用户", value: "user" },
|
||||
{ label: "管理员", value: "admin" },
|
||||
];
|
||||
|
||||
const statusOptions = [
|
||||
{ label: "正常", value: "active" },
|
||||
{ label: "禁用", value: "ban" },
|
||||
];
|
||||
|
||||
export default function AdminUsersPage() {
|
||||
const { users, keyword, page, pageSize, total, isLoading, searchUsers, changePage, changePageSize, resetFilters, refreshUsers, saveUser: saveAdminUser, adjustCredits, deleteUser } = useAdminUsers();
|
||||
const [form] = Form.useForm<UserFormValues>();
|
||||
const [keywordText, setKeywordText] = useState(keyword);
|
||||
const [editingUser, setEditingUser] = useState<Partial<AdminUser> | null>(null);
|
||||
const [deletingUser, setDeletingUser] = useState<AdminUser | null>(null);
|
||||
|
||||
useEffect(() => setKeywordText(keyword), [keyword]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editingUser) form.setFieldsValue({ role: "user", status: "active", ...editingUser, password: "" });
|
||||
}, [editingUser, form]);
|
||||
|
||||
const saveUser = async () => {
|
||||
const value = await form.validateFields();
|
||||
const userValue = { ...value };
|
||||
delete userValue.credits;
|
||||
await saveAdminUser({ ...editingUser, ...userValue, password: value.password || undefined });
|
||||
setEditingUser(null);
|
||||
};
|
||||
|
||||
const saveCredits = async () => {
|
||||
if (!editingUser?.id) return;
|
||||
await adjustCredits(editingUser.id, form.getFieldValue("credits") || 0);
|
||||
};
|
||||
|
||||
const columns: ProColumns<AdminUser>[] = [
|
||||
{
|
||||
title: "用户",
|
||||
dataIndex: "username",
|
||||
width: 260,
|
||||
render: (_, item) => (
|
||||
<Flex align="center" gap={10} style={{ minWidth: 0 }}>
|
||||
<Avatar src={item.avatarUrl || undefined}>{(item.displayName || item.username || "U").slice(0, 1).toUpperCase()}</Avatar>
|
||||
<Flex vertical style={{ minWidth: 0 }}>
|
||||
<Typography.Text strong ellipsis>
|
||||
{item.displayName || item.username}
|
||||
</Typography.Text>
|
||||
<Typography.Text type="secondary" ellipsis>
|
||||
{item.username}
|
||||
</Typography.Text>
|
||||
</Flex>
|
||||
</Flex>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "角色",
|
||||
dataIndex: "role",
|
||||
width: 100,
|
||||
render: (_, item) => <Tag color={item.role === "admin" ? "gold" : "default"}>{item.role === "admin" ? "管理员" : "用户"}</Tag>,
|
||||
},
|
||||
{
|
||||
title: "状态",
|
||||
dataIndex: "status",
|
||||
width: 90,
|
||||
render: (_, item) => <Tag color={item.status === "ban" ? "red" : "green"}>{item.status === "ban" ? "禁用" : "正常"}</Tag>,
|
||||
},
|
||||
{
|
||||
title: "算力点",
|
||||
dataIndex: "credits",
|
||||
width: 100,
|
||||
render: (_, item) => <Typography.Text>{item.credits}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: "Linux.do",
|
||||
dataIndex: "linuxDoId",
|
||||
width: 140,
|
||||
render: (_, item) => <Typography.Text type="secondary">{item.linuxDoId || "-"}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: "最近登录",
|
||||
dataIndex: "lastLoginAt",
|
||||
width: 180,
|
||||
render: (_, item) => <Typography.Text type="secondary">{item.lastLoginAt ? dayjs(item.lastLoginAt).format("YYYY-MM-DD HH:mm:ss") : "-"}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
key: "actions",
|
||||
width: 96,
|
||||
align: "right",
|
||||
render: (_, item) => (
|
||||
<Space size={4}>
|
||||
<Tooltip title="编辑">
|
||||
<Button type="text" size="small" icon={<EditOutlined />} onClick={() => setEditingUser(item)} />
|
||||
</Tooltip>
|
||||
<Tooltip title="删除">
|
||||
<Button danger type="text" size="small" icon={<DeleteOutlined />} onClick={() => setDeletingUser(item)} />
|
||||
</Tooltip>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<main style={{ padding: 24 }}>
|
||||
<Flex vertical gap={16}>
|
||||
<Card variant="borderless">
|
||||
<Form layout="vertical">
|
||||
<Row gutter={16} align="bottom">
|
||||
<Col flex="360px">
|
||||
<Form.Item label="关键词">
|
||||
<Input.Search
|
||||
value={keywordText}
|
||||
placeholder="搜索用户名、昵称、邮箱或 Linux.do ID"
|
||||
allowClear
|
||||
enterButton={<SearchOutlined />}
|
||||
onSearch={() => searchUsers(keywordText)}
|
||||
onChange={(event) => setKeywordText(event.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col flex="none">
|
||||
<Form.Item>
|
||||
<Space>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setKeywordText("");
|
||||
resetFilters();
|
||||
}}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
<Button type="primary" icon={<ReloadOutlined />} onClick={() => searchUsers(keywordText)}>
|
||||
查询
|
||||
</Button>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Form>
|
||||
</Card>
|
||||
<ProTable<AdminUser>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={users}
|
||||
loading={isLoading}
|
||||
search={false}
|
||||
defaultSize="middle"
|
||||
tableLayout="fixed"
|
||||
cardProps={{ variant: "borderless" }}
|
||||
headerTitle={
|
||||
<Space>
|
||||
<Typography.Text strong>用户列表</Typography.Text>
|
||||
<Tag>{total} 人</Tag>
|
||||
</Space>
|
||||
}
|
||||
options={{ density: true, setting: true, reload: () => void refreshUsers() }}
|
||||
toolBarRender={() => [
|
||||
<Button key="add" type="primary" icon={<PlusOutlined />} onClick={() => setEditingUser({ role: "user", status: "active" })}>
|
||||
新增
|
||||
</Button>,
|
||||
]}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [10, 20, 50, 100],
|
||||
showTotal: (value) => `共 ${value} 人`,
|
||||
onChange: (nextPage, nextPageSize) => (nextPageSize !== pageSize ? changePageSize(nextPageSize) : changePage(nextPage)),
|
||||
}}
|
||||
/>
|
||||
</Flex>
|
||||
|
||||
<Modal title={editingUser?.id ? "编辑用户" : "新增用户"} open={Boolean(editingUser)} width={680} onCancel={() => setEditingUser(null)} onOk={() => void saveUser()} okText="保存" cancelText="取消" destroyOnHidden>
|
||||
<Form form={form} layout="vertical" requiredMark={false}>
|
||||
<Typography.Text strong>基础信息</Typography.Text>
|
||||
<Row gutter={14}>
|
||||
<Col span={12}>
|
||||
<Form.Item name="username" label="用户名" rules={[{ required: true, message: "请输入用户名" }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="password" label={editingUser?.id ? "新密码" : "密码"} rules={editingUser?.id ? [] : [{ required: true, message: "请输入密码" }]}>
|
||||
<Input.Password autoComplete="new-password" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="displayName" label="昵称">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="email" label="邮箱">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="role" label="角色" rules={[{ required: true, message: "请选择角色" }]}>
|
||||
<Select options={roleOptions} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item name="status" label="状态" rules={[{ required: true, message: "请选择状态" }]}>
|
||||
<Select options={statusOptions} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
{editingUser?.id ? (
|
||||
<>
|
||||
<Divider style={{ margin: "4px 0 16px" }} />
|
||||
<Typography.Text strong>算力点调整</Typography.Text>
|
||||
<Row gutter={14}>
|
||||
<Col span={12}>
|
||||
<Form.Item label="算力点">
|
||||
<Space.Compact style={{ width: "100%" }}>
|
||||
<Form.Item name="credits" noStyle>
|
||||
<InputNumber min={0} precision={0} style={{ width: "100%" }} />
|
||||
</Form.Item>
|
||||
<Button onClick={() => void saveCredits()}>调整</Button>
|
||||
</Space.Compact>
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</>
|
||||
) : null}
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="删除用户"
|
||||
open={Boolean(deletingUser)}
|
||||
onCancel={() => setDeletingUser(null)}
|
||||
onOk={async () => {
|
||||
if (!deletingUser) return;
|
||||
await deleteUser(deletingUser.id);
|
||||
setDeletingUser(null);
|
||||
}}
|
||||
okText="删除"
|
||||
okButtonProps={{ danger: true }}
|
||||
cancelText="取消"
|
||||
>
|
||||
确定删除「{deletingUser?.displayName || deletingUser?.username}」吗?删除后该账号将无法继续登录。
|
||||
</Modal>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { App } from "antd";
|
||||
|
||||
import { adjustAdminUserCredits, deleteAdminUser, fetchAdminUsers, saveAdminUser, type AdminUser } from "@/services/api/admin";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
|
||||
const defaultPageSize = 10;
|
||||
|
||||
export function useAdminUsers() {
|
||||
const { message } = App.useApp();
|
||||
const queryClient = useQueryClient();
|
||||
const token = useUserStore((state) => state.token);
|
||||
const clearSession = useUserStore((state) => state.clearSession);
|
||||
const [keyword, setKeyword] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ["admin", "users", token, keyword, page, pageSize],
|
||||
queryFn: () => fetchAdminUsers(token, { keyword, page, pageSize }),
|
||||
enabled: Boolean(token),
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (user: Partial<AdminUser> & { password?: string }) => saveAdminUser(token, user),
|
||||
onSuccess: async (_, user) => {
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "users"] });
|
||||
message.success(user.id ? "用户已保存" : "用户已新增");
|
||||
},
|
||||
onError: (error) => message.error(error instanceof Error ? error.message : "保存失败"),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deleteAdminUser(token, id),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "users"] });
|
||||
message.success("用户已删除");
|
||||
},
|
||||
onError: (error) => message.error(error instanceof Error ? error.message : "删除失败"),
|
||||
});
|
||||
|
||||
const creditMutation = useMutation({
|
||||
mutationFn: ({ id, credits }: { id: string; credits: number }) => adjustAdminUserCredits(token, id, credits),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ["admin", "users"] });
|
||||
message.success("算力点已调整");
|
||||
},
|
||||
onError: (error) => message.error(error instanceof Error ? error.message : "调整失败"),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (query.isError) {
|
||||
const errorMessage = query.error instanceof Error ? query.error.message : "读取用户失败";
|
||||
message.error(errorMessage);
|
||||
if (errorMessage.includes("未登录") || errorMessage.includes("权限不足") || errorMessage.includes("登录状态无效")) clearSession();
|
||||
}
|
||||
}, [clearSession, message, query.error, query.isError]);
|
||||
|
||||
const updateFilters = (next: Partial<{ keyword: string; page: number; pageSize: number }>) => {
|
||||
const queryState = { keyword, page, pageSize, ...next };
|
||||
if (next.keyword !== undefined || next.pageSize !== undefined) queryState.page = 1;
|
||||
setKeyword(queryState.keyword);
|
||||
setPage(queryState.page);
|
||||
setPageSize(queryState.pageSize);
|
||||
};
|
||||
|
||||
const data = query.data;
|
||||
|
||||
return {
|
||||
users: data?.items || [],
|
||||
keyword,
|
||||
page,
|
||||
pageSize,
|
||||
total: data?.total || 0,
|
||||
isLoading: query.isFetching || saveMutation.isPending || deleteMutation.isPending || creditMutation.isPending,
|
||||
searchUsers: (value = keyword) => updateFilters({ keyword: value }),
|
||||
changePage: (value: number) => updateFilters({ page: value }),
|
||||
changePageSize: (value: number) => updateFilters({ pageSize: value }),
|
||||
resetFilters: () => updateFilters({ keyword: "", page: 1, pageSize: defaultPageSize }),
|
||||
refreshUsers: () => query.refetch(),
|
||||
saveUser: (user: Partial<AdminUser> & { password?: string }) => saveMutation.mutateAsync(user),
|
||||
adjustCredits: (id: string, credits: number) => creditMutation.mutateAsync({ id, credits }),
|
||||
deleteUser: (id: string) => deleteMutation.mutateAsync(id),
|
||||
};
|
||||
}
|
||||
@@ -1,288 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Copy, FolderPlus, Search } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { App, Button, Card, Drawer, Empty, Image, Input, Pagination, Spin, Tag, Typography } from "antd";
|
||||
import axios from "axios";
|
||||
|
||||
import { useCopyText } from "@/hooks/use-copy-text";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useAssetStore } from "@/stores/use-asset-store";
|
||||
import { fetchAssetLibrary, type AssetLibraryItem } from "@/services/api/assets";
|
||||
import { uploadImage } from "@/services/image-storage";
|
||||
|
||||
const PAGE_SIZE = 12;
|
||||
|
||||
export default function AssetLibraryPage() {
|
||||
const { message } = App.useApp();
|
||||
const copyText = useCopyText();
|
||||
const [keyword, setKeyword] = useState("");
|
||||
const [selectedType, setSelectedType] = useState("");
|
||||
const [selectedTags, setSelectedTags] = useState<string[]>([]);
|
||||
const [page, setPage] = useState(1);
|
||||
const [selectedAsset, setSelectedAsset] = useState<AssetLibraryItem | null>(null);
|
||||
const addAsset = useAssetStore((state) => state.addAsset);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ["asset-library", keyword, selectedType, selectedTags, page],
|
||||
queryFn: () => fetchAssetLibrary({ keyword, type: selectedType, tag: selectedTags, page, pageSize: PAGE_SIZE }),
|
||||
retry: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (query.isError) {
|
||||
message.error(query.error instanceof Error ? query.error.message : "获取素材库失败");
|
||||
}
|
||||
}, [message, query.error, query.isError]);
|
||||
|
||||
const isReady = query.isFetched || query.isError;
|
||||
const items = query.data?.items || [];
|
||||
const availableTags = query.data?.tags || [];
|
||||
const total = query.data?.total || 0;
|
||||
|
||||
const toggleTag = (tag: string) => {
|
||||
setSelectedTags((items) => (items.includes(tag) ? items.filter((item) => item !== tag) : [...items, tag]));
|
||||
};
|
||||
|
||||
const saveToMyAssets = async (asset: AssetLibraryItem) => {
|
||||
try {
|
||||
if (asset.type === "image") {
|
||||
const dataUrl = await remoteImageToDataUrl(asset.url);
|
||||
const image = await uploadImage(dataUrl);
|
||||
addAsset({
|
||||
kind: "image",
|
||||
title: asset.title,
|
||||
coverUrl: asset.coverUrl,
|
||||
tags: asset.tags,
|
||||
source: asset.category,
|
||||
note: asset.description,
|
||||
data: { dataUrl: image.url, storageKey: image.storageKey, width: image.width, height: image.height, bytes: image.bytes, mimeType: image.mimeType },
|
||||
metadata: { source: "asset-library", assetId: asset.id },
|
||||
});
|
||||
} else {
|
||||
addAsset({
|
||||
kind: "text",
|
||||
title: asset.title,
|
||||
coverUrl: asset.coverUrl,
|
||||
tags: asset.tags,
|
||||
source: asset.category,
|
||||
note: asset.description,
|
||||
data: { content: asset.content },
|
||||
metadata: { source: "asset-library", assetId: asset.id },
|
||||
});
|
||||
}
|
||||
message.success("已加入我的素材");
|
||||
} catch {
|
||||
message.error("加入失败");
|
||||
}
|
||||
};
|
||||
|
||||
if (!isReady) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<Spin />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col overflow-hidden bg-background text-stone-800 dark:text-stone-100">
|
||||
<main className="min-h-0 flex-1 overflow-y-auto bg-background bg-[radial-gradient(#e5e7eb_1px,transparent_1px)] px-6 py-8 [background-size:16px_16px] dark:bg-[radial-gradient(rgba(245,245,244,.16)_1px,transparent_1px)]">
|
||||
<div className="pb-8">
|
||||
<div className="mx-auto max-w-5xl text-center">
|
||||
<h1 className="text-4xl font-semibold tracking-tight text-stone-950 dark:text-stone-100">素材库</h1>
|
||||
<p className="mt-3 text-sm text-stone-500 dark:text-stone-400">挑选团队素材,加入我的素材后继续编辑和使用。</p>
|
||||
</div>
|
||||
<div className="mx-auto mt-8 w-full max-w-2xl">
|
||||
<Input
|
||||
size="large"
|
||||
className="w-full"
|
||||
prefix={<Search className="size-4 text-stone-400" />}
|
||||
value={keyword}
|
||||
placeholder="按标题查询"
|
||||
onChange={(event) => {
|
||||
setPage(1);
|
||||
setKeyword(event.target.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="mx-auto mt-6 max-w-6xl space-y-3">
|
||||
<div className="grid gap-2 sm:grid-cols-[56px_minmax(0,1fr)] sm:items-start">
|
||||
<div className="pt-2 text-xs font-medium text-stone-500 dark:text-stone-400">类型</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{[
|
||||
{ label: "全部", value: "" },
|
||||
{ label: "文本", value: "text" },
|
||||
{ label: "图片", value: "image" },
|
||||
].map((item) => (
|
||||
<Tag.CheckableTag
|
||||
key={item.value || "all"}
|
||||
checked={selectedType === item.value}
|
||||
className={cn("prompt-filter-tag", selectedType === item.value && "is-active")}
|
||||
onChange={() => {
|
||||
setPage(1);
|
||||
setSelectedType(item.value);
|
||||
}}
|
||||
>
|
||||
{item.label}
|
||||
</Tag.CheckableTag>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2 sm:grid-cols-[56px_minmax(0,1fr)] sm:items-start">
|
||||
<div className="pt-2 text-xs font-medium text-stone-500 dark:text-stone-400">标签</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Tag.CheckableTag
|
||||
checked={selectedTags.length === 0}
|
||||
className={cn("prompt-filter-tag", selectedTags.length === 0 && "is-active")}
|
||||
onChange={() => {
|
||||
setPage(1);
|
||||
setSelectedTags([]);
|
||||
}}
|
||||
>
|
||||
全部
|
||||
</Tag.CheckableTag>
|
||||
{availableTags.map((tag) => (
|
||||
<Tag.CheckableTag
|
||||
key={tag}
|
||||
checked={selectedTags.includes(tag)}
|
||||
className={cn("prompt-filter-tag", selectedTags.includes(tag) && "is-active")}
|
||||
onChange={() => {
|
||||
setPage(1);
|
||||
toggleTag(tag);
|
||||
}}
|
||||
>
|
||||
{tag}
|
||||
</Tag.CheckableTag>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto flex max-w-7xl flex-col gap-5">
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4 2xl:grid-cols-5">
|
||||
{items.map((asset) => (
|
||||
<LibraryCard key={asset.id} asset={asset} onOpen={() => setSelectedAsset(asset)} onAdd={() => void saveToMyAssets(asset)} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{!items.length ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="没有找到素材" className="py-20" /> : null}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Pagination current={page} pageSize={PAGE_SIZE} total={total} showSizeChanger={false} onChange={(nextPage) => setPage(nextPage)} />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<Drawer title="素材详情" open={Boolean(selectedAsset)} size="large" onClose={() => setSelectedAsset(null)}>
|
||||
{selectedAsset ? (
|
||||
<div className="space-y-5">
|
||||
{selectedAsset.coverUrl ? (
|
||||
<Image src={selectedAsset.coverUrl} alt={selectedAsset.title} className="rounded-lg" />
|
||||
) : (
|
||||
<div className="rounded-lg border border-stone-200 bg-stone-50 p-5 text-sm leading-6 text-stone-600 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-300">{selectedAsset.content || "暂无封面"}</div>
|
||||
)}
|
||||
<div>
|
||||
<Typography.Title level={4} className="!mb-2">
|
||||
{selectedAsset.title}
|
||||
</Typography.Title>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
<Tag>{selectedAsset.type === "image" ? "图片" : "文本"}</Tag>
|
||||
{selectedAsset.tags.map((tag) => (
|
||||
<Tag key={tag}>{tag}</Tag>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg border border-stone-200 p-4 dark:border-stone-800">
|
||||
<Typography.Text type="secondary" className="block text-xs">
|
||||
内容
|
||||
</Typography.Text>
|
||||
{selectedAsset.type === "text" ? <Typography.Paragraph className="mt-2 whitespace-pre-wrap">{selectedAsset.content}</Typography.Paragraph> : <Typography.Text className="mt-2 block">{selectedAsset.url}</Typography.Text>}
|
||||
</div>
|
||||
{selectedAsset.description ? <Typography.Paragraph type="secondary">{selectedAsset.description}</Typography.Paragraph> : null}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{selectedAsset.type === "text" ? (
|
||||
<Button type="primary" icon={<Copy className="size-4" />} onClick={() => copyText(selectedAsset.content)}>
|
||||
复制文本
|
||||
</Button>
|
||||
) : null}
|
||||
{selectedAsset.type === "image" ? (
|
||||
<Button type="primary" icon={<Copy className="size-4" />} onClick={() => copyText(selectedAsset.url)}>
|
||||
复制链接
|
||||
</Button>
|
||||
) : null}
|
||||
<Button icon={<FolderPlus className="size-4" />} onClick={() => void saveToMyAssets(selectedAsset)}>
|
||||
加入我的素材
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LibraryCard({ asset, onOpen, onAdd }: { asset: AssetLibraryItem; onOpen: () => void; onAdd: () => void }) {
|
||||
const cover = asset.coverUrl;
|
||||
return (
|
||||
<Card
|
||||
hoverable
|
||||
className="overflow-hidden"
|
||||
styles={{ body: { padding: 0 } }}
|
||||
cover={
|
||||
<button type="button" className="block w-full text-left" onClick={onOpen}>
|
||||
{cover ? (
|
||||
<img src={cover} alt={asset.title} className="aspect-[4/3] w-full object-cover" />
|
||||
) : (
|
||||
<div className="flex aspect-[4/3] items-center justify-center bg-stone-100 p-5 text-center text-sm leading-6 text-stone-600 dark:bg-stone-900 dark:text-stone-300">{asset.content || "暂无封面"}</div>
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<button type="button" className="block w-full text-left" onClick={onOpen}>
|
||||
<div className="p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<h2 className="line-clamp-1 text-sm font-semibold text-stone-950 dark:text-stone-100">{asset.title}</h2>
|
||||
<Tag className="m-0 shrink-0 text-[11px]">{asset.type === "image" ? "图片" : "文本"}</Tag>
|
||||
</div>
|
||||
<Typography.Paragraph type="secondary" ellipsis={{ rows: 3 }} className="!mb-0 !mt-2 !text-xs !leading-5">
|
||||
{asset.type === "text" ? asset.content : asset.url}
|
||||
</Typography.Paragraph>
|
||||
<div className="mt-3 flex flex-wrap gap-1.5">
|
||||
{asset.tags.slice(0, 3).map((tag) => (
|
||||
<Tag key={tag} className="m-0 text-[11px]">
|
||||
{tag}
|
||||
</Tag>
|
||||
))}
|
||||
{!asset.tags.length ? <Tag className="m-0 text-[11px]">无标签</Tag> : null}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
<div className="flex items-center gap-2 px-4 pb-4">
|
||||
<Button size="small" onClick={onOpen}>
|
||||
查看
|
||||
</Button>
|
||||
<Button size="small" icon={<FolderPlus className="size-3.5" />} onClick={onAdd}>
|
||||
加入我的素材
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
async function remoteImageToDataUrl(url: string) {
|
||||
const response = await axios.get(url, { responseType: "blob" });
|
||||
const blob = response.data as Blob;
|
||||
return await blobToDataUrl(blob);
|
||||
}
|
||||
|
||||
function blobToDataUrl(blob: Blob) {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result || ""));
|
||||
reader.onerror = () => reject(new Error("读取图片失败"));
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import type { ChangeEvent as ReactChangeEvent, DragEvent as ReactDragEvent, MouseEvent as ReactMouseEvent, PointerEvent as ReactPointerEvent } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { BookOpen, Bot, Home, ImageIcon, Images, List, Menu, MessageSquare, Music2, Plus, Redo2, Settings2, Trash2, Undo2, Upload, Video } from "lucide-react";
|
||||
import { BookOpen, Bot, Home, ImageIcon, Images, List, Menu, Music2, Plus, Redo2, Settings2, Trash2, Undo2, Upload, Video } from "lucide-react";
|
||||
import { saveAs } from "file-saver";
|
||||
|
||||
import { requestEdit, requestGeneration, requestImageQuestion } from "@/services/api/image";
|
||||
@@ -26,26 +26,26 @@ import { NODE_DEFAULT_SIZE, getNodeSpec } from "../constants";
|
||||
import { ActiveConnectionPath, ConnectionPath } from "../components/canvas-connections";
|
||||
import { CanvasConfigComposer } from "../components/canvas-config-composer";
|
||||
import { CanvasConfigNodePanel } from "../components/canvas-config-node-panel";
|
||||
import { CanvasAssistantPanel } from "../components/canvas-assistant-panel";
|
||||
import { CanvasLocalAgentPanel } from "../components/canvas-local-agent-panel";
|
||||
import { CANVAS_AGENT_PANEL_MOTION_MS, CanvasAssistantPanel } from "../components/canvas-assistant-panel";
|
||||
import { CanvasNodeContextMenu } from "../components/canvas-context-menu";
|
||||
import { CanvasNodeAngleDialog, type CanvasImageAngleParams } from "../components/canvas-node-angle-dialog";
|
||||
import { CanvasNodeCropDialog, type CanvasImageCropRect } from "../components/canvas-node-crop-dialog";
|
||||
import { CanvasNodeMaskEditDialog, type CanvasImageMaskEditPayload } from "../components/canvas-node-mask-edit-dialog";
|
||||
import { CanvasNodeSplitDialog, type CanvasImageSplitParams } from "../components/canvas-node-split-dialog";
|
||||
import { CanvasNodeUpscaleDialog, type CanvasImageUpscaleParams } from "../components/canvas-node-upscale-dialog";
|
||||
import { buildNodeChatMessages, buildNodeGenerationContext, buildNodeGenerationInputs, hydrateNodeGenerationContext, type NodeGenerationInput } from "../components/canvas-node-generation";
|
||||
import { buildNodeGenerationContext, buildNodeGenerationInputs, buildNodeResponseMessages, hydrateNodeGenerationContext, type NodeGenerationInput } from "../components/canvas-node-generation";
|
||||
import { CanvasNodeHoverToolbar, CanvasNodeInfoModal } from "../components/canvas-node-hover-toolbar";
|
||||
import { InfiniteCanvas } from "../components/infinite-canvas";
|
||||
import { Minimap } from "../components/canvas-mini-map";
|
||||
import { CanvasNode } from "../components/canvas-node";
|
||||
import { CanvasNodePromptPanel, type CanvasNodeGenerationMode } from "../components/canvas-node-prompt-panel";
|
||||
import { CanvasToolbar } from "../components/canvas-toolbar";
|
||||
import { AssetPickerModal, type AssetPickerTab, type InsertAssetPayload } from "../components/asset-picker-modal";
|
||||
import { AssetPickerModal, type InsertAssetPayload } from "../components/asset-picker-modal";
|
||||
import { CanvasZoomControls } from "../components/canvas-zoom-controls";
|
||||
import { useCanvasStore } from "../stores/use-canvas-store";
|
||||
import { applyCanvasAgentOps, type CanvasAgentOp, type CanvasAgentSnapshot } from "../utils/canvas-agent-ops";
|
||||
import { buildCanvasResourceReferences, buildNodeMentionReferences } from "../utils/canvas-resource-references";
|
||||
import type { CanvasAgentMode } from "../components/canvas-agent-chat-ui";
|
||||
import {
|
||||
CanvasNodeType,
|
||||
type CanvasAssistantImage,
|
||||
@@ -275,7 +275,6 @@ function InfiniteCanvasPage() {
|
||||
const [showImageInfo, setShowImageInfo] = useState(false);
|
||||
const [clearConfirmOpen, setClearConfirmOpen] = useState(false);
|
||||
const [assetPickerOpen, setAssetPickerOpen] = useState(false);
|
||||
const [assetPickerTab, setAssetPickerTab] = useState<AssetPickerTab>("my-assets");
|
||||
const [projectLoaded, setProjectLoaded] = useState(false);
|
||||
const [toolbarNodeId, setToolbarNodeId] = useState<string | null>(null);
|
||||
const [nodeImageSettingsOpen, setNodeImageSettingsOpen] = useState(false);
|
||||
@@ -292,8 +291,8 @@ function InfiniteCanvasPage() {
|
||||
const [previewNodeId, setPreviewNodeId] = useState<string | null>(null);
|
||||
const [assistantCollapsed, setAssistantCollapsed] = useState(true);
|
||||
const [assistantMounted, setAssistantMounted] = useState(false);
|
||||
const [localAgentCollapsed, setLocalAgentCollapsed] = useState(true);
|
||||
const [localAgentMounted, setLocalAgentMounted] = useState(false);
|
||||
const [assistantClosing, setAssistantClosing] = useState(false);
|
||||
const [agentMode, setAgentMode] = useState<CanvasAgentMode>("online");
|
||||
const [agentUndoSnapshot, setAgentUndoSnapshot] = useState<CanvasAgentSnapshot | null>(null);
|
||||
const [titleEditing, setTitleEditing] = useState(false);
|
||||
const [titleDraft, setTitleDraft] = useState("");
|
||||
@@ -310,6 +309,7 @@ function InfiniteCanvasPage() {
|
||||
const connectingParamsRef = useRef(connectingParams);
|
||||
const connectionTargetNodeIdRef = useRef(connectionTargetNodeId);
|
||||
const selectionBoxRef = useRef(selectionBox);
|
||||
const agentCloseTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const pendingConnectionCreateRef = useRef(pendingConnectionCreate);
|
||||
|
||||
const createHistoryEntry = useCallback(
|
||||
@@ -395,6 +395,13 @@ function InfiniteCanvasPage() {
|
||||
};
|
||||
}, [activeChatId, backgroundMode, chatSessions, connections, createHistoryEntry, nodes, projectLoaded, showImageInfo]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (agentCloseTimerRef.current) clearTimeout(agentCloseTimerRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!projectLoaded || historyPausedRef.current) return;
|
||||
updateProject(projectId, { nodes, connections, chatSessions, activeChatId, backgroundMode, showImageInfo });
|
||||
@@ -659,10 +666,11 @@ function InfiniteCanvasPage() {
|
||||
[connections, currentProject?.title, nodes, projectId, selectedNodeIds, viewport],
|
||||
);
|
||||
const applyAgentOps = useCallback(
|
||||
(ops: CanvasAgentOp[]) => {
|
||||
(ops?: CanvasAgentOp[]) => {
|
||||
const safeOps = Array.isArray(ops) ? ops.filter((op) => op?.type) : [];
|
||||
const before = { projectId, title: currentProject?.title || "未命名画布", nodes: nodesRef.current, connections: connectionsRef.current, selectedNodeIds: Array.from(selectedNodeIdsRef.current), viewport: viewportRef.current };
|
||||
const generationOps = ops.filter((op): op is Extract<CanvasAgentOp, { type: "run_generation" }> => op.type === "run_generation");
|
||||
const next = applyCanvasAgentOps(before, ops.filter((op) => op.type !== "run_generation"));
|
||||
const generationOps = safeOps.filter((op): op is Extract<CanvasAgentOp, { type: "run_generation" }> => op.type === "run_generation" && Boolean(op.nodeId));
|
||||
const next = applyCanvasAgentOps(before, safeOps.filter((op) => op.type !== "run_generation"));
|
||||
nodesRef.current = next.nodes;
|
||||
connectionsRef.current = next.connections;
|
||||
selectedNodeIdsRef.current = new Set(next.selectedNodeIds);
|
||||
@@ -675,7 +683,13 @@ function InfiniteCanvasPage() {
|
||||
setViewport(next.viewport);
|
||||
setContextMenu(null);
|
||||
if (generationOps.length) {
|
||||
queueMicrotask(() => generationOps.forEach((op) => void generateNodeRef.current?.(op.nodeId, op.mode || "image", op.prompt || "")));
|
||||
queueMicrotask(() =>
|
||||
generationOps.forEach((op) => {
|
||||
const target = nodesRef.current.find((node) => node.id === op.nodeId);
|
||||
const prompt = op.prompt?.trim() ? op.prompt : target?.metadata?.composerContent ?? target?.metadata?.prompt ?? "";
|
||||
void generateNodeRef.current?.(op.nodeId, op.mode || target?.metadata?.generationMode || "image", prompt);
|
||||
}),
|
||||
);
|
||||
}
|
||||
return { ...next, projectId, title: currentProject?.title || "未命名画布" };
|
||||
},
|
||||
@@ -2110,7 +2124,7 @@ function InfiniteCanvasPage() {
|
||||
const answers = await Promise.all(
|
||||
(childIds.length ? childIds : [nodeId]).map((targetNodeId) => {
|
||||
let localStreamed = "";
|
||||
return requestImageQuestion(generationConfig, buildNodeChatMessages({ ...generationContext, prompt: effectivePrompt }), (text) => {
|
||||
return requestImageQuestion(generationConfig, buildNodeResponseMessages({ ...generationContext, prompt: effectivePrompt }), (text) => {
|
||||
localStreamed = text;
|
||||
streamed = text;
|
||||
if (isConfigNode) return;
|
||||
@@ -2191,7 +2205,7 @@ function InfiniteCanvasPage() {
|
||||
if (node.type === CanvasNodeType.Text) {
|
||||
if (!context) return;
|
||||
let streamed = "";
|
||||
const answer = await requestImageQuestion(generationConfig, buildNodeChatMessages({ ...context, prompt }), (text) => {
|
||||
const answer = await requestImageQuestion(generationConfig, buildNodeResponseMessages({ ...context, prompt }), (text) => {
|
||||
streamed = text;
|
||||
setNodes((prev) => prev.map((item) => (item.id === node.id ? { ...item, type: CanvasNodeType.Text, metadata: { ...item.metadata, content: text, status: NODE_STATUS_LOADING } } : item)));
|
||||
});
|
||||
@@ -2337,13 +2351,26 @@ function InfiniteCanvasPage() {
|
||||
[insertAssistantImage, insertAssistantText, screenToCanvas, size.height, size.width],
|
||||
);
|
||||
|
||||
const localAgentOpen = localAgentMounted && !localAgentCollapsed;
|
||||
const openLocalAgent = () => {
|
||||
setLocalAgentMounted(true);
|
||||
setLocalAgentCollapsed(false);
|
||||
const assistantOpen = assistantMounted && !assistantCollapsed;
|
||||
const openAgent = (mode: CanvasAgentMode = agentMode) => {
|
||||
if (agentCloseTimerRef.current) {
|
||||
clearTimeout(agentCloseTimerRef.current);
|
||||
agentCloseTimerRef.current = null;
|
||||
}
|
||||
setAgentMode(mode);
|
||||
setAssistantMounted(true);
|
||||
setAssistantClosing(false);
|
||||
setAssistantCollapsed(false);
|
||||
};
|
||||
const closeLocalAgent = () => {
|
||||
setLocalAgentCollapsed(true);
|
||||
const closeAgent = () => {
|
||||
if (!assistantMounted || assistantClosing) return;
|
||||
setAssistantCollapsed(true);
|
||||
setAssistantClosing(true);
|
||||
agentCloseTimerRef.current = setTimeout(() => {
|
||||
agentCloseTimerRef.current = null;
|
||||
setAssistantMounted(false);
|
||||
setAssistantClosing(false);
|
||||
}, CANVAS_AGENT_PANEL_MOTION_MS);
|
||||
};
|
||||
|
||||
if (!projectLoaded) return <CanvasRefreshShell />;
|
||||
@@ -2368,13 +2395,8 @@ function InfiniteCanvasPage() {
|
||||
onImportImage={() => handleUploadRequest()}
|
||||
onUndo={undoCanvas}
|
||||
onRedo={redoCanvas}
|
||||
assistantCollapsed={assistantCollapsed}
|
||||
localAgentOpen={localAgentOpen}
|
||||
onExpandAssistant={() => {
|
||||
setAssistantMounted(true);
|
||||
setAssistantCollapsed(false);
|
||||
}}
|
||||
onToggleLocalAgent={() => (localAgentOpen ? closeLocalAgent() : openLocalAgent())}
|
||||
agentOpen={assistantOpen}
|
||||
onToggleAgent={() => (assistantOpen ? closeAgent() : openAgent())}
|
||||
/>
|
||||
|
||||
<InfiniteCanvas
|
||||
@@ -2570,12 +2592,7 @@ function InfiniteCanvasPage() {
|
||||
onDeselect={deselectCanvas}
|
||||
onBackgroundModeChange={setBackgroundMode}
|
||||
onShowImageInfoChange={setShowImageInfo}
|
||||
onOpenAssetLibrary={() => {
|
||||
setAssetPickerTab("library");
|
||||
setAssetPickerOpen(true);
|
||||
}}
|
||||
onOpenMyAssets={() => {
|
||||
setAssetPickerTab("my-assets");
|
||||
setAssetPickerOpen(true);
|
||||
}}
|
||||
/>
|
||||
@@ -2657,31 +2674,25 @@ function InfiniteCanvasPage() {
|
||||
<p className="text-sm opacity-60">这会删除当前画布上的所有节点和连线。</p>
|
||||
</Modal>
|
||||
|
||||
<AssetPickerModal open={assetPickerOpen} defaultTab={assetPickerTab} onInsert={handleAssetInsert} onClose={() => setAssetPickerOpen(false)} />
|
||||
<AssetPickerModal open={assetPickerOpen} onInsert={handleAssetInsert} onClose={() => setAssetPickerOpen(false)} />
|
||||
</section>
|
||||
{assistantMounted ? (
|
||||
<CanvasAssistantPanel
|
||||
nodes={nodes}
|
||||
selectedNodeIds={selectedNodeIds}
|
||||
snapshot={agentSnapshot}
|
||||
sessions={chatSessions}
|
||||
activeSessionId={activeChatId}
|
||||
onSelectNodeIds={setSelectedNodeIds}
|
||||
onSessionsChange={handleAssistantSessionsChange}
|
||||
onInsertImage={insertAssistantImage}
|
||||
onInsertText={insertAssistantText}
|
||||
onPasteImage={pasteAssistantImage}
|
||||
onCollapseStart={() => setAssistantCollapsed(true)}
|
||||
onCollapse={() => setAssistantMounted(false)}
|
||||
/>
|
||||
) : null}
|
||||
{localAgentMounted ? (
|
||||
<CanvasLocalAgentPanel
|
||||
snapshot={agentSnapshot}
|
||||
canUndoOps={Boolean(agentUndoSnapshot)}
|
||||
collapsed={localAgentCollapsed}
|
||||
onApplyOps={applyAgentOps}
|
||||
canUndoOps={Boolean(agentUndoSnapshot)}
|
||||
onUndoOps={undoAgentOps}
|
||||
onCollapseStart={closeLocalAgent}
|
||||
onPasteImage={pasteAssistantImage}
|
||||
agentMode={agentMode}
|
||||
onAgentModeChange={setAgentMode}
|
||||
closing={assistantClosing}
|
||||
onCollapse={closeAgent}
|
||||
/>
|
||||
) : null}
|
||||
</main>
|
||||
@@ -2705,10 +2716,8 @@ function CanvasTopBar({
|
||||
onImportImage,
|
||||
onUndo,
|
||||
onRedo,
|
||||
assistantCollapsed,
|
||||
localAgentOpen,
|
||||
onExpandAssistant,
|
||||
onToggleLocalAgent,
|
||||
agentOpen,
|
||||
onToggleAgent,
|
||||
}: {
|
||||
title: string;
|
||||
titleDraft: string;
|
||||
@@ -2726,17 +2735,13 @@ function CanvasTopBar({
|
||||
onImportImage: () => void;
|
||||
onUndo: () => void;
|
||||
onRedo: () => void;
|
||||
assistantCollapsed: boolean;
|
||||
localAgentOpen: boolean;
|
||||
onExpandAssistant: () => void;
|
||||
onToggleLocalAgent: () => void;
|
||||
agentOpen: boolean;
|
||||
onToggleAgent: () => void;
|
||||
}) {
|
||||
const colorTheme = useThemeStore((state) => state.theme);
|
||||
const theme = canvasThemes[colorTheme];
|
||||
const titleRef = useRef<HTMLDivElement>(null);
|
||||
const accountRef = useRef<HTMLDivElement>(null);
|
||||
const [shortcutsOpen, setShortcutsOpen] = useState(false);
|
||||
const [accountOpen, setAccountOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTitleEditing) return;
|
||||
@@ -2747,15 +2752,6 @@ function CanvasTopBar({
|
||||
return () => document.removeEventListener("pointerdown", close, true);
|
||||
}, [isTitleEditing, onFinishTitleEditing]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!accountOpen) return;
|
||||
const close = (event: PointerEvent) => {
|
||||
if (!accountRef.current?.contains(event.target as Node)) setAccountOpen(false);
|
||||
};
|
||||
document.addEventListener("pointerdown", close, true);
|
||||
return () => document.removeEventListener("pointerdown", close, true);
|
||||
}, [accountOpen]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="pointer-events-none absolute left-0 right-0 top-0 z-50 flex h-16 items-center justify-between px-4">
|
||||
@@ -2813,38 +2809,18 @@ function CanvasTopBar({
|
||||
<div className="pointer-events-auto flex items-center gap-1.5">
|
||||
<UserStatusActions
|
||||
variant="canvas"
|
||||
accountOpen={accountOpen}
|
||||
onAccountOpenChange={setAccountOpen}
|
||||
accountRef={accountRef}
|
||||
getPopupContainer={(node) => node.parentElement || document.body}
|
||||
onOpenShortcuts={() => {
|
||||
setShortcutsOpen(true);
|
||||
setAccountOpen(false);
|
||||
}}
|
||||
onOpenShortcuts={() => setShortcutsOpen(true)}
|
||||
/>
|
||||
<span className="h-6 w-px" style={{ background: theme.toolbar.border }} />
|
||||
<Button
|
||||
type="text"
|
||||
className="!h-10 !rounded-xl !px-3 !font-medium"
|
||||
style={{ background: localAgentOpen ? theme.toolbar.activeBg : theme.toolbar.panel, color: theme.node.text, boxShadow: "0 10px 30px rgba(28,25,23,.10)" }}
|
||||
style={{ background: agentOpen ? theme.toolbar.activeBg : theme.toolbar.panel, color: theme.node.text, boxShadow: "0 10px 30px rgba(28,25,23,.10)" }}
|
||||
icon={<Bot className="size-4" />}
|
||||
onClick={onToggleLocalAgent}
|
||||
onClick={onToggleAgent}
|
||||
>
|
||||
Agent
|
||||
</Button>
|
||||
{assistantCollapsed ? (
|
||||
<>
|
||||
<Button
|
||||
type="text"
|
||||
className="!h-10 !rounded-xl !px-3 !font-medium"
|
||||
style={{ background: theme.toolbar.panel, color: theme.node.text, boxShadow: "0 10px 30px rgba(28,25,23,.10)" }}
|
||||
icon={<MessageSquare className="size-4" />}
|
||||
onClick={onExpandAssistant}
|
||||
>
|
||||
助手
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<Modal title="快捷键" open={shortcutsOpen} onCancel={() => setShortcutsOpen(false)} footer={null} centered>
|
||||
@@ -2997,7 +2973,6 @@ async function hydrateAssistantImages(sessions: CanvasAssistantSession[]) {
|
||||
session.messages.map(async (message) => ({
|
||||
...message,
|
||||
references: await Promise.all((message.references || []).map(hydrateItem)),
|
||||
images: await Promise.all((message.images || []).map(hydrateItem)),
|
||||
})),
|
||||
),
|
||||
})),
|
||||
|
||||
@@ -1,43 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { App, Empty, Input, Modal, Pagination, Spin, Tabs, Tag } from "antd";
|
||||
import { Empty, Input, Modal, Pagination, Tag } from "antd";
|
||||
import { Search } from "lucide-react";
|
||||
import axios from "axios";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useAssetStore, type Asset } from "@/stores/use-asset-store";
|
||||
import { fetchAssetLibrary, type AssetLibraryItem } from "@/services/api/assets";
|
||||
|
||||
export type AssetPickerTab = "my-assets" | "library";
|
||||
|
||||
export type InsertAssetPayload = { kind: "text"; content: string; title: string } | { kind: "image"; dataUrl: string; title: string; storageKey?: string } | { kind: "video"; url: string; title: string; storageKey?: string; width?: number; height?: number };
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
defaultTab?: AssetPickerTab;
|
||||
onInsert: (payload: InsertAssetPayload) => void;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
export function AssetPickerModal({ open, defaultTab = "my-assets", onInsert, onClose }: Props) {
|
||||
const [activeTab, setActiveTab] = useState<AssetPickerTab>(defaultTab);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) setActiveTab(defaultTab);
|
||||
}, [open, defaultTab]);
|
||||
|
||||
export function AssetPickerModal({ open, onInsert, onClose }: Props) {
|
||||
return (
|
||||
<Modal title="选择素材" open={open} onCancel={onClose} footer={null} width={860} destroyOnHidden styles={{ body: { padding: "0 24px 24px", minHeight: 480 } }}>
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
onChange={(key) => setActiveTab(key as AssetPickerTab)}
|
||||
items={[
|
||||
{ key: "my-assets", label: "我的素材", children: <MyAssetsTab onInsert={onInsert} /> },
|
||||
{ key: "library", label: "素材库", children: <LibraryTab onInsert={onInsert} /> },
|
||||
]}
|
||||
/>
|
||||
<MyAssetsTab onInsert={onInsert} />
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -51,104 +32,12 @@ const kindOptions = [
|
||||
{ label: "视频", value: "video" },
|
||||
];
|
||||
|
||||
function LibraryTab({ onInsert }: { onInsert: (payload: InsertAssetPayload) => void }) {
|
||||
const { message } = App.useApp();
|
||||
const [keyword, setKeyword] = useState("");
|
||||
const [kindFilter, setKindFilter] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [inserting, setInserting] = useState<string | null>(null);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ["asset-picker-library", keyword, kindFilter, page],
|
||||
queryFn: () => fetchAssetLibrary({ keyword, type: kindFilter, page, pageSize: PAGE_SIZE }),
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const items = query.data?.items || [];
|
||||
const total = query.data?.total || 0;
|
||||
|
||||
const handleInsert = async (asset: AssetLibraryItem) => {
|
||||
try {
|
||||
setInserting(asset.id);
|
||||
if (asset.type === "text") {
|
||||
onInsert({ kind: "text", content: asset.content, title: asset.title });
|
||||
} else {
|
||||
const dataUrl = await remoteImageToDataUrl(asset.url);
|
||||
onInsert({ kind: "image", dataUrl, title: asset.title });
|
||||
}
|
||||
} catch {
|
||||
message.error("插入失败");
|
||||
} finally {
|
||||
setInserting(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Input
|
||||
className="w-56"
|
||||
size="small"
|
||||
prefix={<Search className="size-3.5 text-stone-400" />}
|
||||
placeholder="搜索素材"
|
||||
value={keyword}
|
||||
allowClear
|
||||
onChange={(e) => {
|
||||
setPage(1);
|
||||
setKeyword(e.target.value);
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-1.5">
|
||||
{[
|
||||
{ label: "全部", value: "" },
|
||||
{ label: "文本", value: "text" },
|
||||
{ label: "图片", value: "image" },
|
||||
].map((opt) => (
|
||||
<Tag.CheckableTag
|
||||
key={opt.value || "all"}
|
||||
checked={kindFilter === opt.value}
|
||||
className={cn("prompt-filter-tag", kindFilter === opt.value && "is-active")}
|
||||
onChange={() => {
|
||||
setPage(1);
|
||||
setKindFilter(opt.value);
|
||||
}}
|
||||
>
|
||||
{opt.label}
|
||||
</Tag.CheckableTag>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{query.isLoading ? (
|
||||
<div className="flex justify-center py-16">
|
||||
<Spin />
|
||||
</div>
|
||||
) : items.length ? (
|
||||
<div className="grid grid-cols-4 gap-3">
|
||||
{items.map((asset) => (
|
||||
<PickerCard key={asset.id} title={asset.title} kind={asset.type} cover={asset.coverUrl} loading={inserting === asset.id} onClick={() => void handleInsert(asset)} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="没有素材" className="py-12" />
|
||||
)}
|
||||
|
||||
{total > PAGE_SIZE && (
|
||||
<div className="flex justify-center">
|
||||
<Pagination size="small" current={page} pageSize={PAGE_SIZE} total={total} onChange={setPage} showSizeChanger={false} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PickerCard({ title, kind, cover, loading, onClick }: { title: string; kind: string; cover: string; loading?: boolean; onClick: () => void }) {
|
||||
function PickerCard({ title, kind, cover, onClick }: { title: string; kind: string; cover: string; onClick: () => void }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="group relative cursor-pointer overflow-hidden rounded-lg border border-stone-200 bg-white text-left transition hover:border-stone-400 hover:shadow-md dark:border-stone-700 dark:bg-stone-900 dark:hover:border-stone-500"
|
||||
onClick={onClick}
|
||||
disabled={loading}
|
||||
>
|
||||
{cover ? (
|
||||
<img src={cover} alt={title} className="aspect-[4/3] w-full object-cover" />
|
||||
@@ -161,27 +50,11 @@ function PickerCard({ title, kind, cover, loading, onClick }: { title: string; k
|
||||
<Tag className="m-0 shrink-0 text-[10px]">{kind === "image" ? "图片" : kind === "video" ? "视频" : "文本"}</Tag>
|
||||
</div>
|
||||
</div>
|
||||
{loading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-white/60 dark:bg-stone-900/60">
|
||||
<Spin size="small" />
|
||||
</div>
|
||||
)}
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-stone-950/0 text-sm font-medium text-white opacity-0 transition group-hover:bg-stone-950/55 group-hover:opacity-100">插入</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
async function remoteImageToDataUrl(url: string) {
|
||||
const response = await axios.get(url, { responseType: "blob" });
|
||||
const blob = response.data as Blob;
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result || ""));
|
||||
reader.onerror = () => reject(new Error("读取图片失败"));
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
}
|
||||
|
||||
function MyAssetsTab({ onInsert }: { onInsert: (payload: InsertAssetPayload) => void }) {
|
||||
const assets = useAssetStore((state) => state.assets);
|
||||
const [keyword, setKeyword] = useState("");
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { Button, Tooltip } from "antd";
|
||||
import { ArrowUp, CheckCircle2, CircleAlert, ImagePlus, LoaderCircle, UserRound, Wrench, X, XCircle } from "lucide-react";
|
||||
|
||||
import { canvasThemes } from "@/lib/canvas-theme";
|
||||
import type { LocalUser } from "@/stores/use-user-store";
|
||||
|
||||
export type CanvasAgentChatAttachment = { id: string; name: string; url: string };
|
||||
export type CanvasAgentMode = "online" | "local";
|
||||
export type CanvasAgentChatMessage = {
|
||||
id: string;
|
||||
role: "user" | "assistant" | "system" | "tool" | "error";
|
||||
title?: string;
|
||||
text: string;
|
||||
meta?: string;
|
||||
detail?: unknown;
|
||||
attachments?: CanvasAgentChatAttachment[];
|
||||
};
|
||||
|
||||
const WORKING_TEXT = "working...";
|
||||
|
||||
export function AgentChatMessage({ item, theme, user, onRejectTool, onApproveTool }: { item: CanvasAgentChatMessage; theme: (typeof canvasThemes)[keyof typeof canvasThemes]; user: LocalUser | null; onRejectTool?: (id: string) => void; onApproveTool?: (id: string) => void }) {
|
||||
const isUser = item.role === "user";
|
||||
const isSystem = item.role === "system";
|
||||
const color = item.role === "error" ? "#dc2626" : item.role === "tool" ? "#2563eb" : theme.node.text;
|
||||
if (isSystem) {
|
||||
return (
|
||||
<div className="flex justify-center text-xs">
|
||||
<div className="max-w-[88%] px-3 py-1.5 text-center" style={{ color: theme.node.muted }}>
|
||||
{item.text}
|
||||
{item.meta ? <span className="ml-2 opacity-60">{item.meta}</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (item.role === "tool") {
|
||||
if (objectField(item.detail, "status") === "pending") return <AgentPendingToolCard summary={item.text} detail={item.detail} theme={theme} onReject={() => onRejectTool?.(item.id)} onApprove={() => onApproveTool?.(item.id)} />;
|
||||
return (
|
||||
<div className="flex items-start gap-3">
|
||||
<AgentAvatar theme={theme} />
|
||||
<AgentToolCard title={item.title || "工具调用"} text={item.text} detail={item.detail} theme={theme} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={`flex items-start gap-3 ${isUser ? "justify-end" : "justify-start"}`}>
|
||||
{!isUser ? <AgentAvatar theme={theme} /> : null}
|
||||
<div className={`min-w-0 max-w-[82%] text-sm leading-6 ${isUser ? "text-right" : "text-left"}`} style={{ color }}>
|
||||
<div className="whitespace-pre-wrap break-words text-left">{item.text}</div>
|
||||
{item.attachments?.length ? <AgentMessageAttachments attachments={item.attachments} /> : null}
|
||||
{item.meta ? <div className="mt-1 text-[11px] opacity-45">{item.meta}</div> : null}
|
||||
</div>
|
||||
{isUser ? <AgentUserAvatar user={user} theme={theme} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AgentPendingToolCard({ summary, detail, theme, onReject, onApprove }: { summary: string; detail?: unknown; theme: (typeof canvasThemes)[keyof typeof canvasThemes]; onReject?: () => void; onApprove?: () => void }) {
|
||||
return (
|
||||
<div className="flex items-start gap-3">
|
||||
<AgentAvatar theme={theme} />
|
||||
<div className="min-w-0 flex-1 rounded-xl border p-4" style={{ borderColor: theme.node.stroke, background: "transparent", color: theme.node.text }}>
|
||||
<details>
|
||||
<summary className="cursor-pointer list-none">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg border" style={{ borderColor: "rgba(217,119,6,.24)", color: "#d97706", background: "rgba(217,119,6,.04)" }}>
|
||||
<CircleAlert className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm font-semibold leading-5">
|
||||
<span>确认工具调用</span>
|
||||
<span className="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium" style={{ borderColor: "rgba(217,119,6,.22)", color: "#d97706", background: "rgba(217,119,6,.04)" }}>
|
||||
等待确认
|
||||
</span>
|
||||
{detail ? <span className="ml-auto text-xs font-normal" style={{ color: theme.node.muted }}>详情</span> : null}
|
||||
</div>
|
||||
<div className="mt-2 text-sm leading-6" style={{ color: theme.node.text }}>
|
||||
{summary}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</summary>
|
||||
{detail ? <AgentDetailBlock detail={detail} theme={theme} /> : null}
|
||||
</details>
|
||||
{onReject || onApprove ? (
|
||||
<div className="mt-4 grid grid-cols-2 gap-2">
|
||||
<Button danger className="!h-9" icon={<XCircle className="size-4" />} onClick={() => onReject?.()}>
|
||||
拒绝执行
|
||||
</Button>
|
||||
<Button className="!h-9" icon={<CheckCircle2 className="size-4" />} style={{ borderColor: "rgba(22,163,74,.42)", color: "#16a34a", background: "transparent" }} onClick={() => onApprove?.()}>
|
||||
批准执行
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AgentToolCard({ title, text, detail, theme }: { title: string; text: string; detail?: unknown; theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) {
|
||||
const state = toolCardState(title, text, detail);
|
||||
return (
|
||||
<details className="min-w-0 flex-1 rounded-xl border px-4 py-3.5 text-left" style={{ borderColor: theme.node.stroke, background: "transparent", color: theme.node.text }}>
|
||||
<summary className="cursor-pointer list-none">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg border" style={{ borderColor: state.softBorder, color: state.color, background: state.softBg }}>
|
||||
{state.icon}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm font-semibold leading-5">
|
||||
<span className="min-w-0 truncate">{title}</span>
|
||||
<span className="inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium" style={{ borderColor: state.softBorder, color: state.color, background: state.softBg }}>
|
||||
{state.label}
|
||||
</span>
|
||||
{detail ? <span className="ml-auto text-xs font-normal" style={{ color: theme.node.muted }}>详情</span> : null}
|
||||
</div>
|
||||
<div className="mt-2 text-sm leading-6" style={{ color: state.isError ? state.color : theme.node.muted }}>
|
||||
{text}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</summary>
|
||||
{detail ? <AgentDetailBlock detail={detail} theme={theme} /> : null}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
export function AgentWorkingMessage({ theme }: { theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) {
|
||||
const [length, setLength] = useState(1);
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => setLength((value) => (value >= WORKING_TEXT.length + 4 ? 1 : value + 1)), 120);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [setLength]);
|
||||
return (
|
||||
<div className="flex items-start gap-2.5">
|
||||
<AgentAvatar theme={theme} />
|
||||
<div className="min-w-0 max-w-[82%]">
|
||||
<div className="font-mono text-sm" style={{ color: theme.node.muted }} aria-label={WORKING_TEXT}>
|
||||
<span className="inline-block w-[76px]">{WORKING_TEXT.slice(0, Math.min(length, WORKING_TEXT.length))}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AgentChatComposer({
|
||||
prompt,
|
||||
attachments = [],
|
||||
disabled,
|
||||
sending,
|
||||
placeholder,
|
||||
theme,
|
||||
onPromptChange,
|
||||
onSubmit,
|
||||
onAddFiles,
|
||||
onRemoveAttachment,
|
||||
left,
|
||||
}: {
|
||||
prompt: string;
|
||||
attachments?: CanvasAgentChatAttachment[];
|
||||
disabled?: boolean;
|
||||
sending?: boolean;
|
||||
placeholder: string;
|
||||
theme: (typeof canvasThemes)[keyof typeof canvasThemes];
|
||||
onPromptChange: (value: string) => void;
|
||||
onSubmit: () => void;
|
||||
onAddFiles?: (files: FileList | File[] | null) => void | Promise<void>;
|
||||
onRemoveAttachment?: (id: string) => void;
|
||||
left?: ReactNode;
|
||||
}) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const canSubmit = !disabled && !sending && Boolean(prompt.trim() || attachments.length);
|
||||
return (
|
||||
<div className="px-2 pb-2 pt-2" onWheelCapture={(event) => event.stopPropagation()}>
|
||||
<div className="rounded-[24px] border px-3 pb-3 pt-3 shadow-lg" style={{ background: theme.toolbar.panel, borderColor: theme.node.stroke }}>
|
||||
{attachments.length ? (
|
||||
<div className="thin-scrollbar mb-2 flex gap-2 overflow-x-auto pb-1">
|
||||
{attachments.map((item) => (
|
||||
<div key={item.id} className="group relative size-14 shrink-0 overflow-hidden rounded-xl border" style={{ borderColor: theme.node.stroke }} title={item.name}>
|
||||
<img src={item.url} alt={item.name} className="size-full object-cover" />
|
||||
{onRemoveAttachment ? (
|
||||
<button type="button" className="absolute right-1 top-1 grid size-5 place-items-center rounded-full border opacity-0 shadow-sm transition group-hover:opacity-100" style={{ background: theme.toolbar.panel, borderColor: theme.node.stroke, color: theme.node.text }} onClick={() => onRemoveAttachment(item.id)} aria-label="移除图片">
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<textarea
|
||||
value={prompt}
|
||||
onChange={(event) => onPromptChange(event.target.value)}
|
||||
onPaste={(event) => {
|
||||
if (!onAddFiles) return;
|
||||
const images = Array.from(event.clipboardData.files).filter((file) => file.type.startsWith("image/"));
|
||||
if (!images.length) return;
|
||||
event.preventDefault();
|
||||
void onAddFiles(images);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter" || event.shiftKey || event.ctrlKey || event.metaKey) return;
|
||||
event.preventDefault();
|
||||
void onSubmit();
|
||||
}}
|
||||
className="thin-scrollbar max-h-32 min-h-20 w-full resize-none border-0 bg-transparent px-1 py-1 text-sm leading-5 outline-none placeholder:opacity-45"
|
||||
style={{ color: theme.node.text }}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
<div className="mt-2 flex items-center justify-between gap-2">
|
||||
<div className="flex min-w-0 items-center gap-1">
|
||||
{onAddFiles ? (
|
||||
<>
|
||||
<input ref={fileInputRef} hidden type="file" accept="image/*" multiple onChange={(event) => {
|
||||
void onAddFiles(event.target.files);
|
||||
event.target.value = "";
|
||||
}} />
|
||||
<Tooltip title="上传图片">
|
||||
<Button type="text" shape="circle" className="!h-9 !w-9 !min-w-9" disabled={sending} style={{ color: theme.node.muted }} icon={<ImagePlus className="size-4" />} onClick={() => fileInputRef.current?.click()} />
|
||||
</Tooltip>
|
||||
</>
|
||||
) : null}
|
||||
{left}
|
||||
</div>
|
||||
<Button type="primary" shape="circle" className="!h-10 !w-10 !min-w-10" disabled={!canSubmit} icon={sending ? <LoaderCircle className="size-4 animate-spin" /> : <ArrowUp className="size-4" />} onClick={() => void onSubmit()} aria-label="发送" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AgentModeSwitch({ value, theme, onChange }: { value: CanvasAgentMode; theme: (typeof canvasThemes)[keyof typeof canvasThemes]; onChange: (value: CanvasAgentMode) => void }) {
|
||||
return (
|
||||
<div className="inline-flex shrink-0 rounded-lg border p-0.5 text-xs" style={{ borderColor: theme.node.stroke }}>
|
||||
{(["online", "local"] as const).map((item) => (
|
||||
<button key={item} type="button" className="rounded-md px-2 py-1 transition" style={{ background: value === item ? theme.node.fill : "transparent", color: value === item ? theme.node.text : theme.node.muted }} onClick={() => onChange(item)}>
|
||||
{item === "online" ? "网站" : "本机"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AgentPanelTabs<T extends string>({ value, items, theme, right, onChange }: { value: T; items: { value: T; label: string; icon?: ReactNode; count?: number }[]; theme: (typeof canvasThemes)[keyof typeof canvasThemes]; right?: ReactNode; onChange: (value: T) => void }) {
|
||||
return (
|
||||
<div className="border-b px-3" style={{ borderColor: theme.node.stroke }}>
|
||||
<div className="flex min-h-11 items-center justify-between gap-3">
|
||||
<nav className="thin-scrollbar flex min-w-0 flex-1 items-center gap-3 overflow-x-auto text-sm" role="tablist" aria-label="Agent 面板">
|
||||
{items.map((item) => (
|
||||
<button key={item.value} type="button" role="tab" aria-selected={value === item.value} className={`inline-flex h-11 shrink-0 items-center gap-1.5 border-b-2 px-0.5 transition ${value === item.value ? "font-medium" : "font-normal"}`} style={{ borderColor: value === item.value ? theme.node.text : "transparent", color: value === item.value ? theme.node.text : theme.node.muted }} onClick={() => onChange(item.value)}>
|
||||
{item.icon}
|
||||
{item.label}{item.count ? ` ${item.count}` : ""}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
{right ? <div className="flex shrink-0 items-center gap-2">{right}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentDetailBlock({ detail, theme }: { detail: unknown; theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) {
|
||||
return (
|
||||
<pre className="thin-scrollbar mt-3 max-h-64 overflow-auto rounded-lg border p-3 text-[11px] leading-4" style={{ borderColor: theme.node.stroke, background: theme.toolbar.panel, color: theme.node.muted }}>
|
||||
{JSON.stringify(detail, null, 2)}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentAvatar({ theme }: { theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) {
|
||||
return (
|
||||
<span className="grid size-8 shrink-0 place-items-center" role="img" aria-label="OpenAI">
|
||||
<span className="size-5 opacity-80" style={{ background: theme.node.text, WebkitMask: "url(/icons/openai.svg) center / contain no-repeat", mask: "url(/icons/openai.svg) center / contain no-repeat" }} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentUserAvatar({ user, theme }: { user: LocalUser | null; theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) {
|
||||
const avatarUrl = user?.avatarUrl?.trim();
|
||||
return (
|
||||
<span className="grid size-8 shrink-0 place-items-center overflow-hidden rounded-full" style={{ color: theme.node.text }}>
|
||||
{avatarUrl ? <img src={avatarUrl} alt="" className="size-full object-cover" referrerPolicy="no-referrer" /> : <UserRound className="size-4" />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentMessageAttachments({ attachments }: { attachments: CanvasAgentChatAttachment[] }) {
|
||||
return (
|
||||
<div className="mt-2 grid grid-cols-3 gap-1.5">
|
||||
{attachments.map((item) => (
|
||||
<img key={item.id} src={item.url} alt={item.name} className="aspect-square w-full rounded-lg object-cover" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function toolCardState(title: string, text: string, detail?: unknown) {
|
||||
const raw = `${title} ${text} ${normalizeText(objectField(detail, "error"))}`;
|
||||
const lower = raw.toLowerCase();
|
||||
const tool = String(objectField(detail, "name") || objectField(detail, "tool") || "");
|
||||
if (objectField(detail, "status") === "noop" || /未生效|无需|没有找到|没有.*可|已存在/.test(raw)) return { label: "未生效", color: "#d97706", softBorder: "rgba(217,119,6,.22)", softBg: "rgba(217,119,6,.04)", icon: <CircleAlert className="size-4" />, isError: false };
|
||||
if (/拒绝|取消/.test(raw) || lower.includes("rejected")) return { label: "拒绝执行", color: "#dc2626", softBorder: "rgba(220,38,38,.20)", softBg: "rgba(220,38,38,.04)", icon: <XCircle className="size-4" />, isError: true };
|
||||
if (/失败|错误/.test(raw) || lower.includes("failed") || lower.includes("error")) return { label: "执行失败", color: "#dc2626", softBorder: "rgba(220,38,38,.20)", softBg: "rgba(220,38,38,.04)", icon: <XCircle className="size-4" />, isError: true };
|
||||
if (/完成|成功/.test(raw) || lower.includes("completed") || lower.includes("succeeded")) return { label: tool === "canvas_apply_ops" || /画布操作/.test(title) ? "已批准执行" : "执行完成", color: "#16a34a", softBorder: "rgba(22,163,74,.20)", softBg: "rgba(22,163,74,.04)", icon: <CheckCircle2 className="size-4" />, isError: false };
|
||||
return { label: "工具调用", color: "#2563eb", softBorder: "rgba(37,99,235,.20)", softBg: "rgba(37,99,235,.04)", icon: <Wrench className="size-4" />, isError: false };
|
||||
}
|
||||
|
||||
function normalizeText(value: unknown) {
|
||||
if (typeof value === "string") return value.trim();
|
||||
if (value instanceof Error) return value.message;
|
||||
if (value == null) return "";
|
||||
return JSON.stringify(value, null, 2);
|
||||
}
|
||||
|
||||
function objectField(value: unknown, key: string) {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>)[key] : undefined;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -183,6 +183,12 @@ export function CanvasConfigComposer({ value, inputs, onChange, onClose }: Canva
|
||||
|
||||
function MentionMenu({ inputs, allInputs, activeIndex, theme, onSelect }: { inputs: NodeGenerationInput[]; allInputs: NodeGenerationInput[]; activeIndex: number; theme: (typeof canvasThemes)[keyof typeof canvasThemes]; onSelect: (input: NodeGenerationInput) => void }) {
|
||||
const selectedRef = useRef(false);
|
||||
const activeItemRef = useRef<HTMLButtonElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
activeItemRef.current?.scrollIntoView({ block: "nearest" });
|
||||
}, [activeIndex, inputs]);
|
||||
|
||||
const selectInput = (input: NodeGenerationInput) => {
|
||||
if (selectedRef.current) return;
|
||||
selectedRef.current = true;
|
||||
@@ -194,6 +200,7 @@ function MentionMenu({ inputs, allInputs, activeIndex, theme, onSelect }: { inpu
|
||||
{inputs.map((input, index) => (
|
||||
<button
|
||||
key={input.nodeId}
|
||||
ref={index === activeIndex ? activeItemRef : undefined}
|
||||
type="button"
|
||||
className="flex w-full min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-xs transition"
|
||||
style={{ background: index === activeIndex ? theme.toolbar.activeBg : "transparent", color: index === activeIndex ? theme.toolbar.activeText : theme.node.text }}
|
||||
|
||||
@@ -25,13 +25,12 @@ type CanvasConfigNodePanelProps = {
|
||||
|
||||
export function CanvasConfigNodePanel({ node, isRunning, inputSummary, onConfigChange, onGenerate, onComposerToggle }: CanvasConfigNodePanelProps) {
|
||||
const globalConfig = useEffectiveConfig();
|
||||
const modelCosts = useConfigStore((state) => state.publicSettings?.modelChannel.modelCosts);
|
||||
const openConfigDialog = useConfigStore((state) => state.openConfigDialog);
|
||||
const theme = canvasThemes[useThemeStore((state) => state.theme)];
|
||||
const mode = node.metadata?.generationMode || "image";
|
||||
const config = buildNodeConfig(globalConfig, node, mode);
|
||||
const count = Math.max(1, Math.min(15, Math.floor(Math.abs(Number(config.count)) || 1)));
|
||||
const credits = requestCreditCost({ channelMode: config.channelMode, modelCosts, model: config.model, count: mode === "image" ? count : 1 });
|
||||
const credits = requestCreditCost({ channelMode: config.channelMode, model: config.model, count: mode === "image" ? count : 1 });
|
||||
const chipStyle = { background: theme.node.fill, borderColor: theme.node.stroke, color: theme.node.text };
|
||||
const hasAnyInput = Boolean(inputSummary.textCount || inputSummary.imageCount || inputSummary.videoCount || inputSummary.audioCount);
|
||||
const hasComposerContent = Boolean((node.metadata?.composerContent ?? node.metadata?.prompt ?? "").trim());
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
|
||||
import { App, Button, Input, Segmented, Switch, Tooltip } from "antd";
|
||||
import { App, Button, Input, Segmented, Tooltip } from "antd";
|
||||
import copyToClipboard from "copy-to-clipboard";
|
||||
import { ArrowUp, Bot, CheckCircle2, CircleAlert, Copy, FolderOpen, History, ImagePlus, KeyRound, Link2, LoaderCircle, PlugZap, Plus, RefreshCw, RotateCcw, Terminal, Trash2, UserRound, Wrench, X, XCircle } from "lucide-react";
|
||||
import { Copy, FolderOpen, History, KeyRound, Link2, LoaderCircle, PlugZap, Plus, RefreshCw, RotateCcw, Terminal, Trash2 } from "lucide-react";
|
||||
import { motion } from "motion/react";
|
||||
|
||||
import { canvasThemes } from "@/lib/canvas-theme";
|
||||
import type { AuthUser } from "@/services/api/auth";
|
||||
import { useThemeStore } from "@/stores/use-theme-store";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
import { useCanvasAgentStore, type AgentAttachment, type AgentChatItem, type AgentEventLog, type AgentPanelTab, type AgentPendingToolCall, type AgentThreadSummary } from "../stores/use-canvas-agent-store";
|
||||
import { summarizeCanvasAgentOps, type CanvasAgentOp, type CanvasAgentSnapshot } from "../utils/canvas-agent-ops";
|
||||
import { AgentChatComposer, AgentChatMessage, AgentPanelTabs, AgentPendingToolCard, AgentWorkingMessage, type CanvasAgentChatAttachment } from "./canvas-agent-chat-ui";
|
||||
|
||||
const PANEL_MOTION_SECONDS = 0.5;
|
||||
const MAX_ATTACHMENTS = 6;
|
||||
const MAX_ATTACHMENT_PAYLOAD_BYTES = 28 * 1024 * 1024;
|
||||
const WORKING_TEXT = "working...";
|
||||
const AGENT_CONNECT_STEPS = [
|
||||
{ title: "1. 本机已安装并登录 Codex", text: "先确认本机终端里的 Codex 可以正常使用。", command: "codex --version" },
|
||||
{ title: "2. 安装 Canvas Agent", text: "推荐全局安装,后续可以直接运行 canvas-agent。", command: "npm i -g @basketikun/canvas-agent" },
|
||||
@@ -40,7 +39,7 @@ type AgentWorkspace = { canvasId: string; workspacePath: string; activeThreadId?
|
||||
type AgentThreadsResponse = { ok?: boolean; workspace?: AgentWorkspace; data?: AgentThreadSummary[] };
|
||||
type AgentThreadResponse = { ok?: boolean; workspace?: AgentWorkspace; thread?: AgentThreadSummary; messages?: AgentChatItem[] };
|
||||
|
||||
export function CanvasLocalAgentPanel({ snapshot, canUndoOps, collapsed, onApplyOps, onUndoOps, onCollapseStart }: { snapshot: CanvasAgentSnapshot; canUndoOps: boolean; collapsed: boolean; onApplyOps: (ops: CanvasAgentOp[]) => unknown; onUndoOps: () => CanvasAgentSnapshot | null; onCollapseStart: () => void }) {
|
||||
export function CanvasLocalAgentPanel({ snapshot, canUndoOps, collapsed, embedded, onApplyOps, onUndoOps }: { snapshot: CanvasAgentSnapshot; canUndoOps: boolean; collapsed?: boolean; embedded?: boolean; onApplyOps: (ops: CanvasAgentOp[]) => unknown; onUndoOps: () => CanvasAgentSnapshot | null }) {
|
||||
const theme = canvasThemes[useThemeStore((state) => state.theme)];
|
||||
const user = useUserStore((state) => state.user);
|
||||
const { message, modal } = App.useApp();
|
||||
@@ -56,11 +55,6 @@ export function CanvasLocalAgentPanel({ snapshot, canUndoOps, collapsed, onApply
|
||||
const attachmentUrlsRef = useRef(new Set<string>());
|
||||
const clientIdRef = useRef(typeof crypto === "undefined" ? `${Date.now()}` : crypto.randomUUID());
|
||||
const endpoint = useMemo(() => url.trim().replace(/\/$/, ""), [url]);
|
||||
const tabStyle = (tab: AgentPanelTab) => ({
|
||||
borderColor: activeTab === tab ? theme.node.text : "transparent",
|
||||
color: activeTab === tab ? theme.node.text : theme.node.muted,
|
||||
});
|
||||
|
||||
const loadThreads = useCallback(async () => {
|
||||
const projectId = snapshotRef.current.projectId;
|
||||
if ((!connectedRef.current && !useCanvasAgentStore.getState().connected) || !projectId) return;
|
||||
@@ -75,7 +69,7 @@ export function CanvasLocalAgentPanel({ snapshot, canUndoOps, collapsed, onApply
|
||||
});
|
||||
const nextThreadId = data.workspace?.activeThreadId || current.activeThreadId;
|
||||
if (nextThreadId && !current.messages.length) {
|
||||
const thread = await fetchAgentJson<AgentThreadResponse>(endpoint, token, `/agent/codex/threads/${encodeURIComponent(nextThreadId)}`);
|
||||
const thread = await fetchAgentJson<AgentThreadResponse>(endpoint, token, `/agent/codex/threads/${encodeURIComponent(nextThreadId)}?canvasId=${encodeURIComponent(projectId)}`);
|
||||
setAgentState({ messages: normalizeHistoryMessages(thread.messages || []) });
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -464,73 +458,29 @@ export function CanvasLocalAgentPanel({ snapshot, canUndoOps, collapsed, onApply
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className="relative z-[70] flex h-full shrink-0"
|
||||
initial={{ width: 0, opacity: 0 }}
|
||||
animate={{ width: collapsed ? 0 : width + 1, opacity: collapsed ? 0 : 1 }}
|
||||
transition={{ duration: resizing ? 0 : PANEL_MOTION_SECONDS, ease: [0.22, 1, 0.36, 1] }}
|
||||
style={{ overflow: "clip", pointerEvents: collapsed ? "none" : undefined }}
|
||||
>
|
||||
<motion.aside
|
||||
className="relative flex h-full shrink-0 flex-col border-l"
|
||||
initial={{ x: 48 }}
|
||||
animate={{ x: collapsed ? 28 : 0 }}
|
||||
transition={{ duration: resizing ? 0 : PANEL_MOTION_SECONDS, ease: [0.22, 1, 0.36, 1] }}
|
||||
style={{ width, background: theme.node.panel, borderColor: theme.node.stroke, color: theme.node.text }}
|
||||
>
|
||||
<div className="absolute left-0 top-0 h-full w-1 cursor-col-resize transition hover:bg-current/20" onPointerDown={startResize} />
|
||||
<header className="flex h-14 items-center justify-between border-b px-4" style={{ borderColor: theme.node.stroke }}>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="grid size-8 place-items-center rounded-lg">
|
||||
<Bot className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<div className="text-base font-semibold leading-5">Agent</div>
|
||||
<div className="truncate text-xs" style={{ color: theme.node.muted }}>
|
||||
Codex · {connected ? activity : "离线"}
|
||||
</div>
|
||||
</div>
|
||||
<span className="ml-1 rounded-full border px-2 py-0.5 text-xs" style={{ borderColor: connected ? "#16a34a" : theme.node.stroke, color: connected ? "#16a34a" : theme.node.muted }}>
|
||||
{connected ? "在线" : "离线"}
|
||||
</span>
|
||||
</div>
|
||||
<Button type="text" icon={<X className="size-4" />} onClick={onCollapseStart} />
|
||||
</header>
|
||||
|
||||
<div className="border-b px-3" style={{ borderColor: theme.node.stroke }}>
|
||||
<div className="flex min-h-11 items-center justify-between gap-3">
|
||||
<nav className="thin-scrollbar flex min-w-0 flex-1 items-center gap-3 overflow-x-auto text-sm" role="tablist" aria-label="Agent 面板">
|
||||
<button type="button" role="tab" aria-selected={activeTab === "setup"} className={`inline-flex h-11 shrink-0 items-center gap-1.5 border-b-2 px-0.5 transition ${activeTab === "setup" ? "font-medium" : "font-normal"}`} style={tabStyle("setup")} onClick={() => setAgentState({ activeTab: "setup" })}>
|
||||
<PlugZap className="size-3.5" />
|
||||
连接
|
||||
</button>
|
||||
<button type="button" role="tab" aria-selected={activeTab === "chat"} className={`h-11 shrink-0 border-b-2 px-0.5 transition ${activeTab === "chat" ? "font-medium" : "font-normal"}`} style={tabStyle("chat")} onClick={() => setAgentState({ activeTab: "chat" })}>
|
||||
对话
|
||||
</button>
|
||||
<button type="button" role="tab" aria-selected={activeTab === "history"} className={`inline-flex h-11 shrink-0 items-center gap-1.5 border-b-2 px-0.5 transition ${activeTab === "history" ? "font-medium" : "font-normal"}`} style={tabStyle("history")} onClick={() => {
|
||||
setAgentState({ activeTab: "history" });
|
||||
void loadThreads();
|
||||
}}>
|
||||
<History className="size-3.5" />
|
||||
历史{threads.length ? ` ${threads.length}` : ""}
|
||||
</button>
|
||||
<button type="button" role="tab" aria-selected={activeTab === "log"} className={`inline-flex h-11 shrink-0 items-center gap-1.5 border-b-2 px-0.5 transition ${activeTab === "log" ? "font-medium" : "font-normal"}`} style={tabStyle("log")} onClick={() => setAgentState({ activeTab: "log" })}>
|
||||
<Terminal className="size-3.5" />
|
||||
日志{eventLogs.length ? ` ${eventLogs.length}` : ""}
|
||||
</button>
|
||||
</nav>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<label className="flex items-center gap-1.5 text-xs" style={{ color: theme.node.muted }}>
|
||||
<Switch size="small" checked={confirmTools} onChange={(confirmTools) => setAgentState({ confirmTools })} />
|
||||
工具确认
|
||||
</label>
|
||||
const content = (
|
||||
<>
|
||||
<AgentPanelTabs
|
||||
value={activeTab}
|
||||
theme={theme}
|
||||
items={[
|
||||
{ value: "setup", label: "连接", icon: <PlugZap className="size-3.5" /> },
|
||||
{ value: "chat", label: "对话" },
|
||||
{ value: "history", label: "历史", icon: <History className="size-3.5" />, count: threads.length },
|
||||
{ value: "log", label: "日志", icon: <Terminal className="size-3.5" />, count: eventLogs.length },
|
||||
]}
|
||||
onChange={(activeTab) => {
|
||||
setAgentState({ activeTab });
|
||||
if (activeTab === "history") void loadThreads();
|
||||
}}
|
||||
right={
|
||||
<>
|
||||
<Button size="small" type="text" disabled={!canUndoOps} icon={<RotateCcw className="size-3.5" />} onClick={undoLastTool}>
|
||||
撤销
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{activeTab === "setup" ? (
|
||||
<AgentConnectView
|
||||
@@ -571,71 +521,50 @@ export function CanvasLocalAgentPanel({ snapshot, canUndoOps, collapsed, onApply
|
||||
<>
|
||||
<div ref={listRef} className="thin-scrollbar min-h-0 flex-1 space-y-4 overflow-y-auto p-4">
|
||||
{messages.map((item) => (
|
||||
<ChatMessage key={item.id} item={item} theme={theme} user={user} />
|
||||
<AgentChatMessage key={item.id} item={agentMessageToChatMessage(item)} theme={theme} user={user} />
|
||||
))}
|
||||
{pendingTool ? <PendingToolCard tool={pendingTool} theme={theme} onReject={rejectPendingTool} onApprove={approvePendingTool} /> : null}
|
||||
{waiting && !pendingTool ? <WorkingMessage theme={theme} /> : null}
|
||||
{pendingTool ? <AgentPendingToolCard summary={summarizeCanvasAgentOps(pendingTool.input?.ops || []) || toolName(pendingTool.name)} detail={{ requestId: pendingTool.requestId, name: pendingTool.name, input: pendingTool.input }} theme={theme} onReject={rejectPendingTool} onApprove={approvePendingTool} /> : null}
|
||||
{waiting && !pendingTool ? <AgentWorkingMessage theme={theme} /> : null}
|
||||
</div>
|
||||
<AgentComposer prompt={prompt} attachments={attachments} connected={connected} sending={sending || waiting} theme={theme} onPromptChange={(prompt) => setAgentState({ prompt })} onSubmit={sendPrompt} onAddFiles={addAttachments} onRemoveAttachment={removeAttachment} />
|
||||
<AgentChatComposer
|
||||
prompt={prompt}
|
||||
attachments={attachments.map(agentAttachmentToChatAttachment)}
|
||||
disabled={!connected}
|
||||
sending={sending || waiting}
|
||||
placeholder="询问 Codex,或让它操作画布"
|
||||
theme={theme}
|
||||
onPromptChange={(prompt) => setAgentState({ prompt })}
|
||||
onSubmit={sendPrompt}
|
||||
onAddFiles={addAttachments}
|
||||
onRemoveAttachment={removeAttachment}
|
||||
left={attachments.length ? <span className="text-[11px]" style={{ color: theme.node.muted }}>{formatBytes(attachmentPayloadBytes(attachments))} / 30MB</span> : null}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</motion.aside>
|
||||
</motion.div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentComposer({ prompt, attachments, connected, sending, theme, onPromptChange, onSubmit, onAddFiles, onRemoveAttachment }: { prompt: string; attachments: AgentAttachment[]; connected: boolean; sending: boolean; theme: (typeof canvasThemes)[keyof typeof canvasThemes]; onPromptChange: (value: string) => void; onSubmit: () => void; onAddFiles: (files: FileList | File[] | null) => Promise<void>; onRemoveAttachment: (id: string) => void }) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const canSubmit = connected && !sending && Boolean(prompt.trim() || attachments.length);
|
||||
const sizeText = attachments.length ? `${formatBytes(attachmentPayloadBytes(attachments))} / 30MB` : "";
|
||||
if (embedded) return content;
|
||||
|
||||
return (
|
||||
<div className="border-t px-2 pb-2 pt-2" style={{ borderColor: theme.node.stroke }} onWheelCapture={(event) => event.stopPropagation()}>
|
||||
<div className="rounded-[24px] border px-3 pb-3 pt-3 shadow-lg" style={{ background: theme.toolbar.panel, borderColor: theme.node.stroke }}>
|
||||
{attachments.length ? (
|
||||
<div className="thin-scrollbar mb-2 flex gap-2 overflow-x-auto pb-1">
|
||||
{attachments.map((item) => (
|
||||
<div key={item.id} className="group relative size-14 shrink-0 overflow-hidden rounded-xl border" style={{ borderColor: theme.node.stroke }} title={item.name}>
|
||||
<img src={item.url} alt={item.name} className="size-full object-cover" />
|
||||
<button type="button" className="absolute right-1 top-1 grid size-5 place-items-center rounded-full border opacity-0 shadow-sm transition group-hover:opacity-100" style={{ background: theme.toolbar.panel, borderColor: theme.node.stroke, color: theme.node.text }} onClick={() => onRemoveAttachment(item.id)} aria-label="移除图片">
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<textarea
|
||||
value={prompt}
|
||||
onChange={(event) => onPromptChange(event.target.value)}
|
||||
onPaste={(event) => {
|
||||
const images = Array.from(event.clipboardData.files).filter((file) => file.type.startsWith("image/"));
|
||||
if (!images.length) return;
|
||||
event.preventDefault();
|
||||
void onAddFiles(images);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter" || event.shiftKey || event.ctrlKey || event.metaKey) return;
|
||||
event.preventDefault();
|
||||
void onSubmit();
|
||||
}}
|
||||
className="thin-scrollbar max-h-32 min-h-20 w-full resize-none border-0 bg-transparent px-1 py-1 text-sm leading-5 outline-none placeholder:opacity-45"
|
||||
style={{ color: theme.node.text }}
|
||||
placeholder="询问 Codex,或让它操作画布"
|
||||
/>
|
||||
<div className="mt-2 flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1">
|
||||
<input ref={fileInputRef} hidden type="file" accept="image/*" multiple onChange={(event) => {
|
||||
void onAddFiles(event.target.files);
|
||||
event.target.value = "";
|
||||
}} />
|
||||
<Tooltip title="上传图片">
|
||||
<Button type="text" shape="circle" className="!h-9 !w-9 !min-w-9" disabled={sending} style={{ color: theme.node.muted }} icon={<ImagePlus className="size-4" />} onClick={() => fileInputRef.current?.click()} />
|
||||
</Tooltip>
|
||||
{sizeText ? <span className="text-[11px]" style={{ color: theme.node.muted }}>{sizeText}</span> : null}
|
||||
</div>
|
||||
<Button type="primary" shape="circle" className="!h-10 !w-10 !min-w-10" disabled={!canSubmit} icon={sending ? <LoaderCircle className="size-4 animate-spin" /> : <ArrowUp className="size-4" />} onClick={() => void onSubmit()} aria-label="发送" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<motion.div
|
||||
className="relative z-[70] flex h-full shrink-0"
|
||||
initial={{ width: 0, opacity: 0 }}
|
||||
animate={{ width: collapsed ? 0 : width + 1, opacity: collapsed ? 0 : 1 }}
|
||||
transition={{ duration: resizing ? 0 : PANEL_MOTION_SECONDS, ease: [0.22, 1, 0.36, 1] }}
|
||||
style={{ overflow: "clip", pointerEvents: collapsed ? "none" : undefined }}
|
||||
>
|
||||
<motion.aside
|
||||
className="relative flex h-full shrink-0 flex-col border-l"
|
||||
initial={{ x: 48 }}
|
||||
animate={{ x: collapsed ? 28 : 0 }}
|
||||
transition={{ duration: resizing ? 0 : PANEL_MOTION_SECONDS, ease: [0.22, 1, 0.36, 1] }}
|
||||
style={{ width, background: theme.node.panel, borderColor: theme.node.stroke, color: theme.node.text }}
|
||||
>
|
||||
<div className="absolute left-0 top-0 h-full w-1 cursor-col-resize transition hover:bg-current/20" onPointerDown={startResize} />
|
||||
{content}
|
||||
</motion.aside>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -823,182 +752,6 @@ function AgentHistoryView({ theme, threads, activeThreadId, workspacePath, loadi
|
||||
);
|
||||
}
|
||||
|
||||
function ChatMessage({ item, theme, user }: { item: AgentChatItem; theme: (typeof canvasThemes)[keyof typeof canvasThemes]; user: AuthUser | null }) {
|
||||
const isUser = item.role === "user";
|
||||
const isSystem = item.role === "system";
|
||||
const color = item.role === "error" ? "#dc2626" : item.role === "tool" ? "#2563eb" : theme.node.text;
|
||||
if (isSystem) {
|
||||
return (
|
||||
<div className="flex justify-center text-xs">
|
||||
<div className="max-w-[88%] px-3 py-1.5 text-center" style={{ color: theme.node.muted }}>
|
||||
<div>
|
||||
{item.text}
|
||||
{item.meta ? <span className="ml-2 opacity-60">{item.meta}</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (item.role === "tool") {
|
||||
return (
|
||||
<div className="flex items-start gap-3">
|
||||
<OpenAiAvatar theme={theme} />
|
||||
<ToolCard title={item.title || "工具调用"} text={item.text} detail={item.detail} theme={theme} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={`flex items-start gap-3 ${isUser ? "justify-end" : "justify-start"}`}>
|
||||
{!isUser ? <OpenAiAvatar theme={theme} /> : null}
|
||||
<div className={`min-w-0 max-w-[82%] text-sm leading-6 ${isUser ? "text-right" : "text-left"}`} style={{ color }}>
|
||||
<div className="whitespace-pre-wrap break-words">{item.text}</div>
|
||||
{item.attachments?.length ? <MessageAttachments attachments={item.attachments} /> : null}
|
||||
{item.meta ? <div className="mt-1 text-[11px] opacity-45">{item.meta}</div> : null}
|
||||
</div>
|
||||
{isUser ? <UserAvatar user={user} theme={theme} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PendingToolCard({ tool, theme, onReject, onApprove }: { tool: AgentPendingToolCall; theme: (typeof canvasThemes)[keyof typeof canvasThemes]; onReject: () => void; onApprove: () => void }) {
|
||||
const summary = summarizeCanvasAgentOps(tool.input?.ops || []) || toolName(tool.name);
|
||||
return (
|
||||
<div className="flex items-start gap-3">
|
||||
<OpenAiAvatar theme={theme} />
|
||||
<div className="min-w-0 flex-1 rounded-xl border p-4" style={{ borderColor: theme.node.stroke, background: "transparent", color: theme.node.text }}>
|
||||
<details>
|
||||
<summary className="cursor-pointer list-none">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg border" style={{ borderColor: "rgba(217,119,6,.24)", color: "#d97706", background: "rgba(217,119,6,.04)" }}>
|
||||
<CircleAlert className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm font-semibold leading-5">
|
||||
<span>确认工具调用</span>
|
||||
<span className="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium" style={{ borderColor: "rgba(217,119,6,.22)", color: "#d97706", background: "rgba(217,119,6,.04)" }}>
|
||||
等待确认
|
||||
</span>
|
||||
<span className="ml-auto text-xs font-normal" style={{ color: theme.node.muted }}>详情</span>
|
||||
</div>
|
||||
<div className="mt-2 text-sm leading-6" style={{ color: theme.node.text }}>
|
||||
{summary}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</summary>
|
||||
<DetailBlock detail={{ requestId: tool.requestId, name: tool.name, input: tool.input }} theme={theme} />
|
||||
</details>
|
||||
<div className="mt-4 grid grid-cols-2 gap-2">
|
||||
<Button danger className="!h-9" icon={<XCircle className="size-4" />} onClick={() => void onReject()}>
|
||||
拒绝执行
|
||||
</Button>
|
||||
<Button className="!h-9" icon={<CheckCircle2 className="size-4" />} style={{ borderColor: "rgba(22,163,74,.42)", color: "#16a34a", background: "transparent" }} onClick={() => void onApprove()}>
|
||||
批准执行
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolCard({ title, text, detail, theme }: { title: string; text: string; detail?: unknown; theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) {
|
||||
const state = toolCardState(title, text, detail);
|
||||
return (
|
||||
<details className="min-w-0 flex-1 rounded-xl border px-4 py-3.5 text-left" style={{ borderColor: theme.node.stroke, background: "transparent", color: theme.node.text }}>
|
||||
<summary className="cursor-pointer list-none">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg border" style={{ borderColor: state.softBorder, color: state.color, background: state.softBg }}>
|
||||
{state.icon}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm font-semibold leading-5">
|
||||
<span className="min-w-0 truncate">{title}</span>
|
||||
<span className="inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium" style={{ borderColor: state.softBorder, color: state.color, background: state.softBg }}>
|
||||
{state.label}
|
||||
</span>
|
||||
{detail ? <span className="ml-auto text-xs font-normal" style={{ color: theme.node.muted }}>详情</span> : null}
|
||||
</div>
|
||||
<div className="mt-2 text-sm leading-6" style={{ color: state.isError ? state.color : theme.node.muted }}>
|
||||
{text}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</summary>
|
||||
{detail ? <DetailBlock detail={detail} theme={theme} /> : null}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailBlock({ detail, theme }: { detail: unknown; theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) {
|
||||
return (
|
||||
<pre className="thin-scrollbar mt-3 max-h-64 overflow-auto rounded-lg border p-3 text-[11px] leading-4" style={{ borderColor: theme.node.stroke, background: theme.toolbar.panel, color: theme.node.muted }}>
|
||||
{JSON.stringify(detail, null, 2)}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
function toolCardState(title: string, text: string, detail?: unknown) {
|
||||
const raw = `${title} ${text} ${normalizeText(objectField(detail, "error"))}`;
|
||||
const lower = raw.toLowerCase();
|
||||
const tool = String(objectField(detail, "name") || objectField(detail, "tool") || "");
|
||||
if (/拒绝|取消/.test(raw) || lower.includes("rejected")) {
|
||||
return { label: "拒绝执行", color: "#dc2626", softBorder: "rgba(220,38,38,.20)", softBg: "rgba(220,38,38,.04)", icon: <XCircle className="size-4" />, isError: true };
|
||||
}
|
||||
if (/失败|错误/.test(raw) || lower.includes("failed") || lower.includes("error")) {
|
||||
return { label: "执行失败", color: "#dc2626", softBorder: "rgba(220,38,38,.20)", softBg: "rgba(220,38,38,.04)", icon: <XCircle className="size-4" />, isError: true };
|
||||
}
|
||||
if (/完成|成功/.test(raw) || lower.includes("completed") || lower.includes("succeeded")) {
|
||||
const label = tool === "canvas_apply_ops" || /画布操作/.test(title) ? "已批准执行" : "执行完成";
|
||||
return { label, color: "#16a34a", softBorder: "rgba(22,163,74,.20)", softBg: "rgba(22,163,74,.04)", icon: <CheckCircle2 className="size-4" />, isError: false };
|
||||
}
|
||||
return { label: "工具调用", color: "#2563eb", softBorder: "rgba(37,99,235,.20)", softBg: "rgba(37,99,235,.04)", icon: <Wrench className="size-4" />, isError: false };
|
||||
}
|
||||
|
||||
function WorkingMessage({ theme }: { theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) {
|
||||
const [length, setLength] = useState(1);
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => setLength((value) => (value >= WORKING_TEXT.length + 4 ? 1 : value + 1)), 120);
|
||||
return () => window.clearInterval(timer);
|
||||
}, []);
|
||||
return (
|
||||
<div className="flex items-start gap-2.5">
|
||||
<OpenAiAvatar theme={theme} />
|
||||
<div className="min-w-0 max-w-[82%]">
|
||||
<div className="font-mono text-sm" style={{ color: theme.node.muted }} aria-label={WORKING_TEXT}>
|
||||
<span className="inline-block w-[76px]">{WORKING_TEXT.slice(0, Math.min(length, WORKING_TEXT.length))}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OpenAiAvatar({ theme }: { theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) {
|
||||
return (
|
||||
<span className="grid size-8 shrink-0 place-items-center" role="img" aria-label="OpenAI">
|
||||
<span className="size-5 opacity-80" style={{ background: theme.node.text, WebkitMask: "url(/icons/openai.svg) center / contain no-repeat", mask: "url(/icons/openai.svg) center / contain no-repeat" }} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function UserAvatar({ user, theme }: { user: AuthUser | null; theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) {
|
||||
const avatarUrl = user?.avatarUrl?.trim();
|
||||
return (
|
||||
<span className="grid size-8 shrink-0 place-items-center overflow-hidden rounded-full" style={{ color: theme.node.text }}>
|
||||
{avatarUrl ? <img src={avatarUrl} alt="" className="size-full object-cover" referrerPolicy="no-referrer" /> : <UserRound className="size-4" />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function MessageAttachments({ attachments }: { attachments: AgentAttachment[] }) {
|
||||
return (
|
||||
<div className="mt-2 grid grid-cols-3 gap-1.5">
|
||||
{attachments.map((item) => (
|
||||
<img key={item.id} src={item.dataUrl || item.url} alt={item.name} className="aspect-square w-full rounded-lg object-cover" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function postState(endpoint: string, token: string, clientId: string, snapshot: CanvasAgentSnapshot) {
|
||||
try {
|
||||
await fetch(`${endpoint}/canvas/state?token=${encodeURIComponent(token)}&clientId=${encodeURIComponent(clientId)}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(snapshot) });
|
||||
@@ -1009,6 +762,14 @@ async function postToolResult(endpoint: string, token: string, clientId: string,
|
||||
await fetch(`${endpoint}/canvas/result?token=${encodeURIComponent(token)}&clientId=${encodeURIComponent(clientId)}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
||||
}
|
||||
|
||||
function agentMessageToChatMessage(item: AgentChatItem) {
|
||||
return { ...item, attachments: item.attachments?.map(agentAttachmentToChatAttachment) };
|
||||
}
|
||||
|
||||
function agentAttachmentToChatAttachment(item: AgentAttachment): CanvasAgentChatAttachment {
|
||||
return { id: item.id, name: item.name, url: item.dataUrl || item.url };
|
||||
}
|
||||
|
||||
function formatAgentEvent(event: AgentEventPayload): Omit<AgentChatItem, "id"> | null {
|
||||
const item = event.item;
|
||||
if (event.type === "item.completed" && item?.type === "error") return { role: "error", title: "错误", text: normalizeText(item.message), detail: item };
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ChatCompletionMessage } from "@/services/api/image";
|
||||
import type { AiTextMessage } from "@/services/api/image";
|
||||
import { imageReferenceLabel } from "@/lib/image-reference-prompt";
|
||||
import { seedanceReferenceLabel } from "@/lib/seedance-video";
|
||||
import type { ReferenceImage } from "@/types/image";
|
||||
@@ -127,7 +127,7 @@ export function buildNodeGenerationInputs(nodeId: string, nodes: CanvasNodeData[
|
||||
});
|
||||
}
|
||||
|
||||
export function buildNodeChatMessages(context: NodeGenerationContext): ChatCompletionMessage[] {
|
||||
export function buildNodeResponseMessages(context: NodeGenerationContext): AiTextMessage[] {
|
||||
if (!context.referenceImages.length) {
|
||||
return [{ role: "user", content: context.prompt }];
|
||||
}
|
||||
|
||||
@@ -31,7 +31,6 @@ type CanvasNodePromptPanelProps = {
|
||||
|
||||
export function CanvasNodePromptPanel({ node, isRunning, onPromptChange, onConfigChange, onGenerate, mentionReferences = [], onImageSettingsOpenChange }: CanvasNodePromptPanelProps) {
|
||||
const globalConfig = useEffectiveConfig();
|
||||
const modelCosts = useConfigStore((state) => state.publicSettings?.modelChannel.modelCosts);
|
||||
const openConfigDialog = useConfigStore((state) => state.openConfigDialog);
|
||||
const theme = canvasThemes[useThemeStore((state) => state.theme)];
|
||||
const mode = defaultMode(node.type);
|
||||
@@ -40,7 +39,7 @@ export function CanvasNodePromptPanel({ node, isRunning, onPromptChange, onConfi
|
||||
const hasImageContent = node.type === CanvasNodeType.Image && Boolean(node.metadata?.content);
|
||||
const isEditingExistingContent = hasTextContent || hasImageContent;
|
||||
const [prompt, setPrompt] = useState(isEditingExistingContent ? "" : node.metadata?.prompt || "");
|
||||
const credits = requestCreditCost({ channelMode: config.channelMode, modelCosts, model: config.model, count: mode === "image" ? config.count : 1 });
|
||||
const credits = requestCreditCost({ channelMode: config.channelMode, model: config.model, count: mode === "image" ? config.count : 1 });
|
||||
|
||||
useEffect(() => {
|
||||
setPrompt(isEditingExistingContent ? "" : node.metadata?.prompt || "");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { CSSProperties, MouseEvent as ReactMouseEvent, ReactNode, RefObject } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import { Button, Segmented, Switch } from "antd";
|
||||
import { CircleDot, Eraser, FolderOpen, Grid2x2, Hand, Image as ImageIcon, Info, Library, Moon, Music2, Palette, Redo2, Settings2, Square, Sun, Trash2, Type, Undo2, Upload, Video } from "lucide-react";
|
||||
import { CircleDot, Eraser, FolderOpen, Grid2x2, Hand, Image as ImageIcon, Info, Moon, Music2, Palette, Redo2, Settings2, Square, Sun, Trash2, Type, Undo2, Upload, Video } from "lucide-react";
|
||||
|
||||
import { canvasThemes, type CanvasBackgroundMode, type CanvasColorTheme, type CanvasTheme } from "@/lib/canvas-theme";
|
||||
import { useThemeStore } from "@/stores/use-theme-store";
|
||||
@@ -26,7 +26,6 @@ export function CanvasToolbar({
|
||||
onDeselect,
|
||||
onBackgroundModeChange,
|
||||
onShowImageInfoChange,
|
||||
onOpenAssetLibrary,
|
||||
onOpenMyAssets,
|
||||
}: {
|
||||
selectedCount: number;
|
||||
@@ -47,7 +46,6 @@ export function CanvasToolbar({
|
||||
onDeselect: () => void;
|
||||
onBackgroundModeChange: (mode: CanvasBackgroundMode) => void;
|
||||
onShowImageInfoChange: (show: boolean) => void;
|
||||
onOpenAssetLibrary: () => void;
|
||||
onOpenMyAssets: () => void;
|
||||
}) {
|
||||
const wrapRef = useRef<HTMLDivElement>(null);
|
||||
@@ -96,9 +94,6 @@ export function CanvasToolbar({
|
||||
<Upload className="size-4.5" />
|
||||
</ToolbarButton>
|
||||
<Divider theme={theme} />
|
||||
<ToolbarButton id="tool-library" label="素材库" hovered={hovered} hoverStyle={hoverStyle} wrapRef={wrapRef} onTipX={setTipX} onHover={setHovered} onClick={onOpenAssetLibrary}>
|
||||
<Library className="size-4.5" />
|
||||
</ToolbarButton>
|
||||
<ToolbarButton id="tool-assets" label="我的素材" hovered={hovered} hoverStyle={hoverStyle} wrapRef={wrapRef} onTipX={setTipX} onHover={setHovered} onClick={onOpenMyAssets}>
|
||||
<FolderOpen className="size-4.5" />
|
||||
</ToolbarButton>
|
||||
@@ -287,7 +282,6 @@ function toolLabel(id: string) {
|
||||
if (id === "tool-audio") return "音频";
|
||||
if (id === "tool-config") return "生成配置";
|
||||
if (id === "tool-upload") return "上传素材";
|
||||
if (id === "tool-library") return "素材库";
|
||||
if (id === "tool-assets") return "我的素材";
|
||||
if (id === "tool-style") return "画布外观";
|
||||
if (id === "tool-delete") return "删除选中";
|
||||
|
||||
@@ -92,12 +92,12 @@ export type CanvasAssistantImage = {
|
||||
|
||||
export type CanvasAssistantMessage = {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
mode: "ask" | "image";
|
||||
role: "user" | "assistant" | "system" | "tool" | "error";
|
||||
title?: string;
|
||||
text: string;
|
||||
isLoading?: boolean;
|
||||
meta?: string;
|
||||
detail?: unknown;
|
||||
references?: CanvasAssistantReference[];
|
||||
images?: CanvasAssistantImage[];
|
||||
};
|
||||
|
||||
export type CanvasAssistantSession = {
|
||||
|
||||
@@ -6,7 +6,8 @@ import { CanvasNodeType, type CanvasConnection, type CanvasNodeData, type Canvas
|
||||
export type CanvasAgentOp =
|
||||
| { type: "add_node"; id?: string; nodeType?: CanvasNodeType; title?: string; position?: { x: number; y: number }; x?: number; y?: number; width?: number; height?: number; metadata?: CanvasNodeMetadata }
|
||||
| { type: "update_node"; id: string; patch?: Partial<CanvasNodeData>; metadata?: CanvasNodeMetadata }
|
||||
| { type: "delete_node"; id?: string; ids?: string[] }
|
||||
| { type: "delete_node"; id?: string; ids?: string[]; nodeType?: CanvasNodeType }
|
||||
| { type: "delete_connections"; id?: string; ids?: string[]; all?: boolean }
|
||||
| { type: "connect_nodes"; id?: string; fromNodeId: string; toNodeId: string }
|
||||
| { type: "set_viewport"; viewport: ViewportTransform }
|
||||
| { type: "select_nodes"; ids: string[] }
|
||||
@@ -21,8 +22,9 @@ export type CanvasAgentSnapshot = {
|
||||
viewport: ViewportTransform;
|
||||
};
|
||||
|
||||
export function summarizeCanvasAgentOps(ops: CanvasAgentOp[]) {
|
||||
const counts = ops.reduce<Record<string, number>>((acc, op) => {
|
||||
export function summarizeCanvasAgentOps(ops?: CanvasAgentOp[]) {
|
||||
const counts = (Array.isArray(ops) ? ops : []).reduce<Record<string, number>>((acc, op) => {
|
||||
if (!op?.type) return acc;
|
||||
acc[op.type] = (acc[op.type] || 0) + 1;
|
||||
return acc;
|
||||
}, {});
|
||||
@@ -31,15 +33,16 @@ export function summarizeCanvasAgentOps(ops: CanvasAgentOp[]) {
|
||||
.join(",");
|
||||
}
|
||||
|
||||
export function applyCanvasAgentOps(snapshot: CanvasAgentSnapshot, ops: CanvasAgentOp[]) {
|
||||
export function applyCanvasAgentOps(snapshot: CanvasAgentSnapshot, ops?: CanvasAgentOp[]) {
|
||||
let nodes = snapshot.nodes;
|
||||
let connections = snapshot.connections;
|
||||
let selectedNodeIds = snapshot.selectedNodeIds;
|
||||
let viewport = snapshot.viewport;
|
||||
|
||||
ops.forEach((op, index) => {
|
||||
(Array.isArray(ops) ? ops : []).forEach((op, index) => {
|
||||
if (!op?.type) return;
|
||||
if (op.type === "add_node") {
|
||||
const nodeType = op.nodeType || CanvasNodeType.Text;
|
||||
const nodeType = Object.values(CanvasNodeType).includes(op.nodeType as CanvasNodeType) ? op.nodeType! : CanvasNodeType.Text;
|
||||
const spec = getNodeSpec(nodeType);
|
||||
const node: CanvasNodeData = {
|
||||
id: op.id || `${nodeType}-${Date.now()}-${index}`,
|
||||
@@ -54,21 +57,27 @@ export function applyCanvasAgentOps(snapshot: CanvasAgentSnapshot, ops: CanvasAg
|
||||
selectedNodeIds = [node.id];
|
||||
}
|
||||
if (op.type === "update_node") {
|
||||
if (!op.id) return;
|
||||
nodes = nodes.map((node) => (node.id === op.id ? { ...node, ...op.patch, metadata: { ...node.metadata, ...op.patch?.metadata, ...op.metadata } } : node));
|
||||
}
|
||||
if (op.type === "delete_node") {
|
||||
const ids = new Set(op.ids || (op.id ? [op.id] : []));
|
||||
const ids = new Set(op.ids || (op.id ? [op.id] : op.nodeType ? nodes.filter((node) => node.type === op.nodeType).map((node) => node.id) : []));
|
||||
nodes = nodes.filter((node) => !ids.has(node.id));
|
||||
connections = connections.filter((conn) => !ids.has(conn.fromNodeId) && !ids.has(conn.toNodeId));
|
||||
selectedNodeIds = selectedNodeIds.filter((id) => !ids.has(id));
|
||||
}
|
||||
if (op.type === "delete_connections") {
|
||||
const ids = new Set(op.ids || (op.id ? [op.id] : []));
|
||||
connections = op.all ? [] : connections.filter((conn) => !ids.has(conn.id));
|
||||
}
|
||||
if (op.type === "connect_nodes") {
|
||||
if (!op.fromNodeId || !op.toNodeId) return;
|
||||
const exists = connections.some((conn) => conn.fromNodeId === op.fromNodeId && conn.toNodeId === op.toNodeId);
|
||||
const hasNodes = nodes.some((node) => node.id === op.fromNodeId) && nodes.some((node) => node.id === op.toNodeId);
|
||||
if (!exists && hasNodes) connections = [...connections, { id: op.id || nanoid(), fromNodeId: op.fromNodeId, toNodeId: op.toNodeId }];
|
||||
}
|
||||
if (op.type === "set_viewport") viewport = op.viewport;
|
||||
if (op.type === "select_nodes") selectedNodeIds = op.ids.filter((id) => nodes.some((node) => node.id === id));
|
||||
if (op.type === "set_viewport" && op.viewport) viewport = op.viewport;
|
||||
if (op.type === "select_nodes") selectedNodeIds = (op.ids || []).filter((id) => nodes.some((node) => node.id === id));
|
||||
});
|
||||
|
||||
return { ...snapshot, nodes, connections, selectedNodeIds, viewport };
|
||||
@@ -78,6 +87,7 @@ function opLabel(type: string) {
|
||||
if (type === "add_node") return "新增节点";
|
||||
if (type === "update_node") return "更新节点";
|
||||
if (type === "delete_node") return "删除节点";
|
||||
if (type === "delete_connections") return "删除连线";
|
||||
if (type === "connect_nodes") return "连接";
|
||||
if (type === "set_viewport") return "调整视图";
|
||||
if (type === "select_nodes") return "选择节点";
|
||||
|
||||
@@ -12,7 +12,7 @@ import { PromptSelectDialog } from "@/components/prompts/prompt-select-dialog";
|
||||
import { AssetPickerModal, type InsertAssetPayload } from "@/app/(user)/canvas/components/asset-picker-modal";
|
||||
import { canvasThemes } from "@/lib/canvas-theme";
|
||||
import { imageReferenceLabel } from "@/lib/image-reference-prompt";
|
||||
import { useConfigStore, useEffectiveConfig, type AiConfig } from "@/stores/use-config-store";
|
||||
import { modelOptionLabel, useConfigStore, useEffectiveConfig, type AiConfig } from "@/stores/use-config-store";
|
||||
import { useThemeStore } from "@/stores/use-theme-store";
|
||||
import { nanoid } from "nanoid";
|
||||
import { formatBytes, formatDuration, getDataUrlByteSize, readImageMeta } from "@/lib/image-utils";
|
||||
@@ -396,7 +396,7 @@ export default function ImagePage() {
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border border-stone-200 bg-stone-50 px-3 py-2 text-sm dark:border-stone-800 dark:bg-stone-900 sm:hidden">
|
||||
<span className="truncate text-stone-500 dark:text-stone-400">
|
||||
{model} · {effectiveConfig.size} · {effectiveConfig.quality}
|
||||
{modelOptionLabel(effectiveConfig, model)} · {effectiveConfig.size} · {effectiveConfig.quality}
|
||||
</span>
|
||||
<Button size="small" type="text" icon={<SlidersHorizontal className="size-4" />} onClick={() => setSettingsOpen(true)}>
|
||||
调整
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { LockOutlined, UserOutlined } from "@ant-design/icons";
|
||||
import { App, Button, Form, Input, Segmented, Space } from "antd";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
|
||||
import { fetchCurrentUser } from "@/services/api/auth";
|
||||
import { useConfigStore } from "@/stores/use-config-store";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
|
||||
type LoginFormValues = {
|
||||
username: string;
|
||||
password: string;
|
||||
confirmPassword?: string;
|
||||
};
|
||||
|
||||
// 仅放行站内相对路径,拦截开放重定向。浏览器会忽略 URL 中的 Tab/换行/回车,并把
|
||||
// //host 或 /\host 解析为协议相对的跨站地址,因此先剥离控制字符,再拒绝 // 与 /\ 前缀。
|
||||
function safeRedirect(value: string | null): string {
|
||||
const cleaned = (value ?? "").replace(/[\t\n\r]/g, "");
|
||||
if (!cleaned.startsWith("/") || cleaned.startsWith("//") || cleaned.startsWith("/\\")) {
|
||||
return "/";
|
||||
}
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<LoginContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginContent() {
|
||||
const { message } = App.useApp();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const login = useUserStore((state) => state.login);
|
||||
const register = useUserStore((state) => state.register);
|
||||
const setSession = useUserStore((state) => state.setSession);
|
||||
const isLoading = useUserStore((state) => state.isLoading);
|
||||
const linuxDoEnabled = useConfigStore((state) => state.publicSettings?.auth?.linuxDo?.enabled === true);
|
||||
const allowRegister = useConfigStore((state) => state.publicSettings?.auth?.allowRegister !== false);
|
||||
const [mode, setMode] = useState<"login" | "register">("login");
|
||||
const redirect = safeRedirect(searchParams.get("redirect"));
|
||||
|
||||
useEffect(() => {
|
||||
const token = searchParams.get("token");
|
||||
const error = searchParams.get("error");
|
||||
if (error) message.error(error);
|
||||
if (!token) return;
|
||||
void fetchCurrentUser(token).then((user) => {
|
||||
setSession(token, user);
|
||||
message.success("登录成功");
|
||||
router.replace(redirect);
|
||||
router.refresh();
|
||||
});
|
||||
}, [message, redirect, router, searchParams, setSession]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!allowRegister && mode === "register") setMode("login");
|
||||
}, [allowRegister, mode]);
|
||||
|
||||
const submit = async (values: LoginFormValues) => {
|
||||
try {
|
||||
if (mode === "register" && !allowRegister) {
|
||||
message.error("当前未开放注册");
|
||||
return;
|
||||
}
|
||||
if (mode === "register" && values.password !== values.confirmPassword) {
|
||||
message.error("两次输入的密码不一致");
|
||||
return;
|
||||
}
|
||||
const action = mode === "register" ? register : login;
|
||||
const user = await action({ username: values.username, password: values.password });
|
||||
message.success(mode === "register" ? "注册成功" : "登录成功");
|
||||
router.replace(redirect);
|
||||
router.refresh();
|
||||
if (user.role !== "admin") router.replace("/");
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : "登录失败");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex h-full min-h-0 items-center justify-center overflow-y-auto bg-background bg-[radial-gradient(#e5e7eb_1px,transparent_1px)] px-6 py-10 [background-size:16px_16px] dark:bg-[radial-gradient(rgba(245,245,244,.16)_1px,transparent_1px)]">
|
||||
<section className="w-full max-w-[420px]">
|
||||
<div className="mb-7 text-center">
|
||||
<span
|
||||
className="mx-auto mb-4 block size-12 bg-stone-950 dark:bg-stone-100"
|
||||
style={{
|
||||
mask: "url(/logo.svg) center / contain no-repeat",
|
||||
WebkitMask: "url(/logo.svg) center / contain no-repeat",
|
||||
}}
|
||||
aria-label="无限画布"
|
||||
/>
|
||||
<h1 className="text-3xl font-semibold tracking-normal text-stone-950 dark:text-stone-100">账号登录</h1>
|
||||
<p className="mt-3 text-base leading-7 text-stone-500 dark:text-stone-400">支持账号密码和 Linux.do 登录。</p>
|
||||
</div>
|
||||
|
||||
<Form<LoginFormValues> layout="vertical" size="large" requiredMark={false} onFinish={submit}>
|
||||
<Form.Item>
|
||||
<Segmented
|
||||
block
|
||||
value={mode}
|
||||
onChange={(value) => setMode(value as "login" | "register")}
|
||||
options={allowRegister ? [{ label: "登录", value: "login" }, { label: "注册", value: "register" }] : [{ label: "登录", value: "login" }]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="username" label={<span className="font-medium text-stone-800 dark:text-stone-200">用户名</span>} rules={[{ required: true, message: "请输入用户名" }]}>
|
||||
<Input prefix={<UserOutlined />} autoComplete="username" />
|
||||
</Form.Item>
|
||||
<Form.Item name="password" label={<span className="font-medium text-stone-800 dark:text-stone-200">密码</span>} rules={[{ required: true, message: "请输入密码" }]}>
|
||||
<Input.Password prefix={<LockOutlined />} autoComplete="current-password" />
|
||||
</Form.Item>
|
||||
{mode === "register" ? (
|
||||
<Form.Item name="confirmPassword" label={<span className="font-medium text-stone-800 dark:text-stone-200">确认密码</span>} rules={[{ required: true, message: "请再次输入密码" }]}>
|
||||
<Input.Password prefix={<LockOutlined />} autoComplete="new-password" />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
<Space orientation="vertical" size={12} style={{ width: "100%" }}>
|
||||
<Button block type="primary" htmlType="submit" loading={isLoading}>
|
||||
{mode === "register" ? "注册" : "登录"}
|
||||
</Button>
|
||||
{linuxDoEnabled ? (
|
||||
<Button block href={`/api/auth/linux-do/authorize?redirect=${encodeURIComponent(redirect)}`} icon={<img src="/icons/linuxdo.svg" alt="" width={18} height={18} />}>
|
||||
使用 Linux.do 登录
|
||||
</Button>
|
||||
) : null}
|
||||
</Space>
|
||||
</Form>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import { deleteStoredMedia, resolveMediaUrl, uploadMediaFile } from "@/services/
|
||||
import { resolveImageUrl, uploadImage } from "@/services/image-storage";
|
||||
import { createVideoGenerationTask, pollVideoGenerationTask, storeGeneratedVideo, type VideoGenerationTask } from "@/services/api/video";
|
||||
import { useAssetStore } from "@/stores/use-asset-store";
|
||||
import { useConfigStore, useEffectiveConfig, type AiConfig } from "@/stores/use-config-store";
|
||||
import { modelOptionLabel, useConfigStore, useEffectiveConfig, type AiConfig } from "@/stores/use-config-store";
|
||||
import { useThemeStore } from "@/stores/use-theme-store";
|
||||
import type { ReferenceImage } from "@/types/image";
|
||||
import type { ReferenceAudio, ReferenceVideo } from "@/types/media";
|
||||
@@ -460,7 +460,7 @@ export default function VideoPage() {
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border border-stone-200 bg-stone-50 px-3 py-2 text-sm dark:border-stone-800 dark:bg-stone-900 sm:hidden">
|
||||
<span className="truncate text-stone-500 dark:text-stone-400">
|
||||
{model} · {normalizeResolution(effectiveConfig.vquality)}p · {videoSizeLabel(effectiveConfig.size)} · {normalizeVideoSeconds(effectiveConfig.videoSeconds)}s
|
||||
{modelOptionLabel(effectiveConfig, model)} · {normalizeResolution(effectiveConfig.vquality)}p · {videoSizeLabel(effectiveConfig.size)} · {normalizeVideoSeconds(effectiveConfig.videoSeconds)}s
|
||||
</span>
|
||||
<Button size="small" type="text" icon={<SlidersHorizontal className="size-4" />} onClick={() => setSettingsOpen(true)}>
|
||||
调整
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const maxDuration = 300;
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{ path: string[] }>;
|
||||
};
|
||||
|
||||
function proxyHeaders(request: NextRequest) {
|
||||
const headers = new Headers(request.headers);
|
||||
headers.delete("host");
|
||||
headers.delete("content-length");
|
||||
headers.delete("connection");
|
||||
headers.set("x-forwarded-host", request.nextUrl.host);
|
||||
headers.set("x-forwarded-proto", request.nextUrl.protocol.replace(":", ""));
|
||||
return headers;
|
||||
}
|
||||
|
||||
function responseHeaders(response: Response) {
|
||||
const headers = new Headers(response.headers);
|
||||
headers.delete("content-length");
|
||||
headers.delete("content-encoding");
|
||||
headers.delete("transfer-encoding");
|
||||
return headers;
|
||||
}
|
||||
|
||||
async function proxy(request: NextRequest, context: RouteContext) {
|
||||
const { path } = await context.params;
|
||||
const apiBaseUrl = process.env.API_BASE_URL || "http://127.0.0.1:8080";
|
||||
const target = `${apiBaseUrl.replace(/\/$/, "")}/api/${path.map(encodeURIComponent).join("/")}${request.nextUrl.search}`;
|
||||
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
||||
|
||||
try {
|
||||
const response = await fetch(target, {
|
||||
method: request.method,
|
||||
headers: proxyHeaders(request),
|
||||
body: hasBody ? request.body : undefined,
|
||||
duplex: hasBody ? "half" : undefined,
|
||||
redirect: "manual",
|
||||
} as RequestInit & { duplex?: "half" });
|
||||
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: responseHeaders(response),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to proxy", target, error);
|
||||
return Response.json({ code: 1, data: null, msg: "接口连接失败,请确认后端服务已启动" }, { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = proxy;
|
||||
export const HEAD = proxy;
|
||||
export const POST = proxy;
|
||||
export const PUT = proxy;
|
||||
export const PATCH = proxy;
|
||||
export const DELETE = proxy;
|
||||
export const OPTIONS = proxy;
|
||||
@@ -0,0 +1,258 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Prompt = {
|
||||
id: string;
|
||||
title: string;
|
||||
coverUrl: string;
|
||||
prompt: string;
|
||||
tags: string[];
|
||||
category: string;
|
||||
githubUrl: string;
|
||||
preview: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
type PromptCategory = {
|
||||
category: string;
|
||||
githubUrl: string;
|
||||
build: () => Promise<Omit<Prompt, "category" | "githubUrl">[]>;
|
||||
};
|
||||
|
||||
const gptImage2RawBase = "https://raw.githubusercontent.com/EvoLinkAI/awesome-gpt-image-2-API-and-Prompts/main";
|
||||
const awesomeGptImageRawBase = "https://raw.githubusercontent.com/ZeroLu/awesome-gpt-image/main";
|
||||
const awesomeGpt4oImagePromptsBase = "https://raw.githubusercontent.com/ImgEdify/Awesome-GPT4o-Image-Prompts/main";
|
||||
const youMindGptImage2RawBase = "https://raw.githubusercontent.com/YouMind-OpenLab/awesome-gpt-image-2/main";
|
||||
const youMindNanoBananaProRawBase = "https://raw.githubusercontent.com/YouMind-OpenLab/awesome-nano-banana-pro-prompts/main";
|
||||
const davidWuGptImage2RawBase = "https://raw.githubusercontent.com/davidwuw0811-boop/awesome-gpt-image2-prompts/main";
|
||||
const gptImage2CaseFiles = ["README.md", "cases/ad-creative.md", "cases/character.md", "cases/comparison.md", "cases/ecommerce.md", "cases/portrait.md", "cases/poster.md", "cases/ui.md"];
|
||||
const cacheTtlMs = 1000 * 60 * 60;
|
||||
|
||||
const categories: PromptCategory[] = [
|
||||
{ category: "gpt-image-2-prompts", githubUrl: "https://github.com/EvoLinkAI/awesome-gpt-image-2-API-and-Prompts", build: buildGptImage2Prompts },
|
||||
{ category: "awesome-gpt-image", githubUrl: "https://github.com/ZeroLu/awesome-gpt-image", build: buildAwesomeGptImagePrompts },
|
||||
{ category: "awesome-gpt4o-image-prompts", githubUrl: "https://github.com/ImgEdify/Awesome-GPT4o-Image-Prompts", build: buildAwesomeGpt4oImagePrompts },
|
||||
{ category: "youmind-gpt-image-2", githubUrl: "https://github.com/YouMind-OpenLab/awesome-gpt-image-2", build: () => buildYouMindPrompts(youMindGptImage2RawBase, "youmind-gpt-image-2", "gpt-image-2") },
|
||||
{ category: "youmind-nano-banana-pro", githubUrl: "https://github.com/YouMind-OpenLab/awesome-nano-banana-pro-prompts", build: () => buildYouMindPrompts(youMindNanoBananaProRawBase, "youmind-nano-banana-pro", "nano-banana-pro") },
|
||||
{ category: "davidwu-gpt-image2-prompts", githubUrl: "https://github.com/davidwuw0811-boop/awesome-gpt-image2-prompts", build: buildDavidWuGptImage2Prompts },
|
||||
];
|
||||
|
||||
let memoryCache: { items: Prompt[]; fetchedAt: number } | null = null;
|
||||
let loadingPrompts: Promise<Prompt[]> | null = null;
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const params = request.nextUrl.searchParams;
|
||||
const keyword = (params.get("keyword") || "").trim().toLowerCase();
|
||||
const tags = params.getAll("tag").filter(Boolean);
|
||||
const category = params.get("category") || "";
|
||||
const page = Math.max(1, Number(params.get("page")) || 1);
|
||||
const pageSize = Math.max(1, Math.min(100, Number(params.get("pageSize")) || 20));
|
||||
const items = await getPrompts();
|
||||
const withoutTagFilter = filterPrompts(items, { keyword, category, tags: [] });
|
||||
const filtered = filterPrompts(items, { keyword, category, tags });
|
||||
|
||||
return Response.json({
|
||||
items: filtered.slice((page - 1) * pageSize, page * pageSize),
|
||||
tags: collectTags(withoutTagFilter),
|
||||
categories: categories.map((item) => item.category),
|
||||
total: filtered.length,
|
||||
});
|
||||
}
|
||||
|
||||
async function getPrompts() {
|
||||
if (memoryCache && Date.now() - memoryCache.fetchedAt < cacheTtlMs) return memoryCache.items;
|
||||
if (loadingPrompts) return loadingPrompts;
|
||||
loadingPrompts = loadPrompts().finally(() => {
|
||||
loadingPrompts = null;
|
||||
});
|
||||
return loadingPrompts;
|
||||
}
|
||||
|
||||
async function loadPrompts() {
|
||||
const settled = await Promise.all(
|
||||
categories.map(async (category) => {
|
||||
try {
|
||||
const items = await category.build();
|
||||
return items.map((item) => ({ ...item, category: category.category, githubUrl: category.githubUrl }));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}),
|
||||
);
|
||||
const items = settled.flat();
|
||||
memoryCache = { items, fetchedAt: Date.now() };
|
||||
return items;
|
||||
}
|
||||
|
||||
function filterPrompts(items: Prompt[], options: { keyword: string; category: string; tags: string[] }) {
|
||||
return items.filter((item) => {
|
||||
if (isActiveOption(options.category) && item.category !== options.category) return false;
|
||||
if (options.tags.length && !options.tags.some((tag) => item.tags.includes(tag))) return false;
|
||||
if (!options.keyword) return true;
|
||||
return [item.title, item.prompt, item.category, ...item.tags].join(" ").toLowerCase().includes(options.keyword);
|
||||
});
|
||||
}
|
||||
|
||||
async function buildGptImage2Prompts() {
|
||||
const data = (await fetchJson<{ records?: Array<{ title?: string; tweet_url?: string; image_dir?: string; category?: string; added_at?: string }> }>(gptImage2RawBase, "data/ingested_tweets.json")).records || [];
|
||||
const cases = new Map<string, string>();
|
||||
const markdowns = await Promise.all(gptImage2CaseFiles.map((file) => fetchText(gptImage2RawBase, file)));
|
||||
markdowns.forEach((markdown) => collectGptImage2Cases(cases, markdown));
|
||||
const items: Omit<Prompt, "category" | "githubUrl">[] = [];
|
||||
data.forEach((item) => {
|
||||
const prompt = cases.get(item.tweet_url || "");
|
||||
if (!item.title || !prompt || !item.image_dir) return;
|
||||
const image = `${gptImage2RawBase}/${item.image_dir}/output.jpg`;
|
||||
items.push({ id: `gpt-image-2-prompts-${leftPad(items.length + 1)}`, title: item.title, coverUrl: image, prompt, tags: tagsFromCategory(item.category || ""), preview: markdownPreview([image]), createdAt: item.added_at || "", updatedAt: item.added_at || "" });
|
||||
});
|
||||
return items;
|
||||
}
|
||||
|
||||
function collectGptImage2Cases(cases: Map<string, string>, markdown: string) {
|
||||
for (const match of markdown.matchAll(/### Case \d+: \[[^\]]+]\(([^)]+)\).*?\*\*Prompt:\*\*\s*\r?\n\s*```[\w-]*\r?\n(.*?)\r?\n```/gs)) {
|
||||
cases.set(match[1], match[2].trim());
|
||||
}
|
||||
}
|
||||
|
||||
async function buildAwesomeGptImagePrompts() {
|
||||
const markdown = await fetchText(awesomeGptImageRawBase, "README.zh-CN.md");
|
||||
const items: Omit<Prompt, "category" | "githubUrl">[] = [];
|
||||
for (const section of splitBeforeHeading(markdown, "## ")) {
|
||||
const tags = tagsFromHeading(firstMatch(section, /^##\s+(.+)$/m));
|
||||
for (const block of splitBeforeHeading(section, "### ")) {
|
||||
const title = firstMatch(block, /^###\s+(.+)$/m).replace(/\[([^\]]+)]\([^)]+\)/g, "$1").trim();
|
||||
const prompt = firstMatch(block, /\*\*提示词:\*\*\s*\r?\n\s*```[\w-]*\r?\n(.*?)\r?\n```/s).trim();
|
||||
if (!title || !prompt) continue;
|
||||
const images = extractMarkdownImages(awesomeGptImageRawBase, block);
|
||||
items.push(defaultPrompt(`awesome-gpt-image-${leftPad(items.length + 1)}`, title, prompt, images[0] || "", tags, markdownPreview(images)));
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
async function buildAwesomeGpt4oImagePrompts() {
|
||||
const markdown = await fetchText(awesomeGpt4oImagePromptsBase, "README.zh-CN.md");
|
||||
const items: Omit<Prompt, "category" | "githubUrl">[] = [];
|
||||
for (const block of splitBeforeHeading(markdown, "### ")) {
|
||||
const title = firstMatch(block, /^###\s+(.+)$/m).trim();
|
||||
const prompt = firstMatch(block, /- \*\*提示词文本:\*\*\s*`(.*?)`/s).trim();
|
||||
if (!title || !prompt) continue;
|
||||
const images = extractMarkdownImages(awesomeGpt4oImagePromptsBase, block);
|
||||
items.push(defaultPrompt(`awesome-gpt4o-image-prompts-${leftPad(items.length + 1)}`, title, prompt, images[0] || "", ["gpt4o"], markdownPreview(images)));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
async function buildYouMindPrompts(baseUrl: string, idPrefix: string, modelTag: string) {
|
||||
const markdown = await fetchText(baseUrl, "README_zh.md");
|
||||
const items: Omit<Prompt, "category" | "githubUrl">[] = [];
|
||||
for (const block of splitBeforeHeading(markdown, "### ")) {
|
||||
const title = firstMatch(block, /^###\s+No\.\s*\d+:\s*(.+)$/m).trim();
|
||||
const prompt = firstMatch(block, /#### .*?提示词\s*\r?\n\s*```[\w-]*\r?\n(.*?)\r?\n```/s).trim();
|
||||
if (!title || !prompt) continue;
|
||||
const images = extractMarkdownImages(baseUrl, block);
|
||||
items.push(defaultPrompt(`${idPrefix}-${leftPad(items.length + 1)}`, title, prompt, images[0] || "", youMindTags(title, modelTag), markdownPreview(images)));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
async function buildDavidWuGptImage2Prompts() {
|
||||
const data = await fetchJson<Array<{ id?: number; title_en?: string; title_cn?: string; category?: string; category_cn?: string; prompt?: string; note?: string; author?: string; source?: string; needs_ref?: boolean; image?: string }>>(davidWuGptImage2RawBase, "prompts.json");
|
||||
return data
|
||||
.map((item, index) => {
|
||||
const title = (item.title_cn || item.title_en || "").trim();
|
||||
const prompt = (item.prompt || "").trim();
|
||||
if (!title || !prompt) return null;
|
||||
const image = absoluteImage(davidWuGptImage2RawBase, item.image || "");
|
||||
const preview = [item.title_en, item.note, image ? `` : ""].filter(Boolean).join("\n\n");
|
||||
return defaultPrompt(`davidwu-gpt-image2-prompts-${leftPad(item.id || index + 1)}`, title, prompt, image, davidWuTags(item), preview);
|
||||
})
|
||||
.filter((item): item is Omit<Prompt, "category" | "githubUrl"> => Boolean(item));
|
||||
}
|
||||
|
||||
function defaultPrompt(id: string, title: string, prompt: string, coverUrl: string, tags: string[], preview: string): Omit<Prompt, "category" | "githubUrl"> {
|
||||
return { id, title, coverUrl, prompt, tags, preview, createdAt: "", updatedAt: "" };
|
||||
}
|
||||
|
||||
async function fetchText(baseUrl: string, file: string) {
|
||||
const response = await fetch(`${baseUrl}/${file}`, { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`${file} 拉取失败`);
|
||||
return response.text();
|
||||
}
|
||||
|
||||
async function fetchJson<T>(baseUrl: string, file: string) {
|
||||
return JSON.parse(await fetchText(baseUrl, file)) as T;
|
||||
}
|
||||
|
||||
function splitBeforeHeading(markdown: string, prefix: string) {
|
||||
const blocks: string[] = [];
|
||||
let current: string[] = [];
|
||||
for (const line of markdown.split("\n")) {
|
||||
if (line.startsWith(prefix) && current.length) {
|
||||
blocks.push(current.join("\n"));
|
||||
current = [];
|
||||
}
|
||||
current.push(line);
|
||||
}
|
||||
blocks.push(current.join("\n"));
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function firstMatch(value: string, pattern: RegExp) {
|
||||
return pattern.exec(value)?.[1] || "";
|
||||
}
|
||||
|
||||
function extractMarkdownImages(baseUrl: string, markdown: string) {
|
||||
return Array.from(markdown.matchAll(/!\[[^\]]*]\(([^)]+)\)/g), (match) => absoluteImage(baseUrl, match[1])).filter(Boolean);
|
||||
}
|
||||
|
||||
function absoluteImage(baseUrl: string, image: string) {
|
||||
if (!image) return "";
|
||||
if (/^https?:\/\//i.test(image)) return image;
|
||||
return `${baseUrl}/${image.replace(/^\.?\//, "")}`;
|
||||
}
|
||||
|
||||
function tagsFromCategory(category: string) {
|
||||
return splitTags(category.replace(/\s+Cases$/i, ""), /\s*(?:&|and)\s*/);
|
||||
}
|
||||
|
||||
function tagsFromHeading(heading: string) {
|
||||
return splitTags(heading.replace(/[^\p{L}\p{N}/&、与 ]/gu, ""), /\s*(?:\/|&|、|与)\s*/);
|
||||
}
|
||||
|
||||
function youMindTags(title: string, modelTag: string) {
|
||||
const [, prefix] = title.match(/^(.+?) - /) || [];
|
||||
return [modelTag, ...tagsFromHeading(prefix || "")];
|
||||
}
|
||||
|
||||
function davidWuTags(item: { category_cn?: string; category?: string; author?: string; source?: string; needs_ref?: boolean }) {
|
||||
const tags = splitTags([item.category_cn, item.category, item.author, item.source].filter(Boolean).join("/"), /\//);
|
||||
if (item.needs_ref) tags.push("需要参考图");
|
||||
return tags;
|
||||
}
|
||||
|
||||
function splitTags(value: string, pattern: RegExp) {
|
||||
return value
|
||||
.split(pattern)
|
||||
.map((tag) => tag.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function markdownPreview(images: string[]) {
|
||||
return images.filter(Boolean).map((image) => ``).join("\n\n");
|
||||
}
|
||||
|
||||
function collectTags(items: Prompt[]) {
|
||||
return Array.from(new Set(items.flatMap((item) => item.tags).filter(Boolean)));
|
||||
}
|
||||
|
||||
function leftPad(value: number) {
|
||||
return String(value).padStart(4, "0");
|
||||
}
|
||||
|
||||
function isActiveOption(value: string) {
|
||||
return value && value !== "全部" && value !== "all";
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Home, LogIn } from "lucide-react";
|
||||
import { Home } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
export default function NotFound() {
|
||||
@@ -14,13 +14,6 @@ export default function NotFound() {
|
||||
<Home className="size-4" />
|
||||
返回首页
|
||||
</Link>
|
||||
<Link
|
||||
href="/login"
|
||||
className="inline-flex h-10 items-center gap-2 rounded-lg border border-stone-200 bg-background px-4 text-sm font-medium text-stone-900 transition hover:bg-stone-100 dark:border-stone-800 dark:text-stone-100 dark:hover:bg-stone-800"
|
||||
>
|
||||
<LogIn className="size-4" />
|
||||
去登录
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
@@ -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, useEffectiveConfig, type AiConfig, 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,60 +68,80 @@ export function AppConfigModal() {
|
||||
const shouldPromptContinue = useConfigStore((state) => state.shouldPromptContinue);
|
||||
const setConfigDialogOpen = useConfigStore((state) => state.setConfigDialogOpen);
|
||||
const clearPromptContinue = useConfigStore((state) => state.clearPromptContinue);
|
||||
const publicSettings = useConfigStore((state) => state.publicSettings);
|
||||
const effectiveConfig = useEffectiveConfig();
|
||||
const modelChannel = publicSettings?.modelChannel;
|
||||
const allowCustomChannel = modelChannel?.allowCustomChannel === true;
|
||||
const effectiveMode = allowCustomChannel ? config.channelMode : "remote";
|
||||
const modelConfig = effectiveMode === "remote" ? effectiveConfig : config;
|
||||
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 (effectiveMode === "local" && (!config.baseUrl.trim() || !config.apiKey.trim())) return;
|
||||
if (!modelConfig.imageModel.trim() || !modelConfig.videoModel.trim() || !modelConfig.textModel.trim()) return;
|
||||
if (!allowCustomChannel && config.channelMode !== "remote") updateConfig("channelMode", "remote");
|
||||
if (!ready) return;
|
||||
message.success(shouldPromptContinue ? "配置已保存,请继续刚才的请求" : "配置已保存");
|
||||
clearPromptContinue();
|
||||
};
|
||||
|
||||
const refreshModels = async () => {
|
||||
if (effectiveMode === "remote") return;
|
||||
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] || "");
|
||||
};
|
||||
@@ -181,212 +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}>
|
||||
{allowCustomChannel ? (
|
||||
<Form.Item label="渠道模式" className="mb-5">
|
||||
<Segmented
|
||||
block
|
||||
size="middle"
|
||||
value={effectiveMode}
|
||||
onChange={(value) => updateConfig("channelMode", value as AiConfig["channelMode"])}
|
||||
options={[
|
||||
{ label: "本地直连", value: "local" },
|
||||
{ label: "云端渠道", value: "remote" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
) : null}
|
||||
{effectiveMode === "local" ? (
|
||||
<>
|
||||
<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>
|
||||
<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 URL、API 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>
|
||||
<Button size="small" loading={loadingModels} onClick={() => void refreshModels()}>
|
||||
拉取模型列表
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="mb-5 rounded-lg border border-stone-200 p-3 text-sm text-stone-500 dark:border-stone-800">
|
||||
<div className="font-medium text-stone-900 dark:text-stone-100">云端渠道</div>
|
||||
<div className="mt-1">由系统后台渠道转发请求,当前可用 {modelChannel?.availableModels.length || 0} 个模型。</div>
|
||||
</div>
|
||||
)}
|
||||
{effectiveMode === "local" ? (
|
||||
<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="multiple"
|
||||
showSearch
|
||||
allowClear
|
||||
maxTagCount="responsive"
|
||||
placeholder={config.models.length ? `请选择${group.optionsLabel}` : "请先拉取模型列表"}
|
||||
value={config[group.modelsKey]}
|
||||
options={modelOptions}
|
||||
onChange={(models) => updateCapabilityModels(group, models)}
|
||||
<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>
|
||||
<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>
|
||||
</section>
|
||||
) : null}
|
||||
<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={modelConfig} value={modelConfig[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>
|
||||
{effectiveMode === "local" ? (
|
||||
<Form.Item label="系统提示词" className="mb-0">
|
||||
<Input.TextArea rows={3} value={config.systemPrompt} placeholder="例如:你是一位擅长电影感写实摄影的视觉导演。" onChange={(event) => updateConfig("systemPrompt", event.target.value)} />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
<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 同步
|
||||
</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>
|
||||
<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>
|
||||
<Progress percent={getWebdavProgressPercent(item)} size="small" status={getWebdavProgressStatus(item)} showInfo={false} />
|
||||
<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)));
|
||||
}
|
||||
@@ -395,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));
|
||||
|
||||
@@ -2,30 +2,16 @@
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { App } from "antd";
|
||||
|
||||
import { useConfigStore } from "@/stores/use-config-store";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
import { createModelChannel, useConfigStore } from "@/stores/use-config-store";
|
||||
|
||||
export function ClientRootInit({ children }: { children: ReactNode }) {
|
||||
const { message } = App.useApp();
|
||||
const handledConfigParams = useRef(false);
|
||||
const pathname = usePathname();
|
||||
const hydrateUser = useUserStore((state) => state.hydrateUser);
|
||||
const loadPublicSettings = useConfigStore((state) => state.loadPublicSettings);
|
||||
const publicSettings = useConfigStore((state) => state.publicSettings);
|
||||
const updateConfig = useConfigStore((state) => state.updateConfig);
|
||||
const config = useConfigStore((state) => state.config);
|
||||
const openConfigDialog = useConfigStore((state) => state.openConfigDialog);
|
||||
const isLoginPage = pathname === "/login" || pathname === "/admin/login";
|
||||
|
||||
useEffect(() => {
|
||||
void loadPublicSettings();
|
||||
}, [loadPublicSettings]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoginPage) void hydrateUser();
|
||||
}, [hydrateUser, isLoginPage]);
|
||||
|
||||
useEffect(() => {
|
||||
if (handledConfigParams.current) return;
|
||||
@@ -33,23 +19,32 @@ export function ClientRootInit({ children }: { children: ReactNode }) {
|
||||
const baseUrl = searchParams.get("baseUrl") || searchParams.get("baseurl");
|
||||
const apiKey = searchParams.get("apiKey") || searchParams.get("apikey");
|
||||
if (!baseUrl && !apiKey) return;
|
||||
if (!publicSettings) return;
|
||||
handledConfigParams.current = true;
|
||||
searchParams.delete("baseUrl");
|
||||
searchParams.delete("baseurl");
|
||||
searchParams.delete("apiKey");
|
||||
searchParams.delete("apikey");
|
||||
window.history.replaceState(null, "", `${window.location.pathname}${searchParams.size ? `?${searchParams}` : ""}${window.location.hash}`);
|
||||
if (!publicSettings.modelChannel.allowCustomChannel) {
|
||||
openConfigDialog(false);
|
||||
message.error("后台未允许用户自定义渠道,请联系管理员进行配置");
|
||||
return;
|
||||
}
|
||||
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, openConfigDialog, publicSettings, updateConfig]);
|
||||
message.success("已导入本地直连配置");
|
||||
}, [config.channels, message, openConfigDialog, updateConfig]);
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user