v2
这个提交包含在:
25
components.json
普通文件
25
components.json
普通文件
@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema.json",
|
||||||
|
"style": "base-nova",
|
||||||
|
"rsc": true,
|
||||||
|
"tsx": true,
|
||||||
|
"tailwind": {
|
||||||
|
"config": "",
|
||||||
|
"css": "src/app/globals.css",
|
||||||
|
"baseColor": "neutral",
|
||||||
|
"cssVariables": true,
|
||||||
|
"prefix": ""
|
||||||
|
},
|
||||||
|
"iconLibrary": "lucide",
|
||||||
|
"rtl": false,
|
||||||
|
"aliases": {
|
||||||
|
"components": "@/components",
|
||||||
|
"utils": "@/lib/utils",
|
||||||
|
"ui": "@/components/ui",
|
||||||
|
"lib": "@/lib",
|
||||||
|
"hooks": "@/hooks"
|
||||||
|
},
|
||||||
|
"menuColor": "default",
|
||||||
|
"menuAccent": "subtle",
|
||||||
|
"registries": {}
|
||||||
|
}
|
||||||
@ -4,4 +4,8 @@ const nextConfig: NextConfig = {
|
|||||||
/* config options here */
|
/* config options here */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
allowedDevOrigins: ['192.168.1.38','10.70.105.134'],
|
||||||
|
}
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig;
|
||||||
|
|||||||
6077
package-lock.json
自动生成的
6077
package-lock.json
自动生成的
文件差异内容过多而无法显示
加载差异
24
package.json
24
package.json
@ -1,23 +1,41 @@
|
|||||||
{
|
{
|
||||||
"name": "webchat-tmp",
|
"name": "webchat",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev -H 0.0.0.0",
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "eslint"
|
"lint": "eslint"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@base-ui/react": "^1.4.1",
|
||||||
|
"@libsql/client": "^0.17.3",
|
||||||
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
||||||
|
"@prisma/adapter-libsql": "^7.8.0",
|
||||||
|
"@prisma/client": "^7.8.0",
|
||||||
|
"bcryptjs": "^3.0.3",
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"lucide-react": "^1.14.0",
|
||||||
"next": "16.2.4",
|
"next": "16.2.4",
|
||||||
|
"prisma": "^7.8.0",
|
||||||
"react": "19.2.4",
|
"react": "19.2.4",
|
||||||
"react-dom": "19.2.4"
|
"react-dom": "19.2.4",
|
||||||
|
"react-markdown": "^10.1.0",
|
||||||
|
"remark-gfm": "^4.0.1",
|
||||||
|
"shadcn": "^4.6.0",
|
||||||
|
"tailwind-merge": "^3.5.0",
|
||||||
|
"tw-animate-css": "^1.4.0",
|
||||||
|
"uuid": "^14.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4",
|
||||||
|
"@types/bcryptjs": "^2.4.6",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
|
"@types/uuid": "^10.0.0",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "16.2.4",
|
"eslint-config-next": "16.2.4",
|
||||||
"tailwindcss": "^4",
|
"tailwindcss": "^4",
|
||||||
|
|||||||
11
prisma.config.ts
普通文件
11
prisma.config.ts
普通文件
@ -0,0 +1,11 @@
|
|||||||
|
import { defineConfig } from "prisma/config"
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
schema: "prisma/schema.prisma",
|
||||||
|
migrations: {
|
||||||
|
path: "prisma/migrations",
|
||||||
|
},
|
||||||
|
datasource: {
|
||||||
|
url: "file:./dev.db",
|
||||||
|
},
|
||||||
|
})
|
||||||
@ -0,0 +1,182 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "User" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"password" TEXT NOT NULL,
|
||||||
|
"name" TEXT,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" DATETIME NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Account" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"type" TEXT NOT NULL,
|
||||||
|
"provider" TEXT NOT NULL,
|
||||||
|
"providerAccountId" TEXT NOT NULL,
|
||||||
|
"refresh_token" TEXT,
|
||||||
|
"access_token" TEXT,
|
||||||
|
"expires_at" INTEGER,
|
||||||
|
"token_type" TEXT,
|
||||||
|
"scope" TEXT,
|
||||||
|
"id_token" TEXT,
|
||||||
|
"session_state" TEXT,
|
||||||
|
CONSTRAINT "Account_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Session" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"sessionToken" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"expires" DATETIME NOT NULL,
|
||||||
|
CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "VerificationToken" (
|
||||||
|
"identifier" TEXT NOT NULL,
|
||||||
|
"token" TEXT NOT NULL,
|
||||||
|
"expires" DATETIME NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Provider" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"baseUrl" TEXT NOT NULL,
|
||||||
|
"apiKey" TEXT NOT NULL,
|
||||||
|
"modelName" TEXT NOT NULL,
|
||||||
|
"customHeaders" TEXT,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" DATETIME NOT NULL,
|
||||||
|
CONSTRAINT "Provider_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Preset" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"isDefault" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" DATETIME NOT NULL,
|
||||||
|
CONSTRAINT "Preset_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Fragment" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"presetId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"content" TEXT NOT NULL,
|
||||||
|
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"order" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
CONSTRAINT "Fragment_presetId_fkey" FOREIGN KEY ("presetId") REFERENCES "Preset" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Skill" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"content" TEXT NOT NULL,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" DATETIME NOT NULL,
|
||||||
|
CONSTRAINT "Skill_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "MCPServer" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"transportType" TEXT NOT NULL,
|
||||||
|
"config" TEXT NOT NULL,
|
||||||
|
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" DATETIME NOT NULL,
|
||||||
|
CONSTRAINT "MCPServer_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "MCPTool" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"serverId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"description" TEXT,
|
||||||
|
"inputSchema" TEXT,
|
||||||
|
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT "MCPTool_serverId_fkey" FOREIGN KEY ("serverId") REFERENCES "MCPServer" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ChatSession" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL DEFAULT '新会话',
|
||||||
|
"providerId" TEXT,
|
||||||
|
"presetId" TEXT,
|
||||||
|
"pinned" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"archived" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"totalCost" REAL NOT NULL DEFAULT 0,
|
||||||
|
"enabledSkillIds" TEXT,
|
||||||
|
"enabledToolIds" TEXT,
|
||||||
|
"draft" TEXT,
|
||||||
|
"compressEnabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"compressTrigger" REAL NOT NULL DEFAULT 0.2,
|
||||||
|
"keepRounds" INTEGER NOT NULL DEFAULT 3,
|
||||||
|
"thinkingEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" DATETIME NOT NULL,
|
||||||
|
CONSTRAINT "ChatSession_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Message" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"sessionId" TEXT NOT NULL,
|
||||||
|
"role" TEXT NOT NULL,
|
||||||
|
"content" TEXT NOT NULL,
|
||||||
|
"thinking" TEXT,
|
||||||
|
"toolCalls" TEXT,
|
||||||
|
"toolResults" TEXT,
|
||||||
|
"tokenUsage" TEXT,
|
||||||
|
"cost" REAL NOT NULL DEFAULT 0,
|
||||||
|
"branchParent" TEXT,
|
||||||
|
"isSummary" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"isHidden" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT "Message_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "ChatSession" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "PricingConfig" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"modelName" TEXT NOT NULL,
|
||||||
|
"inputPrice" REAL NOT NULL,
|
||||||
|
"outputPrice" REAL NOT NULL,
|
||||||
|
"currency" TEXT NOT NULL DEFAULT 'CNY',
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" DATETIME NOT NULL,
|
||||||
|
CONSTRAINT "PricingConfig_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "Account_provider_providerAccountId_key" ON "Account"("provider", "providerAccountId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "Session_sessionToken_key" ON "Session"("sessionToken");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "VerificationToken_token_key" ON "VerificationToken"("token");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "VerificationToken_identifier_token_key" ON "VerificationToken"("identifier", "token");
|
||||||
@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Message" ADD COLUMN "toolCallId" TEXT;
|
||||||
@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "ChatSession" ADD COLUMN "enabledBuiltInTools" TEXT;
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "ChatSession" ADD COLUMN "enabledHttpTools" TEXT;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "HttpTool" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"description" TEXT,
|
||||||
|
"method" TEXT NOT NULL DEFAULT 'GET',
|
||||||
|
"url" TEXT NOT NULL,
|
||||||
|
"headers" TEXT,
|
||||||
|
"parameters" TEXT,
|
||||||
|
"bodyTemplate" TEXT,
|
||||||
|
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" DATETIME NOT NULL,
|
||||||
|
CONSTRAINT "HttpTool_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
@ -0,0 +1,31 @@
|
|||||||
|
-- RedefineTables
|
||||||
|
PRAGMA defer_foreign_keys=ON;
|
||||||
|
PRAGMA foreign_keys=OFF;
|
||||||
|
CREATE TABLE "new_ChatSession" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL DEFAULT '新会话',
|
||||||
|
"providerId" TEXT,
|
||||||
|
"presetId" TEXT,
|
||||||
|
"pinned" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"archived" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"totalCost" REAL NOT NULL DEFAULT 0,
|
||||||
|
"enabledSkillIds" TEXT,
|
||||||
|
"enabledToolIds" TEXT,
|
||||||
|
"enabledBuiltInTools" TEXT,
|
||||||
|
"enabledHttpTools" TEXT,
|
||||||
|
"draft" TEXT,
|
||||||
|
"compressEnabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"compressTrigger" REAL NOT NULL DEFAULT 0.2,
|
||||||
|
"keepRounds" INTEGER NOT NULL DEFAULT 3,
|
||||||
|
"thinkingEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"markdownEnabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" DATETIME NOT NULL,
|
||||||
|
CONSTRAINT "ChatSession_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
INSERT INTO "new_ChatSession" ("archived", "compressEnabled", "compressTrigger", "createdAt", "draft", "enabledBuiltInTools", "enabledHttpTools", "enabledSkillIds", "enabledToolIds", "id", "keepRounds", "pinned", "presetId", "providerId", "thinkingEnabled", "title", "totalCost", "updatedAt", "userId") SELECT "archived", "compressEnabled", "compressTrigger", "createdAt", "draft", "enabledBuiltInTools", "enabledHttpTools", "enabledSkillIds", "enabledToolIds", "id", "keepRounds", "pinned", "presetId", "providerId", "thinkingEnabled", "title", "totalCost", "updatedAt", "userId" FROM "ChatSession";
|
||||||
|
DROP TABLE "ChatSession";
|
||||||
|
ALTER TABLE "new_ChatSession" RENAME TO "ChatSession";
|
||||||
|
PRAGMA foreign_keys=ON;
|
||||||
|
PRAGMA defer_foreign_keys=OFF;
|
||||||
@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "sqlite"
|
||||||
199
prisma/schema.prisma
普通文件
199
prisma/schema.prisma
普通文件
@ -0,0 +1,199 @@
|
|||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "sqlite"
|
||||||
|
}
|
||||||
|
|
||||||
|
model User {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
email String @unique
|
||||||
|
password String
|
||||||
|
name String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
providers Provider[]
|
||||||
|
presets Preset[]
|
||||||
|
skills Skill[]
|
||||||
|
mcpServers MCPServer[]
|
||||||
|
httpTools HttpTool[]
|
||||||
|
chatSessions ChatSession[]
|
||||||
|
pricingConfigs PricingConfig[]
|
||||||
|
accounts Account[]
|
||||||
|
sessions Session[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model Account {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
userId String
|
||||||
|
type String
|
||||||
|
provider String
|
||||||
|
providerAccountId String
|
||||||
|
refresh_token String?
|
||||||
|
access_token String?
|
||||||
|
expires_at Int?
|
||||||
|
token_type String?
|
||||||
|
scope String?
|
||||||
|
id_token String?
|
||||||
|
session_state String?
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([provider, providerAccountId])
|
||||||
|
}
|
||||||
|
|
||||||
|
model Session {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
sessionToken String @unique
|
||||||
|
userId String
|
||||||
|
expires DateTime
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
}
|
||||||
|
|
||||||
|
model VerificationToken {
|
||||||
|
identifier String
|
||||||
|
token String @unique
|
||||||
|
expires DateTime
|
||||||
|
|
||||||
|
@@unique([identifier, token])
|
||||||
|
}
|
||||||
|
|
||||||
|
model Provider {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
userId String
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
name String
|
||||||
|
baseUrl String
|
||||||
|
apiKey String
|
||||||
|
modelName String
|
||||||
|
customHeaders String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
model Preset {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
userId String
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
name String
|
||||||
|
isDefault Boolean @default(false)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
fragments Fragment[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model Fragment {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
presetId String
|
||||||
|
preset Preset @relation(fields: [presetId], references: [id], onDelete: Cascade)
|
||||||
|
name String
|
||||||
|
content String
|
||||||
|
enabled Boolean @default(true)
|
||||||
|
order Int @default(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
model Skill {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
userId String
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
name String
|
||||||
|
content String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
model MCPServer {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
userId String
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
name String
|
||||||
|
transportType String
|
||||||
|
config String
|
||||||
|
enabled Boolean @default(true)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
tools MCPTool[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model MCPTool {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
serverId String
|
||||||
|
server MCPServer @relation(fields: [serverId], references: [id], onDelete: Cascade)
|
||||||
|
name String
|
||||||
|
description String?
|
||||||
|
inputSchema String?
|
||||||
|
enabled Boolean @default(true)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
}
|
||||||
|
|
||||||
|
model HttpTool {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
userId String
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
name String
|
||||||
|
description String?
|
||||||
|
method String @default("GET")
|
||||||
|
url String
|
||||||
|
headers String?
|
||||||
|
parameters String?
|
||||||
|
bodyTemplate String?
|
||||||
|
enabled Boolean @default(true)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
model ChatSession {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
userId String
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
title String @default("新会话")
|
||||||
|
providerId String?
|
||||||
|
presetId String?
|
||||||
|
pinned Boolean @default(false)
|
||||||
|
archived Boolean @default(false)
|
||||||
|
totalCost Float @default(0)
|
||||||
|
enabledSkillIds String?
|
||||||
|
enabledToolIds String?
|
||||||
|
enabledBuiltInTools String?
|
||||||
|
enabledHttpTools String?
|
||||||
|
draft String?
|
||||||
|
compressEnabled Boolean @default(true)
|
||||||
|
compressTrigger Float @default(0.2)
|
||||||
|
keepRounds Int @default(3)
|
||||||
|
thinkingEnabled Boolean @default(false)
|
||||||
|
markdownEnabled Boolean @default(true)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
messages Message[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model Message {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
sessionId String
|
||||||
|
session ChatSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||||
|
role String
|
||||||
|
content String
|
||||||
|
thinking String?
|
||||||
|
toolCalls String?
|
||||||
|
toolResults String?
|
||||||
|
toolCallId String?
|
||||||
|
tokenUsage String?
|
||||||
|
cost Float @default(0)
|
||||||
|
branchParent String?
|
||||||
|
isSummary Boolean @default(false)
|
||||||
|
isHidden Boolean @default(false)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
}
|
||||||
|
|
||||||
|
model PricingConfig {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
userId String
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
modelName String
|
||||||
|
inputPrice Float
|
||||||
|
outputPrice Float
|
||||||
|
currency String @default("CNY")
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
}
|
||||||
24
src/app/api/auth/login/route.ts
普通文件
24
src/app/api/auth/login/route.ts
普通文件
@ -0,0 +1,24 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { authenticate, signToken, setAuthCookie } from "@/lib/auth"
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const { email, password } = await req.json()
|
||||||
|
if (!email || !password) {
|
||||||
|
return NextResponse.json({ error: "邮箱和密码不能为空" }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await authenticate(email, password)
|
||||||
|
if (!user) {
|
||||||
|
return NextResponse.json({ error: "邮箱或密码错误" }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = await signToken(user)
|
||||||
|
await setAuthCookie(token)
|
||||||
|
|
||||||
|
return NextResponse.json({ user: { id: user.id, email: user.email, name: user.name } })
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Login error:", error)
|
||||||
|
return NextResponse.json({ error: "登录失败" }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,28 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import bcrypt from "bcryptjs"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const { email, password, name } = await req.json()
|
||||||
|
|
||||||
|
if (!email || !password) {
|
||||||
|
return NextResponse.json({ error: "邮箱和密码不能为空" }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await prisma.user.findUnique({ where: { email } })
|
||||||
|
if (existing) {
|
||||||
|
return NextResponse.json({ error: "该邮箱已被注册" }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const hashedPassword = await bcrypt.hash(password, 12)
|
||||||
|
const user = await prisma.user.create({
|
||||||
|
data: { email, password: hashedPassword, name: name || email.split("@")[0] },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json({ id: user.id, email: user.email, name: user.name }, { status: 201 })
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Register error:", error)
|
||||||
|
return NextResponse.json({ error: "注册失败" }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
import { NextResponse } from "next/server"
|
||||||
|
import { getSession, clearAuthCookie, signToken, setAuthCookie } from "@/lib/auth"
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const session = await getSession()
|
||||||
|
if (!session) {
|
||||||
|
return NextResponse.json(null, { status: 200 })
|
||||||
|
}
|
||||||
|
return NextResponse.json({ user: { id: session.id, email: session.email, name: session.name } })
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST() {
|
||||||
|
const session = await getSession()
|
||||||
|
if (!session) {
|
||||||
|
await clearAuthCookie()
|
||||||
|
return NextResponse.json(null, { status: 200 })
|
||||||
|
}
|
||||||
|
const token = await signToken(session)
|
||||||
|
await setAuthCookie(token)
|
||||||
|
return NextResponse.json({ user: { id: session.id, email: session.email, name: session.name } })
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE() {
|
||||||
|
await clearAuthCookie()
|
||||||
|
return NextResponse.json(null, { status: 200 })
|
||||||
|
}
|
||||||
691
src/app/api/chat/send/route.ts
普通文件
691
src/app/api/chat/send/route.ts
普通文件
@ -0,0 +1,691 @@
|
|||||||
|
import { NextRequest } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
import { decryptApiKey } from "@/lib/encryption"
|
||||||
|
import { BUILT_IN_TOOLS } from "@/lib/builtin-tools"
|
||||||
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
|
||||||
|
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
|
||||||
|
import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js"
|
||||||
|
|
||||||
|
const MAX_TOOL_CALL_ROUNDS = 10
|
||||||
|
|
||||||
|
interface ToolCall {
|
||||||
|
id: string
|
||||||
|
type: string
|
||||||
|
function: { name: string; arguments: string }
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ToolMessage {
|
||||||
|
role: string
|
||||||
|
content: string
|
||||||
|
toolName?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return new Response("Unauthorized", { status: 401 })
|
||||||
|
}
|
||||||
|
const userId = session.user.id
|
||||||
|
|
||||||
|
const { sessionId, message, providerId, presetId, enabledSkillIds, enabledToolIds, enabledBuiltInTools, enabledHttpTools, thinkingEnabled } = await req.json()
|
||||||
|
|
||||||
|
if (!sessionId || !message) {
|
||||||
|
return new Response("Missing required fields", { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const chatSession = await prisma.chatSession.findFirst({
|
||||||
|
where: { id: sessionId, userId: userId },
|
||||||
|
})
|
||||||
|
if (!chatSession) {
|
||||||
|
return new Response("Session not found", { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const effectiveProviderId = providerId || chatSession.providerId
|
||||||
|
if (!effectiveProviderId) {
|
||||||
|
return new Response("No provider configured", { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const provider = await prisma.provider.findFirst({
|
||||||
|
where: { id: effectiveProviderId, userId: userId },
|
||||||
|
})
|
||||||
|
if (!provider) {
|
||||||
|
return new Response("Provider not found", { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const effectivePresetId = presetId || chatSession.presetId
|
||||||
|
let systemPrompt = ""
|
||||||
|
|
||||||
|
if (effectivePresetId) {
|
||||||
|
const preset = await prisma.preset.findFirst({
|
||||||
|
where: { id: effectivePresetId, userId: userId },
|
||||||
|
include: { fragments: { orderBy: { order: "asc" } } },
|
||||||
|
})
|
||||||
|
if (preset) {
|
||||||
|
systemPrompt = preset.fragments
|
||||||
|
.filter((f) => f.enabled)
|
||||||
|
.map((f) => f.content)
|
||||||
|
.join("\n\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const effectiveSkillIds = enabledSkillIds
|
||||||
|
? enabledSkillIds
|
||||||
|
: safeParse(chatSession.enabledSkillIds)
|
||||||
|
|
||||||
|
if (effectiveSkillIds && effectiveSkillIds.length > 0) {
|
||||||
|
const skills = await prisma.skill.findMany({
|
||||||
|
where: { id: { in: effectiveSkillIds }, userId: userId },
|
||||||
|
})
|
||||||
|
for (const skill of skills) {
|
||||||
|
systemPrompt += `\n\n---\n【激活技能:${skill.name}】\n${skill.content}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const effectiveToolIds = enabledToolIds
|
||||||
|
? enabledToolIds
|
||||||
|
: safeParse(chatSession.enabledToolIds)
|
||||||
|
|
||||||
|
const visibleMessages = await prisma.message.findMany({
|
||||||
|
where: { sessionId, isHidden: false },
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
})
|
||||||
|
|
||||||
|
let messagesToSend: Array<{ role: string; content: string | null; tool_call_id?: string; tool_calls?: unknown[]; name?: string; reasoning_content?: string }> = []
|
||||||
|
|
||||||
|
if (systemPrompt) {
|
||||||
|
messagesToSend.push({ role: "system", content: systemPrompt })
|
||||||
|
}
|
||||||
|
|
||||||
|
const summaryMessages = visibleMessages.filter((m) => m.isSummary)
|
||||||
|
for (const sm of summaryMessages) {
|
||||||
|
messagesToSend.push({ role: "system", content: `[对话摘要] ${sm.content}` })
|
||||||
|
}
|
||||||
|
|
||||||
|
const nonSummaryMessages = visibleMessages.filter((m) => !m.isSummary)
|
||||||
|
let hasPendingToolCalls = false
|
||||||
|
for (const m of nonSummaryMessages) {
|
||||||
|
if (m.role === "tool") {
|
||||||
|
if (hasPendingToolCalls) {
|
||||||
|
messagesToSend.push({ role: "tool", content: m.content, tool_call_id: m.toolCallId || m.id })
|
||||||
|
}
|
||||||
|
} else if (m.role === "assistant" && m.toolCalls) {
|
||||||
|
try {
|
||||||
|
const toolCalls = JSON.parse(m.toolCalls)
|
||||||
|
messagesToSend.push({ role: "assistant", content: m.content, tool_calls: toolCalls, ...(m.thinking ? { reasoning_content: m.thinking } : {}) })
|
||||||
|
hasPendingToolCalls = toolCalls.length > 0
|
||||||
|
} catch {
|
||||||
|
messagesToSend.push({ role: "assistant", content: m.content, ...(m.thinking ? { reasoning_content: m.thinking } : {}) })
|
||||||
|
hasPendingToolCalls = false
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
messagesToSend.push({ role: m.role, content: m.content })
|
||||||
|
hasPendingToolCalls = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
messagesToSend.push({ role: "user", content: message })
|
||||||
|
|
||||||
|
// Compression check
|
||||||
|
let compressionApplied = false
|
||||||
|
let compressedContent = ""
|
||||||
|
if (chatSession.compressEnabled && effectivePresetId) {
|
||||||
|
const estimatedTokens = estimateTokenCount(messagesToSend)
|
||||||
|
const contextLimit = getContextLimit(provider.modelName)
|
||||||
|
if (estimatedTokens > contextLimit * (1 - chatSession.compressTrigger)) {
|
||||||
|
const keepRounds = chatSession.keepRounds || 3
|
||||||
|
const toCompress = nonSummaryMessages.slice(0, -keepRounds * 2)
|
||||||
|
if (toCompress.length > 1) {
|
||||||
|
compressedContent = await compressHistory(toCompress, provider)
|
||||||
|
compressionApplied = true
|
||||||
|
|
||||||
|
messagesToSend = []
|
||||||
|
if (systemPrompt) messagesToSend.push({ role: "system", content: systemPrompt })
|
||||||
|
messagesToSend.push({ role: "system", content: `[对话摘要 - 自动压缩] ${compressedContent}` })
|
||||||
|
|
||||||
|
const recentMsgs = nonSummaryMessages.slice(-keepRounds * 2)
|
||||||
|
let hasPendingToolCalls = false
|
||||||
|
for (const m of recentMsgs) {
|
||||||
|
if (m.role === "tool") {
|
||||||
|
if (hasPendingToolCalls) {
|
||||||
|
messagesToSend.push({ role: "tool", content: m.content, tool_call_id: m.toolCallId || m.id })
|
||||||
|
}
|
||||||
|
} else if (m.role === "assistant" && m.toolCalls) {
|
||||||
|
try {
|
||||||
|
const toolCalls = JSON.parse(m.toolCalls)
|
||||||
|
messagesToSend.push({ role: "assistant", content: m.content, tool_calls: toolCalls, ...(m.thinking ? { reasoning_content: m.thinking } : {}) })
|
||||||
|
hasPendingToolCalls = toolCalls.length > 0
|
||||||
|
} catch {
|
||||||
|
messagesToSend.push({ role: "assistant", content: m.content, ...(m.thinking ? { reasoning_content: m.thinking } : {}) })
|
||||||
|
hasPendingToolCalls = false
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
messagesToSend.push({ role: m.role, content: m.content })
|
||||||
|
hasPendingToolCalls = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
messagesToSend.push({ role: "user", content: message })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save user message
|
||||||
|
const userMessage = await prisma.message.create({
|
||||||
|
data: { sessionId, role: "user", content: message },
|
||||||
|
})
|
||||||
|
|
||||||
|
const apiKey = decryptApiKey(provider.apiKey)
|
||||||
|
const baseUrl = provider.baseUrl.replace(/\/+$/, "")
|
||||||
|
const url = baseUrl + "/chat/completions"
|
||||||
|
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${apiKey}`,
|
||||||
|
}
|
||||||
|
if (provider.customHeaders) {
|
||||||
|
try { Object.assign(headers, JSON.parse(provider.customHeaders)) } catch {/* ignore */}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get MCP tools
|
||||||
|
let mcpTools: Array<{
|
||||||
|
type: string
|
||||||
|
function: { name: string; description: string; parameters: unknown }
|
||||||
|
}> = []
|
||||||
|
|
||||||
|
// Built-in tools (per-session configurable)
|
||||||
|
const effectiveBuiltInTools = enabledBuiltInTools
|
||||||
|
? enabledBuiltInTools
|
||||||
|
: safeParse(chatSession.enabledBuiltInTools)
|
||||||
|
|
||||||
|
const builtInTools: Array<{
|
||||||
|
type: string
|
||||||
|
function: { name: string; description: string; parameters: unknown }
|
||||||
|
}> = BUILT_IN_TOOLS
|
||||||
|
.filter((t) => effectiveBuiltInTools?.includes(t.id))
|
||||||
|
.map((t) => ({
|
||||||
|
type: "function",
|
||||||
|
function: {
|
||||||
|
name: t.name,
|
||||||
|
description: t.description,
|
||||||
|
parameters: t.parameters,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
const mcpClientMap = new Map<string, { client: Client; serverId: string }>()
|
||||||
|
|
||||||
|
// HTTP tools (per-session configurable)
|
||||||
|
const effectiveHttpTools = enabledHttpTools
|
||||||
|
? enabledHttpTools
|
||||||
|
: safeParse(chatSession.enabledHttpTools)
|
||||||
|
|
||||||
|
let httpTools: Array<{
|
||||||
|
type: string
|
||||||
|
function: { name: string; description: string; parameters: unknown }
|
||||||
|
}> = []
|
||||||
|
const httpToolDefs = new Map<string, { url: string; method: string; headers: Record<string, string> | null; bodyTemplate: string | null }>()
|
||||||
|
|
||||||
|
if (effectiveHttpTools && effectiveHttpTools.length > 0) {
|
||||||
|
const tools = await prisma.httpTool.findMany({
|
||||||
|
where: { id: { in: effectiveHttpTools }, userId: userId, enabled: true },
|
||||||
|
})
|
||||||
|
for (const t of tools) {
|
||||||
|
const params = safeParseJson(t.parameters) || { type: "object", properties: {}, required: [] }
|
||||||
|
httpTools.push({
|
||||||
|
type: "function",
|
||||||
|
function: {
|
||||||
|
name: t.name,
|
||||||
|
description: t.description || `HTTP ${t.method} ${t.url}`,
|
||||||
|
parameters: params,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
httpToolDefs.set(t.name, {
|
||||||
|
url: t.url,
|
||||||
|
method: t.method,
|
||||||
|
headers: (safeParseJson(t.headers) as Record<string, string>) || {},
|
||||||
|
bodyTemplate: t.bodyTemplate,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (effectiveToolIds && effectiveToolIds.length > 0) {
|
||||||
|
const tools = await prisma.mCPTool.findMany({
|
||||||
|
where: { id: { in: effectiveToolIds }, enabled: true },
|
||||||
|
include: { server: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
const servers = new Map<string, typeof tools[0]["server"]>()
|
||||||
|
for (const tool of tools) {
|
||||||
|
if (!servers.has(tool.serverId)) servers.set(tool.serverId, tool.server)
|
||||||
|
|
||||||
|
mcpTools.push({
|
||||||
|
type: "function",
|
||||||
|
function: {
|
||||||
|
name: tool.name,
|
||||||
|
description: tool.description || "",
|
||||||
|
parameters: safeParseJson(tool.inputSchema) || {},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [, server] of servers) {
|
||||||
|
if (!server.enabled) continue
|
||||||
|
try {
|
||||||
|
const config = safeParseJson(server.config)
|
||||||
|
|
||||||
|
let transport
|
||||||
|
if (server.transportType === "stdio") {
|
||||||
|
transport = new StdioClientTransport({
|
||||||
|
command: (config.command as string) || "",
|
||||||
|
args: (config.args as string[]) || [],
|
||||||
|
env: { ...getDefaultEnvironment(), ...((config.env as Record<string, string>) || {}) },
|
||||||
|
})
|
||||||
|
} else if (server.transportType === "sse") {
|
||||||
|
transport = new SSEClientTransport(new URL((config.url as string) || "http://localhost:3001/sse"))
|
||||||
|
} else continue
|
||||||
|
|
||||||
|
const client = new Client(
|
||||||
|
{ name: "webchat-mcp-client", version: "1.0.0" },
|
||||||
|
{ capabilities: {} }
|
||||||
|
)
|
||||||
|
await client.connect(transport)
|
||||||
|
mcpClientMap.set(server.id, { client, serverId: server.id })
|
||||||
|
} catch {
|
||||||
|
// Server unavailable, skip
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create SSE stream
|
||||||
|
const encoder = new TextEncoder()
|
||||||
|
const stream = new ReadableStream({
|
||||||
|
async start(controller) {
|
||||||
|
const sendEvent = (type: string, data: unknown) => {
|
||||||
|
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type, ...(typeof data === "object" ? data : { content: data }) })}\n\n`))
|
||||||
|
}
|
||||||
|
|
||||||
|
let roundCount = 0
|
||||||
|
let currentMessages = [...messagesToSend]
|
||||||
|
let totalPromptTokens = 0
|
||||||
|
let totalCompletionTokens = 0
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (roundCount < MAX_TOOL_CALL_ROUNDS) {
|
||||||
|
roundCount++
|
||||||
|
|
||||||
|
const body: Record<string, unknown> = {
|
||||||
|
model: provider.modelName,
|
||||||
|
messages: currentMessages,
|
||||||
|
stream: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
const isReasonerModel = provider.modelName.includes("reasoner") || provider.modelName.includes("o1") || provider.modelName.includes("o3")
|
||||||
|
const effectiveThinking = thinkingEnabled !== undefined ? thinkingEnabled : (isReasonerModel || chatSession.thinkingEnabled)
|
||||||
|
|
||||||
|
const allTools = [...builtInTools, ...httpTools, ...mcpTools]
|
||||||
|
if (allTools.length > 0) {
|
||||||
|
body.tools = allTools
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: "POST",
|
||||||
|
headers,
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errText = await response.text().catch(() => "Unknown error")
|
||||||
|
sendEvent("error", { content: `API 错误: ${response.status} ${errText}` })
|
||||||
|
controller.close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.body) {
|
||||||
|
sendEvent("error", { content: "No response body" })
|
||||||
|
controller.close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = response.body.getReader()
|
||||||
|
const decoder = new TextDecoder()
|
||||||
|
let buffer = ""
|
||||||
|
let assistantContent = ""
|
||||||
|
let reasoningContent = ""
|
||||||
|
let toolCallsMap = new Map<number, ToolCall>()
|
||||||
|
let finishReason = ""
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read()
|
||||||
|
if (done) break
|
||||||
|
|
||||||
|
buffer += decoder.decode(value, { stream: true })
|
||||||
|
const lines = buffer.split("\n")
|
||||||
|
buffer = lines.pop() || ""
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
const trimmed = line.trim()
|
||||||
|
if (!trimmed || !trimmed.startsWith("data: ")) continue
|
||||||
|
const data = trimmed.slice(6)
|
||||||
|
if (data === "[DONE]") continue
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(data)
|
||||||
|
const choice = parsed.choices?.[0]
|
||||||
|
if (!choice) continue
|
||||||
|
|
||||||
|
const delta = choice.delta
|
||||||
|
if (!delta) continue
|
||||||
|
|
||||||
|
if (delta.content) {
|
||||||
|
assistantContent += delta.content
|
||||||
|
sendEvent("delta", { content: delta.content })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (delta.reasoning_content) {
|
||||||
|
reasoningContent += delta.reasoning_content
|
||||||
|
sendEvent("reasoning_delta", { content: delta.reasoning_content })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (delta.tool_calls) {
|
||||||
|
for (const tc of delta.tool_calls) {
|
||||||
|
const idx = tc.index ?? 0
|
||||||
|
if (!toolCallsMap.has(idx)) {
|
||||||
|
toolCallsMap.set(idx, {
|
||||||
|
id: tc.id || "",
|
||||||
|
type: "function",
|
||||||
|
function: { name: tc.function?.name || "", arguments: "" },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const existing = toolCallsMap.get(idx)!
|
||||||
|
if (tc.id) existing.id = tc.id
|
||||||
|
if (tc.function?.name) existing.function.name = tc.function.name
|
||||||
|
if (tc.function?.arguments) existing.function.arguments += tc.function.arguments
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
finishReason = choice.finish_reason || ""
|
||||||
|
|
||||||
|
if (parsed.usage) {
|
||||||
|
totalPromptTokens = parsed.usage.prompt_tokens || 0
|
||||||
|
totalCompletionTokens = parsed.usage.completion_tokens || 0
|
||||||
|
}
|
||||||
|
} catch {/* ignore parse errors */}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const toolCalls = Array.from(toolCallsMap.values()).sort((a, b) =>
|
||||||
|
parseInt(a.id) - parseInt(b.id)
|
||||||
|
)
|
||||||
|
|
||||||
|
if (finishReason === "tool_calls" && toolCalls.length > 0) {
|
||||||
|
sendEvent("tool_calls", { calls: toolCalls })
|
||||||
|
|
||||||
|
const toolResultsList: Array<{ toolName: string; result: string; callId: string }> = []
|
||||||
|
|
||||||
|
currentMessages.push({
|
||||||
|
role: "assistant",
|
||||||
|
content: assistantContent,
|
||||||
|
tool_calls: toolCalls,
|
||||||
|
...(reasoningContent ? { reasoning_content: reasoningContent } : {}),
|
||||||
|
})
|
||||||
|
|
||||||
|
for (const tc of toolCalls) {
|
||||||
|
const toolName = tc.function.name
|
||||||
|
let toolArgs: Record<string, unknown> = {}
|
||||||
|
try { toolArgs = JSON.parse(tc.function.arguments || "{}") } catch {/* ignore */}
|
||||||
|
|
||||||
|
sendEvent("tool_start", { toolName, args: toolArgs })
|
||||||
|
|
||||||
|
let toolResult = ""
|
||||||
|
|
||||||
|
// Handle built-in tools
|
||||||
|
if (toolName === "rename_session") {
|
||||||
|
const newTitle = (toolArgs.title as string) || ""
|
||||||
|
if (newTitle) {
|
||||||
|
await prisma.chatSession.update({
|
||||||
|
where: { id: sessionId },
|
||||||
|
data: { title: newTitle },
|
||||||
|
})
|
||||||
|
toolResult = `对话已重命名为: ${newTitle}`
|
||||||
|
} else {
|
||||||
|
toolResult = "Error: title is required"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle HTTP tools
|
||||||
|
if (!toolResult) {
|
||||||
|
const httpDef = httpToolDefs.get(toolName)
|
||||||
|
if (httpDef) {
|
||||||
|
try {
|
||||||
|
let reqUrl = httpDef.url
|
||||||
|
let reqBody: string | undefined
|
||||||
|
for (const [key, value] of Object.entries(toolArgs)) {
|
||||||
|
const placeholder = `{{${key}}}`
|
||||||
|
reqUrl = reqUrl.replaceAll(placeholder, String(value))
|
||||||
|
if (httpDef.bodyTemplate) {
|
||||||
|
reqBody = httpDef.bodyTemplate.replaceAll(placeholder, String(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const fetchHeaders: Record<string, string> = { ...httpDef.headers }
|
||||||
|
if (httpDef.bodyTemplate && !fetchHeaders["Content-Type"]) {
|
||||||
|
fetchHeaders["Content-Type"] = "application/json"
|
||||||
|
}
|
||||||
|
const fetchRes = await fetch(reqUrl, {
|
||||||
|
method: httpDef.method,
|
||||||
|
headers: fetchHeaders,
|
||||||
|
body: httpDef.method !== "GET" && reqBody ? reqBody : undefined,
|
||||||
|
})
|
||||||
|
const text = await fetchRes.text()
|
||||||
|
toolResult = text || `HTTP ${httpDef.method} ${reqUrl} → ${fetchRes.status}`
|
||||||
|
} catch (err) {
|
||||||
|
toolResult = `Error: HTTP 请求失败: ${err instanceof Error ? err.message : "未知错误"}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!toolResult) {
|
||||||
|
for (const [, { client }] of mcpClientMap) {
|
||||||
|
try {
|
||||||
|
const result = await client.callTool({
|
||||||
|
name: toolName,
|
||||||
|
arguments: toolArgs,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (result.content) {
|
||||||
|
const contents = result.content as Array<{ type: string; text?: string }>
|
||||||
|
toolResult = contents
|
||||||
|
.map((c) => (c.type === "text" ? c.text || "" : ""))
|
||||||
|
.join("\n")
|
||||||
|
}
|
||||||
|
break
|
||||||
|
} catch {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!toolResult) {
|
||||||
|
toolResult = `Error: Tool "${toolName}" not found or failed on available MCP servers`
|
||||||
|
}
|
||||||
|
|
||||||
|
sendEvent("tool_result", { toolName, result: toolResult, callId: tc.id })
|
||||||
|
toolResultsList.push({ toolName, result: toolResult, callId: tc.id })
|
||||||
|
|
||||||
|
currentMessages.push({
|
||||||
|
role: "tool",
|
||||||
|
content: toolResult,
|
||||||
|
tool_call_id: tc.id,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Save tool message to DB
|
||||||
|
await prisma.message.create({
|
||||||
|
data: {
|
||||||
|
sessionId,
|
||||||
|
role: "tool",
|
||||||
|
content: toolResult,
|
||||||
|
toolCallId: tc.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.message.create({
|
||||||
|
data: {
|
||||||
|
sessionId,
|
||||||
|
role: "assistant",
|
||||||
|
content: assistantContent,
|
||||||
|
thinking: reasoningContent || null,
|
||||||
|
toolCalls: JSON.stringify(toolCalls),
|
||||||
|
toolResults: JSON.stringify(toolResultsList),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Continue the loop to send tool results back to LLM
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// No more tool calls - save final assistant message
|
||||||
|
const pricingConfig = await prisma.pricingConfig.findFirst({
|
||||||
|
where: { userId: userId, modelName: provider.modelName },
|
||||||
|
})
|
||||||
|
|
||||||
|
let cost = 0
|
||||||
|
if (pricingConfig) {
|
||||||
|
cost = (totalPromptTokens / 1000) * pricingConfig.inputPrice +
|
||||||
|
(totalCompletionTokens / 1000) * pricingConfig.outputPrice
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenUsage = totalPromptTokens > 0 || totalCompletionTokens > 0
|
||||||
|
? JSON.stringify({ prompt_tokens: totalPromptTokens, completion_tokens: totalCompletionTokens })
|
||||||
|
: null
|
||||||
|
|
||||||
|
await prisma.message.create({
|
||||||
|
data: {
|
||||||
|
sessionId,
|
||||||
|
role: "assistant",
|
||||||
|
content: assistantContent,
|
||||||
|
thinking: reasoningContent || null,
|
||||||
|
toolCalls: toolCalls.length > 0 ? JSON.stringify(toolCalls) : null,
|
||||||
|
cost,
|
||||||
|
tokenUsage,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (compressionApplied && compressedContent) {
|
||||||
|
await prisma.message.create({
|
||||||
|
data: {
|
||||||
|
sessionId,
|
||||||
|
role: "system",
|
||||||
|
content: `📝 已压缩前期对话摘要: ${compressedContent}`,
|
||||||
|
isSummary: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.chatSession.update({
|
||||||
|
where: { id: sessionId },
|
||||||
|
data: { totalCost: { increment: cost }, updatedAt: new Date(), draft: null },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (tokenUsage) {
|
||||||
|
sendEvent("usage", { usage: { prompt_tokens: totalPromptTokens, completion_tokens: totalCompletionTokens }, cost })
|
||||||
|
}
|
||||||
|
|
||||||
|
sendEvent("done", { messageId: userMessage.id })
|
||||||
|
break
|
||||||
|
}
|
||||||
|
} catch (error: unknown) {
|
||||||
|
sendEvent("error", { content: `流式处理错误: ${error instanceof Error ? error.message : "未知错误"}` })
|
||||||
|
} finally {
|
||||||
|
for (const [, { client }] of mcpClientMap) {
|
||||||
|
try { await client.close() } catch {/* ignore */}
|
||||||
|
}
|
||||||
|
controller.close()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return new Response(stream, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "text/event-stream",
|
||||||
|
"Cache-Control": "no-cache",
|
||||||
|
Connection: "keep-alive",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Helpers ---
|
||||||
|
|
||||||
|
function safeParse(str: string | null): string[] | null {
|
||||||
|
if (!str) return null
|
||||||
|
try { return JSON.parse(str) } catch { return null }
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeParseJson(str: string | null): Record<string, unknown> {
|
||||||
|
if (!str) return {}
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(str)
|
||||||
|
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {}
|
||||||
|
} catch { return {} }
|
||||||
|
}
|
||||||
|
|
||||||
|
function estimateTokenCount(messages: Array<{ role: string; content: string | null }>): number {
|
||||||
|
let total = 0
|
||||||
|
for (const msg of messages) {
|
||||||
|
total += (msg.content || "").length * 0.4
|
||||||
|
}
|
||||||
|
return Math.ceil(total)
|
||||||
|
}
|
||||||
|
|
||||||
|
function getContextLimit(modelName: string): number {
|
||||||
|
const limits: Record<string, number> = {
|
||||||
|
"deepseek-chat": 65536,
|
||||||
|
"deepseek-reasoner": 65536,
|
||||||
|
"gpt-4": 8192,
|
||||||
|
"gpt-4-turbo": 128000,
|
||||||
|
"gpt-4o": 128000,
|
||||||
|
"gpt-4o-mini": 128000,
|
||||||
|
"gpt-3.5-turbo": 4096,
|
||||||
|
"claude-3-opus": 200000,
|
||||||
|
"claude-3-sonnet": 200000,
|
||||||
|
"claude-3-haiku": 200000,
|
||||||
|
}
|
||||||
|
return limits[modelName] || 8192
|
||||||
|
}
|
||||||
|
|
||||||
|
async function compressHistory(
|
||||||
|
messages: Array<{ role: string; content: string }>,
|
||||||
|
provider: { baseUrl: string; apiKey: string; modelName: string }
|
||||||
|
): Promise<string> {
|
||||||
|
const summary = messages
|
||||||
|
.map((m) => `[${m.role}] ${m.content}`)
|
||||||
|
.join("\n")
|
||||||
|
|
||||||
|
const prompt = `请为以下对话历史生成一个简洁的结构化摘要,保留关键信息、决策和动作:
|
||||||
|
|
||||||
|
${summary.substring(0, 8000)}
|
||||||
|
|
||||||
|
请用中文输出摘要。`
|
||||||
|
|
||||||
|
const apiKey = decryptApiKey(provider.apiKey)
|
||||||
|
const baseUrl = provider.baseUrl.replace(/\/+$/, "")
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(baseUrl + "/chat/completions", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${apiKey}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
model: provider.modelName,
|
||||||
|
messages: [{ role: "user", content: prompt }],
|
||||||
|
max_tokens: 1024,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!res.ok) return "压缩失败"
|
||||||
|
|
||||||
|
const data = await res.json() as { choices?: Array<{ message?: { content?: string } }> }
|
||||||
|
return data.choices?.[0]?.message?.content || "压缩失败"
|
||||||
|
} catch {
|
||||||
|
return "压缩生成失败"
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,66 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function POST(_req: NextRequest, { params }: { params: Promise<{ sessionId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { sessionId } = await params
|
||||||
|
const { format = "markdown" } = await _req.json()
|
||||||
|
|
||||||
|
const chatSession = await prisma.chatSession.findFirst({
|
||||||
|
where: { id: sessionId, userId: session.user.id },
|
||||||
|
include: {
|
||||||
|
messages: {
|
||||||
|
where: { isHidden: false },
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!chatSession) return NextResponse.json({ error: "会话不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
if (format === "json") {
|
||||||
|
return NextResponse.json(chatSession)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (format === "text") {
|
||||||
|
const text = chatSession.messages
|
||||||
|
.map((m) => `[${m.role.toUpperCase()}] ${new Date(m.createdAt).toISOString()}\n${m.content}`)
|
||||||
|
.join("\n\n---\n\n")
|
||||||
|
return new NextResponse(text, {
|
||||||
|
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const md = `# ${chatSession.title}
|
||||||
|
|
||||||
|
> 会话 ID: ${chatSession.id}
|
||||||
|
> 创建时间: ${new Date(chatSession.createdAt).toLocaleString()}
|
||||||
|
> 总费用: ${chatSession.totalCost.toFixed(4)}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
${chatSession.messages.map((m) => {
|
||||||
|
const time = new Date(m.createdAt).toLocaleString()
|
||||||
|
if (m.isSummary) return `📝 *${m.content}*`
|
||||||
|
if (m.role === "tool") return `🔧 **工具调用** (${time})\n\`\`\`\n${m.content}\n\`\`\``
|
||||||
|
|
||||||
|
let prefix = m.role === "user" ? "🧑 **用户**" : "🤖 **助手**"
|
||||||
|
if (m.toolResults) {
|
||||||
|
try {
|
||||||
|
const results = JSON.parse(m.toolResults)
|
||||||
|
prefix += `\n\n> 工具调用: ${results.map((r: { toolName: string }) => r.toolName).join(", ")}`
|
||||||
|
} catch {/* ignore */}
|
||||||
|
}
|
||||||
|
if (m.cost > 0) prefix += ` | 费用: ¥${m.cost.toFixed(4)}`
|
||||||
|
|
||||||
|
return `${prefix} (${time})\n\n${m.content}`
|
||||||
|
}).join("\n\n---\n\n")}
|
||||||
|
`
|
||||||
|
|
||||||
|
return new NextResponse(md, {
|
||||||
|
headers: { "Content-Type": "text/markdown; charset=utf-8" },
|
||||||
|
})
|
||||||
|
}
|
||||||
@ -0,0 +1,37 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function POST(_req: NextRequest, { params }: { params: Promise<{ sessionId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { sessionId } = await params
|
||||||
|
const { messageId, includeTarget } = await _req.json()
|
||||||
|
|
||||||
|
const chatSession = await prisma.chatSession.findFirst({
|
||||||
|
where: { id: sessionId, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (!chatSession) return NextResponse.json({ error: "会话不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const targetMessage = await prisma.message.findFirst({
|
||||||
|
where: { id: messageId, sessionId },
|
||||||
|
})
|
||||||
|
if (!targetMessage) return NextResponse.json({ error: "消息不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const laterMessages = await prisma.message.findMany({
|
||||||
|
where: { sessionId, createdAt: { gt: targetMessage.createdAt } },
|
||||||
|
})
|
||||||
|
|
||||||
|
const idsToHide = laterMessages.map((m) => m.id)
|
||||||
|
if (includeTarget) {
|
||||||
|
idsToHide.push(targetMessage.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.message.updateMany({
|
||||||
|
where: { id: { in: idsToHide } },
|
||||||
|
data: { isHidden: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
}
|
||||||
@ -0,0 +1,69 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function GET(_req: NextRequest, { params }: { params: Promise<{ sessionId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { sessionId } = await params
|
||||||
|
const chatSession = await prisma.chatSession.findFirst({
|
||||||
|
where: { id: sessionId, userId: session.user.id },
|
||||||
|
include: {
|
||||||
|
messages: {
|
||||||
|
where: { isHidden: false, role: { not: "tool" } },
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!chatSession) return NextResponse.json({ error: "会话不存在" }, { status: 404 })
|
||||||
|
return NextResponse.json(chatSession)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ sessionId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { sessionId } = await params
|
||||||
|
const body = await req.json()
|
||||||
|
|
||||||
|
const chatSession = await prisma.chatSession.findFirst({
|
||||||
|
where: { id: sessionId, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (!chatSession) return NextResponse.json({ error: "会话不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const data: Record<string, unknown> = {}
|
||||||
|
if (body.title !== undefined) data.title = body.title
|
||||||
|
if (body.pinned !== undefined) data.pinned = body.pinned
|
||||||
|
if (body.archived !== undefined) data.archived = body.archived
|
||||||
|
if (body.providerId !== undefined) data.providerId = body.providerId
|
||||||
|
if (body.presetId !== undefined) data.presetId = body.presetId
|
||||||
|
if (body.draft !== undefined) data.draft = body.draft
|
||||||
|
if (body.compressEnabled !== undefined) data.compressEnabled = body.compressEnabled
|
||||||
|
if (body.compressTrigger !== undefined) data.compressTrigger = body.compressTrigger
|
||||||
|
if (body.keepRounds !== undefined) data.keepRounds = body.keepRounds
|
||||||
|
if (body.thinkingEnabled !== undefined) data.thinkingEnabled = body.thinkingEnabled
|
||||||
|
if (body.markdownEnabled !== undefined) data.markdownEnabled = body.markdownEnabled
|
||||||
|
if (body.enabledSkillIds !== undefined) data.enabledSkillIds = JSON.stringify(body.enabledSkillIds)
|
||||||
|
if (body.enabledToolIds !== undefined) data.enabledToolIds = JSON.stringify(body.enabledToolIds)
|
||||||
|
if (body.enabledBuiltInTools !== undefined) data.enabledBuiltInTools = JSON.stringify(body.enabledBuiltInTools)
|
||||||
|
if (body.enabledHttpTools !== undefined) data.enabledHttpTools = JSON.stringify(body.enabledHttpTools)
|
||||||
|
|
||||||
|
const updated = await prisma.chatSession.update({ where: { id: sessionId }, data })
|
||||||
|
return NextResponse.json(updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ sessionId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { sessionId } = await params
|
||||||
|
const chatSession = await prisma.chatSession.findFirst({
|
||||||
|
where: { id: sessionId, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (!chatSession) return NextResponse.json({ error: "会话不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
await prisma.chatSession.delete({ where: { id: sessionId } })
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
}
|
||||||
@ -0,0 +1,59 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { searchParams } = req.nextUrl
|
||||||
|
const q = searchParams.get("q") || ""
|
||||||
|
const archived = searchParams.get("archived") === "true"
|
||||||
|
|
||||||
|
const sessions = await prisma.chatSession.findMany({
|
||||||
|
where: {
|
||||||
|
userId: session.user.id,
|
||||||
|
archived,
|
||||||
|
...(q ? { title: { contains: q } } : {}),
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
messages: {
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: [{ pinned: "desc" }, { updatedAt: "desc" }],
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(sessions)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const body = await req.json().catch(() => ({}))
|
||||||
|
const { title, providerId, presetId, enabledSkillIds, enabledToolIds, enabledBuiltInTools, enabledHttpTools, compressEnabled, compressTrigger, keepRounds } = body
|
||||||
|
|
||||||
|
const defaultPreset = await prisma.preset.findFirst({
|
||||||
|
where: { userId: session.user.id, isDefault: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
const chatSession = await prisma.chatSession.create({
|
||||||
|
data: {
|
||||||
|
userId: session.user.id,
|
||||||
|
title: title || "新会话",
|
||||||
|
providerId: providerId || null,
|
||||||
|
presetId: presetId || defaultPreset?.id || null,
|
||||||
|
enabledSkillIds: enabledSkillIds ? JSON.stringify(enabledSkillIds) : null,
|
||||||
|
enabledToolIds: enabledToolIds ? JSON.stringify(enabledToolIds) : null,
|
||||||
|
enabledBuiltInTools: enabledBuiltInTools ? JSON.stringify(enabledBuiltInTools) : null,
|
||||||
|
enabledHttpTools: enabledHttpTools ? JSON.stringify(enabledHttpTools) : null,
|
||||||
|
compressEnabled: compressEnabled !== undefined ? compressEnabled : true,
|
||||||
|
compressTrigger: compressTrigger || 0.2,
|
||||||
|
keepRounds: keepRounds || 3,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(chatSession, { status: 201 })
|
||||||
|
}
|
||||||
@ -0,0 +1,38 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const body = await req.json()
|
||||||
|
|
||||||
|
const tool = await prisma.httpTool.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!tool) return NextResponse.json({ error: "工具不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const data: Record<string, unknown> = {}
|
||||||
|
if (body.name !== undefined) data.name = body.name
|
||||||
|
if (body.description !== undefined) data.description = body.description
|
||||||
|
if (body.method !== undefined) data.method = body.method
|
||||||
|
if (body.url !== undefined) data.url = body.url
|
||||||
|
if (body.headers !== undefined) data.headers = typeof body.headers === "string" ? body.headers : JSON.stringify(body.headers)
|
||||||
|
if (body.parameters !== undefined) data.parameters = typeof body.parameters === "string" ? body.parameters : JSON.stringify(body.parameters)
|
||||||
|
if (body.bodyTemplate !== undefined) data.bodyTemplate = body.bodyTemplate
|
||||||
|
|
||||||
|
const updated = await prisma.httpTool.update({ where: { id }, data })
|
||||||
|
return NextResponse.json(updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const tool = await prisma.httpTool.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!tool) return NextResponse.json({ error: "工具不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
await prisma.httpTool.delete({ where: { id } })
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
}
|
||||||
38
src/app/api/http-tools/route.ts
普通文件
38
src/app/api/http-tools/route.ts
普通文件
@ -0,0 +1,38 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function GET(_req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const tools = await prisma.httpTool.findMany({
|
||||||
|
where: { userId: session.user.id },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(tools)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { name, description, method, url, headers, parameters, bodyTemplate } = await req.json()
|
||||||
|
if (!name || !url) return NextResponse.json({ error: "名称和 URL 不能为空" }, { status: 400 })
|
||||||
|
|
||||||
|
const tool = await prisma.httpTool.create({
|
||||||
|
data: {
|
||||||
|
userId: session.user.id,
|
||||||
|
name,
|
||||||
|
description: description || null,
|
||||||
|
method: method || "GET",
|
||||||
|
url,
|
||||||
|
headers: headers ? JSON.stringify(headers) : null,
|
||||||
|
parameters: parameters ? JSON.stringify(parameters) : null,
|
||||||
|
bodyTemplate: bodyTemplate || null,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(tool, { status: 201 })
|
||||||
|
}
|
||||||
@ -0,0 +1,68 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
|
||||||
|
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
|
||||||
|
import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js"
|
||||||
|
|
||||||
|
export async function POST(_req: NextRequest, { params }: { params: Promise<{ serverId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { serverId } = await params
|
||||||
|
const server = await prisma.mCPServer.findFirst({
|
||||||
|
where: { id: serverId, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (!server) return NextResponse.json({ error: "服务器不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const config = JSON.parse(server.config || "{}")
|
||||||
|
|
||||||
|
try {
|
||||||
|
let transport
|
||||||
|
|
||||||
|
if (server.transportType === "stdio") {
|
||||||
|
transport = new StdioClientTransport({
|
||||||
|
command: config.command || "",
|
||||||
|
args: config.args || [],
|
||||||
|
env: { ...getDefaultEnvironment(), ...(config.env || {}) },
|
||||||
|
})
|
||||||
|
} else if (server.transportType === "sse") {
|
||||||
|
transport = new SSEClientTransport(new URL(config.url || "http://localhost:3001/sse"))
|
||||||
|
} else {
|
||||||
|
return NextResponse.json({ error: "不支持的传输类型" }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = new Client(
|
||||||
|
{ name: "webchat-mcp-client", version: "1.0.0" },
|
||||||
|
{ capabilities: {} }
|
||||||
|
)
|
||||||
|
|
||||||
|
await client.connect(transport)
|
||||||
|
const toolsResult = await client.listTools()
|
||||||
|
|
||||||
|
await prisma.mCPTool.deleteMany({ where: { serverId } })
|
||||||
|
|
||||||
|
const tools = toolsResult.tools.map((tool) => ({
|
||||||
|
serverId,
|
||||||
|
name: tool.name,
|
||||||
|
description: tool.description || null,
|
||||||
|
inputSchema: JSON.stringify(tool.inputSchema || {}),
|
||||||
|
enabled: true,
|
||||||
|
}))
|
||||||
|
|
||||||
|
if (tools.length > 0) {
|
||||||
|
await prisma.mCPTool.createMany({ data: tools })
|
||||||
|
}
|
||||||
|
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
const savedTools = await prisma.mCPTool.findMany({ where: { serverId } })
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true, tools: savedTools })
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return NextResponse.json({
|
||||||
|
success: false,
|
||||||
|
error: `连接失败: ${error instanceof Error ? error.message : "未知错误"}`,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,35 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ serverId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { serverId } = await params
|
||||||
|
const { name, transportType, config, enabled } = await req.json()
|
||||||
|
|
||||||
|
const server = await prisma.mCPServer.findFirst({ where: { id: serverId, userId: session.user.id } })
|
||||||
|
if (!server) return NextResponse.json({ error: "服务器不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const data: Record<string, unknown> = {}
|
||||||
|
if (name !== undefined) data.name = name
|
||||||
|
if (transportType !== undefined) data.transportType = transportType
|
||||||
|
if (config !== undefined) data.config = JSON.stringify(config)
|
||||||
|
if (enabled !== undefined) data.enabled = enabled
|
||||||
|
|
||||||
|
const updated = await prisma.mCPServer.update({ where: { id: serverId }, data, include: { tools: true } })
|
||||||
|
return NextResponse.json(updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ serverId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { serverId } = await params
|
||||||
|
const server = await prisma.mCPServer.findFirst({ where: { id: serverId, userId: session.user.id } })
|
||||||
|
if (!server) return NextResponse.json({ error: "服务器不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
await prisma.mCPServer.delete({ where: { id: serverId } })
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
}
|
||||||
@ -0,0 +1,27 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function GET(_req: NextRequest, { params }: { params: Promise<{ serverId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { serverId } = await params
|
||||||
|
const tools = await prisma.mCPTool.findMany({ where: { serverId }, orderBy: { name: "asc" } })
|
||||||
|
|
||||||
|
return NextResponse.json(tools)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ serverId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { serverId } = await params
|
||||||
|
const { toolId, enabled } = await req.json()
|
||||||
|
|
||||||
|
const tool = await prisma.mCPTool.findFirst({ where: { id: toolId, serverId } })
|
||||||
|
if (!tool) return NextResponse.json({ error: "工具不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const updated = await prisma.mCPTool.update({ where: { id: toolId }, data: { enabled } })
|
||||||
|
return NextResponse.json(updated)
|
||||||
|
}
|
||||||
36
src/app/api/mcp/servers/route.ts
普通文件
36
src/app/api/mcp/servers/route.ts
普通文件
@ -0,0 +1,36 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function GET(_req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const servers = await prisma.mCPServer.findMany({
|
||||||
|
where: { userId: session.user.id },
|
||||||
|
include: { tools: true },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(servers)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { name, transportType, config } = await req.json()
|
||||||
|
if (!name || !transportType) return NextResponse.json({ error: "名称和传输类型不能为空" }, { status: 400 })
|
||||||
|
|
||||||
|
const server = await prisma.mCPServer.create({
|
||||||
|
data: {
|
||||||
|
userId: session.user.id,
|
||||||
|
name,
|
||||||
|
transportType,
|
||||||
|
config: JSON.stringify(config || {}),
|
||||||
|
},
|
||||||
|
include: { tools: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(server, { status: 201 })
|
||||||
|
}
|
||||||
@ -0,0 +1,35 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string; fragmentId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id, fragmentId } = await params
|
||||||
|
const { name, content, enabled } = await req.json()
|
||||||
|
|
||||||
|
const preset = await prisma.preset.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!preset) return NextResponse.json({ error: "预设不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const data: Record<string, unknown> = {}
|
||||||
|
if (name !== undefined) data.name = name
|
||||||
|
if (content !== undefined) data.content = content
|
||||||
|
if (enabled !== undefined) data.enabled = enabled
|
||||||
|
|
||||||
|
const fragment = await prisma.fragment.update({ where: { id: fragmentId }, data })
|
||||||
|
return NextResponse.json(fragment)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string; fragmentId: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id, fragmentId } = await params
|
||||||
|
|
||||||
|
const preset = await prisma.preset.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!preset) return NextResponse.json({ error: "预设不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
await prisma.fragment.delete({ where: { id: fragmentId } })
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
}
|
||||||
@ -0,0 +1,49 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const { name, content } = await req.json()
|
||||||
|
|
||||||
|
const preset = await prisma.preset.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!preset) return NextResponse.json({ error: "预设不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const maxOrder = await prisma.fragment.aggregate({ where: { presetId: id }, _max: { order: true } })
|
||||||
|
const nextOrder = (maxOrder._max.order ?? -1) + 1
|
||||||
|
|
||||||
|
const fragment = await prisma.fragment.create({
|
||||||
|
data: { presetId: id, name: name || "新片段", content: content || "", order: nextOrder },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(fragment, { status: 201 })
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const { fragments: newOrder } = await req.json()
|
||||||
|
|
||||||
|
const preset = await prisma.preset.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!preset) return NextResponse.json({ error: "预设不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
if (Array.isArray(newOrder)) {
|
||||||
|
await Promise.all(
|
||||||
|
newOrder.map((f: { id: string; order: number }) =>
|
||||||
|
prisma.fragment.update({ where: { id: f.id }, data: { order: f.order } })
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await prisma.preset.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: { fragments: { orderBy: { order: "asc" } } },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(updated)
|
||||||
|
}
|
||||||
@ -0,0 +1,40 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const { name, isDefault } = await req.json()
|
||||||
|
|
||||||
|
const preset = await prisma.preset.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!preset) return NextResponse.json({ error: "预设不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
if (isDefault) {
|
||||||
|
await prisma.preset.updateMany({
|
||||||
|
where: { userId: session.user.id, isDefault: true },
|
||||||
|
data: { isDefault: false },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const data: Record<string, unknown> = {}
|
||||||
|
if (name !== undefined) data.name = name
|
||||||
|
if (isDefault !== undefined) data.isDefault = isDefault
|
||||||
|
|
||||||
|
const updated = await prisma.preset.update({ where: { id }, data, include: { fragments: { orderBy: { order: "asc" } } } })
|
||||||
|
return NextResponse.json(updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const preset = await prisma.preset.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!preset) return NextResponse.json({ error: "预设不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
await prisma.preset.delete({ where: { id } })
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
}
|
||||||
38
src/app/api/presets/route.ts
普通文件
38
src/app/api/presets/route.ts
普通文件
@ -0,0 +1,38 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function GET(_req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const presets = await prisma.preset.findMany({
|
||||||
|
where: { userId: session.user.id },
|
||||||
|
include: { fragments: { orderBy: { order: "asc" } } },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(presets)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { name, isDefault } = await req.json()
|
||||||
|
if (!name) return NextResponse.json({ error: "名称不能为空" }, { status: 400 })
|
||||||
|
|
||||||
|
if (isDefault) {
|
||||||
|
await prisma.preset.updateMany({
|
||||||
|
where: { userId: session.user.id, isDefault: true },
|
||||||
|
data: { isDefault: false },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const preset = await prisma.preset.create({
|
||||||
|
data: { userId: session.user.id, name, isDefault: isDefault || false },
|
||||||
|
include: { fragments: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(preset, { status: 201 })
|
||||||
|
}
|
||||||
@ -0,0 +1,35 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const { modelName, inputPrice, outputPrice, currency } = await req.json()
|
||||||
|
|
||||||
|
const config = await prisma.pricingConfig.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!config) return NextResponse.json({ error: "定价配置不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const data: Record<string, unknown> = {}
|
||||||
|
if (modelName !== undefined) data.modelName = modelName
|
||||||
|
if (inputPrice !== undefined) data.inputPrice = inputPrice
|
||||||
|
if (outputPrice !== undefined) data.outputPrice = outputPrice
|
||||||
|
if (currency !== undefined) data.currency = currency
|
||||||
|
|
||||||
|
const updated = await prisma.pricingConfig.update({ where: { id }, data })
|
||||||
|
return NextResponse.json(updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const config = await prisma.pricingConfig.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!config) return NextResponse.json({ error: "定价配置不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
await prisma.pricingConfig.delete({ where: { id } })
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
}
|
||||||
31
src/app/api/pricing/route.ts
普通文件
31
src/app/api/pricing/route.ts
普通文件
@ -0,0 +1,31 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function GET(_req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const configs = await prisma.pricingConfig.findMany({
|
||||||
|
where: { userId: session.user.id },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(configs)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { modelName, inputPrice, outputPrice, currency } = await req.json()
|
||||||
|
if (!modelName || inputPrice == null || outputPrice == null) {
|
||||||
|
return NextResponse.json({ error: "缺少必要参数" }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = await prisma.pricingConfig.create({
|
||||||
|
data: { userId: session.user.id, modelName, inputPrice, outputPrice, currency: currency || "CNY" },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(config, { status: 201 })
|
||||||
|
}
|
||||||
@ -0,0 +1,41 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
import { encryptApiKey, decryptApiKey, maskApiKey } from "@/lib/encryption"
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const { name, baseUrl, apiKey, modelName, customHeaders } = await req.json()
|
||||||
|
|
||||||
|
const data: Record<string, unknown> = {}
|
||||||
|
if (name !== undefined) data.name = name
|
||||||
|
if (baseUrl !== undefined) data.baseUrl = baseUrl
|
||||||
|
if (apiKey !== undefined) data.apiKey = encryptApiKey(apiKey)
|
||||||
|
if (modelName !== undefined) data.modelName = modelName
|
||||||
|
if (customHeaders !== undefined) data.customHeaders = JSON.stringify(customHeaders)
|
||||||
|
|
||||||
|
const provider = await prisma.provider.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!provider) return NextResponse.json({ error: "Provider 不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const updated = await prisma.provider.update({ where: { id }, data })
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
...updated,
|
||||||
|
apiKey: maskApiKey(apiKey !== undefined ? apiKey : decryptApiKey(updated.apiKey)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const provider = await prisma.provider.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!provider) return NextResponse.json({ error: "Provider 不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
await prisma.provider.delete({ where: { id } })
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
}
|
||||||
@ -0,0 +1,45 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
import { decryptApiKey } from "@/lib/encryption"
|
||||||
|
|
||||||
|
export async function POST(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const provider = await prisma.provider.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!provider) return NextResponse.json({ error: "Provider 不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
try {
|
||||||
|
const apiKey = decryptApiKey(provider.apiKey)
|
||||||
|
const url = provider.baseUrl.replace(/\/+$/, "") + "/chat/completions"
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${apiKey}`,
|
||||||
|
}
|
||||||
|
if (provider.customHeaders) {
|
||||||
|
try { Object.assign(headers, JSON.parse(provider.customHeaders)) } catch {/* ignore */}
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: "POST",
|
||||||
|
headers,
|
||||||
|
body: JSON.stringify({
|
||||||
|
model: provider.modelName,
|
||||||
|
messages: [{ role: "user", content: "Hi" }],
|
||||||
|
max_tokens: 5,
|
||||||
|
}),
|
||||||
|
signal: AbortSignal.timeout(15000),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.text().catch(() => "")
|
||||||
|
return NextResponse.json({ success: false, error: `API 返回错误 ${res.status}: ${err}` })
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true, message: "连接成功" })
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return NextResponse.json({ success: false, error: `连接失败: ${error instanceof Error ? error.message : "未知错误"}` })
|
||||||
|
}
|
||||||
|
}
|
||||||
54
src/app/api/providers/route.ts
普通文件
54
src/app/api/providers/route.ts
普通文件
@ -0,0 +1,54 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
import { encryptApiKey, decryptApiKey, maskApiKey } from "@/lib/encryption"
|
||||||
|
|
||||||
|
export async function GET(_req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const providers = await prisma.provider.findMany({
|
||||||
|
where: { userId: session.user.id },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
providers.map((p) => ({
|
||||||
|
...p,
|
||||||
|
apiKey: maskApiKey(decryptApiKey(p.apiKey)),
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { name, baseUrl, apiKey, modelName, customHeaders } = await req.json()
|
||||||
|
|
||||||
|
if (!name || !baseUrl || !apiKey || !modelName) {
|
||||||
|
return NextResponse.json({ error: "缺少必要参数" }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const encryptedKey = encryptApiKey(apiKey)
|
||||||
|
|
||||||
|
const provider = await prisma.provider.create({
|
||||||
|
data: {
|
||||||
|
userId: session.user.id,
|
||||||
|
name,
|
||||||
|
baseUrl,
|
||||||
|
apiKey: encryptedKey,
|
||||||
|
modelName,
|
||||||
|
customHeaders: customHeaders ? JSON.stringify(customHeaders) : null,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
...provider,
|
||||||
|
apiKey: maskApiKey(apiKey),
|
||||||
|
}, { status: 201 })
|
||||||
|
}
|
||||||
33
src/app/api/skills/[id]/route.ts
普通文件
33
src/app/api/skills/[id]/route.ts
普通文件
@ -0,0 +1,33 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const { name, content } = await req.json()
|
||||||
|
|
||||||
|
const skill = await prisma.skill.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!skill) return NextResponse.json({ error: "技能不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const data: Record<string, unknown> = {}
|
||||||
|
if (name !== undefined) data.name = name
|
||||||
|
if (content !== undefined) data.content = content
|
||||||
|
|
||||||
|
const updated = await prisma.skill.update({ where: { id }, data })
|
||||||
|
return NextResponse.json(updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { id } = await params
|
||||||
|
const skill = await prisma.skill.findFirst({ where: { id, userId: session.user.id } })
|
||||||
|
if (!skill) return NextResponse.json({ error: "技能不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
await prisma.skill.delete({ where: { id } })
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
}
|
||||||
29
src/app/api/skills/route.ts
普通文件
29
src/app/api/skills/route.ts
普通文件
@ -0,0 +1,29 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
export async function GET(_req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const skills = await prisma.skill.findMany({
|
||||||
|
where: { userId: session.user.id },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(skills)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
|
const { name, content } = await req.json()
|
||||||
|
if (!name || !content) return NextResponse.json({ error: "名称和内容不能为空" }, { status: 400 })
|
||||||
|
|
||||||
|
const skill = await prisma.skill.create({
|
||||||
|
data: { userId: session.user.id, name, content },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(skill, { status: 201 })
|
||||||
|
}
|
||||||
@ -1,26 +1,139 @@
|
|||||||
@import "tailwindcss";
|
@import "tailwindcss";
|
||||||
|
@import "tw-animate-css";
|
||||||
|
@import "shadcn/tailwind.css";
|
||||||
|
|
||||||
:root {
|
@custom-variant dark (&:is(.dark *));
|
||||||
--background: #ffffff;
|
|
||||||
--foreground: #171717;
|
|
||||||
}
|
|
||||||
|
|
||||||
@theme inline {
|
@theme inline {
|
||||||
--color-background: var(--background);
|
--color-background: var(--background);
|
||||||
--color-foreground: var(--foreground);
|
--color-foreground: var(--foreground);
|
||||||
--font-sans: var(--font-geist-sans);
|
--font-sans: var(--font-sans);
|
||||||
--font-mono: var(--font-geist-mono);
|
--font-mono: var(--font-geist-mono);
|
||||||
|
--font-heading: var(--font-sans);
|
||||||
|
--color-sidebar-ring: var(--sidebar-ring);
|
||||||
|
--color-sidebar-border: var(--sidebar-border);
|
||||||
|
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||||
|
--color-sidebar-accent: var(--sidebar-accent);
|
||||||
|
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||||
|
--color-sidebar-primary: var(--sidebar-primary);
|
||||||
|
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||||
|
--color-sidebar: var(--sidebar);
|
||||||
|
--color-chart-5: var(--chart-5);
|
||||||
|
--color-chart-4: var(--chart-4);
|
||||||
|
--color-chart-3: var(--chart-3);
|
||||||
|
--color-chart-2: var(--chart-2);
|
||||||
|
--color-chart-1: var(--chart-1);
|
||||||
|
--color-ring: var(--ring);
|
||||||
|
--color-input: var(--input);
|
||||||
|
--color-border: var(--border);
|
||||||
|
--color-destructive: var(--destructive);
|
||||||
|
--color-accent-foreground: var(--accent-foreground);
|
||||||
|
--color-accent: var(--accent);
|
||||||
|
--color-muted-foreground: var(--muted-foreground);
|
||||||
|
--color-muted: var(--muted);
|
||||||
|
--color-secondary-foreground: var(--secondary-foreground);
|
||||||
|
--color-secondary: var(--secondary);
|
||||||
|
--color-primary-foreground: var(--primary-foreground);
|
||||||
|
--color-primary: var(--primary);
|
||||||
|
--color-popover-foreground: var(--popover-foreground);
|
||||||
|
--color-popover: var(--popover);
|
||||||
|
--color-card-foreground: var(--card-foreground);
|
||||||
|
--color-card: var(--card);
|
||||||
|
--radius-sm: calc(var(--radius) * 0.6);
|
||||||
|
--radius-md: calc(var(--radius) * 0.8);
|
||||||
|
--radius-lg: var(--radius);
|
||||||
|
--radius-xl: calc(var(--radius) * 1.4);
|
||||||
|
--radius-2xl: calc(var(--radius) * 1.8);
|
||||||
|
--radius-3xl: calc(var(--radius) * 2.2);
|
||||||
|
--radius-4xl: calc(var(--radius) * 2.6);
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
:root {
|
||||||
:root {
|
--background: oklch(1 0 0);
|
||||||
--background: #0a0a0a;
|
--foreground: oklch(0.145 0 0);
|
||||||
--foreground: #ededed;
|
--card: oklch(1 0 0);
|
||||||
|
--card-foreground: oklch(0.145 0 0);
|
||||||
|
--popover: oklch(1 0 0);
|
||||||
|
--popover-foreground: oklch(0.145 0 0);
|
||||||
|
--primary: oklch(0.205 0 0);
|
||||||
|
--primary-foreground: oklch(0.985 0 0);
|
||||||
|
--secondary: oklch(0.97 0 0);
|
||||||
|
--secondary-foreground: oklch(0.205 0 0);
|
||||||
|
--muted: oklch(0.97 0 0);
|
||||||
|
--muted-foreground: oklch(0.556 0 0);
|
||||||
|
--accent: oklch(0.97 0 0);
|
||||||
|
--accent-foreground: oklch(0.205 0 0);
|
||||||
|
--destructive: oklch(0.577 0.245 27.325);
|
||||||
|
--border: oklch(0.922 0 0);
|
||||||
|
--input: oklch(0.922 0 0);
|
||||||
|
--ring: oklch(0.708 0 0);
|
||||||
|
--chart-1: oklch(0.87 0 0);
|
||||||
|
--chart-2: oklch(0.556 0 0);
|
||||||
|
--chart-3: oklch(0.439 0 0);
|
||||||
|
--chart-4: oklch(0.371 0 0);
|
||||||
|
--chart-5: oklch(0.269 0 0);
|
||||||
|
--radius: 0.625rem;
|
||||||
|
--sidebar: oklch(0.985 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.145 0 0);
|
||||||
|
--sidebar-primary: oklch(0.205 0 0);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.97 0 0);
|
||||||
|
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||||
|
--sidebar-border: oklch(0.922 0 0);
|
||||||
|
--sidebar-ring: oklch(0.708 0 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
--background: oklch(0.145 0 0);
|
||||||
|
--foreground: oklch(0.985 0 0);
|
||||||
|
--card: oklch(0.205 0 0);
|
||||||
|
--card-foreground: oklch(0.985 0 0);
|
||||||
|
--popover: oklch(0.205 0 0);
|
||||||
|
--popover-foreground: oklch(0.985 0 0);
|
||||||
|
--primary: oklch(0.922 0 0);
|
||||||
|
--primary-foreground: oklch(0.205 0 0);
|
||||||
|
--secondary: oklch(0.269 0 0);
|
||||||
|
--secondary-foreground: oklch(0.985 0 0);
|
||||||
|
--muted: oklch(0.269 0 0);
|
||||||
|
--muted-foreground: oklch(0.708 0 0);
|
||||||
|
--accent: oklch(0.269 0 0);
|
||||||
|
--accent-foreground: oklch(0.985 0 0);
|
||||||
|
--destructive: oklch(0.704 0.191 22.216);
|
||||||
|
--border: oklch(1 0 0 / 10%);
|
||||||
|
--input: oklch(1 0 0 / 15%);
|
||||||
|
--ring: oklch(0.556 0 0);
|
||||||
|
--chart-1: oklch(0.87 0 0);
|
||||||
|
--chart-2: oklch(0.556 0 0);
|
||||||
|
--chart-3: oklch(0.439 0 0);
|
||||||
|
--chart-4: oklch(0.371 0 0);
|
||||||
|
--chart-5: oklch(0.269 0 0);
|
||||||
|
--sidebar: oklch(0.205 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.269 0 0);
|
||||||
|
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-border: oklch(1 0 0 / 10%);
|
||||||
|
--sidebar-ring: oklch(0.556 0 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
* {
|
||||||
|
@apply border-border outline-ring/50;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
@apply bg-background text-foreground overscroll-none;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
html {
|
||||||
|
@apply font-sans;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
@utility pb-safe {
|
||||||
background: var(--background);
|
padding-bottom: env(safe-area-inset-bottom, 0px);
|
||||||
color: var(--foreground);
|
|
||||||
font-family: Arial, Helvetica, sans-serif;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@utility pt-safe {
|
||||||
|
padding-top: env(safe-area-inset-top, 0px);
|
||||||
|
}
|
||||||
@ -1,33 +1,22 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next"
|
||||||
import { Geist, Geist_Mono } from "next/font/google";
|
import "./globals.css"
|
||||||
import "./globals.css";
|
import Providers from "@/components/Providers"
|
||||||
|
import { TooltipProvider } from "@/components/ui/tooltip"
|
||||||
const geistSans = Geist({
|
|
||||||
variable: "--font-geist-sans",
|
|
||||||
subsets: ["latin"],
|
|
||||||
});
|
|
||||||
|
|
||||||
const geistMono = Geist_Mono({
|
|
||||||
variable: "--font-geist-mono",
|
|
||||||
subsets: ["latin"],
|
|
||||||
});
|
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "Create Next App",
|
title: "AI Chat",
|
||||||
description: "Generated by create next app",
|
description: "AI 聊天接口网站",
|
||||||
};
|
viewport: "width=device-width, initial-scale=1, viewport-fit=cover",
|
||||||
|
}
|
||||||
export default function RootLayout({
|
|
||||||
children,
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||||
}: Readonly<{
|
return (
|
||||||
children: React.ReactNode;
|
<html lang="zh-CN" suppressHydrationWarning>
|
||||||
}>) {
|
<body className="font-sans">
|
||||||
return (
|
<TooltipProvider>
|
||||||
<html
|
<Providers>{children}</Providers>
|
||||||
lang="en"
|
</TooltipProvider>
|
||||||
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
|
</body>
|
||||||
>
|
</html>
|
||||||
<body className="min-h-full flex flex-col">{children}</body>
|
)
|
||||||
</html>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
77
src/app/login/page.tsx
普通文件
77
src/app/login/page.tsx
普通文件
@ -0,0 +1,77 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useState } from "react"
|
||||||
|
import { useAuth } from "@/components/AuthProvider"
|
||||||
|
import Link from "next/link"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Input } from "@/components/ui/input"
|
||||||
|
import { Label } from "@/components/ui/label"
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
const { login } = useAuth()
|
||||||
|
const [email, setEmail] = useState("")
|
||||||
|
const [password, setPassword] = useState("")
|
||||||
|
const [error, setError] = useState("")
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setLoading(true)
|
||||||
|
setError("")
|
||||||
|
|
||||||
|
const result = await login(email, password)
|
||||||
|
|
||||||
|
if (result?.error) {
|
||||||
|
setError(result.error)
|
||||||
|
}
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||||
|
<Card className="w-full max-w-md">
|
||||||
|
<CardHeader className="text-center">
|
||||||
|
<CardTitle className="text-2xl">AI Chat</CardTitle>
|
||||||
|
<CardDescription>登录你的账户</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="email">邮箱</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
placeholder="请输入邮箱"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">密码</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
placeholder="请输入密码"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||||
|
<Button type="submit" className="w-full" disabled={loading}>
|
||||||
|
{loading ? "登录中..." : "登录"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
<p className="text-center text-sm text-muted-foreground mt-4">
|
||||||
|
还没有账户?{" "}
|
||||||
|
<Link href="/register" className="text-primary hover:underline">
|
||||||
|
注册
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
358
src/app/page.tsx
358
src/app/page.tsx
@ -1,65 +1,297 @@
|
|||||||
import Image from "next/image";
|
"use client"
|
||||||
|
|
||||||
export default function Home() {
|
import { useAuth } from "@/components/AuthProvider"
|
||||||
return (
|
import { useState, useCallback, useEffect, useRef } from "react"
|
||||||
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
|
import { useRouter } from "next/navigation"
|
||||||
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
|
import { Plus, MessageSquare, Search, Settings, LogOut, Pin, Archive, Trash2, MoreVertical, Download, ChevronDown, ChevronRight, Pencil, Check, X, ArrowLeft } from "lucide-react"
|
||||||
<Image
|
import { Button } from "@/components/ui/button"
|
||||||
className="dark:invert"
|
import { Input } from "@/components/ui/input"
|
||||||
src="/next.svg"
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||||
alt="Next.js logo"
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||||
width={100}
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||||
height={20}
|
import { Badge } from "@/components/ui/badge"
|
||||||
priority
|
import { ChatArea } from "@/components/chat/ChatArea"
|
||||||
/>
|
import { SettingsPanel } from "@/components/settings/SettingsPanel"
|
||||||
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
|
|
||||||
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
|
interface ChatSession {
|
||||||
To get started, edit the page.tsx file.
|
id: string
|
||||||
</h1>
|
title: string
|
||||||
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
|
pinned: boolean
|
||||||
Looking for a starting point or more instructions? Head over to{" "}
|
archived: boolean
|
||||||
<a
|
totalCost: number
|
||||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
updatedAt: string
|
||||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
messages?: Array<{ id: string }>
|
||||||
>
|
providerId: string | null
|
||||||
Templates
|
presetId: string | null
|
||||||
</a>{" "}
|
enabledBuiltInTools: string | null
|
||||||
or the{" "}
|
enabledHttpTools: string | null
|
||||||
<a
|
}
|
||||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
|
||||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
export default function HomePage() {
|
||||||
>
|
const { user, loading: authLoading, logout } = useAuth()
|
||||||
Learning
|
const router = useRouter()
|
||||||
</a>{" "}
|
const [sessions, setSessions] = useState<ChatSession[]>([])
|
||||||
center.
|
const [activeSessionId, setActiveSessionId] = useState<string | null>(null)
|
||||||
</p>
|
const [searchQuery, setSearchQuery] = useState("")
|
||||||
</div>
|
const [showArchived, setShowArchived] = useState(false)
|
||||||
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
|
const [settingsOpen, setSettingsOpen] = useState(false)
|
||||||
<a
|
const [deleteDialog, setDeleteDialog] = useState<string | null>(null)
|
||||||
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
|
const [loading, setLoading] = useState(true)
|
||||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
const [editingId, setEditingId] = useState<string | null>(null)
|
||||||
target="_blank"
|
const [editTitle, setEditTitle] = useState("")
|
||||||
rel="noopener noreferrer"
|
const editInputRef = useRef<HTMLInputElement>(null)
|
||||||
>
|
|
||||||
<Image
|
useEffect(() => {
|
||||||
className="dark:invert"
|
if (!authLoading && !user) router.push("/login")
|
||||||
src="/vercel.svg"
|
}, [authLoading, user, router])
|
||||||
alt="Vercel logomark"
|
|
||||||
width={16}
|
const fetchSessions = useCallback(async () => {
|
||||||
height={16}
|
const params = new URLSearchParams()
|
||||||
/>
|
if (searchQuery) params.set("q", searchQuery)
|
||||||
Deploy Now
|
params.set("archived", String(showArchived))
|
||||||
</a>
|
const res = await fetch(`/api/chat/sessions?${params}`)
|
||||||
<a
|
if (res.ok) setSessions(await res.json())
|
||||||
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
|
setLoading(false)
|
||||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
}, [searchQuery, showArchived])
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
useEffect(() => {
|
||||||
>
|
if (user) fetchSessions()
|
||||||
Documentation
|
}, [user, fetchSessions])
|
||||||
</a>
|
|
||||||
</div>
|
const createSession = async () => {
|
||||||
</main>
|
const res = await fetch("/api/chat/sessions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({}) })
|
||||||
</div>
|
if (res.ok) {
|
||||||
);
|
const s = await res.json()
|
||||||
|
setSessions((prev) => [s, ...prev])
|
||||||
|
setActiveSessionId(s.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteSession = async (id: string) => {
|
||||||
|
await fetch(`/api/chat/sessions/${id}`, { method: "DELETE" })
|
||||||
|
setSessions((prev) => prev.filter((s) => s.id !== id))
|
||||||
|
if (activeSessionId === id) setActiveSessionId(null)
|
||||||
|
setDeleteDialog(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const togglePin = async (s: ChatSession) => {
|
||||||
|
await fetch(`/api/chat/sessions/${s.id}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ pinned: !s.pinned }),
|
||||||
|
})
|
||||||
|
fetchSessions()
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleArchive = async (s: ChatSession) => {
|
||||||
|
await fetch(`/api/chat/sessions/${s.id}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ archived: !s.archived }),
|
||||||
|
})
|
||||||
|
fetchSessions()
|
||||||
|
}
|
||||||
|
|
||||||
|
const renameSession = async (s: ChatSession, title: string) => {
|
||||||
|
const trimmed = title.trim()
|
||||||
|
if (!trimmed || trimmed === s.title) return
|
||||||
|
setSessions((prev) => prev.map((x) => (x.id === s.id ? { ...x, title: trimmed } : x)))
|
||||||
|
await fetch(`/api/chat/sessions/${s.id}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ title: trimmed }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const startEdit = (s: ChatSession) => {
|
||||||
|
setEditingId(s.id)
|
||||||
|
setEditTitle(s.title)
|
||||||
|
setTimeout(() => editInputRef.current?.focus(), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
const saveEdit = (s: ChatSession) => {
|
||||||
|
renameSession(s, editTitle)
|
||||||
|
setEditingId(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const cancelEdit = () => {
|
||||||
|
setEditingId(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const exportSession = async (s: ChatSession, format: string) => {
|
||||||
|
const res = await fetch(`/api/chat/sessions/${s.id}/export`, {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ format }),
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
const blob = await res.blob()
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
const a = document.createElement("a")
|
||||||
|
a.href = url
|
||||||
|
a.download = `${s.title}.${format === "json" ? "json" : format === "text" ? "txt" : "md"}`
|
||||||
|
a.click()
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (authLoading || loading) {
|
||||||
|
return <div className="flex items-center justify-center min-h-screen"><p>加载中...</p></div>
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-dvh overflow-hidden bg-background">
|
||||||
|
{/* Sidebar: desktop always, mobile when no session */}
|
||||||
|
<div className={`${activeSessionId ? "hidden md:flex" : "flex"} w-full md:w-72 border-r flex-col bg-card/50 shrink-0`}>
|
||||||
|
<div className="p-3 border-b space-y-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h1 className="font-bold text-lg">AI Chat</h1>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => setSettingsOpen(true)} title="设置">
|
||||||
|
<Settings className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => logout()} title="退出登录">
|
||||||
|
<LogOut className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button className="w-full" onClick={createSession}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />新会话
|
||||||
|
</Button>
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
className="pl-8 h-9"
|
||||||
|
placeholder="搜索会话..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ScrollArea className="flex-1 px-2">
|
||||||
|
<div className="space-y-1 py-2">
|
||||||
|
{sessions.map((s) => (
|
||||||
|
<div
|
||||||
|
key={s.id}
|
||||||
|
className={`group flex items-center gap-2 px-3 py-2 rounded-lg cursor-pointer transition-colors hover:bg-accent ${
|
||||||
|
activeSessionId === s.id ? "bg-accent" : ""
|
||||||
|
}`}
|
||||||
|
onClick={() => setActiveSessionId(s.id)}
|
||||||
|
>
|
||||||
|
<MessageSquare className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||||
|
{editingId === s.id ? (
|
||||||
|
<div className="flex-1 flex items-center gap-1 min-w-0" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<Input
|
||||||
|
ref={editInputRef}
|
||||||
|
className="h-6 text-sm flex-1 min-w-0"
|
||||||
|
value={editTitle}
|
||||||
|
onChange={(e) => setEditTitle(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") { e.preventDefault(); saveEdit(s) }
|
||||||
|
if (e.key === "Escape") { e.preventDefault(); cancelEdit() }
|
||||||
|
}}
|
||||||
|
onBlur={() => saveEdit(s)}
|
||||||
|
/>
|
||||||
|
<Button variant="ghost" size="icon" className="h-5 w-5 shrink-0" onClick={() => saveEdit(s)}>
|
||||||
|
<Check className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" className="h-5 w-5 shrink-0" onClick={cancelEdit}>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="flex-1 truncate text-sm">{s.title}</span>
|
||||||
|
)}
|
||||||
|
{s.totalCost > 0 && (
|
||||||
|
<Badge variant="secondary" className="text-xs shrink-0">¥{s.totalCost.toFixed(2)}</Badge>
|
||||||
|
)}
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger
|
||||||
|
className="inline-flex items-center justify-center rounded-md h-6 w-6 opacity-0 group-hover:opacity-100 shrink-0 hover:bg-accent-foreground/10"
|
||||||
|
>
|
||||||
|
<MoreVertical className="h-3 w-3" />
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end" className="w-40">
|
||||||
|
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); startEdit(s) }}>
|
||||||
|
<Pencil className="h-4 w-4 mr-2" />重命名
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); togglePin(s) }}>
|
||||||
|
<Pin className="h-4 w-4 mr-2" />{s.pinned ? "取消置顶" : "置顶"}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); toggleArchive(s) }}>
|
||||||
|
<Archive className="h-4 w-4 mr-2" />{s.archived ? "取消归档" : "归档"}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); exportSession(s, "markdown") }}>
|
||||||
|
<Download className="h-4 w-4 mr-2" />导出 Markdown
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={(e) => { e.stopPropagation(); exportSession(s, "json") }}>
|
||||||
|
<Download className="h-4 w-4 mr-2" />导出 JSON
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="text-destructive"
|
||||||
|
onClick={(e) => { e.stopPropagation(); setDeleteDialog(s.id) }}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4 mr-2" />删除
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
|
||||||
|
<div className="p-2 border-t">
|
||||||
|
<button
|
||||||
|
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground w-full px-2 py-1 rounded"
|
||||||
|
onClick={() => setShowArchived(!showArchived)}
|
||||||
|
>
|
||||||
|
{showArchived ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
|
||||||
|
{showArchived ? "显示活跃会话" : "显示已归档"}
|
||||||
|
</button>
|
||||||
|
<div className="text-xs text-muted-foreground px-2 pt-1">
|
||||||
|
{user?.email}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Main Chat Area: desktop always, mobile when session active */}
|
||||||
|
<div className={`${activeSessionId ? "flex" : "hidden md:flex"} flex-1 flex-col`}>
|
||||||
|
{activeSessionId ? (
|
||||||
|
<>
|
||||||
|
<div className="md:hidden flex items-center gap-2 px-3 py-2 border-b">
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => setActiveSessionId(null)}>
|
||||||
|
<ArrowLeft className="h-5 w-5" />
|
||||||
|
</Button>
|
||||||
|
<span className="text-sm font-medium truncate">{sessions.find(s => s.id === activeSessionId)?.title || "聊天"}</span>
|
||||||
|
</div>
|
||||||
|
<ChatArea sessionId={activeSessionId} onSessionUpdated={fetchSessions} />
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="hidden md:flex items-center justify-center h-full text-muted-foreground">
|
||||||
|
<div className="text-center space-y-2">
|
||||||
|
<MessageSquare className="h-12 w-12 mx-auto opacity-30" />
|
||||||
|
<p>选择一个会话或创建一个新会话开始聊天</p>
|
||||||
|
<Button onClick={createSession}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />创建新会话
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Settings Panel */}
|
||||||
|
<SettingsPanel open={settingsOpen} onClose={() => setSettingsOpen(false)} onUpdate={fetchSessions} />
|
||||||
|
|
||||||
|
{/* Delete Confirmation */}
|
||||||
|
<Dialog open={!!deleteDialog} onOpenChange={() => setDeleteDialog(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>确认删除</DialogTitle>
|
||||||
|
<DialogDescription>此操作不可撤销,确定要删除该会话吗?</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setDeleteDialog(null)}>取消</Button>
|
||||||
|
<Button variant="destructive" onClick={() => deleteDialog && deleteSession(deleteDialog)}>删除</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
96
src/app/register/page.tsx
普通文件
96
src/app/register/page.tsx
普通文件
@ -0,0 +1,96 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useState } from "react"
|
||||||
|
import { useRouter } from "next/navigation"
|
||||||
|
import Link from "next/link"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Input } from "@/components/ui/input"
|
||||||
|
import { Label } from "@/components/ui/label"
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
|
|
||||||
|
export default function RegisterPage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const [email, setEmail] = useState("")
|
||||||
|
const [password, setPassword] = useState("")
|
||||||
|
const [name, setName] = useState("")
|
||||||
|
const [error, setError] = useState("")
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setLoading(true)
|
||||||
|
setError("")
|
||||||
|
|
||||||
|
const res = await fetch("/api/auth/register", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ email, password, name }),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const data = await res.json()
|
||||||
|
setError(data.error || "注册失败")
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
router.push("/login")
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||||
|
<Card className="w-full max-w-md">
|
||||||
|
<CardHeader className="text-center">
|
||||||
|
<CardTitle className="text-2xl">注册</CardTitle>
|
||||||
|
<CardDescription>创建你的 AI Chat 账户</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="name">用户名</Label>
|
||||||
|
<Input
|
||||||
|
id="name"
|
||||||
|
type="text"
|
||||||
|
placeholder="请输入用户名"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="email">邮箱</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
placeholder="请输入邮箱"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">密码</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
placeholder="请输入密码"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||||
|
<Button type="submit" className="w-full" disabled={loading}>
|
||||||
|
{loading ? "注册中..." : "注册"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
<p className="text-center text-sm text-muted-foreground mt-4">
|
||||||
|
已有账户?{" "}
|
||||||
|
<Link href="/login" className="text-primary hover:underline">
|
||||||
|
登录
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
88
src/components/AuthProvider.tsx
普通文件
88
src/components/AuthProvider.tsx
普通文件
@ -0,0 +1,88 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { createContext, useContext, useState, useEffect, useCallback } from "react"
|
||||||
|
import { useRouter } from "next/navigation"
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
id: string
|
||||||
|
email: string
|
||||||
|
name: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuthState {
|
||||||
|
user: User | null
|
||||||
|
loading: boolean
|
||||||
|
login: (email: string, password: string) => Promise<{ error?: string }>
|
||||||
|
logout: () => Promise<void>
|
||||||
|
refresh: () => Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
const AuthContext = createContext<AuthState>({
|
||||||
|
user: null,
|
||||||
|
loading: true,
|
||||||
|
login: async () => ({}),
|
||||||
|
logout: async () => {},
|
||||||
|
refresh: async () => {},
|
||||||
|
})
|
||||||
|
|
||||||
|
export function useAuth() {
|
||||||
|
return useContext(AuthContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchSession(): Promise<User | null> {
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/auth/session")
|
||||||
|
if (!res.ok) return null
|
||||||
|
const data = await res.json()
|
||||||
|
return data?.user ?? null
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const [user, setUser] = useState<User | null>(null)
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchSession().then((user) => {
|
||||||
|
setUser(user)
|
||||||
|
setLoading(false)
|
||||||
|
})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const login = useCallback(async (email: string, password: string) => {
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/auth/login", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ email, password }),
|
||||||
|
})
|
||||||
|
const data = await res.json()
|
||||||
|
if (!res.ok) return { error: data.error || "登录失败" }
|
||||||
|
setUser(data.user)
|
||||||
|
router.push("/")
|
||||||
|
return {}
|
||||||
|
} catch {
|
||||||
|
return { error: "登录失败" }
|
||||||
|
}
|
||||||
|
}, [router])
|
||||||
|
|
||||||
|
const logout = useCallback(async () => {
|
||||||
|
await fetch("/api/auth/session", { method: "DELETE" })
|
||||||
|
setUser(null)
|
||||||
|
router.push("/login")
|
||||||
|
}, [router])
|
||||||
|
|
||||||
|
const refresh = useCallback(async () => {
|
||||||
|
const user = await fetchSession()
|
||||||
|
setUser(user)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthContext.Provider value={{ user, loading, login, logout, refresh }}>
|
||||||
|
{children}
|
||||||
|
</AuthContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
7
src/components/Providers.tsx
普通文件
7
src/components/Providers.tsx
普通文件
@ -0,0 +1,7 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { AuthProvider } from "@/components/AuthProvider"
|
||||||
|
|
||||||
|
export default function Providers({ children }: { children: React.ReactNode }) {
|
||||||
|
return <AuthProvider>{children}</AuthProvider>
|
||||||
|
}
|
||||||
856
src/components/chat/ChatArea.tsx
普通文件
856
src/components/chat/ChatArea.tsx
普通文件
@ -0,0 +1,856 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useState, useEffect, useRef, useCallback } from "react"
|
||||||
|
import { Send, Square, RefreshCw, ChevronDown, AlertTriangle, Wrench, Bug } from "lucide-react"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Textarea } from "@/components/ui/textarea"
|
||||||
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
|
||||||
|
import { Badge } from "@/components/ui/badge"
|
||||||
|
import { Switch } from "@/components/ui/switch"
|
||||||
|
import { Label } from "@/components/ui/label"
|
||||||
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||||
|
import {
|
||||||
|
Sheet, SheetContent, SheetHeader, SheetTitle,
|
||||||
|
} from "@/components/ui/sheet"
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu"
|
||||||
|
import { MessageBubble } from "@/components/chat/MessageBubble"
|
||||||
|
import { BUILT_IN_TOOLS } from "@/lib/builtin-tools"
|
||||||
|
|
||||||
|
interface Message {
|
||||||
|
id: string
|
||||||
|
role: string
|
||||||
|
content: string
|
||||||
|
toolCalls?: string | null
|
||||||
|
toolResults?: string | null
|
||||||
|
tokenUsage?: string | null
|
||||||
|
cost: number
|
||||||
|
isSummary: boolean
|
||||||
|
createdAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ChatSession {
|
||||||
|
id: string
|
||||||
|
title: string
|
||||||
|
providerId: string | null
|
||||||
|
presetId: string | null
|
||||||
|
totalCost: number
|
||||||
|
draft: string | null
|
||||||
|
messages: Message[]
|
||||||
|
enabledSkillIds: string | null
|
||||||
|
enabledToolIds: string | null
|
||||||
|
enabledBuiltInTools: string | null
|
||||||
|
enabledHttpTools: string | null
|
||||||
|
thinkingEnabled: boolean
|
||||||
|
markdownEnabled: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Provider {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
modelName: string
|
||||||
|
baseUrl: string
|
||||||
|
apiKey: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Preset {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
isDefault: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ChatArea({ sessionId, onSessionUpdated }: { sessionId: string; onSessionUpdated: () => void }) {
|
||||||
|
const [chatSession, setChatSession] = useState<ChatSession | null>(null)
|
||||||
|
const [input, setInput] = useState("")
|
||||||
|
const [streamingContent, setStreamingContent] = useState("")
|
||||||
|
const [streamingReasoning, setStreamingReasoning] = useState("")
|
||||||
|
const [isStreaming, setIsStreaming] = useState(false)
|
||||||
|
const [toolCalls, setToolCalls] = useState<Array<{ toolName: string; status: string; args?: unknown; result?: string }>>([])
|
||||||
|
const [providers, setProviders] = useState<Provider[]>([])
|
||||||
|
const [presets, setPresets] = useState<Preset[]>([])
|
||||||
|
const scrollRef = useRef<HTMLDivElement>(null)
|
||||||
|
const inputRef = useRef<HTMLTextAreaElement>(null)
|
||||||
|
const abortRef = useRef<AbortController | null>(null)
|
||||||
|
const [toolsPanelOpen, setToolsPanelOpen] = useState(false)
|
||||||
|
const [allSkills, setAllSkills] = useState<Array<{ id: string; name: string; content: string }>>([])
|
||||||
|
const [allMcpTools, setAllMcpTools] = useState<Array<{ id: string; name: string; description: string | null; serverName: string }>>([])
|
||||||
|
const [allHttpTools, setAllHttpTools] = useState<Array<{ id: string; name: string; description: string | null; method: string; url: string }>>([])
|
||||||
|
const [debugOpen, setDebugOpen] = useState(false)
|
||||||
|
const [debugMode, setDebugMode] = useState(false)
|
||||||
|
const [debugRounds, setDebugRounds] = useState<Array<{
|
||||||
|
round: number
|
||||||
|
request: Record<string, unknown>
|
||||||
|
responseContent: string
|
||||||
|
reasoningContent: string
|
||||||
|
toolCalls: Array<{ name: string; args: unknown }>
|
||||||
|
toolResults: Array<{ name: string; result: string }>
|
||||||
|
}>>([])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setDebugMode(localStorage.getItem("debug-mode") === "true")
|
||||||
|
const onStorage = () => setDebugMode(localStorage.getItem("debug-mode") === "true")
|
||||||
|
window.addEventListener("storage", onStorage)
|
||||||
|
return () => window.removeEventListener("storage", onStorage)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleResize = () => {
|
||||||
|
if (inputRef.current && document.activeElement === inputRef.current) {
|
||||||
|
inputRef.current.scrollIntoView({ block: "end", behavior: "smooth" })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (typeof window !== "undefined" && "visualViewport" in window) {
|
||||||
|
window.visualViewport?.addEventListener("resize", handleResize)
|
||||||
|
window.visualViewport?.addEventListener("scroll", handleResize)
|
||||||
|
return () => {
|
||||||
|
window.visualViewport?.removeEventListener("resize", handleResize)
|
||||||
|
window.visualViewport?.removeEventListener("scroll", handleResize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const fetchSession = useCallback(async () => {
|
||||||
|
const res = await fetch(`/api/chat/sessions/${sessionId}`)
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json()
|
||||||
|
setChatSession(data)
|
||||||
|
setInput(data.draft || "")
|
||||||
|
}
|
||||||
|
}, [sessionId])
|
||||||
|
|
||||||
|
const fetchProviders = useCallback(async () => {
|
||||||
|
const res = await fetch("/api/providers")
|
||||||
|
if (res.ok) setProviders(await res.json())
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const fetchPresets = useCallback(async () => {
|
||||||
|
const res = await fetch("/api/presets")
|
||||||
|
if (res.ok) setPresets(await res.json())
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const fetchToolsAndSkills = useCallback(async () => {
|
||||||
|
const [skillsRes, mcpRes, httpRes] = await Promise.all([
|
||||||
|
fetch("/api/skills"),
|
||||||
|
fetch("/api/mcp/servers"),
|
||||||
|
fetch("/api/http-tools"),
|
||||||
|
])
|
||||||
|
if (skillsRes.ok) setAllSkills(await skillsRes.json())
|
||||||
|
if (mcpRes.ok) {
|
||||||
|
const servers = await mcpRes.json()
|
||||||
|
const tools: Array<{ id: string; name: string; description: string | null; serverName: string }> = []
|
||||||
|
for (const srv of servers) {
|
||||||
|
for (const tool of srv.tools || []) {
|
||||||
|
tools.push({ ...tool, serverName: srv.name })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setAllMcpTools(tools)
|
||||||
|
}
|
||||||
|
if (httpRes.ok) setAllHttpTools(await httpRes.json())
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => { fetchSession(); fetchProviders(); fetchPresets() }, [fetchSession, fetchProviders, fetchPresets])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (scrollRef.current) {
|
||||||
|
scrollRef.current.scrollTop = scrollRef.current.scrollHeight
|
||||||
|
}
|
||||||
|
}, [chatSession?.messages, streamingContent])
|
||||||
|
|
||||||
|
const activeProvider = providers.find((p) => p.id === chatSession?.providerId)
|
||||||
|
const activePreset = presets.find((p) => p.id === chatSession?.presetId)
|
||||||
|
const sendDisabled = !input.trim() || isStreaming || !activeProvider
|
||||||
|
|
||||||
|
const updateSession = async (data: Record<string, unknown>) => {
|
||||||
|
await fetch(`/api/chat/sessions/${sessionId}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
})
|
||||||
|
fetchSession()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleProviderChange = (providerId: string) => {
|
||||||
|
updateSession({ providerId })
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlePresetChange = (presetId: string) => {
|
||||||
|
updateSession({ presetId })
|
||||||
|
}
|
||||||
|
|
||||||
|
const openToolsPanel = () => {
|
||||||
|
fetchToolsAndSkills()
|
||||||
|
setToolsPanelOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const enabledSkillIds: string[] = (() => {
|
||||||
|
try { return chatSession?.enabledSkillIds ? JSON.parse(chatSession.enabledSkillIds) : [] } catch { return [] }
|
||||||
|
})()
|
||||||
|
const enabledToolIds: string[] = (() => {
|
||||||
|
try { return chatSession?.enabledToolIds ? JSON.parse(chatSession.enabledToolIds) : [] } catch { return [] }
|
||||||
|
})()
|
||||||
|
const enabledBuiltInTools: string[] = (() => {
|
||||||
|
try { return chatSession?.enabledBuiltInTools ? JSON.parse(chatSession.enabledBuiltInTools) : [] } catch { return [] }
|
||||||
|
})()
|
||||||
|
const enabledHttpTools: string[] = (() => {
|
||||||
|
try { return chatSession?.enabledHttpTools ? JSON.parse(chatSession.enabledHttpTools) : [] } catch { return [] }
|
||||||
|
})()
|
||||||
|
|
||||||
|
const toggleSkill = (skillId: string) => {
|
||||||
|
const next = enabledSkillIds.includes(skillId)
|
||||||
|
? enabledSkillIds.filter((id) => id !== skillId)
|
||||||
|
: [...enabledSkillIds, skillId]
|
||||||
|
updateSession({ enabledSkillIds: next })
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleMcpTool = (toolId: string) => {
|
||||||
|
const next = enabledToolIds.includes(toolId)
|
||||||
|
? enabledToolIds.filter((id) => id !== toolId)
|
||||||
|
: [...enabledToolIds, toolId]
|
||||||
|
updateSession({ enabledToolIds: next })
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleBuiltInTool = (toolId: string) => {
|
||||||
|
const next = enabledBuiltInTools.includes(toolId)
|
||||||
|
? enabledBuiltInTools.filter((id) => id !== toolId)
|
||||||
|
: [...enabledBuiltInTools, toolId]
|
||||||
|
updateSession({ enabledBuiltInTools: next })
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleHttpTool = (toolId: string) => {
|
||||||
|
const next = enabledHttpTools.includes(toolId)
|
||||||
|
? enabledHttpTools.filter((id) => id !== toolId)
|
||||||
|
: [...enabledHttpTools, toolId]
|
||||||
|
updateSession({ enabledHttpTools: next })
|
||||||
|
}
|
||||||
|
|
||||||
|
const sendMessage = async (content: string) => {
|
||||||
|
if (!content.trim() || isStreaming) return false
|
||||||
|
setIsStreaming(true)
|
||||||
|
setStreamingContent("")
|
||||||
|
setStreamingReasoning("")
|
||||||
|
setToolCalls([])
|
||||||
|
abortRef.current = new AbortController()
|
||||||
|
|
||||||
|
const requestBody = {
|
||||||
|
sessionId,
|
||||||
|
message: content,
|
||||||
|
providerId: chatSession?.providerId,
|
||||||
|
presetId: chatSession?.presetId,
|
||||||
|
enabledSkillIds: chatSession?.enabledSkillIds ? JSON.parse(chatSession.enabledSkillIds) : null,
|
||||||
|
enabledToolIds: chatSession?.enabledToolIds ? JSON.parse(chatSession.enabledToolIds) : null,
|
||||||
|
enabledBuiltInTools: chatSession?.enabledBuiltInTools ? JSON.parse(chatSession.enabledBuiltInTools) : null,
|
||||||
|
enabledHttpTools: chatSession?.enabledHttpTools ? JSON.parse(chatSession.enabledHttpTools) : null,
|
||||||
|
thinkingEnabled: chatSession?.thinkingEnabled,
|
||||||
|
}
|
||||||
|
|
||||||
|
const debugRoundsAcc: Array<{
|
||||||
|
round: number
|
||||||
|
responseContent: string
|
||||||
|
reasoningContent: string
|
||||||
|
toolCalls: Array<{ name: string; args: unknown }>
|
||||||
|
toolResults: Array<{ name: string; result: string }>
|
||||||
|
}> = []
|
||||||
|
let debugRoundIdx = 0
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/chat/send", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(requestBody),
|
||||||
|
signal: abortRef.current.signal,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!res.ok || !res.body) { setIsStreaming(false); return false }
|
||||||
|
|
||||||
|
const reader = res.body.getReader()
|
||||||
|
const decoder = new TextDecoder()
|
||||||
|
let buffer = ""
|
||||||
|
let fullContent = ""
|
||||||
|
|
||||||
|
// Debug accumulators
|
||||||
|
let dbgRoundContent = ""
|
||||||
|
let dbgRoundReasoning = ""
|
||||||
|
let dbgRoundToolCalls: Array<{ name: string; args: unknown }> = []
|
||||||
|
let dbgPendingResults: Array<{ name: string; result: string }> = []
|
||||||
|
|
||||||
|
const flushDebugRound = (additionalResults: Array<{ name: string; result: string }> = []) => {
|
||||||
|
debugRoundIdx++
|
||||||
|
debugRoundsAcc.push({
|
||||||
|
round: debugRoundIdx,
|
||||||
|
responseContent: dbgRoundContent,
|
||||||
|
reasoningContent: dbgRoundReasoning,
|
||||||
|
toolCalls: [...dbgRoundToolCalls],
|
||||||
|
toolResults: [...dbgPendingResults, ...additionalResults],
|
||||||
|
})
|
||||||
|
dbgRoundContent = ""
|
||||||
|
dbgRoundReasoning = ""
|
||||||
|
dbgRoundToolCalls = []
|
||||||
|
dbgPendingResults = []
|
||||||
|
}
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read()
|
||||||
|
if (done) break
|
||||||
|
buffer += decoder.decode(value, { stream: true })
|
||||||
|
const lines = buffer.split("\n")
|
||||||
|
buffer = lines.pop() || ""
|
||||||
|
for (const line of lines) {
|
||||||
|
const trimmed = line.trim()
|
||||||
|
if (!trimmed.startsWith("data: ")) continue
|
||||||
|
try {
|
||||||
|
const event = JSON.parse(trimmed.slice(6))
|
||||||
|
switch (event.type) {
|
||||||
|
case "delta":
|
||||||
|
fullContent += event.content
|
||||||
|
setStreamingContent(fullContent)
|
||||||
|
dbgRoundContent += event.content
|
||||||
|
break
|
||||||
|
case "reasoning_delta":
|
||||||
|
setStreamingReasoning((prev: string) => prev + event.content)
|
||||||
|
dbgRoundReasoning += event.content
|
||||||
|
break
|
||||||
|
case "tool_calls":
|
||||||
|
flushDebugRound()
|
||||||
|
setToolCalls((prev) => [
|
||||||
|
...prev,
|
||||||
|
...event.calls.map((c: { function: { name: string; arguments: string } }) => ({
|
||||||
|
toolName: c.function.name,
|
||||||
|
status: "preparing" as const,
|
||||||
|
args: (() => { try { return JSON.parse(c.function.arguments || "{}") } catch { return {} } })(),
|
||||||
|
})),
|
||||||
|
])
|
||||||
|
dbgRoundToolCalls = event.calls.map((c: { function: { name: string; arguments: string } }) => ({
|
||||||
|
name: c.function.name,
|
||||||
|
args: (() => { try { return JSON.parse(c.function.arguments || "{}") } catch { return {} } })(),
|
||||||
|
}))
|
||||||
|
break
|
||||||
|
case "tool_start":
|
||||||
|
setToolCalls((prev) =>
|
||||||
|
prev.map((tc) =>
|
||||||
|
tc.toolName === event.toolName && tc.status === "preparing"
|
||||||
|
? { ...tc, status: "running" }
|
||||||
|
: tc
|
||||||
|
)
|
||||||
|
)
|
||||||
|
break
|
||||||
|
case "tool_result":
|
||||||
|
setToolCalls((prev) =>
|
||||||
|
prev.map((tc) =>
|
||||||
|
tc.toolName === event.toolName && tc.status === "running"
|
||||||
|
? { ...tc, status: "done", result: event.result }
|
||||||
|
: tc
|
||||||
|
)
|
||||||
|
)
|
||||||
|
dbgPendingResults.push({ name: event.toolName, result: event.result })
|
||||||
|
break
|
||||||
|
case "done":
|
||||||
|
flushDebugRound()
|
||||||
|
break
|
||||||
|
case "error":
|
||||||
|
console.error(event.content)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
} catch (err: unknown) {
|
||||||
|
if (err instanceof Error && err.name !== "AbortError") console.error(err)
|
||||||
|
return false
|
||||||
|
} finally {
|
||||||
|
setIsStreaming(false)
|
||||||
|
setStreamingContent("")
|
||||||
|
setStreamingReasoning("")
|
||||||
|
if (debugMode && debugRoundsAcc.length > 0) {
|
||||||
|
const rounds = debugRoundsAcc.map((r, i) => ({
|
||||||
|
...r,
|
||||||
|
request: (i === 0 ? requestBody : {}) as Record<string, unknown>,
|
||||||
|
}))
|
||||||
|
setDebugRounds(rounds)
|
||||||
|
}
|
||||||
|
fetchSession()
|
||||||
|
onSessionUpdated()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSend = async () => {
|
||||||
|
if (!input.trim() || !activeProvider) return
|
||||||
|
const content = input.trim()
|
||||||
|
setInput("")
|
||||||
|
await fetch(`/api/chat/sessions/${sessionId}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ draft: "" }),
|
||||||
|
})
|
||||||
|
sendMessage(content)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleStop = () => {
|
||||||
|
abortRef.current?.abort()
|
||||||
|
setIsStreaming(false)
|
||||||
|
fetchSession()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||||
|
if (e.key === "Enter" && !e.shiftKey) {
|
||||||
|
e.preventDefault()
|
||||||
|
handleSend()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRollback = async (messageId: string) => {
|
||||||
|
await fetch(`/api/chat/sessions/${sessionId}/rollback`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ messageId }),
|
||||||
|
})
|
||||||
|
fetchSession()
|
||||||
|
onSessionUpdated()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleEdit = async (messageId: string, content: string) => {
|
||||||
|
await fetch(`/api/chat/sessions/${sessionId}/rollback`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ messageId, includeTarget: true }),
|
||||||
|
})
|
||||||
|
const res = await fetch(`/api/chat/sessions/${sessionId}`)
|
||||||
|
if (res.ok) setChatSession(await res.json())
|
||||||
|
onSessionUpdated()
|
||||||
|
setInput(content)
|
||||||
|
setTimeout(() => inputRef.current?.focus(), 50)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCopyMessage = (content: string) => {
|
||||||
|
navigator.clipboard.writeText(content)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRegenerate = async () => {
|
||||||
|
if (isStreaming || !activeProvider) return
|
||||||
|
const msgs = chatSession?.messages || []
|
||||||
|
const lastUserMsg = [...msgs].reverse().find((m) => m.role === "user")
|
||||||
|
if (!lastUserMsg) return
|
||||||
|
|
||||||
|
await fetch(`/api/chat/sessions/${sessionId}/rollback`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ messageId: lastUserMsg.id }),
|
||||||
|
})
|
||||||
|
const res = await fetch(`/api/chat/sessions/${sessionId}`)
|
||||||
|
if (res.ok) setChatSession(await res.json())
|
||||||
|
onSessionUpdated()
|
||||||
|
await sendMessage(lastUserMsg.content)
|
||||||
|
}
|
||||||
|
|
||||||
|
const messages = chatSession?.messages || []
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="border-b px-4 py-2 flex items-center gap-3 shrink-0 flex-wrap">
|
||||||
|
<h2 className="font-semibold truncate max-w-[200px]">{chatSession?.title || "聊天"}</h2>
|
||||||
|
|
||||||
|
{/* Provider selector */}
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger className="inline-flex items-center gap-1 h-8 rounded-md border border-input bg-background px-3 text-xs hover:bg-accent hover:text-accent-foreground">
|
||||||
|
{activeProvider ? `${activeProvider.name} (${activeProvider.modelName})` : "选择模型"}
|
||||||
|
<ChevronDown className="h-3 w-3" />
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="start" className="w-64">
|
||||||
|
{providers.length === 0 && (
|
||||||
|
<div className="px-2 py-3 text-xs text-muted-foreground text-center">
|
||||||
|
暂无 Provider,请在设置中添加
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{providers.map((p) => (
|
||||||
|
<DropdownMenuItem
|
||||||
|
key={p.id}
|
||||||
|
onClick={() => handleProviderChange(p.id)}
|
||||||
|
className="flex flex-col items-start gap-0.5"
|
||||||
|
>
|
||||||
|
<span className="font-medium">{p.name}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{p.modelName} @ {p.baseUrl}</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
|
||||||
|
{/* Preset selector */}
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger className="inline-flex items-center gap-1 h-8 rounded-md border border-input bg-background px-3 text-xs hover:bg-accent hover:text-accent-foreground">
|
||||||
|
{activePreset ? `预设: ${activePreset.name}` : "选择预设"}
|
||||||
|
<ChevronDown className="h-3 w-3" />
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="start" className="w-56">
|
||||||
|
<DropdownMenuItem onClick={() => handlePresetChange("")}>
|
||||||
|
<span className="text-muted-foreground">无预设</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
{presets.map((p) => (
|
||||||
|
<DropdownMenuItem
|
||||||
|
key={p.id}
|
||||||
|
onClick={() => handlePresetChange(p.id)}
|
||||||
|
className="flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<span>{p.name}</span>
|
||||||
|
{p.isDefault && <Badge variant="secondary" className="text-[10px]">默认</Badge>}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
|
||||||
|
<div className="flex-1" />
|
||||||
|
|
||||||
|
{chatSession && chatSession.totalCost > 0 && (
|
||||||
|
<Badge variant="outline" className="text-[10px]">¥{chatSession.totalCost.toFixed(4)}</Badge>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={openToolsPanel} title="工具 & Skills 配置">
|
||||||
|
<Wrench className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{debugMode && (
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setDebugOpen(true)} title="调试信息">
|
||||||
|
<Bug className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={handleRegenerate} disabled={isStreaming} title="重新生成">
|
||||||
|
<RefreshCw className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Warning when no provider */}
|
||||||
|
{!activeProvider && (
|
||||||
|
<div className="flex items-center gap-2 px-4 py-2 text-xs text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-950/30 border-b">
|
||||||
|
<AlertTriangle className="h-3.5 w-3.5 shrink-0" />
|
||||||
|
<span>请先在顶部选择一个模型才能发送消息</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Messages */}
|
||||||
|
<div className="flex-1 overflow-y-auto overscroll-contain px-4" ref={scrollRef as React.RefObject<HTMLDivElement>}>
|
||||||
|
<div className="max-w-3xl mx-auto py-4 space-y-4">
|
||||||
|
{messages.map((msg) => (
|
||||||
|
<MessageBubble
|
||||||
|
key={msg.id}
|
||||||
|
message={msg}
|
||||||
|
markdownEnabled={chatSession?.markdownEnabled !== false}
|
||||||
|
onRollback={() => handleRollback(msg.id)}
|
||||||
|
onEdit={() => handleEdit(msg.id, msg.content)}
|
||||||
|
onCopy={() => handleCopyMessage(msg.content)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Streaming reasoning / thinking chain */}
|
||||||
|
{streamingReasoning && (
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Avatar className="h-8 w-8 shrink-0">
|
||||||
|
<AvatarFallback className="bg-primary text-primary-foreground text-xs">AI</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="flex-1">
|
||||||
|
<details className="mb-1" open>
|
||||||
|
<summary className="text-[10px] text-muted-foreground cursor-pointer hover:text-foreground inline-flex items-center gap-1">
|
||||||
|
🧠 正在思考...
|
||||||
|
</summary>
|
||||||
|
<div className="mt-1 bg-muted/30 border border-muted rounded-md px-3 py-2 text-xs text-muted-foreground whitespace-pre-wrap max-h-60 overflow-y-auto">
|
||||||
|
{streamingReasoning}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Streaming content */}
|
||||||
|
{(streamingContent || (!streamingContent && streamingReasoning && !toolCalls.length)) && (
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Avatar className="h-8 w-8 shrink-0">
|
||||||
|
<AvatarFallback className="bg-primary text-primary-foreground text-xs">AI</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="flex-1">
|
||||||
|
<div className="bg-muted rounded-lg px-4 py-2 text-sm whitespace-pre-wrap">
|
||||||
|
{streamingContent || (streamingReasoning && !streamingContent ? "" : "")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tool calls display */}
|
||||||
|
{toolCalls.map((tc, i) => (
|
||||||
|
<div key={i} className="flex gap-3 pl-11">
|
||||||
|
<div className="flex-1">
|
||||||
|
<div className={`text-xs px-3 py-2 rounded-lg border ${
|
||||||
|
tc.status === "running" ? "border-yellow-500/50 bg-yellow-500/5" :
|
||||||
|
tc.status === "done" ? "border-green-500/50 bg-green-500/5" :
|
||||||
|
"border-muted bg-muted/50"
|
||||||
|
}`}>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="font-mono text-xs font-medium">🔧 {tc.toolName}</span>
|
||||||
|
<Badge variant="outline" className="text-[10px] px-1 py-0">
|
||||||
|
{tc.status === "preparing" ? "准备中" : tc.status === "running" ? "执行中..." : "完成"}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
{tc.result && (
|
||||||
|
<pre className="mt-1 text-[10px] text-muted-foreground whitespace-pre-wrap max-h-24 overflow-auto">
|
||||||
|
{typeof tc.result === "string" ? tc.result : JSON.stringify(tc.result, null, 2)}
|
||||||
|
</pre>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<div className="h-4" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Input */}
|
||||||
|
<div className="border-t p-4 shrink-0 pb-safe">
|
||||||
|
<div className="max-w-3xl mx-auto">
|
||||||
|
<div className="flex gap-2 items-end">
|
||||||
|
<Textarea
|
||||||
|
ref={inputRef}
|
||||||
|
placeholder="输入消息... (Shift+Enter 换行, Enter 发送)"
|
||||||
|
value={input}
|
||||||
|
onChange={(e) => {
|
||||||
|
setInput(e.target.value)
|
||||||
|
fetch(`/api/chat/sessions/${sessionId}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ draft: e.target.value }),
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
onFocus={() => { setTimeout(() => inputRef.current?.scrollIntoView({ block: "end" }), 100) }}
|
||||||
|
className="min-h-[44px] max-h-[200px] resize-none"
|
||||||
|
rows={1}
|
||||||
|
disabled={isStreaming}
|
||||||
|
/>
|
||||||
|
{isStreaming ? (
|
||||||
|
<Button variant="destructive" size="icon" onClick={handleStop} title="停止生成">
|
||||||
|
<Square className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Button size="icon" onClick={handleSend} disabled={sendDisabled} title={!activeProvider ? "请先选择模型" : "发送"}>
|
||||||
|
<Send className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tools & Skills Panel */}
|
||||||
|
<Sheet open={toolsPanelOpen} onOpenChange={setToolsPanelOpen}>
|
||||||
|
<SheetContent side="right" className="w-full sm:max-w-md p-0">
|
||||||
|
<SheetHeader className="px-6 py-4 border-b">
|
||||||
|
<SheetTitle>工具 & Skills 配置</SheetTitle>
|
||||||
|
</SheetHeader>
|
||||||
|
<ScrollArea className="h-[calc(100vh-80px)] px-6 py-4 space-y-6">
|
||||||
|
{/* Chat Settings */}
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold text-sm mb-3">对话设置</h3>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center justify-between border rounded-lg p-3">
|
||||||
|
<div className="flex-1 min-w-0 mr-2">
|
||||||
|
<p className="text-sm font-medium">思考模式</p>
|
||||||
|
<p className="text-[11px] text-muted-foreground">启用后 AI 会在回复前进行深度思考(仅部分模型支持)</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={chatSession?.thinkingEnabled ?? false}
|
||||||
|
onCheckedChange={(v) => updateSession({ thinkingEnabled: v })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between border rounded-lg p-3">
|
||||||
|
<div className="flex-1 min-w-0 mr-2">
|
||||||
|
<p className="text-sm font-medium">Markdown 渲染</p>
|
||||||
|
<p className="text-[11px] text-muted-foreground">启用后 AI 回复将以富文本格式显示</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={chatSession?.markdownEnabled !== false}
|
||||||
|
onCheckedChange={(v) => updateSession({ markdownEnabled: v })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Skills */}
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold text-sm mb-3">Skills</h3>
|
||||||
|
{allSkills.length === 0 ? (
|
||||||
|
<p className="text-xs text-muted-foreground">暂无 Skills,请在设置中添加</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{allSkills.map((skill) => (
|
||||||
|
<div key={skill.id} className="flex items-center justify-between border rounded-lg p-3">
|
||||||
|
<div className="flex-1 min-w-0 mr-2">
|
||||||
|
<p className="text-sm font-medium truncate">{skill.name}</p>
|
||||||
|
<p className="text-[11px] text-muted-foreground line-clamp-2">{skill.content}</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={enabledSkillIds.includes(skill.id)}
|
||||||
|
onCheckedChange={() => toggleSkill(skill.id)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* MCP Tools */}
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold text-sm mb-3 mt-6">MCP 工具</h3>
|
||||||
|
{allMcpTools.length === 0 ? (
|
||||||
|
<p className="text-xs text-muted-foreground">暂无 MCP 工具,请先在设置中连接 MCP 服务器</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{allMcpTools.map((tool) => (
|
||||||
|
<div key={tool.id} className="flex items-center justify-between border rounded-lg p-3">
|
||||||
|
<div className="flex-1 min-w-0 mr-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<p className="text-sm font-medium font-mono truncate">{tool.name}</p>
|
||||||
|
<Badge variant="outline" className="text-[10px] shrink-0">{tool.serverName}</Badge>
|
||||||
|
</div>
|
||||||
|
{tool.description && (
|
||||||
|
<p className="text-[11px] text-muted-foreground line-clamp-2 mt-0.5">{tool.description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={enabledToolIds.includes(tool.id)}
|
||||||
|
onCheckedChange={() => toggleMcpTool(tool.id)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Built-in Tools */}
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold text-sm mb-3 mt-6">内置工具</h3>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{BUILT_IN_TOOLS.map((tool) => (
|
||||||
|
<div key={tool.id} className="flex items-center justify-between border rounded-lg p-3">
|
||||||
|
<div className="flex-1 min-w-0 mr-2">
|
||||||
|
<p className="text-sm font-medium font-mono">{tool.name}</p>
|
||||||
|
<p className="text-[11px] text-muted-foreground line-clamp-2 mt-0.5">{tool.description}</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={enabledBuiltInTools.includes(tool.id)}
|
||||||
|
onCheckedChange={() => toggleBuiltInTool(tool.id)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* HTTP Tools */}
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold text-sm mb-3 mt-6">HTTP 工具</h3>
|
||||||
|
{allHttpTools.length === 0 ? (
|
||||||
|
<p className="text-xs text-muted-foreground">暂无 HTTP 工具,请先在设置中添加</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{allHttpTools.map((tool) => (
|
||||||
|
<div key={tool.id} className="flex items-center justify-between border rounded-lg p-3">
|
||||||
|
<div className="flex-1 min-w-0 mr-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge variant="outline" className="text-[10px]">{tool.method}</Badge>
|
||||||
|
<p className="text-sm font-medium font-mono truncate">{tool.name}</p>
|
||||||
|
</div>
|
||||||
|
<p className="text-[11px] text-muted-foreground truncate mt-0.5">{tool.url}</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={enabledHttpTools.includes(tool.id)}
|
||||||
|
onCheckedChange={() => toggleHttpTool(tool.id)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
|
||||||
|
{/* Debug Panel */}
|
||||||
|
<Sheet open={debugOpen} onOpenChange={setDebugOpen}>
|
||||||
|
<SheetContent side="right" className="w-full sm:max-w-2xl p-0">
|
||||||
|
<SheetHeader className="px-6 py-4 border-b">
|
||||||
|
<SheetTitle>调试信息</SheetTitle>
|
||||||
|
</SheetHeader>
|
||||||
|
<ScrollArea className="h-[calc(100vh-80px)] px-6 py-4">
|
||||||
|
{debugRounds.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground text-center py-8">发送消息后,此处将显示调试信息</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{debugRounds.map((dr, i) => (
|
||||||
|
<div key={i} className="border rounded-lg overflow-hidden">
|
||||||
|
<div className="bg-muted/50 px-4 py-2 text-sm font-medium border-b">
|
||||||
|
Round {dr.round}{i === 0 ? " - 请求" : dr.toolCalls.length > 0 ? " - AI 响应 + 工具调用" : " - AI 最终响应"}
|
||||||
|
</div>
|
||||||
|
{i === 0 && (
|
||||||
|
<details className="border-b" open>
|
||||||
|
<summary className="px-4 py-2 text-xs cursor-pointer hover:bg-muted/30">📤 发送给 AI 的请求</summary>
|
||||||
|
<pre className="px-4 py-2 text-[11px] bg-muted/30 overflow-x-auto whitespace-pre-wrap max-h-80">
|
||||||
|
{JSON.stringify(dr.request, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
{dr.reasoningContent && (
|
||||||
|
<details className="border-b">
|
||||||
|
<summary className="px-4 py-2 text-xs cursor-pointer hover:bg-muted/30">🧠 思考过程</summary>
|
||||||
|
<pre className="px-4 py-2 text-[11px] bg-muted/30 overflow-x-auto whitespace-pre-wrap max-h-60">
|
||||||
|
{dr.reasoningContent}
|
||||||
|
</pre>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
{dr.responseContent && (
|
||||||
|
<details className="border-b" open>
|
||||||
|
<summary className="px-4 py-2 text-xs cursor-pointer hover:bg-muted/30">📥 AI 响应内容</summary>
|
||||||
|
<pre className="px-4 py-2 text-[11px] bg-muted/30 overflow-x-auto whitespace-pre-wrap max-h-80">
|
||||||
|
{dr.responseContent}
|
||||||
|
</pre>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
{dr.toolCalls.length > 0 && (
|
||||||
|
<details className="border-b" open>
|
||||||
|
<summary className="px-4 py-2 text-xs cursor-pointer hover:bg-muted/30">🔧 工具调用 ({dr.toolCalls.length})</summary>
|
||||||
|
<div className="space-y-2 p-3">
|
||||||
|
{dr.toolCalls.map((tc, j) => (
|
||||||
|
<div key={j} className="text-[11px]">
|
||||||
|
<div className="font-mono font-medium text-xs mb-1">{tc.name}</div>
|
||||||
|
<pre className="bg-muted/30 rounded p-2 overflow-x-auto whitespace-pre-wrap">
|
||||||
|
{JSON.stringify(tc.args, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
{dr.toolResults.length > 0 && (
|
||||||
|
<details className="border-b" open>
|
||||||
|
<summary className="px-4 py-2 text-xs cursor-pointer hover:bg-muted/30">✅ 工具结果 ({dr.toolResults.length})</summary>
|
||||||
|
<div className="space-y-2 p-3">
|
||||||
|
{dr.toolResults.map((tr, j) => (
|
||||||
|
<div key={j} className="text-[11px]">
|
||||||
|
<div className="font-mono font-medium text-xs mb-1">{tr.name}</div>
|
||||||
|
<pre className="bg-green-50 dark:bg-green-950/30 rounded p-2 overflow-x-auto whitespace-pre-wrap max-h-40">
|
||||||
|
{typeof tr.result === "string" ? tr.result : JSON.stringify(tr.result, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</ScrollArea>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -0,0 +1,213 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import ReactMarkdown from "react-markdown"
|
||||||
|
import remarkGfm from "remark-gfm"
|
||||||
|
import type { Components } from "react-markdown"
|
||||||
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
|
||||||
|
import { Badge } from "@/components/ui/badge"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Copy, RotateCcw, Pencil, Check } from "lucide-react"
|
||||||
|
import { useState } from "react"
|
||||||
|
|
||||||
|
interface Message {
|
||||||
|
id: string
|
||||||
|
role: string
|
||||||
|
content: string
|
||||||
|
thinking?: string | null
|
||||||
|
toolCalls?: string | null
|
||||||
|
toolResults?: string | null
|
||||||
|
tokenUsage?: string | null
|
||||||
|
cost: number
|
||||||
|
isSummary: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
function CodeBlock({ language, code }: { language?: string; code: string }) {
|
||||||
|
const [copied, setCopied] = useState(false)
|
||||||
|
const handleCopy = () => {
|
||||||
|
navigator.clipboard.writeText(code)
|
||||||
|
setCopied(true)
|
||||||
|
setTimeout(() => setCopied(false), 2000)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="my-2 rounded-md border overflow-hidden">
|
||||||
|
<div className="flex items-center justify-between bg-muted/70 px-3 py-1.5 text-[10px] text-muted-foreground">
|
||||||
|
<span>{language || "code"}</span>
|
||||||
|
<button onClick={handleCopy} className="hover:text-foreground transition-colors">
|
||||||
|
{copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<pre className="px-3 py-2 text-xs overflow-x-auto bg-muted/30">{code}</pre>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const markdownComponents: Partial<Components> = {
|
||||||
|
code({ className, children, ...props }) {
|
||||||
|
const match = /language-(\w+)/.exec(className || "")
|
||||||
|
const code = String(children).replace(/\n$/, "")
|
||||||
|
// @ts-expect-error className from react-markdown
|
||||||
|
const inline = props.inline
|
||||||
|
if (!inline && match) {
|
||||||
|
return <CodeBlock language={match[1]} code={code} />
|
||||||
|
}
|
||||||
|
if (!inline) {
|
||||||
|
return <CodeBlock code={code} />
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<code className="bg-muted/70 rounded px-1 py-0.5 text-[0.85em] font-mono" {...props}>
|
||||||
|
{children}
|
||||||
|
</code>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
pre({ children }) {
|
||||||
|
return <>{children}</>
|
||||||
|
},
|
||||||
|
a({ href, children }) {
|
||||||
|
return (
|
||||||
|
<a href={href} target="_blank" rel="noopener noreferrer" className="text-primary underline underline-offset-2">
|
||||||
|
{children}
|
||||||
|
</a>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
table({ children }) {
|
||||||
|
return <div className="overflow-x-auto my-2"><table className="min-w-full border-collapse border text-xs">{children}</table></div>
|
||||||
|
},
|
||||||
|
th({ children }) {
|
||||||
|
return <th className="border px-2 py-1 bg-muted text-left font-medium">{children}</th>
|
||||||
|
},
|
||||||
|
td({ children }) {
|
||||||
|
return <td className="border px-2 py-1">{children}</td>
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MessageBubble({
|
||||||
|
message,
|
||||||
|
markdownEnabled,
|
||||||
|
onRollback,
|
||||||
|
onEdit,
|
||||||
|
onCopy,
|
||||||
|
}: {
|
||||||
|
message: Message
|
||||||
|
markdownEnabled?: boolean
|
||||||
|
onRollback: () => void
|
||||||
|
onEdit: () => void
|
||||||
|
onCopy: () => void
|
||||||
|
}) {
|
||||||
|
const isUser = message.role === "user"
|
||||||
|
const isSystem = message.role === "system" || message.isSummary
|
||||||
|
const isTool = message.role === "tool"
|
||||||
|
|
||||||
|
if (isSystem) {
|
||||||
|
return (
|
||||||
|
<div className="flex justify-center my-4">
|
||||||
|
<div className="bg-muted/50 rounded-lg px-4 py-2 text-xs text-muted-foreground max-w-md text-center">
|
||||||
|
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||||
|
{message.content}
|
||||||
|
</ReactMarkdown>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isTool) {
|
||||||
|
return (
|
||||||
|
<div className="flex justify-end my-2 pl-12">
|
||||||
|
<div className="bg-muted/30 border rounded-lg px-3 py-2 text-xs text-muted-foreground max-w-md">
|
||||||
|
<div className="font-mono font-medium mb-1">🔧 工具结果</div>
|
||||||
|
<pre className="whitespace-pre-wrap text-[11px]">{message.content}</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
let toolCallsParsed: Array<{ id: string; function: { name: string; arguments: string } }> = []
|
||||||
|
if (message.toolCalls) {
|
||||||
|
try { toolCallsParsed = JSON.parse(message.toolCalls) } catch {/* ignore */}
|
||||||
|
}
|
||||||
|
|
||||||
|
let tokenUsageParsed: { prompt_tokens?: number; completion_tokens?: number } | null = null
|
||||||
|
if (message.tokenUsage) {
|
||||||
|
try { tokenUsageParsed = JSON.parse(message.tokenUsage) } catch {/* ignore */}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`flex gap-3 ${isUser ? "justify-end" : ""}`}>
|
||||||
|
{!isUser && (
|
||||||
|
<Avatar className="h-8 w-8 shrink-0">
|
||||||
|
<AvatarFallback className="bg-primary text-primary-foreground text-xs">AI</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className={`flex-1 max-w-[80%] ${isUser ? "flex flex-col items-end" : ""}`}>
|
||||||
|
{/* Tool call badges */}
|
||||||
|
{toolCallsParsed.length > 0 && (
|
||||||
|
<div className="flex flex-wrap gap-1 mb-1">
|
||||||
|
{toolCallsParsed.map((tc, i) => (
|
||||||
|
<Badge key={i} variant="outline" className="text-[10px]">
|
||||||
|
🔧 {tc.function.name}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Thinking / Reasoning chain */}
|
||||||
|
{!isUser && message.thinking && (
|
||||||
|
<details className="mb-1">
|
||||||
|
<summary className="text-[10px] text-muted-foreground cursor-pointer hover:text-foreground inline-flex items-center gap-1">
|
||||||
|
🧠 思考过程
|
||||||
|
</summary>
|
||||||
|
<div className="mt-1 bg-muted/50 border border-muted rounded-md px-3 py-2 text-xs text-muted-foreground whitespace-pre-wrap max-h-60 overflow-y-auto">
|
||||||
|
{message.thinking}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className={`rounded-lg px-4 py-2 text-sm ${
|
||||||
|
isUser ? "bg-primary text-primary-foreground" : "bg-muted"
|
||||||
|
}`}>
|
||||||
|
{isUser ? (
|
||||||
|
<div className="whitespace-pre-wrap">{message.content}</div>
|
||||||
|
) : markdownEnabled !== false ? (
|
||||||
|
<div className="prose prose-sm dark:prose-invert max-w-none prose-pre:bg-transparent prose-pre:p-0 prose-img:rounded-md">
|
||||||
|
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||||
|
{message.content}
|
||||||
|
</ReactMarkdown>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="whitespace-pre-wrap">{message.content}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Meta info */}
|
||||||
|
<div className={`flex items-center gap-1 mt-1 ${isUser ? "flex-row-reverse" : ""}`}>
|
||||||
|
{(message.cost > 0 || tokenUsageParsed) && (
|
||||||
|
<span className="text-[10px] text-muted-foreground">
|
||||||
|
{tokenUsageParsed && `${tokenUsageParsed.prompt_tokens || 0}+${tokenUsageParsed.completion_tokens || 0} tokens`}
|
||||||
|
{message.cost > 0 && ` | ¥${message.cost.toFixed(6)}`}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<div className="flex opacity-20 hover:opacity-100 transition-opacity">
|
||||||
|
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={onCopy} title="复制">
|
||||||
|
<Copy className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
{isUser && (
|
||||||
|
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={onEdit} title="编辑此消息">
|
||||||
|
<Pencil className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={onRollback} title="回退到此(删除之后的所有消息)">
|
||||||
|
<RotateCcw className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isUser && (
|
||||||
|
<Avatar className="h-8 w-8 shrink-0">
|
||||||
|
<AvatarFallback className="bg-secondary text-secondary-foreground text-xs">U</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -0,0 +1,760 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useState, useEffect, useRef, useCallback } from "react"
|
||||||
|
import { Plus, Trash2, Play, Bug, Pencil, Download, Upload, Check, X } from "lucide-react"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Input } from "@/components/ui/input"
|
||||||
|
import { Label } from "@/components/ui/label"
|
||||||
|
import { Textarea } from "@/components/ui/textarea"
|
||||||
|
import { Switch } from "@/components/ui/switch"
|
||||||
|
import { Badge } from "@/components/ui/badge"
|
||||||
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||||
|
import {
|
||||||
|
Sheet, SheetContent, SheetHeader, SheetTitle,
|
||||||
|
} from "@/components/ui/sheet"
|
||||||
|
import {
|
||||||
|
Accordion, AccordionContent, AccordionItem, AccordionTrigger,
|
||||||
|
} from "@/components/ui/accordion"
|
||||||
|
|
||||||
|
interface Provider {
|
||||||
|
id: string; name: string; baseUrl: string; apiKey: string; modelName: string; customHeaders: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Preset {
|
||||||
|
id: string; name: string; isDefault: boolean
|
||||||
|
fragments: Array<{ id: string; name: string; content: string; enabled: boolean; order: number }>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Skill {
|
||||||
|
id: string; name: string; content: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MCPServer {
|
||||||
|
id: string; name: string; transportType: string; config: string; enabled: boolean
|
||||||
|
tools: Array<{ id: string; name: string; description: string | null; enabled: boolean }>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PricingConfig {
|
||||||
|
id: string; modelName: string; inputPrice: number; outputPrice: number; currency: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HttpTool {
|
||||||
|
id: string; name: string; description: string | null; method: string; url: string; headers: string | null; parameters: string | null; bodyTemplate: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SettingsPanel({ open, onClose, onUpdate }: { open: boolean; onClose: () => void; onUpdate: () => void }) {
|
||||||
|
const [tab, setTab] = useState("providers")
|
||||||
|
const [providers, setProviders] = useState<Provider[]>([])
|
||||||
|
const [presets, setPresets] = useState<Preset[]>([])
|
||||||
|
const [skills, setSkills] = useState<Skill[]>([])
|
||||||
|
const [mcpServers, setMCPServers] = useState<MCPServer[]>([])
|
||||||
|
const [pricingConfigs, setPricingConfigs] = useState<PricingConfig[]>([])
|
||||||
|
const [httpTools, setHttpTools] = useState<HttpTool[]>([])
|
||||||
|
const [testResults, setTestResults] = useState<Record<string, string>>({})
|
||||||
|
const [debugMode, setDebugMode] = useState(false)
|
||||||
|
|
||||||
|
const debounceTimers = useRef<Record<string, NodeJS.Timeout>>({})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setDebugMode(localStorage.getItem("debug-mode") === "true")
|
||||||
|
if (!open) return
|
||||||
|
refreshAll()
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
const toggleDebugMode = (v: boolean) => {
|
||||||
|
setDebugMode(v)
|
||||||
|
localStorage.setItem("debug-mode", String(v))
|
||||||
|
}
|
||||||
|
|
||||||
|
const refreshAll = useCallback(() => {
|
||||||
|
fetch("/api/providers").then(r => r.json()).then(d => setProviders(Array.isArray(d) ? d : []))
|
||||||
|
fetch("/api/presets").then(r => r.json()).then(d => setPresets(Array.isArray(d) ? d : []))
|
||||||
|
fetch("/api/skills").then(r => r.json()).then(d => setSkills(Array.isArray(d) ? d : []))
|
||||||
|
fetch("/api/mcp/servers").then(r => r.json()).then(d => setMCPServers(Array.isArray(d) ? d : []))
|
||||||
|
fetch("/api/pricing").then(r => r.json()).then(d => setPricingConfigs(Array.isArray(d) ? d : []))
|
||||||
|
fetch("/api/http-tools").then(r => r.json()).then(d => setHttpTools(Array.isArray(d) ? d : []))
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const refreshPresets = useCallback(() => {
|
||||||
|
fetch("/api/presets").then(r => r.json()).then(d => setPresets(Array.isArray(d) ? d : []))
|
||||||
|
onUpdate()
|
||||||
|
}, [onUpdate])
|
||||||
|
|
||||||
|
const refresh = useCallback(() => {
|
||||||
|
refreshAll()
|
||||||
|
onUpdate()
|
||||||
|
}, [refreshAll, onUpdate])
|
||||||
|
|
||||||
|
// --- Provider CRUD ---
|
||||||
|
const [newProvider, setNewProvider] = useState({ name: "", baseUrl: "", apiKey: "", modelName: "" })
|
||||||
|
|
||||||
|
const addProvider = async () => {
|
||||||
|
await fetch("/api/providers", {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(newProvider),
|
||||||
|
})
|
||||||
|
setNewProvider({ name: "", baseUrl: "", apiKey: "", modelName: "" })
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteProvider = async (id: string) => {
|
||||||
|
await fetch(`/api/providers/${id}`, { method: "DELETE" })
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
const testProvider = async (id: string) => {
|
||||||
|
setTestResults((prev) => ({ ...prev, [id]: "测试中..." }))
|
||||||
|
const res = await fetch(`/api/providers/${id}/test`, { method: "POST" })
|
||||||
|
const data = await res.json()
|
||||||
|
setTestResults((prev) => ({ ...prev, [id]: data.success ? "连接成功" : `失败: ${data.error}` }))
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Preset CRUD (optimistic updates) ---
|
||||||
|
const [newPresetName, setNewPresetName] = useState("")
|
||||||
|
|
||||||
|
const addPreset = async () => {
|
||||||
|
if (!newPresetName.trim()) return
|
||||||
|
const res = await fetch("/api/presets", {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ name: newPresetName }),
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
const preset = await res.json()
|
||||||
|
setPresets(prev => [...prev, preset])
|
||||||
|
onUpdate()
|
||||||
|
}
|
||||||
|
setNewPresetName("")
|
||||||
|
}
|
||||||
|
|
||||||
|
const deletePreset = async (id: string) => {
|
||||||
|
setPresets(prev => prev.filter(p => p.id !== id))
|
||||||
|
await fetch(`/api/presets/${id}`, { method: "DELETE" })
|
||||||
|
onUpdate()
|
||||||
|
}
|
||||||
|
|
||||||
|
const addFragment = async (presetId: string) => {
|
||||||
|
const res = await fetch(`/api/presets/${presetId}/fragments`, {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ name: "新片段", content: "" }),
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
const fragment = await res.json()
|
||||||
|
setPresets(prev => prev.map(p =>
|
||||||
|
p.id === presetId ? { ...p, fragments: [...p.fragments, fragment] } : p
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateFragment = (presetId: string, fragmentId: string, data: Record<string, unknown>) => {
|
||||||
|
setPresets(prev => prev.map(p =>
|
||||||
|
p.id === presetId ? {
|
||||||
|
...p,
|
||||||
|
fragments: p.fragments.map(f =>
|
||||||
|
f.id === fragmentId ? { ...f, ...data } as typeof f : f
|
||||||
|
),
|
||||||
|
} : p
|
||||||
|
))
|
||||||
|
|
||||||
|
const key = `${presetId}:${fragmentId}`
|
||||||
|
if (debounceTimers.current[key]) clearTimeout(debounceTimers.current[key])
|
||||||
|
debounceTimers.current[key] = setTimeout(async () => {
|
||||||
|
await fetch(`/api/presets/${presetId}/fragments/${fragmentId}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
})
|
||||||
|
onUpdate()
|
||||||
|
}, 300)
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteFragment = async (presetId: string, fragmentId: string) => {
|
||||||
|
setPresets(prev => prev.map(p =>
|
||||||
|
p.id === presetId ? { ...p, fragments: p.fragments.filter(f => f.id !== fragmentId) } : p
|
||||||
|
))
|
||||||
|
await fetch(`/api/presets/${presetId}/fragments/${fragmentId}`, { method: "DELETE" })
|
||||||
|
onUpdate()
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Skills CRUD ---
|
||||||
|
const [newSkill, setNewSkill] = useState({ name: "", content: "" })
|
||||||
|
|
||||||
|
const addSkill = async () => {
|
||||||
|
await fetch("/api/skills", {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(newSkill),
|
||||||
|
})
|
||||||
|
setNewSkill({ name: "", content: "" })
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteSkill = async (id: string) => {
|
||||||
|
await fetch(`/api/skills/${id}`, { method: "DELETE" })
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- MCP Server CRUD ---
|
||||||
|
const [newMCPServer, setNewMCPServer] = useState({ name: "", transportType: "sse", config: "{}" })
|
||||||
|
|
||||||
|
const addMCPServer = async () => {
|
||||||
|
await fetch("/api/mcp/servers", {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ ...newMCPServer, config: JSON.parse(newMCPServer.config || "{}") }),
|
||||||
|
})
|
||||||
|
setNewMCPServer({ name: "", transportType: "sse", config: "{}" })
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteMCPServer = async (id: string) => {
|
||||||
|
await fetch(`/api/mcp/servers/${id}`, { method: "DELETE" })
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
const connectMCPServer = async (id: string) => {
|
||||||
|
const res = await fetch(`/api/mcp/servers/${id}/connect`, { method: "POST" })
|
||||||
|
const data = await res.json()
|
||||||
|
if (data.success) {
|
||||||
|
setTestResults((prev) => ({ ...prev, [`mcp_${id}`]: `已连接,发现 ${data.tools.length} 个工具` }))
|
||||||
|
} else {
|
||||||
|
setTestResults((prev) => ({ ...prev, [`mcp_${id}`]: `失败: ${data.error}` }))
|
||||||
|
}
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleMCPServerEnabled = async (id: string, enabled: boolean) => {
|
||||||
|
await fetch(`/api/mcp/servers/${id}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ enabled }),
|
||||||
|
})
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- HTTP Tools CRUD ---
|
||||||
|
const [newHttpTool, setNewHttpTool] = useState({ name: "", description: "", method: "GET", url: "", headers: "", parameters: "", bodyTemplate: "" })
|
||||||
|
const [editingHttpId, setEditingHttpId] = useState<string | null>(null)
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
|
const startEditHttpTool = (t: HttpTool) => {
|
||||||
|
setEditingHttpId(t.id)
|
||||||
|
setNewHttpTool({
|
||||||
|
name: t.name,
|
||||||
|
description: t.description || "",
|
||||||
|
method: t.method,
|
||||||
|
url: t.url,
|
||||||
|
headers: t.headers || "",
|
||||||
|
parameters: t.parameters || "",
|
||||||
|
bodyTemplate: t.bodyTemplate || "",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const cancelEditHttpTool = () => {
|
||||||
|
setEditingHttpId(null)
|
||||||
|
setNewHttpTool({ name: "", description: "", method: "GET", url: "", headers: "", parameters: "", bodyTemplate: "" })
|
||||||
|
}
|
||||||
|
|
||||||
|
const saveHttpTool = async () => {
|
||||||
|
if (!newHttpTool.name.trim() || !newHttpTool.url.trim()) return
|
||||||
|
const body = {
|
||||||
|
name: newHttpTool.name,
|
||||||
|
description: newHttpTool.description || null,
|
||||||
|
method: newHttpTool.method,
|
||||||
|
url: newHttpTool.url,
|
||||||
|
headers: newHttpTool.headers ? JSON.parse(newHttpTool.headers) : null,
|
||||||
|
parameters: newHttpTool.parameters ? JSON.parse(newHttpTool.parameters) : null,
|
||||||
|
bodyTemplate: newHttpTool.bodyTemplate || null,
|
||||||
|
}
|
||||||
|
if (editingHttpId) {
|
||||||
|
await fetch(`/api/http-tools/${editingHttpId}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
await fetch("/api/http-tools", {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
cancelEditHttpTool()
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteHttpTool = async (id: string) => {
|
||||||
|
await fetch(`/api/http-tools/${id}`, { method: "DELETE" })
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
const exportHttpTools = () => {
|
||||||
|
const data = httpTools.map((t) => ({
|
||||||
|
name: t.name,
|
||||||
|
description: t.description,
|
||||||
|
method: t.method,
|
||||||
|
url: t.url,
|
||||||
|
headers: t.headers ? JSON.parse(t.headers) : null,
|
||||||
|
parameters: t.parameters ? JSON.parse(t.parameters) : null,
|
||||||
|
bodyTemplate: t.bodyTemplate,
|
||||||
|
}))
|
||||||
|
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" })
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
const a = document.createElement("a")
|
||||||
|
a.href = url
|
||||||
|
a.download = "http-tools.json"
|
||||||
|
a.click()
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
}
|
||||||
|
|
||||||
|
const importHttpTools = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0]
|
||||||
|
if (!file) return
|
||||||
|
try {
|
||||||
|
const text = await file.text()
|
||||||
|
const data = JSON.parse(text)
|
||||||
|
const tools = Array.isArray(data) ? data : [data]
|
||||||
|
for (const t of tools) {
|
||||||
|
if (t.name && t.url) {
|
||||||
|
await fetch("/api/http-tools", {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: t.name,
|
||||||
|
description: t.description || null,
|
||||||
|
method: t.method || "GET",
|
||||||
|
url: t.url,
|
||||||
|
headers: t.headers || null,
|
||||||
|
parameters: t.parameters || null,
|
||||||
|
bodyTemplate: t.bodyTemplate || null,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
refresh()
|
||||||
|
} catch {
|
||||||
|
alert("导入失败:请检查 JSON 格式")
|
||||||
|
}
|
||||||
|
if (fileInputRef.current) fileInputRef.current.value = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Pricing CRUD ---
|
||||||
|
const [newPricing, setNewPricing] = useState({ modelName: "", inputPrice: "", outputPrice: "", currency: "CNY" })
|
||||||
|
|
||||||
|
const addPricing = async () => {
|
||||||
|
await fetch("/api/pricing", {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
modelName: newPricing.modelName,
|
||||||
|
inputPrice: parseFloat(newPricing.inputPrice),
|
||||||
|
outputPrice: parseFloat(newPricing.outputPrice),
|
||||||
|
currency: newPricing.currency,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
setNewPricing({ modelName: "", inputPrice: "", outputPrice: "", currency: "CNY" })
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
const deletePricing = async (id: string) => {
|
||||||
|
await fetch(`/api/pricing/${id}`, { method: "DELETE" })
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
const tabs = [
|
||||||
|
{ key: "providers", label: "API 引擎" },
|
||||||
|
{ key: "presets", label: "System Prompt" },
|
||||||
|
{ key: "skills", label: "Skills" },
|
||||||
|
{ key: "mcp", label: "MCP / Tools" },
|
||||||
|
{ key: "httptools", label: "HTTP 工具" },
|
||||||
|
{ key: "pricing", label: "定价与费用" },
|
||||||
|
]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sheet open={open} onOpenChange={onClose}>
|
||||||
|
<SheetContent side="right" className="w-full sm:max-w-xl p-0">
|
||||||
|
<SheetHeader className="px-6 py-4 border-b">
|
||||||
|
<SheetTitle>设置</SheetTitle>
|
||||||
|
</SheetHeader>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between px-6 py-2 border-b bg-muted/30">
|
||||||
|
<div className="flex items-center gap-2 text-xs">
|
||||||
|
<Bug className="h-3.5 w-3.5" />
|
||||||
|
<span>调试模式</span>
|
||||||
|
</div>
|
||||||
|
<Switch checked={debugMode} onCheckedChange={toggleDebugMode} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex border-b">
|
||||||
|
{tabs.map((t) => (
|
||||||
|
<button
|
||||||
|
key={t.key}
|
||||||
|
onClick={() => setTab(t.key)}
|
||||||
|
className={`flex-1 text-xs py-2.5 px-1 text-center border-b-2 transition-colors ${
|
||||||
|
tab === t.key ? "border-primary text-primary font-medium" : "border-transparent text-muted-foreground hover:text-foreground"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{t.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ScrollArea className="h-[calc(100vh-120px)] px-6 py-4">
|
||||||
|
{/* Providers Tab */}
|
||||||
|
{tab === "providers" && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="space-y-4 border rounded-lg p-4">
|
||||||
|
<h3 className="font-semibold text-sm">添加新 Provider</h3>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-xs">名称</Label>
|
||||||
|
<Input placeholder="我的 DeepSeek" value={newProvider.name} onChange={(e) => setNewProvider({ ...newProvider, name: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-xs">API 地址 (Base URL)</Label>
|
||||||
|
<Input placeholder="https://api.deepseek.com" value={newProvider.baseUrl} onChange={(e) => setNewProvider({ ...newProvider, baseUrl: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-xs">API Key</Label>
|
||||||
|
<Input type="password" placeholder="sk-..." value={newProvider.apiKey} onChange={(e) => setNewProvider({ ...newProvider, apiKey: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-xs">模型名称</Label>
|
||||||
|
<Input placeholder="deepseek-chat" value={newProvider.modelName} onChange={(e) => setNewProvider({ ...newProvider, modelName: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
<Button size="sm" onClick={addProvider}>
|
||||||
|
<Plus className="h-3 w-3 mr-1" />添加
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
<h3 className="font-semibold text-sm">已配置的 Provider</h3>
|
||||||
|
{providers.map((p) => (
|
||||||
|
<div key={p.id} className="border rounded-lg p-3 space-y-1">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="font-medium text-sm">{p.name}</span>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => testProvider(p.id)}>
|
||||||
|
<Play className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => deleteProvider(p.id)}>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-muted-foreground">{p.baseUrl} | {p.modelName} | Key: {p.apiKey}</div>
|
||||||
|
{testResults[p.id] && (
|
||||||
|
<p className={`text-xs ${testResults[p.id].startsWith("成功") ? "text-green-600" : "text-destructive"}`}>
|
||||||
|
{testResults[p.id]}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Presets Tab */}
|
||||||
|
{tab === "presets" && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input placeholder="新预设名称" value={newPresetName} onChange={(e) => setNewPresetName(e.target.value)} className="text-sm" />
|
||||||
|
<Button size="sm" onClick={addPreset}><Plus className="h-3 w-3 mr-1" />创建</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{presets.map((preset) => (
|
||||||
|
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="font-medium">{preset.name}</span>
|
||||||
|
{preset.isDefault && <Badge variant="secondary" className="text-[10px]">默认</Badge>}
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => deletePreset(preset.id)}>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{preset.fragments.map((frag) => (
|
||||||
|
<div key={frag.id} className="border rounded p-3 space-y-2 bg-background/50">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Input
|
||||||
|
className="text-sm h-8 flex-1"
|
||||||
|
value={frag.name}
|
||||||
|
onChange={(e) => updateFragment(preset.id, frag.id, { name: e.target.value })}
|
||||||
|
placeholder="片段名称"
|
||||||
|
/>
|
||||||
|
<Switch
|
||||||
|
checked={frag.enabled}
|
||||||
|
onCheckedChange={(v) => updateFragment(preset.id, frag.id, { enabled: v })}
|
||||||
|
/>
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => deleteFragment(preset.id, frag.id)}>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<Textarea
|
||||||
|
className="text-xs min-h-[60px] font-mono"
|
||||||
|
value={frag.content}
|
||||||
|
onChange={(e) => updateFragment(preset.id, frag.id, { content: e.target.value })}
|
||||||
|
placeholder="Markdown 内容..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<Button variant="outline" size="sm" onClick={() => addFragment(preset.id)}>
|
||||||
|
<Plus className="h-3 w-3 mr-1" />添加片段
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{/* System Prompt Preview */}
|
||||||
|
{preset.fragments.filter(f => f.enabled).length > 0 && (
|
||||||
|
<details className="text-xs">
|
||||||
|
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">预览完整 System Prompt</summary>
|
||||||
|
<pre className="mt-2 p-2 bg-muted rounded text-[11px] whitespace-pre-wrap max-h-40 overflow-auto">
|
||||||
|
{preset.fragments.filter(f => f.enabled).map(f => f.content).join("\n\n")}
|
||||||
|
</pre>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Skills Tab */}
|
||||||
|
{tab === "skills" && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="space-y-3 border rounded-lg p-4">
|
||||||
|
<h3 className="font-semibold text-sm">添加新技能</h3>
|
||||||
|
<Input className="text-sm" placeholder="技能名称" value={newSkill.name} onChange={(e) => setNewSkill({ ...newSkill, name: e.target.value })} />
|
||||||
|
<Textarea
|
||||||
|
className="text-xs min-h-[80px] font-mono"
|
||||||
|
placeholder="Markdown 技能说明..."
|
||||||
|
value={newSkill.content}
|
||||||
|
onChange={(e) => setNewSkill({ ...newSkill, content: e.target.value })}
|
||||||
|
/>
|
||||||
|
<Button size="sm" onClick={addSkill}><Plus className="h-3 w-3 mr-1" />添加</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{skills.map((skill) => (
|
||||||
|
<div key={skill.id} className="border rounded-lg p-3 space-y-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="font-medium text-sm">{skill.name}</span>
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => deleteSkill(skill.id)}>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<pre className="text-xs text-muted-foreground whitespace-pre-wrap max-h-24 overflow-auto">{skill.content}</pre>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* MCP Tab */}
|
||||||
|
{tab === "mcp" && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="space-y-3 border rounded-lg p-4">
|
||||||
|
<h3 className="font-semibold text-sm">添加 MCP 服务器</h3>
|
||||||
|
<Input className="text-sm" placeholder="服务器名称" value={newMCPServer.name} onChange={(e) => setNewMCPServer({ ...newMCPServer, name: e.target.value })} />
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs">传输类型</Label>
|
||||||
|
<select
|
||||||
|
className="w-full border rounded-md px-3 py-1.5 text-sm mt-1 bg-background"
|
||||||
|
value={newMCPServer.transportType}
|
||||||
|
onChange={(e) => setNewMCPServer({ ...newMCPServer, transportType: e.target.value })}
|
||||||
|
>
|
||||||
|
<option value="sse">SSE(推荐)</option>
|
||||||
|
<option value="stdio">Stdio</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<Textarea
|
||||||
|
className="text-xs min-h-[60px] font-mono"
|
||||||
|
placeholder='{"url": "http://localhost:3001/sse"} 或 {"command": "npx", "args": ["-y", "server"]}'
|
||||||
|
value={newMCPServer.config}
|
||||||
|
onChange={(e) => setNewMCPServer({ ...newMCPServer, config: e.target.value })}
|
||||||
|
/>
|
||||||
|
<Button size="sm" onClick={addMCPServer}><Plus className="h-3 w-3 mr-1" />添加</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{mcpServers.map((srv) => (
|
||||||
|
<div key={srv.id} className="border rounded-lg p-4 space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="font-medium text-sm">{srv.name}</span>
|
||||||
|
<Badge variant="outline" className="text-[10px]">{srv.transportType}</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Switch checked={srv.enabled} onCheckedChange={(v) => toggleMCPServerEnabled(srv.id, v)} />
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => connectMCPServer(srv.id)}>
|
||||||
|
<Play className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => deleteMCPServer(srv.id)}>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{testResults[`mcp_${srv.id}`] && (
|
||||||
|
<p className={`text-xs ${testResults[`mcp_${srv.id}`].startsWith("已连接") ? "text-green-600" : "text-destructive"}`}>
|
||||||
|
{testResults[`mcp_${srv.id}`]}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{srv.tools.length > 0 && (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-xs text-muted-foreground">工具列表:</p>
|
||||||
|
{srv.tools.map((tool) => (
|
||||||
|
<div key={tool.id} className="flex items-center gap-2 text-xs py-1">
|
||||||
|
<Switch
|
||||||
|
checked={tool.enabled}
|
||||||
|
onCheckedChange={async (v) => {
|
||||||
|
await fetch(`/api/mcp/servers/${srv.id}/tools`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ toolId: tool.id, enabled: v }),
|
||||||
|
})
|
||||||
|
refresh()
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span className="font-mono">{tool.name}</span>
|
||||||
|
{tool.description && <span className="text-muted-foreground truncate">- {tool.description}</span>}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* HTTP Tools Tab */}
|
||||||
|
{tab === "httptools" && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" onClick={exportHttpTools} disabled={httpTools.length === 0}>
|
||||||
|
<Download className="h-3 w-3 mr-1" />导出
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
|
||||||
|
<Upload className="h-3 w-3 mr-1" />导入
|
||||||
|
</Button>
|
||||||
|
<input ref={fileInputRef} type="file" accept=".json" className="hidden" onChange={importHttpTools} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-3 border rounded-lg p-4">
|
||||||
|
<h3 className="font-semibold text-sm">{editingHttpId ? "编辑 HTTP 工具" : "添加 HTTP 工具"}</h3>
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs">工具名称(AI 调用时的函数名)</Label>
|
||||||
|
<Input className="text-sm mt-1" placeholder="search_web" value={newHttpTool.name} onChange={(e) => setNewHttpTool({ ...newHttpTool, name: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs">描述(AI 根据描述决定何时调用)</Label>
|
||||||
|
<Input className="text-sm mt-1" placeholder="搜索网页内容" value={newHttpTool.description} onChange={(e) => setNewHttpTool({ ...newHttpTool, description: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs">HTTP 方法</Label>
|
||||||
|
<select className="w-full border rounded-md px-3 py-1.5 text-sm mt-1 bg-background" value={newHttpTool.method} onChange={(e) => setNewHttpTool({ ...newHttpTool, method: e.target.value })}>
|
||||||
|
<option value="GET">GET</option>
|
||||||
|
<option value="POST">POST</option>
|
||||||
|
<option value="PUT">PUT</option>
|
||||||
|
<option value="DELETE">DELETE</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs">URL(用 {'{{'}param{'}}'} 引用参数)</Label>
|
||||||
|
<Input className="text-sm mt-1" placeholder={'https://api.example.com/search?q={{query}}'} value={newHttpTool.url} onChange={(e) => setNewHttpTool({ ...newHttpTool, url: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs">Headers(JSON 对象,如 {"{"}"Content-Type": "application/json"{"}"})</Label>
|
||||||
|
<Textarea className="text-xs min-h-[40px] font-mono mt-1" placeholder='{"Authorization": "Bearer xxx"}' value={newHttpTool.headers} onChange={(e) => setNewHttpTool({ ...newHttpTool, headers: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs">参数定义(JSON Schema,AI 根据此生成参数)</Label>
|
||||||
|
<Textarea className="text-xs min-h-[60px] font-mono mt-1" placeholder='{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}' value={newHttpTool.parameters} onChange={(e) => setNewHttpTool({ ...newHttpTool, parameters: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
{(newHttpTool.method === "POST" || newHttpTool.method === "PUT") && (
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs">Body 模板(用 {'{{'}param{'}}'} 引用参数,仅 POST/PUT)</Label>
|
||||||
|
<Textarea className="text-xs min-h-[40px] font-mono mt-1" placeholder={'{"search": "{{query}}"}'} value={newHttpTool.bodyTemplate} onChange={(e) => setNewHttpTool({ ...newHttpTool, bodyTemplate: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button size="sm" onClick={saveHttpTool}>
|
||||||
|
{editingHttpId ? <Check className="h-3 w-3 mr-1" /> : <Plus className="h-3 w-3 mr-1" />}
|
||||||
|
{editingHttpId ? "保存" : "添加"}
|
||||||
|
</Button>
|
||||||
|
{editingHttpId && (
|
||||||
|
<Button size="sm" variant="outline" onClick={cancelEditHttpTool}>
|
||||||
|
<X className="h-3 w-3 mr-1" />取消
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{httpTools.length === 0 ? (
|
||||||
|
<p className="text-xs text-muted-foreground text-center py-4">暂无 HTTP 工具</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{httpTools.map((t) => (
|
||||||
|
<div key={t.id} className="border rounded-lg p-3 space-y-1">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge variant="outline" className="text-[10px]">{t.method}</Badge>
|
||||||
|
<span className="font-medium text-sm font-mono">{t.name}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => startEditHttpTool(t)} title="编辑">
|
||||||
|
<Pencil className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => deleteHttpTool(t.id)}>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground truncate">{t.url}</p>
|
||||||
|
{t.description && <p className="text-xs text-muted-foreground">{t.description}</p>}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Pricing Tab */}
|
||||||
|
{tab === "pricing" && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="space-y-3 border rounded-lg p-4">
|
||||||
|
<h3 className="font-semibold text-sm">添加定价规则</h3>
|
||||||
|
<Input className="text-sm" placeholder="模型名称 (如 deepseek-chat)" value={newPricing.modelName} onChange={(e) => setNewPricing({ ...newPricing, modelName: e.target.value })} />
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs">Input 价格 (每1K tokens)</Label>
|
||||||
|
<Input className="text-sm" placeholder="0.14" value={newPricing.inputPrice} onChange={(e) => setNewPricing({ ...newPricing, inputPrice: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs">Output 价格 (每1K tokens)</Label>
|
||||||
|
<Input className="text-sm" placeholder="0.28" value={newPricing.outputPrice} onChange={(e) => setNewPricing({ ...newPricing, outputPrice: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs">货币单位</Label>
|
||||||
|
<select
|
||||||
|
className="w-full border rounded-md px-3 py-1.5 text-sm mt-1 bg-background"
|
||||||
|
value={newPricing.currency}
|
||||||
|
onChange={(e) => setNewPricing({ ...newPricing, currency: e.target.value })}
|
||||||
|
>
|
||||||
|
<option value="CNY">CNY (¥)</option>
|
||||||
|
<option value="USD">USD ($)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<Button size="sm" onClick={addPricing}><Plus className="h-3 w-3 mr-1" />添加</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h3 className="font-semibold text-sm">已配置的定价</h3>
|
||||||
|
{pricingConfigs.map((pc) => (
|
||||||
|
<div key={pc.id} className="border rounded-lg p-3 flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<span className="text-sm font-medium">{pc.modelName}</span>
|
||||||
|
<span className="text-xs text-muted-foreground ml-2">
|
||||||
|
Input: {pc.inputPrice} / Output: {pc.outputPrice} ({pc.currency})
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => deletePricing(pc.id)}>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</ScrollArea>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
)
|
||||||
|
}
|
||||||
72
src/components/ui/accordion.tsx
普通文件
72
src/components/ui/accordion.tsx
普通文件
@ -0,0 +1,72 @@
|
|||||||
|
import { Accordion as AccordionPrimitive } from "@base-ui/react/accordion"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||||
|
|
||||||
|
function Accordion({ className, ...props }: AccordionPrimitive.Root.Props) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Root
|
||||||
|
data-slot="accordion"
|
||||||
|
className={cn("flex w-full flex-col", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionItem({ className, ...props }: AccordionPrimitive.Item.Props) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Item
|
||||||
|
data-slot="accordion-item"
|
||||||
|
className={cn("not-last:border-b", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionTrigger({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: AccordionPrimitive.Trigger.Props) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Header className="flex">
|
||||||
|
<AccordionPrimitive.Trigger
|
||||||
|
data-slot="accordion-trigger"
|
||||||
|
className={cn(
|
||||||
|
"group/accordion-trigger relative flex flex-1 items-start justify-between rounded-lg border border-transparent py-2.5 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:after:border-ring aria-disabled:pointer-events-none aria-disabled:opacity-50 **:data-[slot=accordion-trigger-icon]:ml-auto **:data-[slot=accordion-trigger-icon]:size-4 **:data-[slot=accordion-trigger-icon]:text-muted-foreground",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronDownIcon data-slot="accordion-trigger-icon" className="pointer-events-none shrink-0 group-aria-expanded/accordion-trigger:hidden" />
|
||||||
|
<ChevronUpIcon data-slot="accordion-trigger-icon" className="pointer-events-none hidden shrink-0 group-aria-expanded/accordion-trigger:inline" />
|
||||||
|
</AccordionPrimitive.Trigger>
|
||||||
|
</AccordionPrimitive.Header>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: AccordionPrimitive.Panel.Props) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Panel
|
||||||
|
data-slot="accordion-content"
|
||||||
|
className="overflow-hidden text-sm data-open:animate-accordion-down data-closed:animate-accordion-up"
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"h-(--accordion-panel-height) pt-0 pb-2.5 data-ending-style:h-0 data-starting-style:h-0 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</AccordionPrimitive.Panel>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
|
||||||
109
src/components/ui/avatar.tsx
普通文件
109
src/components/ui/avatar.tsx
普通文件
@ -0,0 +1,109 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Avatar({
|
||||||
|
className,
|
||||||
|
size = "default",
|
||||||
|
...props
|
||||||
|
}: AvatarPrimitive.Root.Props & {
|
||||||
|
size?: "default" | "sm" | "lg"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Root
|
||||||
|
data-slot="avatar"
|
||||||
|
data-size={size}
|
||||||
|
className={cn(
|
||||||
|
"group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Image
|
||||||
|
data-slot="avatar-image"
|
||||||
|
className={cn(
|
||||||
|
"aspect-square size-full rounded-full object-cover",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarFallback({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: AvatarPrimitive.Fallback.Props) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Fallback
|
||||||
|
data-slot="avatar-fallback"
|
||||||
|
className={cn(
|
||||||
|
"flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="avatar-badge"
|
||||||
|
className={cn(
|
||||||
|
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
|
||||||
|
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
|
||||||
|
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
|
||||||
|
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="avatar-group"
|
||||||
|
className={cn(
|
||||||
|
"group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarGroupCount({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="avatar-group-count"
|
||||||
|
className={cn(
|
||||||
|
"relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Avatar,
|
||||||
|
AvatarImage,
|
||||||
|
AvatarFallback,
|
||||||
|
AvatarGroup,
|
||||||
|
AvatarGroupCount,
|
||||||
|
AvatarBadge,
|
||||||
|
}
|
||||||
52
src/components/ui/badge.tsx
普通文件
52
src/components/ui/badge.tsx
普通文件
@ -0,0 +1,52 @@
|
|||||||
|
import { mergeProps } from "@base-ui/react/merge-props"
|
||||||
|
import { useRender } from "@base-ui/react/use-render"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const badgeVariants = cva(
|
||||||
|
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
||||||
|
secondary:
|
||||||
|
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
|
||||||
|
destructive:
|
||||||
|
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
|
||||||
|
outline:
|
||||||
|
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
|
||||||
|
ghost:
|
||||||
|
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
|
||||||
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Badge({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
render,
|
||||||
|
...props
|
||||||
|
}: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {
|
||||||
|
return useRender({
|
||||||
|
defaultTagName: "span",
|
||||||
|
props: mergeProps<"span">(
|
||||||
|
{
|
||||||
|
className: cn(badgeVariants({ variant }), className),
|
||||||
|
},
|
||||||
|
props
|
||||||
|
),
|
||||||
|
render,
|
||||||
|
state: {
|
||||||
|
slot: "badge",
|
||||||
|
variant,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Badge, badgeVariants }
|
||||||
58
src/components/ui/button.tsx
普通文件
58
src/components/ui/button.tsx
普通文件
@ -0,0 +1,58 @@
|
|||||||
|
import { Button as ButtonPrimitive } from "@base-ui/react/button"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const buttonVariants = cva(
|
||||||
|
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
||||||
|
outline:
|
||||||
|
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||||
|
secondary:
|
||||||
|
"bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
|
||||||
|
ghost:
|
||||||
|
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
|
||||||
|
destructive:
|
||||||
|
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
|
||||||
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default:
|
||||||
|
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||||
|
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||||
|
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
|
||||||
|
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||||
|
icon: "size-8",
|
||||||
|
"icon-xs":
|
||||||
|
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
|
||||||
|
"icon-sm":
|
||||||
|
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
|
||||||
|
"icon-lg": "size-9",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Button({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
size = "default",
|
||||||
|
...props
|
||||||
|
}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {
|
||||||
|
return (
|
||||||
|
<ButtonPrimitive
|
||||||
|
data-slot="button"
|
||||||
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Button, buttonVariants }
|
||||||
103
src/components/ui/card.tsx
普通文件
103
src/components/ui/card.tsx
普通文件
@ -0,0 +1,103 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Card({
|
||||||
|
className,
|
||||||
|
size = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card"
|
||||||
|
data-size={size}
|
||||||
|
className={cn(
|
||||||
|
"group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-header"
|
||||||
|
className={cn(
|
||||||
|
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-title"
|
||||||
|
className={cn(
|
||||||
|
"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-description"
|
||||||
|
className={cn("text-sm text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-action"
|
||||||
|
className={cn(
|
||||||
|
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-content"
|
||||||
|
className={cn("px-4 group-data-[size=sm]/card:px-3", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-footer"
|
||||||
|
className={cn(
|
||||||
|
"flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Card,
|
||||||
|
CardHeader,
|
||||||
|
CardFooter,
|
||||||
|
CardTitle,
|
||||||
|
CardAction,
|
||||||
|
CardDescription,
|
||||||
|
CardContent,
|
||||||
|
}
|
||||||
160
src/components/ui/dialog.tsx
普通文件
160
src/components/ui/dialog.tsx
普通文件
@ -0,0 +1,160 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { XIcon } from "lucide-react"
|
||||||
|
|
||||||
|
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
|
||||||
|
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
|
||||||
|
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
|
||||||
|
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
|
||||||
|
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogOverlay({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: DialogPrimitive.Backdrop.Props) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Backdrop
|
||||||
|
data-slot="dialog-overlay"
|
||||||
|
className={cn(
|
||||||
|
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
showCloseButton = true,
|
||||||
|
...props
|
||||||
|
}: DialogPrimitive.Popup.Props & {
|
||||||
|
showCloseButton?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DialogPortal>
|
||||||
|
<DialogOverlay />
|
||||||
|
<DialogPrimitive.Popup
|
||||||
|
data-slot="dialog-content"
|
||||||
|
className={cn(
|
||||||
|
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{showCloseButton && (
|
||||||
|
<DialogPrimitive.Close
|
||||||
|
data-slot="dialog-close"
|
||||||
|
render={
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
className="absolute top-2 right-2"
|
||||||
|
size="icon-sm"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<XIcon
|
||||||
|
/>
|
||||||
|
<span className="sr-only">Close</span>
|
||||||
|
</DialogPrimitive.Close>
|
||||||
|
)}
|
||||||
|
</DialogPrimitive.Popup>
|
||||||
|
</DialogPortal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="dialog-header"
|
||||||
|
className={cn("flex flex-col gap-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogFooter({
|
||||||
|
className,
|
||||||
|
showCloseButton = false,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
showCloseButton?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="dialog-footer"
|
||||||
|
className={cn(
|
||||||
|
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{showCloseButton && (
|
||||||
|
<DialogPrimitive.Close render={<Button variant="outline" />}>
|
||||||
|
Close
|
||||||
|
</DialogPrimitive.Close>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Title
|
||||||
|
data-slot="dialog-title"
|
||||||
|
className={cn(
|
||||||
|
"font-heading text-base leading-none font-medium",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: DialogPrimitive.Description.Props) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Description
|
||||||
|
data-slot="dialog-description"
|
||||||
|
className={cn(
|
||||||
|
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogOverlay,
|
||||||
|
DialogPortal,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
}
|
||||||
268
src/components/ui/dropdown-menu.tsx
普通文件
268
src/components/ui/dropdown-menu.tsx
普通文件
@ -0,0 +1,268 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Menu as MenuPrimitive } from "@base-ui/react/menu"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { ChevronRightIcon, CheckIcon } from "lucide-react"
|
||||||
|
|
||||||
|
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {
|
||||||
|
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {
|
||||||
|
return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {
|
||||||
|
return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuContent({
|
||||||
|
align = "start",
|
||||||
|
alignOffset = 0,
|
||||||
|
side = "bottom",
|
||||||
|
sideOffset = 4,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.Popup.Props &
|
||||||
|
Pick<
|
||||||
|
MenuPrimitive.Positioner.Props,
|
||||||
|
"align" | "alignOffset" | "side" | "sideOffset"
|
||||||
|
>) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.Portal>
|
||||||
|
<MenuPrimitive.Positioner
|
||||||
|
className="isolate z-50 outline-none"
|
||||||
|
align={align}
|
||||||
|
alignOffset={alignOffset}
|
||||||
|
side={side}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
>
|
||||||
|
<MenuPrimitive.Popup
|
||||||
|
data-slot="dropdown-menu-content"
|
||||||
|
className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</MenuPrimitive.Positioner>
|
||||||
|
</MenuPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {
|
||||||
|
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuLabel({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.GroupLabel.Props & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.GroupLabel
|
||||||
|
data-slot="dropdown-menu-label"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuItem({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.Item.Props & {
|
||||||
|
inset?: boolean
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.Item
|
||||||
|
data-slot="dropdown-menu-item"
|
||||||
|
data-inset={inset}
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {
|
||||||
|
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubTrigger({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.SubmenuTrigger.Props & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.SubmenuTrigger
|
||||||
|
data-slot="dropdown-menu-sub-trigger"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRightIcon className="ml-auto" />
|
||||||
|
</MenuPrimitive.SubmenuTrigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubContent({
|
||||||
|
align = "start",
|
||||||
|
alignOffset = -3,
|
||||||
|
side = "right",
|
||||||
|
sideOffset = 0,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuContent>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuContent
|
||||||
|
data-slot="dropdown-menu-sub-content"
|
||||||
|
className={cn("w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||||
|
align={align}
|
||||||
|
alignOffset={alignOffset}
|
||||||
|
side={side}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuCheckboxItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
checked,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.CheckboxItem.Props & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.CheckboxItem
|
||||||
|
data-slot="dropdown-menu-checkbox-item"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="pointer-events-none absolute right-2 flex items-center justify-center"
|
||||||
|
data-slot="dropdown-menu-checkbox-item-indicator"
|
||||||
|
>
|
||||||
|
<MenuPrimitive.CheckboxItemIndicator>
|
||||||
|
<CheckIcon
|
||||||
|
/>
|
||||||
|
</MenuPrimitive.CheckboxItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</MenuPrimitive.CheckboxItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.RadioGroup
|
||||||
|
data-slot="dropdown-menu-radio-group"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.RadioItem.Props & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.RadioItem
|
||||||
|
data-slot="dropdown-menu-radio-item"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="pointer-events-none absolute right-2 flex items-center justify-center"
|
||||||
|
data-slot="dropdown-menu-radio-item-indicator"
|
||||||
|
>
|
||||||
|
<MenuPrimitive.RadioItemIndicator>
|
||||||
|
<CheckIcon
|
||||||
|
/>
|
||||||
|
</MenuPrimitive.RadioItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</MenuPrimitive.RadioItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: MenuPrimitive.Separator.Props) {
|
||||||
|
return (
|
||||||
|
<MenuPrimitive.Separator
|
||||||
|
data-slot="dropdown-menu-separator"
|
||||||
|
className={cn("-mx-1 my-1 h-px bg-border", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuShortcut({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="dropdown-menu-shortcut"
|
||||||
|
className={cn(
|
||||||
|
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuPortal,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuGroup,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuCheckboxItem,
|
||||||
|
DropdownMenuRadioGroup,
|
||||||
|
DropdownMenuRadioItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuShortcut,
|
||||||
|
DropdownMenuSub,
|
||||||
|
DropdownMenuSubTrigger,
|
||||||
|
DropdownMenuSubContent,
|
||||||
|
}
|
||||||
20
src/components/ui/input.tsx
普通文件
20
src/components/ui/input.tsx
普通文件
@ -0,0 +1,20 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { Input as InputPrimitive } from "@base-ui/react/input"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||||
|
return (
|
||||||
|
<InputPrimitive
|
||||||
|
type={type}
|
||||||
|
data-slot="input"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Input }
|
||||||
20
src/components/ui/label.tsx
普通文件
20
src/components/ui/label.tsx
普通文件
@ -0,0 +1,20 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Label({ className, ...props }: React.ComponentProps<"label">) {
|
||||||
|
return (
|
||||||
|
<label
|
||||||
|
data-slot="label"
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Label }
|
||||||
90
src/components/ui/popover.tsx
普通文件
90
src/components/ui/popover.tsx
普通文件
@ -0,0 +1,90 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Popover as PopoverPrimitive } from "@base-ui/react/popover"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Popover({ ...props }: PopoverPrimitive.Root.Props) {
|
||||||
|
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function PopoverTrigger({ ...props }: PopoverPrimitive.Trigger.Props) {
|
||||||
|
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function PopoverContent({
|
||||||
|
className,
|
||||||
|
align = "center",
|
||||||
|
alignOffset = 0,
|
||||||
|
side = "bottom",
|
||||||
|
sideOffset = 4,
|
||||||
|
...props
|
||||||
|
}: PopoverPrimitive.Popup.Props &
|
||||||
|
Pick<
|
||||||
|
PopoverPrimitive.Positioner.Props,
|
||||||
|
"align" | "alignOffset" | "side" | "sideOffset"
|
||||||
|
>) {
|
||||||
|
return (
|
||||||
|
<PopoverPrimitive.Portal>
|
||||||
|
<PopoverPrimitive.Positioner
|
||||||
|
align={align}
|
||||||
|
alignOffset={alignOffset}
|
||||||
|
side={side}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className="isolate z-50"
|
||||||
|
>
|
||||||
|
<PopoverPrimitive.Popup
|
||||||
|
data-slot="popover-content"
|
||||||
|
className={cn(
|
||||||
|
"z-50 flex w-72 origin-(--transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</PopoverPrimitive.Positioner>
|
||||||
|
</PopoverPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="popover-header"
|
||||||
|
className={cn("flex flex-col gap-0.5 text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PopoverTitle({ className, ...props }: PopoverPrimitive.Title.Props) {
|
||||||
|
return (
|
||||||
|
<PopoverPrimitive.Title
|
||||||
|
data-slot="popover-title"
|
||||||
|
className={cn("font-medium", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PopoverDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: PopoverPrimitive.Description.Props) {
|
||||||
|
return (
|
||||||
|
<PopoverPrimitive.Description
|
||||||
|
data-slot="popover-description"
|
||||||
|
className={cn("text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverDescription,
|
||||||
|
PopoverHeader,
|
||||||
|
PopoverTitle,
|
||||||
|
PopoverTrigger,
|
||||||
|
}
|
||||||
@ -0,0 +1,55 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function ScrollArea({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: ScrollAreaPrimitive.Root.Props) {
|
||||||
|
return (
|
||||||
|
<ScrollAreaPrimitive.Root
|
||||||
|
data-slot="scroll-area"
|
||||||
|
className={cn("relative", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ScrollAreaPrimitive.Viewport
|
||||||
|
data-slot="scroll-area-viewport"
|
||||||
|
className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</ScrollAreaPrimitive.Viewport>
|
||||||
|
<ScrollBar />
|
||||||
|
<ScrollAreaPrimitive.Corner />
|
||||||
|
</ScrollAreaPrimitive.Root>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ScrollBar({
|
||||||
|
className,
|
||||||
|
orientation = "vertical",
|
||||||
|
...props
|
||||||
|
}: ScrollAreaPrimitive.Scrollbar.Props) {
|
||||||
|
return (
|
||||||
|
<ScrollAreaPrimitive.Scrollbar
|
||||||
|
data-slot="scroll-area-scrollbar"
|
||||||
|
data-orientation={orientation}
|
||||||
|
orientation={orientation}
|
||||||
|
className={cn(
|
||||||
|
"flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ScrollAreaPrimitive.Thumb
|
||||||
|
data-slot="scroll-area-thumb"
|
||||||
|
className="relative flex-1 rounded-full bg-border"
|
||||||
|
/>
|
||||||
|
</ScrollAreaPrimitive.Scrollbar>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { ScrollArea, ScrollBar }
|
||||||
201
src/components/ui/select.tsx
普通文件
201
src/components/ui/select.tsx
普通文件
@ -0,0 +1,201 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Select as SelectPrimitive } from "@base-ui/react/select"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
|
||||||
|
|
||||||
|
const Select = SelectPrimitive.Root
|
||||||
|
|
||||||
|
function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Group
|
||||||
|
data-slot="select-group"
|
||||||
|
className={cn("scroll-my-1 p-1", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Value
|
||||||
|
data-slot="select-value"
|
||||||
|
className={cn("flex flex-1 text-left", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectTrigger({
|
||||||
|
className,
|
||||||
|
size = "default",
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: SelectPrimitive.Trigger.Props & {
|
||||||
|
size?: "sm" | "default"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Trigger
|
||||||
|
data-slot="select-trigger"
|
||||||
|
data-size={size}
|
||||||
|
className={cn(
|
||||||
|
"flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<SelectPrimitive.Icon
|
||||||
|
render={
|
||||||
|
<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</SelectPrimitive.Trigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
side = "bottom",
|
||||||
|
sideOffset = 4,
|
||||||
|
align = "center",
|
||||||
|
alignOffset = 0,
|
||||||
|
alignItemWithTrigger = true,
|
||||||
|
...props
|
||||||
|
}: SelectPrimitive.Popup.Props &
|
||||||
|
Pick<
|
||||||
|
SelectPrimitive.Positioner.Props,
|
||||||
|
"align" | "alignOffset" | "side" | "sideOffset" | "alignItemWithTrigger"
|
||||||
|
>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Portal>
|
||||||
|
<SelectPrimitive.Positioner
|
||||||
|
side={side}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
align={align}
|
||||||
|
alignOffset={alignOffset}
|
||||||
|
alignItemWithTrigger={alignItemWithTrigger}
|
||||||
|
className="isolate z-50"
|
||||||
|
>
|
||||||
|
<SelectPrimitive.Popup
|
||||||
|
data-slot="select-content"
|
||||||
|
data-align-trigger={alignItemWithTrigger}
|
||||||
|
className={cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<SelectScrollUpButton />
|
||||||
|
<SelectPrimitive.List>{children}</SelectPrimitive.List>
|
||||||
|
<SelectScrollDownButton />
|
||||||
|
</SelectPrimitive.Popup>
|
||||||
|
</SelectPrimitive.Positioner>
|
||||||
|
</SelectPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectLabel({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: SelectPrimitive.GroupLabel.Props) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.GroupLabel
|
||||||
|
data-slot="select-label"
|
||||||
|
className={cn("px-1.5 py-1 text-xs text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: SelectPrimitive.Item.Props) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Item
|
||||||
|
data-slot="select-item"
|
||||||
|
className={cn(
|
||||||
|
"relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<SelectPrimitive.ItemText className="flex flex-1 shrink-0 gap-2 whitespace-nowrap">
|
||||||
|
{children}
|
||||||
|
</SelectPrimitive.ItemText>
|
||||||
|
<SelectPrimitive.ItemIndicator
|
||||||
|
render={
|
||||||
|
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<CheckIcon className="pointer-events-none" />
|
||||||
|
</SelectPrimitive.ItemIndicator>
|
||||||
|
</SelectPrimitive.Item>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: SelectPrimitive.Separator.Props) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Separator
|
||||||
|
data-slot="select-separator"
|
||||||
|
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectScrollUpButton({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpArrow>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.ScrollUpArrow
|
||||||
|
data-slot="select-scroll-up-button"
|
||||||
|
className={cn(
|
||||||
|
"top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ChevronUpIcon
|
||||||
|
/>
|
||||||
|
</SelectPrimitive.ScrollUpArrow>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectScrollDownButton({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownArrow>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.ScrollDownArrow
|
||||||
|
data-slot="select-scroll-down-button"
|
||||||
|
className={cn(
|
||||||
|
"bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ChevronDownIcon
|
||||||
|
/>
|
||||||
|
</SelectPrimitive.ScrollDownArrow>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectGroup,
|
||||||
|
SelectItem,
|
||||||
|
SelectLabel,
|
||||||
|
SelectScrollDownButton,
|
||||||
|
SelectScrollUpButton,
|
||||||
|
SelectSeparator,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
}
|
||||||
25
src/components/ui/separator.tsx
普通文件
25
src/components/ui/separator.tsx
普通文件
@ -0,0 +1,25 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Separator({
|
||||||
|
className,
|
||||||
|
orientation = "horizontal",
|
||||||
|
...props
|
||||||
|
}: SeparatorPrimitive.Props) {
|
||||||
|
return (
|
||||||
|
<SeparatorPrimitive
|
||||||
|
data-slot="separator"
|
||||||
|
orientation={orientation}
|
||||||
|
className={cn(
|
||||||
|
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Separator }
|
||||||
138
src/components/ui/sheet.tsx
普通文件
138
src/components/ui/sheet.tsx
普通文件
@ -0,0 +1,138 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Dialog as SheetPrimitive } from "@base-ui/react/dialog"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { XIcon } from "lucide-react"
|
||||||
|
|
||||||
|
function Sheet({ ...props }: SheetPrimitive.Root.Props) {
|
||||||
|
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetTrigger({ ...props }: SheetPrimitive.Trigger.Props) {
|
||||||
|
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetClose({ ...props }: SheetPrimitive.Close.Props) {
|
||||||
|
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetPortal({ ...props }: SheetPrimitive.Portal.Props) {
|
||||||
|
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetOverlay({ className, ...props }: SheetPrimitive.Backdrop.Props) {
|
||||||
|
return (
|
||||||
|
<SheetPrimitive.Backdrop
|
||||||
|
data-slot="sheet-overlay"
|
||||||
|
className={cn(
|
||||||
|
"fixed inset-0 z-50 bg-black/10 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
side = "right",
|
||||||
|
showCloseButton = true,
|
||||||
|
...props
|
||||||
|
}: SheetPrimitive.Popup.Props & {
|
||||||
|
side?: "top" | "right" | "bottom" | "left"
|
||||||
|
showCloseButton?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SheetPortal>
|
||||||
|
<SheetOverlay />
|
||||||
|
<SheetPrimitive.Popup
|
||||||
|
data-slot="sheet-content"
|
||||||
|
data-side={side}
|
||||||
|
className={cn(
|
||||||
|
"fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0 data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem] data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem] data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem] data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem] data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{showCloseButton && (
|
||||||
|
<SheetPrimitive.Close
|
||||||
|
data-slot="sheet-close"
|
||||||
|
render={
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
className="absolute top-3 right-3"
|
||||||
|
size="icon-sm"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<XIcon
|
||||||
|
/>
|
||||||
|
<span className="sr-only">Close</span>
|
||||||
|
</SheetPrimitive.Close>
|
||||||
|
)}
|
||||||
|
</SheetPrimitive.Popup>
|
||||||
|
</SheetPortal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="sheet-header"
|
||||||
|
className={cn("flex flex-col gap-0.5 p-4", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="sheet-footer"
|
||||||
|
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) {
|
||||||
|
return (
|
||||||
|
<SheetPrimitive.Title
|
||||||
|
data-slot="sheet-title"
|
||||||
|
className={cn(
|
||||||
|
"font-heading text-base font-medium text-foreground",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SheetDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: SheetPrimitive.Description.Props) {
|
||||||
|
return (
|
||||||
|
<SheetPrimitive.Description
|
||||||
|
data-slot="sheet-description"
|
||||||
|
className={cn("text-sm text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Sheet,
|
||||||
|
SheetTrigger,
|
||||||
|
SheetClose,
|
||||||
|
SheetContent,
|
||||||
|
SheetHeader,
|
||||||
|
SheetFooter,
|
||||||
|
SheetTitle,
|
||||||
|
SheetDescription,
|
||||||
|
}
|
||||||
32
src/components/ui/switch.tsx
普通文件
32
src/components/ui/switch.tsx
普通文件
@ -0,0 +1,32 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Switch({
|
||||||
|
className,
|
||||||
|
size = "default",
|
||||||
|
...props
|
||||||
|
}: SwitchPrimitive.Root.Props & {
|
||||||
|
size?: "sm" | "default"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SwitchPrimitive.Root
|
||||||
|
data-slot="switch"
|
||||||
|
data-size={size}
|
||||||
|
className={cn(
|
||||||
|
"peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<SwitchPrimitive.Thumb
|
||||||
|
data-slot="switch-thumb"
|
||||||
|
className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
|
||||||
|
/>
|
||||||
|
</SwitchPrimitive.Root>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Switch }
|
||||||
18
src/components/ui/textarea.tsx
普通文件
18
src/components/ui/textarea.tsx
普通文件
@ -0,0 +1,18 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||||
|
return (
|
||||||
|
<textarea
|
||||||
|
data-slot="textarea"
|
||||||
|
className={cn(
|
||||||
|
"flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Textarea }
|
||||||
66
src/components/ui/tooltip.tsx
普通文件
66
src/components/ui/tooltip.tsx
普通文件
@ -0,0 +1,66 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function TooltipProvider({
|
||||||
|
delay = 0,
|
||||||
|
...props
|
||||||
|
}: TooltipPrimitive.Provider.Props) {
|
||||||
|
return (
|
||||||
|
<TooltipPrimitive.Provider
|
||||||
|
data-slot="tooltip-provider"
|
||||||
|
delay={delay}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Tooltip({ ...props }: TooltipPrimitive.Root.Props) {
|
||||||
|
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function TooltipTrigger({ ...props }: TooltipPrimitive.Trigger.Props) {
|
||||||
|
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function TooltipContent({
|
||||||
|
className,
|
||||||
|
side = "top",
|
||||||
|
sideOffset = 4,
|
||||||
|
align = "center",
|
||||||
|
alignOffset = 0,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: TooltipPrimitive.Popup.Props &
|
||||||
|
Pick<
|
||||||
|
TooltipPrimitive.Positioner.Props,
|
||||||
|
"align" | "alignOffset" | "side" | "sideOffset"
|
||||||
|
>) {
|
||||||
|
return (
|
||||||
|
<TooltipPrimitive.Portal>
|
||||||
|
<TooltipPrimitive.Positioner
|
||||||
|
align={align}
|
||||||
|
alignOffset={alignOffset}
|
||||||
|
side={side}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className="isolate z-50"
|
||||||
|
>
|
||||||
|
<TooltipPrimitive.Popup
|
||||||
|
data-slot="tooltip-content"
|
||||||
|
className={cn(
|
||||||
|
"z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5" />
|
||||||
|
</TooltipPrimitive.Popup>
|
||||||
|
</TooltipPrimitive.Positioner>
|
||||||
|
</TooltipPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||||
84
src/lib/auth.ts
普通文件
84
src/lib/auth.ts
普通文件
@ -0,0 +1,84 @@
|
|||||||
|
import { SignJWT, jwtVerify } from "jose"
|
||||||
|
import { cookies } from "next/headers"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
const secret = new TextEncoder().encode(process.env.AUTH_SECRET || "fallback-secret-change-me")
|
||||||
|
const cookieName = "auth-token"
|
||||||
|
const maxAge = 30 * 24 * 60 * 60 // 30 days
|
||||||
|
|
||||||
|
export interface SessionUser {
|
||||||
|
id: string
|
||||||
|
email: string
|
||||||
|
name: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function signToken(user: SessionUser): Promise<string> {
|
||||||
|
return new SignJWT({ sub: user.id, email: user.email, name: user.name })
|
||||||
|
.setProtectedHeader({ alg: "HS256" })
|
||||||
|
.setIssuedAt()
|
||||||
|
.setExpirationTime(`${maxAge}s`)
|
||||||
|
.sign(secret)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyToken(token: string): Promise<SessionUser | null> {
|
||||||
|
try {
|
||||||
|
const { payload } = await jwtVerify(token, secret)
|
||||||
|
if (!payload.sub || !payload.email) return null
|
||||||
|
return {
|
||||||
|
id: payload.sub,
|
||||||
|
email: payload.email as string,
|
||||||
|
name: (payload.name as string) || null,
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getSession(): Promise<SessionUser | null> {
|
||||||
|
const cookieStore = await cookies()
|
||||||
|
const token = cookieStore.get(cookieName)?.value
|
||||||
|
if (!token) return null
|
||||||
|
return verifyToken(token)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setAuthCookie(token: string): Promise<void> {
|
||||||
|
const cookieStore = await cookies()
|
||||||
|
cookieStore.set(cookieName, token, {
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: "lax",
|
||||||
|
path: "/",
|
||||||
|
secure: false,
|
||||||
|
maxAge,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function clearAuthCookie(): Promise<void> {
|
||||||
|
const cookieStore = await cookies()
|
||||||
|
cookieStore.set(cookieName, "", {
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: "lax",
|
||||||
|
path: "/",
|
||||||
|
secure: false,
|
||||||
|
maxAge: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function authenticate(
|
||||||
|
email: string,
|
||||||
|
password: string
|
||||||
|
): Promise<SessionUser | null> {
|
||||||
|
const bcrypt = await import("bcryptjs")
|
||||||
|
const user = await prisma.user.findUnique({ where: { email } })
|
||||||
|
if (!user) return null
|
||||||
|
|
||||||
|
const isValid = await bcrypt.compare(password, user.password)
|
||||||
|
if (!isValid) return null
|
||||||
|
|
||||||
|
return { id: user.id, email: user.email, name: user.name }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function auth() {
|
||||||
|
const session = await getSession()
|
||||||
|
if (!session) return null
|
||||||
|
return { user: session }
|
||||||
|
}
|
||||||
21
src/lib/builtin-tools.ts
普通文件
21
src/lib/builtin-tools.ts
普通文件
@ -0,0 +1,21 @@
|
|||||||
|
export interface BuiltInTool {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
description: string
|
||||||
|
parameters: Record<string, unknown>
|
||||||
|
}
|
||||||
|
|
||||||
|
export const BUILT_IN_TOOLS: BuiltInTool[] = [
|
||||||
|
{
|
||||||
|
id: "rename_session",
|
||||||
|
name: "rename_session",
|
||||||
|
description: "给当前对话重命名。根据对话内容生成一个简短、准确的中文标题(不要超过20个字),或使用用户指定的名称。",
|
||||||
|
parameters: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
title: { type: "string", description: "新的对话标题" },
|
||||||
|
},
|
||||||
|
required: ["title"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
47
src/lib/encryption.ts
普通文件
47
src/lib/encryption.ts
普通文件
@ -0,0 +1,47 @@
|
|||||||
|
import crypto from "crypto"
|
||||||
|
|
||||||
|
const ALGORITHM = "aes-256-gcm"
|
||||||
|
const IV_LENGTH = 12
|
||||||
|
const AUTH_TAG_LENGTH = 16
|
||||||
|
|
||||||
|
function getEncryptionKey(): Buffer {
|
||||||
|
const key = process.env.ENCRYPTION_KEY
|
||||||
|
if (!key) {
|
||||||
|
throw new Error("ENCRYPTION_KEY environment variable is not set")
|
||||||
|
}
|
||||||
|
return crypto.scryptSync(key, "salt", 32)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encryptApiKey(plaintext: string): string {
|
||||||
|
const key = getEncryptionKey()
|
||||||
|
const iv = crypto.randomBytes(IV_LENGTH)
|
||||||
|
const cipher = crypto.createCipheriv(ALGORITHM, key, iv)
|
||||||
|
|
||||||
|
let encrypted = cipher.update(plaintext, "utf8", "hex")
|
||||||
|
encrypted += cipher.final("hex")
|
||||||
|
const authTag = cipher.getAuthTag()
|
||||||
|
|
||||||
|
return iv.toString("hex") + ":" + authTag.toString("hex") + ":" + encrypted
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decryptApiKey(encryptedData: string): string {
|
||||||
|
const key = getEncryptionKey()
|
||||||
|
const parts = encryptedData.split(":")
|
||||||
|
if (parts.length !== 3) throw new Error("Invalid encrypted data format")
|
||||||
|
|
||||||
|
const iv = Buffer.from(parts[0], "hex")
|
||||||
|
const authTag = Buffer.from(parts[1], "hex")
|
||||||
|
const encrypted = parts[2]
|
||||||
|
|
||||||
|
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv)
|
||||||
|
decipher.setAuthTag(authTag)
|
||||||
|
|
||||||
|
let decrypted = decipher.update(encrypted, "hex", "utf8")
|
||||||
|
decrypted += decipher.final("utf8")
|
||||||
|
return decrypted
|
||||||
|
}
|
||||||
|
|
||||||
|
export function maskApiKey(apiKey: string): string {
|
||||||
|
if (apiKey.length <= 4) return "****"
|
||||||
|
return "****" + apiKey.slice(-4)
|
||||||
|
}
|
||||||
15
src/lib/prisma.ts
普通文件
15
src/lib/prisma.ts
普通文件
@ -0,0 +1,15 @@
|
|||||||
|
import { PrismaClient } from "@prisma/client"
|
||||||
|
import { PrismaLibSql } from "@prisma/adapter-libsql"
|
||||||
|
|
||||||
|
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }
|
||||||
|
|
||||||
|
function createPrismaClient() {
|
||||||
|
const adapter = new PrismaLibSql({
|
||||||
|
url: process.env.DATABASE_URL || "file:./dev.db",
|
||||||
|
})
|
||||||
|
return new PrismaClient({ adapter })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const prisma = globalForPrisma.prisma || createPrismaClient()
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma
|
||||||
6
src/lib/utils.ts
普通文件
6
src/lib/utils.ts
普通文件
@ -0,0 +1,6 @@
|
|||||||
|
import { clsx, type ClassValue } from "clsx"
|
||||||
|
import { twMerge } from "tailwind-merge"
|
||||||
|
|
||||||
|
export function cn(...inputs: ClassValue[]) {
|
||||||
|
return twMerge(clsx(inputs))
|
||||||
|
}
|
||||||
45
src/middleware.ts
普通文件
45
src/middleware.ts
普通文件
@ -0,0 +1,45 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { jwtVerify } from "jose"
|
||||||
|
|
||||||
|
const secret = new TextEncoder().encode(process.env.AUTH_SECRET || "fallback-secret-change-me")
|
||||||
|
const cookieName = "auth-token"
|
||||||
|
|
||||||
|
const publicPaths = ["/login", "/register", "/api/auth/login", "/api/auth/register"]
|
||||||
|
|
||||||
|
export default async function middleware(req: NextRequest) {
|
||||||
|
const { pathname } = req.nextUrl
|
||||||
|
|
||||||
|
if (publicPaths.some((p) => pathname.startsWith(p))) {
|
||||||
|
return NextResponse.next()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pathname.startsWith("/_next") || pathname.startsWith("/api/auth/session")) {
|
||||||
|
return NextResponse.next()
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = req.cookies.get(cookieName)?.value
|
||||||
|
if (!token) {
|
||||||
|
if (pathname.startsWith("/api/")) {
|
||||||
|
return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
}
|
||||||
|
const url = new URL("/login", req.url)
|
||||||
|
url.searchParams.set("callbackUrl", pathname)
|
||||||
|
return NextResponse.redirect(url)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await jwtVerify(token, secret)
|
||||||
|
return NextResponse.next()
|
||||||
|
} catch {
|
||||||
|
if (pathname.startsWith("/api/")) {
|
||||||
|
return NextResponse.json({ error: "登录已过期" }, { status: 401 })
|
||||||
|
}
|
||||||
|
const url = new URL("/login", req.url)
|
||||||
|
url.searchParams.set("callbackUrl", pathname)
|
||||||
|
return NextResponse.redirect(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
|
||||||
|
}
|
||||||
在新工单中引用
屏蔽一个用户