v3
这个提交包含在:
2
.gitignore
vendored
2
.gitignore
vendored
@ -39,3 +39,5 @@ yarn-error.log*
|
|||||||
# typescript
|
# typescript
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
|
|
||||||
|
dev.db
|
||||||
|
|||||||
@ -60,27 +60,33 @@ model VerificationToken {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model Provider {
|
model Provider {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
userId String
|
userId String
|
||||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
name String
|
name String
|
||||||
baseUrl String
|
baseUrl String
|
||||||
apiKey String
|
apiKey String
|
||||||
modelName String
|
modelName String
|
||||||
customHeaders String?
|
customHeaders String?
|
||||||
createdAt DateTime @default(now())
|
compressEnabled Boolean @default(true)
|
||||||
updatedAt DateTime @updatedAt
|
compressTrigger Int @default(0)
|
||||||
|
contextLimit Int @default(128000)
|
||||||
|
keepRounds Int @default(3)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
}
|
}
|
||||||
|
|
||||||
model Preset {
|
model Preset {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
userId String
|
userId String
|
||||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
name String
|
name String
|
||||||
isDefault Boolean @default(false)
|
isDefault Boolean @default(false)
|
||||||
createdAt DateTime @default(now())
|
compressPrompt String?
|
||||||
updatedAt DateTime @updatedAt
|
compressRole String @default("system")
|
||||||
fragments Fragment[]
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
fragments Fragment[]
|
||||||
}
|
}
|
||||||
|
|
||||||
model Fragment {
|
model Fragment {
|
||||||
|
|||||||
@ -126,22 +126,30 @@ export async function POST(req: NextRequest) {
|
|||||||
|
|
||||||
messagesToSend.push({ role: "user", content: message })
|
messagesToSend.push({ role: "user", content: message })
|
||||||
|
|
||||||
// Compression check
|
// Compression check — use provider settings (trigger is absolute token count, 0 = disabled)
|
||||||
let compressionApplied = false
|
let compressionApplied = false
|
||||||
let compressedContent = ""
|
let compressedContent = ""
|
||||||
if (chatSession.compressEnabled && effectivePresetId) {
|
let compressRole = "system"
|
||||||
|
const compressTrigger = provider.compressTrigger ?? 0
|
||||||
|
const compressEnabled = provider.compressEnabled !== false
|
||||||
|
if (compressEnabled && compressTrigger > 0 && effectivePresetId) {
|
||||||
const estimatedTokens = estimateTokenCount(messagesToSend)
|
const estimatedTokens = estimateTokenCount(messagesToSend)
|
||||||
const contextLimit = getContextLimit(provider.modelName)
|
if (estimatedTokens > compressTrigger) {
|
||||||
if (estimatedTokens > contextLimit * (1 - chatSession.compressTrigger)) {
|
// Load compressPrompt from preset
|
||||||
const keepRounds = chatSession.keepRounds || 3
|
const preset = await prisma.preset.findFirst({
|
||||||
|
where: { id: effectivePresetId, userId: userId },
|
||||||
|
})
|
||||||
|
const keepRounds = provider.keepRounds || 3
|
||||||
const toCompress = nonSummaryMessages.slice(0, -keepRounds * 2)
|
const toCompress = nonSummaryMessages.slice(0, -keepRounds * 2)
|
||||||
if (toCompress.length > 1) {
|
if (toCompress.length > 1) {
|
||||||
compressedContent = await compressHistory(toCompress, provider)
|
const customPrompt = preset?.compressPrompt || null
|
||||||
|
compressedContent = await compressHistory(toCompress, provider, customPrompt)
|
||||||
compressionApplied = true
|
compressionApplied = true
|
||||||
|
compressRole = preset?.compressRole || "system"
|
||||||
|
|
||||||
messagesToSend = []
|
messagesToSend = []
|
||||||
if (systemPrompt) messagesToSend.push({ role: "system", content: systemPrompt })
|
if (systemPrompt) messagesToSend.push({ role: "system", content: systemPrompt })
|
||||||
messagesToSend.push({ role: "system", content: `[对话摘要 - 自动压缩] ${compressedContent}` })
|
messagesToSend.push({ role: compressRole, content: `[对话摘要 - 自动压缩] ${compressedContent}` })
|
||||||
|
|
||||||
const recentMsgs = nonSummaryMessages.slice(-keepRounds * 2)
|
const recentMsgs = nonSummaryMessages.slice(-keepRounds * 2)
|
||||||
let hasPendingToolCalls = false
|
let hasPendingToolCalls = false
|
||||||
@ -572,7 +580,7 @@ export async function POST(req: NextRequest) {
|
|||||||
await prisma.message.create({
|
await prisma.message.create({
|
||||||
data: {
|
data: {
|
||||||
sessionId,
|
sessionId,
|
||||||
role: "system",
|
role: compressRole,
|
||||||
content: `📝 已压缩前期对话摘要: ${compressedContent}`,
|
content: `📝 已压缩前期对话摘要: ${compressedContent}`,
|
||||||
isSummary: true,
|
isSummary: true,
|
||||||
},
|
},
|
||||||
@ -652,13 +660,16 @@ function getContextLimit(modelName: string): number {
|
|||||||
|
|
||||||
async function compressHistory(
|
async function compressHistory(
|
||||||
messages: Array<{ role: string; content: string }>,
|
messages: Array<{ role: string; content: string }>,
|
||||||
provider: { baseUrl: string; apiKey: string; modelName: string }
|
provider: { baseUrl: string; apiKey: string; modelName: string },
|
||||||
|
customPrompt?: string | null
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const summary = messages
|
const summary = messages
|
||||||
.map((m) => `[${m.role}] ${m.content}`)
|
.map((m) => `[${m.role}] ${m.content}`)
|
||||||
.join("\n")
|
.join("\n")
|
||||||
|
|
||||||
const prompt = `请为以下对话历史生成一个简洁的结构化摘要,保留关键信息、决策和动作:
|
const prompt = customPrompt
|
||||||
|
? customPrompt.replace("{{content}}", summary.substring(0, 8000))
|
||||||
|
: `请为以下对话历史生成一个简洁的结构化摘要,保留关键信息、决策和动作:
|
||||||
|
|
||||||
${summary.substring(0, 8000)}
|
${summary.substring(0, 8000)}
|
||||||
|
|
||||||
|
|||||||
@ -0,0 +1,92 @@
|
|||||||
|
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<{ 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, isSummary: false }, orderBy: { createdAt: "asc" } } },
|
||||||
|
})
|
||||||
|
if (!chatSession) return NextResponse.json({ error: "会话不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const messages = chatSession.messages
|
||||||
|
if (messages.length === 0) return NextResponse.json({ error: "没有可压缩的消息" }, { status: 400 })
|
||||||
|
|
||||||
|
const providerId = chatSession.providerId
|
||||||
|
if (!providerId) return NextResponse.json({ error: "未选择模型" }, { status: 400 })
|
||||||
|
|
||||||
|
const provider = await prisma.provider.findFirst({
|
||||||
|
where: { id: providerId, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (!provider) return NextResponse.json({ error: "模型不存在" }, { status: 404 })
|
||||||
|
|
||||||
|
const presetId = chatSession.presetId
|
||||||
|
let compressPrompt = `请为以下对话历史生成一个简洁的结构化摘要,保留关键信息、决策和动作:
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
|
请用中文输出摘要。`
|
||||||
|
let compressRole = "system"
|
||||||
|
|
||||||
|
if (presetId) {
|
||||||
|
const preset = await prisma.preset.findFirst({
|
||||||
|
where: { id: presetId, userId: session.user.id },
|
||||||
|
})
|
||||||
|
if (preset?.compressPrompt) {
|
||||||
|
compressPrompt = preset.compressPrompt
|
||||||
|
compressRole = preset.compressRole || "system"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const summary = messages
|
||||||
|
.map((m) => `[${m.role}] ${m.content}`)
|
||||||
|
.join("\n")
|
||||||
|
|
||||||
|
const prompt = compressPrompt.replace("{{content}}", summary.substring(0, 8000))
|
||||||
|
|
||||||
|
const apiKey = decryptApiKey(provider.apiKey)
|
||||||
|
const baseUrl = provider.baseUrl.replace(/\/+$/, "")
|
||||||
|
|
||||||
|
let compressedContent = "压缩失败"
|
||||||
|
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: 2048,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json() as { choices?: Array<{ message?: { content?: string } }> }
|
||||||
|
compressedContent = data.choices?.[0]?.message?.content || "压缩失败"
|
||||||
|
}
|
||||||
|
} catch {/* ignore */}
|
||||||
|
|
||||||
|
const idsToHide = messages.map((m) => m.id)
|
||||||
|
await prisma.message.updateMany({
|
||||||
|
where: { id: { in: idsToHide } },
|
||||||
|
data: { isHidden: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
const summaryMsg = await prisma.message.create({
|
||||||
|
data: {
|
||||||
|
sessionId,
|
||||||
|
role: compressRole,
|
||||||
|
content: `📝 已压缩对话摘要: ${compressedContent}`,
|
||||||
|
isSummary: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true, summary: summaryMsg })
|
||||||
|
}
|
||||||
@ -0,0 +1,70 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { prisma } from "@/lib/prisma"
|
||||||
|
|
||||||
|
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(() => null)
|
||||||
|
if (!body || typeof body !== "object") {
|
||||||
|
return NextResponse.json({ error: "无效的数据格式" }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!body.messages || !Array.isArray(body.messages)) {
|
||||||
|
return NextResponse.json({ error: "数据中缺少 messages 字段" }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const title = body.title || "导入的会话"
|
||||||
|
const validRoles = ["user", "assistant", "system", "tool"]
|
||||||
|
|
||||||
|
const chatSession = await prisma.chatSession.create({
|
||||||
|
data: {
|
||||||
|
userId: session.user.id,
|
||||||
|
title,
|
||||||
|
totalCost: typeof body.totalCost === "number" ? body.totalCost : 0,
|
||||||
|
thinkingEnabled: body.thinkingEnabled === true,
|
||||||
|
markdownEnabled: body.markdownEnabled !== false,
|
||||||
|
compressEnabled: body.compressEnabled !== false,
|
||||||
|
compressTrigger: typeof body.compressTrigger === "number" ? body.compressTrigger : 0.2,
|
||||||
|
keepRounds: typeof body.keepRounds === "number" ? body.keepRounds : 3,
|
||||||
|
createdAt: body.createdAt ? new Date(body.createdAt) : undefined,
|
||||||
|
messages: {
|
||||||
|
createMany: {
|
||||||
|
data: body.messages
|
||||||
|
.filter((m: { role: string; content?: string }) => m.role && validRoles.includes(m.role) && m.content !== undefined)
|
||||||
|
.map((m: {
|
||||||
|
role: string
|
||||||
|
content: string
|
||||||
|
thinking?: string | null
|
||||||
|
toolCalls?: string | null
|
||||||
|
toolResults?: string | null
|
||||||
|
toolCallId?: string | null
|
||||||
|
tokenUsage?: string | null
|
||||||
|
cost?: number
|
||||||
|
branchParent?: string | null
|
||||||
|
isSummary?: boolean
|
||||||
|
isHidden?: boolean
|
||||||
|
createdAt?: string
|
||||||
|
}) => ({
|
||||||
|
role: m.role,
|
||||||
|
content: m.content,
|
||||||
|
thinking: m.thinking ?? null,
|
||||||
|
toolCalls: m.toolCalls ?? null,
|
||||||
|
toolResults: m.toolResults ?? null,
|
||||||
|
toolCallId: m.toolCallId ?? null,
|
||||||
|
tokenUsage: m.tokenUsage ?? null,
|
||||||
|
cost: typeof m.cost === "number" ? m.cost : 0,
|
||||||
|
branchParent: m.branchParent ?? null,
|
||||||
|
isSummary: m.isSummary === true,
|
||||||
|
isHidden: m.isHidden === true,
|
||||||
|
createdAt: m.createdAt ? new Date(m.createdAt) : undefined,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: { messages: { orderBy: { createdAt: "asc" } } },
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json(chatSession, { status: 201 })
|
||||||
|
}
|
||||||
@ -7,7 +7,7 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
const { id } = await params
|
const { id } = await params
|
||||||
const { name, isDefault } = await req.json()
|
const { name, isDefault, compressPrompt, compressRole } = await req.json()
|
||||||
|
|
||||||
const preset = await prisma.preset.findFirst({ where: { id, userId: session.user.id } })
|
const preset = await prisma.preset.findFirst({ where: { id, userId: session.user.id } })
|
||||||
if (!preset) return NextResponse.json({ error: "预设不存在" }, { status: 404 })
|
if (!preset) return NextResponse.json({ error: "预设不存在" }, { status: 404 })
|
||||||
@ -22,6 +22,8 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
const data: Record<string, unknown> = {}
|
const data: Record<string, unknown> = {}
|
||||||
if (name !== undefined) data.name = name
|
if (name !== undefined) data.name = name
|
||||||
if (isDefault !== undefined) data.isDefault = isDefault
|
if (isDefault !== undefined) data.isDefault = isDefault
|
||||||
|
if (compressPrompt !== undefined) data.compressPrompt = compressPrompt
|
||||||
|
if (compressRole !== undefined) data.compressRole = compressRole
|
||||||
|
|
||||||
const updated = await prisma.preset.update({ where: { id }, data, include: { fragments: { orderBy: { order: "asc" } } } })
|
const updated = await prisma.preset.update({ where: { id }, data, include: { fragments: { orderBy: { order: "asc" } } } })
|
||||||
return NextResponse.json(updated)
|
return NextResponse.json(updated)
|
||||||
|
|||||||
@ -12,14 +12,19 @@ export async function GET(_req: NextRequest) {
|
|||||||
orderBy: { createdAt: "desc" },
|
orderBy: { createdAt: "desc" },
|
||||||
})
|
})
|
||||||
|
|
||||||
return NextResponse.json(presets)
|
return NextResponse.json(
|
||||||
|
presets.map((p) => ({
|
||||||
|
...p,
|
||||||
|
compressRole: p.compressRole || "system",
|
||||||
|
}))
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
const session = await auth()
|
const session = await auth()
|
||||||
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
const { name, isDefault } = await req.json()
|
const { name, isDefault, compressPrompt, compressRole } = await req.json()
|
||||||
if (!name) return NextResponse.json({ error: "名称不能为空" }, { status: 400 })
|
if (!name) return NextResponse.json({ error: "名称不能为空" }, { status: 400 })
|
||||||
|
|
||||||
if (isDefault) {
|
if (isDefault) {
|
||||||
@ -30,7 +35,13 @@ export async function POST(req: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const preset = await prisma.preset.create({
|
const preset = await prisma.preset.create({
|
||||||
data: { userId: session.user.id, name, isDefault: isDefault || false },
|
data: {
|
||||||
|
userId: session.user.id,
|
||||||
|
name,
|
||||||
|
isDefault: isDefault || false,
|
||||||
|
compressPrompt: compressPrompt || null,
|
||||||
|
compressRole: compressRole || "system",
|
||||||
|
},
|
||||||
include: { fragments: true },
|
include: { fragments: true },
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@ -8,7 +8,7 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
|
|
||||||
const { id } = await params
|
const { id } = await params
|
||||||
const { name, baseUrl, apiKey, modelName, customHeaders } = await req.json()
|
const { name, baseUrl, apiKey, modelName, customHeaders, compressEnabled, compressTrigger, contextLimit, keepRounds } = await req.json()
|
||||||
|
|
||||||
const data: Record<string, unknown> = {}
|
const data: Record<string, unknown> = {}
|
||||||
if (name !== undefined) data.name = name
|
if (name !== undefined) data.name = name
|
||||||
@ -16,6 +16,10 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
|
|||||||
if (apiKey !== undefined) data.apiKey = encryptApiKey(apiKey)
|
if (apiKey !== undefined) data.apiKey = encryptApiKey(apiKey)
|
||||||
if (modelName !== undefined) data.modelName = modelName
|
if (modelName !== undefined) data.modelName = modelName
|
||||||
if (customHeaders !== undefined) data.customHeaders = JSON.stringify(customHeaders)
|
if (customHeaders !== undefined) data.customHeaders = JSON.stringify(customHeaders)
|
||||||
|
if (compressEnabled !== undefined) data.compressEnabled = compressEnabled
|
||||||
|
if (compressTrigger !== undefined) data.compressTrigger = compressTrigger
|
||||||
|
if (contextLimit !== undefined) data.contextLimit = contextLimit
|
||||||
|
if (keepRounds !== undefined) data.keepRounds = keepRounds
|
||||||
|
|
||||||
const provider = await prisma.provider.findFirst({ where: { id, userId: session.user.id } })
|
const provider = await prisma.provider.findFirst({ where: { id, userId: session.user.id } })
|
||||||
if (!provider) return NextResponse.json({ error: "Provider 不存在" }, { status: 404 })
|
if (!provider) return NextResponse.json({ error: "Provider 不存在" }, { status: 404 })
|
||||||
|
|||||||
@ -18,6 +18,10 @@ export async function GET(_req: NextRequest) {
|
|||||||
providers.map((p) => ({
|
providers.map((p) => ({
|
||||||
...p,
|
...p,
|
||||||
apiKey: maskApiKey(decryptApiKey(p.apiKey)),
|
apiKey: maskApiKey(decryptApiKey(p.apiKey)),
|
||||||
|
compressEnabled: p.compressEnabled ?? true,
|
||||||
|
compressTrigger: p.compressTrigger ?? 0,
|
||||||
|
contextLimit: p.contextLimit ?? 128000,
|
||||||
|
keepRounds: p.keepRounds ?? 3,
|
||||||
}))
|
}))
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -28,7 +32,7 @@ export async function POST(req: NextRequest) {
|
|||||||
return NextResponse.json({ error: "未登录" }, { status: 401 })
|
return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const { name, baseUrl, apiKey, modelName, customHeaders } = await req.json()
|
const { name, baseUrl, apiKey, modelName, customHeaders, compressEnabled, compressTrigger, contextLimit, keepRounds } = await req.json()
|
||||||
|
|
||||||
if (!name || !baseUrl || !apiKey || !modelName) {
|
if (!name || !baseUrl || !apiKey || !modelName) {
|
||||||
return NextResponse.json({ error: "缺少必要参数" }, { status: 400 })
|
return NextResponse.json({ error: "缺少必要参数" }, { status: 400 })
|
||||||
@ -44,6 +48,10 @@ export async function POST(req: NextRequest) {
|
|||||||
apiKey: encryptedKey,
|
apiKey: encryptedKey,
|
||||||
modelName,
|
modelName,
|
||||||
customHeaders: customHeaders ? JSON.stringify(customHeaders) : null,
|
customHeaders: customHeaders ? JSON.stringify(customHeaders) : null,
|
||||||
|
compressEnabled: compressEnabled !== false,
|
||||||
|
compressTrigger: typeof compressTrigger === "number" ? compressTrigger : 0,
|
||||||
|
contextLimit: typeof contextLimit === "number" ? contextLimit : 128000,
|
||||||
|
keepRounds: typeof keepRounds === "number" ? keepRounds : 3,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
import { useAuth } from "@/components/AuthProvider"
|
import { useAuth } from "@/components/AuthProvider"
|
||||||
import { useState, useCallback, useEffect, useRef } from "react"
|
import { useState, useCallback, useEffect, useRef } from "react"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
import { Plus, MessageSquare, Search, Settings, LogOut, Pin, Archive, Trash2, MoreVertical, Download, ChevronDown, ChevronRight, Pencil, Check, X, ArrowLeft } from "lucide-react"
|
import { Plus, MessageSquare, Search, Settings, LogOut, Pin, Archive, Trash2, MoreVertical, Download, Upload, ChevronDown, ChevronRight, Pencil, Check, X, ArrowLeft } from "lucide-react"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input"
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||||
@ -40,6 +40,7 @@ export default function HomePage() {
|
|||||||
const [editingId, setEditingId] = useState<string | null>(null)
|
const [editingId, setEditingId] = useState<string | null>(null)
|
||||||
const [editTitle, setEditTitle] = useState("")
|
const [editTitle, setEditTitle] = useState("")
|
||||||
const editInputRef = useRef<HTMLInputElement>(null)
|
const editInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!authLoading && !user) router.push("/login")
|
if (!authLoading && !user) router.push("/login")
|
||||||
@ -131,6 +132,38 @@ export default function HomePage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const importSession = async (file: File) => {
|
||||||
|
try {
|
||||||
|
const text = await file.text()
|
||||||
|
const data = JSON.parse(text)
|
||||||
|
const res = await fetch("/api/chat/sessions/import", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
const s = await res.json()
|
||||||
|
setSessions((prev) => [s, ...prev])
|
||||||
|
setActiveSessionId(s.id)
|
||||||
|
} else {
|
||||||
|
const err = await res.json().catch(() => ({ error: "导入失败" }))
|
||||||
|
alert(err.error || "导入失败")
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
alert("文件格式无效,请选择 JSON 格式的导出文件")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleImportClick = () => {
|
||||||
|
fileInputRef.current?.click()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0]
|
||||||
|
if (file) importSession(file)
|
||||||
|
if (fileInputRef.current) fileInputRef.current.value = ""
|
||||||
|
}
|
||||||
|
|
||||||
if (authLoading || loading) {
|
if (authLoading || loading) {
|
||||||
return <div className="flex items-center justify-center min-h-screen"><p>加载中...</p></div>
|
return <div className="flex items-center justify-center min-h-screen"><p>加载中...</p></div>
|
||||||
}
|
}
|
||||||
@ -146,6 +179,9 @@ export default function HomePage() {
|
|||||||
<Button variant="ghost" size="icon" onClick={() => setSettingsOpen(true)} title="设置">
|
<Button variant="ghost" size="icon" onClick={() => setSettingsOpen(true)} title="设置">
|
||||||
<Settings className="h-4 w-4" />
|
<Settings className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" onClick={handleImportClick} title="导入会话">
|
||||||
|
<Upload className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
<Button variant="ghost" size="icon" onClick={() => logout()} title="退出登录">
|
<Button variant="ghost" size="icon" onClick={() => logout()} title="退出登录">
|
||||||
<LogOut className="h-4 w-4" />
|
<LogOut className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
@ -249,6 +285,13 @@ export default function HomePage() {
|
|||||||
{user?.email}
|
{user?.email}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept=".json"
|
||||||
|
className="hidden"
|
||||||
|
onChange={handleFileChange}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Main Chat Area: desktop always, mobile when session active */}
|
{/* Main Chat Area: desktop always, mobile when session active */}
|
||||||
|
|||||||
@ -433,15 +433,31 @@ export function ChatArea({ sessionId, onSessionUpdated }: { sessionId: string; o
|
|||||||
const lastUserMsg = [...msgs].reverse().find((m) => m.role === "user")
|
const lastUserMsg = [...msgs].reverse().find((m) => m.role === "user")
|
||||||
if (!lastUserMsg) return
|
if (!lastUserMsg) return
|
||||||
|
|
||||||
|
const content = lastUserMsg.content
|
||||||
await fetch(`/api/chat/sessions/${sessionId}/rollback`, {
|
await fetch(`/api/chat/sessions/${sessionId}/rollback`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ messageId: lastUserMsg.id }),
|
body: JSON.stringify({ messageId: lastUserMsg.id, includeTarget: true }),
|
||||||
})
|
})
|
||||||
const res = await fetch(`/api/chat/sessions/${sessionId}`)
|
const res = await fetch(`/api/chat/sessions/${sessionId}`)
|
||||||
if (res.ok) setChatSession(await res.json())
|
if (res.ok) setChatSession(await res.json())
|
||||||
onSessionUpdated()
|
onSessionUpdated()
|
||||||
await sendMessage(lastUserMsg.content)
|
await sendMessage(content)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCompress = async () => {
|
||||||
|
if (isStreaming) return
|
||||||
|
const res = await fetch(`/api/chat/sessions/${sessionId}/compress`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
fetchSession()
|
||||||
|
onSessionUpdated()
|
||||||
|
} else {
|
||||||
|
const err = await res.json().catch(() => ({ error: "压缩失败" }))
|
||||||
|
alert(err.error || "压缩失败")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const messages = chatSession?.messages || []
|
const messages = chatSession?.messages || []
|
||||||
@ -781,6 +797,12 @@ export function ChatArea({ sessionId, onSessionUpdated }: { sessionId: string; o
|
|||||||
<SheetTitle>调试信息</SheetTitle>
|
<SheetTitle>调试信息</SheetTitle>
|
||||||
</SheetHeader>
|
</SheetHeader>
|
||||||
<ScrollArea className="h-[calc(100vh-80px)] px-6 py-4">
|
<ScrollArea className="h-[calc(100vh-80px)] px-6 py-4">
|
||||||
|
<div className="mb-4">
|
||||||
|
<Button variant="outline" size="sm" onClick={handleCompress} disabled={isStreaming} className="w-full">
|
||||||
|
压缩上下文 (Compress)
|
||||||
|
</Button>
|
||||||
|
<p className="text-[10px] text-muted-foreground mt-1 text-center">压缩当前所有对话消息为摘要,并清空消息列表</p>
|
||||||
|
</div>
|
||||||
{debugRounds.length === 0 ? (
|
{debugRounds.length === 0 ? (
|
||||||
<p className="text-sm text-muted-foreground text-center py-8">发送消息后,此处将显示调试信息</p>
|
<p className="text-sm text-muted-foreground text-center py-8">发送消息后,此处将显示调试信息</p>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@ -18,10 +18,12 @@ import {
|
|||||||
|
|
||||||
interface Provider {
|
interface Provider {
|
||||||
id: string; name: string; baseUrl: string; apiKey: string; modelName: string; customHeaders: string | null
|
id: string; name: string; baseUrl: string; apiKey: string; modelName: string; customHeaders: string | null
|
||||||
|
compressEnabled: boolean; compressTrigger: number; contextLimit: number; keepRounds: number
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Preset {
|
interface Preset {
|
||||||
id: string; name: string; isDefault: boolean
|
id: string; name: string; isDefault: boolean
|
||||||
|
compressPrompt: string | null; compressRole: string
|
||||||
fragments: Array<{ id: string; name: string; content: string; enabled: boolean; order: number }>
|
fragments: Array<{ id: string; name: string; content: string; enabled: boolean; order: number }>
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -86,14 +88,51 @@ export function SettingsPanel({ open, onClose, onUpdate }: { open: boolean; onCl
|
|||||||
}, [refreshAll, onUpdate])
|
}, [refreshAll, onUpdate])
|
||||||
|
|
||||||
// --- Provider CRUD ---
|
// --- Provider CRUD ---
|
||||||
const [newProvider, setNewProvider] = useState({ name: "", baseUrl: "", apiKey: "", modelName: "" })
|
const defaultProvider = { name: "", baseUrl: "", apiKey: "", modelName: "", compressEnabled: true, compressTrigger: 0, contextLimit: 128000, keepRounds: 3 }
|
||||||
|
const [newProvider, setNewProvider] = useState(defaultProvider)
|
||||||
|
const [editingProviderId, setEditingProviderId] = useState<string | null>(null)
|
||||||
|
|
||||||
const addProvider = async () => {
|
const startEditProvider = (p: Provider) => {
|
||||||
await fetch("/api/providers", {
|
setEditingProviderId(p.id)
|
||||||
method: "POST", headers: { "Content-Type": "application/json" },
|
setNewProvider({
|
||||||
body: JSON.stringify(newProvider),
|
name: p.name, baseUrl: p.baseUrl, apiKey: p.apiKey, modelName: p.modelName,
|
||||||
|
compressEnabled: p.compressEnabled ?? true,
|
||||||
|
compressTrigger: p.compressTrigger ?? 0,
|
||||||
|
contextLimit: p.contextLimit ?? 128000,
|
||||||
|
keepRounds: p.keepRounds ?? 3,
|
||||||
})
|
})
|
||||||
setNewProvider({ name: "", baseUrl: "", apiKey: "", modelName: "" })
|
}
|
||||||
|
|
||||||
|
const cancelEditProvider = () => {
|
||||||
|
setEditingProviderId(null)
|
||||||
|
setNewProvider(defaultProvider)
|
||||||
|
}
|
||||||
|
|
||||||
|
const saveProvider = async () => {
|
||||||
|
if (!newProvider.name || !newProvider.baseUrl || !newProvider.modelName) return
|
||||||
|
const body: Record<string, unknown> = {
|
||||||
|
name: newProvider.name, baseUrl: newProvider.baseUrl, modelName: newProvider.modelName,
|
||||||
|
compressEnabled: newProvider.compressEnabled,
|
||||||
|
compressTrigger: Number(newProvider.compressTrigger) || 0,
|
||||||
|
contextLimit: Number(newProvider.contextLimit) || 128000,
|
||||||
|
keepRounds: Number(newProvider.keepRounds) || 3,
|
||||||
|
}
|
||||||
|
if (newProvider.apiKey && newProvider.apiKey !== "****") {
|
||||||
|
body.apiKey = newProvider.apiKey
|
||||||
|
}
|
||||||
|
if (editingProviderId) {
|
||||||
|
await fetch(`/api/providers/${editingProviderId}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
if (!newProvider.apiKey) return
|
||||||
|
await fetch("/api/providers", {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
cancelEditProvider()
|
||||||
refresh()
|
refresh()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -395,26 +434,90 @@ export function SettingsPanel({ open, onClose, onUpdate }: { open: boolean; onCl
|
|||||||
{tab === "providers" && (
|
{tab === "providers" && (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="space-y-4 border rounded-lg p-4">
|
<div className="space-y-4 border rounded-lg p-4">
|
||||||
<h3 className="font-semibold text-sm">添加新 Provider</h3>
|
<h3 className="font-semibold text-sm">{editingProviderId ? "编辑 Provider" : "添加新 Provider"}</h3>
|
||||||
<div className="space-y-2">
|
<div className="grid grid-cols-2 gap-2">
|
||||||
<Label className="text-xs">名称</Label>
|
<div className="space-y-2">
|
||||||
<Input placeholder="我的 DeepSeek" value={newProvider.name} onChange={(e) => setNewProvider({ ...newProvider, name: e.target.value })} />
|
<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">模型名称</Label>
|
||||||
|
<Input placeholder="deepseek-chat" value={newProvider.modelName} onChange={(e) => setNewProvider({ ...newProvider, modelName: e.target.value })} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label className="text-xs">API 地址 (Base URL)</Label>
|
<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 })} />
|
<Input placeholder="https://api.deepseek.com" value={newProvider.baseUrl} onChange={(e) => setNewProvider({ ...newProvider, baseUrl: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label className="text-xs">API Key</Label>
|
<Label className="text-xs">API Key {editingProviderId ? "(留空则不修改)" : ""}</Label>
|
||||||
<Input type="password" placeholder="sk-..." value={newProvider.apiKey} onChange={(e) => setNewProvider({ ...newProvider, apiKey: e.target.value })} />
|
<Input type="password" placeholder="sk-..." value={newProvider.apiKey} onChange={(e) => setNewProvider({ ...newProvider, apiKey: e.target.value })} />
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="text-xs">模型名称</Label>
|
<Accordion>
|
||||||
<Input placeholder="deepseek-chat" value={newProvider.modelName} onChange={(e) => setNewProvider({ ...newProvider, modelName: e.target.value })} />
|
<AccordionItem value="compress">
|
||||||
|
<AccordionTrigger className="text-xs font-medium">上下文压缩设置</AccordionTrigger>
|
||||||
|
<AccordionContent className="space-y-3 pt-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">关闭后不会自动压缩上下文(1M 上下文模型建议关闭)</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={newProvider.compressEnabled}
|
||||||
|
onCheckedChange={(v) => setNewProvider({ ...newProvider, compressEnabled: v })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{newProvider.compressEnabled && (
|
||||||
|
<>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-xs">触发压缩的 Token 阈值(0 = 禁用自动压缩)</Label>
|
||||||
|
<Input
|
||||||
|
type="number" min="0" step="1000"
|
||||||
|
placeholder="例如 4000(超过 4000 tokens 时自动压缩)"
|
||||||
|
value={newProvider.compressTrigger || 0}
|
||||||
|
onChange={(e) => setNewProvider({ ...newProvider, compressTrigger: parseInt(e.target.value) || 0 })}
|
||||||
|
/>
|
||||||
|
<p className="text-[10px] text-muted-foreground">当预估输入 tokens 数超过此值时,自动触发压缩。设为 0 则只可手动压缩</p>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-xs">上下文窗口大小</Label>
|
||||||
|
<Input
|
||||||
|
type="number" min="0" step="1000"
|
||||||
|
placeholder="128000"
|
||||||
|
value={newProvider.contextLimit}
|
||||||
|
onChange={(e) => setNewProvider({ ...newProvider, contextLimit: parseInt(e.target.value) || 128000 })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-xs">保留最近对话轮数</Label>
|
||||||
|
<Input
|
||||||
|
type="number" min="1" max="100"
|
||||||
|
placeholder="3"
|
||||||
|
value={newProvider.keepRounds}
|
||||||
|
onChange={(e) => setNewProvider({ ...newProvider, keepRounds: parseInt(e.target.value) || 3 })}
|
||||||
|
/>
|
||||||
|
<p className="text-[10px] text-muted-foreground">压缩后保留的完整对话轮数(用户+AI 各算一轮)</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</AccordionContent>
|
||||||
|
</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button size="sm" onClick={saveProvider}>
|
||||||
|
{editingProviderId ? <Check className="h-3 w-3 mr-1" /> : <Plus className="h-3 w-3 mr-1" />}
|
||||||
|
{editingProviderId ? "保存" : "添加"}
|
||||||
|
</Button>
|
||||||
|
{editingProviderId && (
|
||||||
|
<Button size="sm" variant="outline" onClick={cancelEditProvider}>
|
||||||
|
<X className="h-3 w-3 mr-1" />取消
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<Button size="sm" onClick={addProvider}>
|
|
||||||
<Plus className="h-3 w-3 mr-1" />添加
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
@ -427,14 +530,21 @@ export function SettingsPanel({ open, onClose, onUpdate }: { open: boolean; onCl
|
|||||||
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => testProvider(p.id)}>
|
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => testProvider(p.id)}>
|
||||||
<Play className="h-3 w-3" />
|
<Play className="h-3 w-3" />
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => startEditProvider(p)} title="编辑">
|
||||||
|
<Pencil className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => deleteProvider(p.id)}>
|
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => deleteProvider(p.id)}>
|
||||||
<Trash2 className="h-3 w-3" />
|
<Trash2 className="h-3 w-3" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs text-muted-foreground">{p.baseUrl} | {p.modelName} | Key: {p.apiKey}</div>
|
<div className="text-xs text-muted-foreground">{p.modelName} @ {p.baseUrl}</div>
|
||||||
|
<div className="text-xs text-muted-foreground">
|
||||||
|
压缩: {p.compressEnabled && p.compressTrigger > 0 ? `> ${p.compressTrigger} tokens 触发, 保留 ${p.keepRounds} 轮` : "已禁用"}
|
||||||
|
{" | "}上下文: {p.contextLimit}
|
||||||
|
</div>
|
||||||
{testResults[p.id] && (
|
{testResults[p.id] && (
|
||||||
<p className={`text-xs ${testResults[p.id].startsWith("成功") ? "text-green-600" : "text-destructive"}`}>
|
<p className={`text-xs ${testResults[p.id].startsWith("成功") || testResults[p.id].startsWith("已连接") ? "text-green-600" : "text-destructive"}`}>
|
||||||
{testResults[p.id]}
|
{testResults[p.id]}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
@ -494,6 +604,61 @@ export function SettingsPanel({ open, onClose, onUpdate }: { open: boolean; onCl
|
|||||||
<Plus className="h-3 w-3 mr-1" />添加片段
|
<Plus className="h-3 w-3 mr-1" />添加片段
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{/* Compression Settings for Preset */}
|
||||||
|
<Accordion>
|
||||||
|
<AccordionItem value="compress">
|
||||||
|
<AccordionTrigger className="text-xs font-medium">压缩提示词设置</AccordionTrigger>
|
||||||
|
<AccordionContent className="space-y-3 pt-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-xs">压缩提示词(用 {"{{content}}"} 表示待压缩内容)</Label>
|
||||||
|
<Textarea
|
||||||
|
className="text-xs min-h-[60px] font-mono"
|
||||||
|
placeholder={`请为以下对话历史生成一个简洁的结构化摘要,保留关键信息、决策和动作:
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
|
请用中文输出摘要。`}
|
||||||
|
value={preset.compressPrompt || ""}
|
||||||
|
onChange={(e) => {
|
||||||
|
setPresets(prev => prev.map(p => p.id === preset.id ? { ...p, compressPrompt: e.target.value || null } : p))
|
||||||
|
const key = `preset-compress-${preset.id}`
|
||||||
|
if (debounceTimers.current[key]) clearTimeout(debounceTimers.current[key])
|
||||||
|
debounceTimers.current[key] = setTimeout(async () => {
|
||||||
|
await fetch(`/api/presets/${preset.id}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ compressPrompt: e.target.value || null }),
|
||||||
|
})
|
||||||
|
}, 300)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-xs">压缩内容放置位置</Label>
|
||||||
|
<select
|
||||||
|
className="w-full border rounded-md px-3 py-1.5 text-sm bg-background"
|
||||||
|
value={preset.compressRole || "system"}
|
||||||
|
onChange={(e) => {
|
||||||
|
const val = e.target.value
|
||||||
|
setPresets(prev => prev.map(p => p.id === preset.id ? { ...p, compressRole: val } : p))
|
||||||
|
const key = `preset-compress-role-${preset.id}`
|
||||||
|
if (debounceTimers.current[key]) clearTimeout(debounceTimers.current[key])
|
||||||
|
debounceTimers.current[key] = setTimeout(async () => {
|
||||||
|
await fetch(`/api/presets/${preset.id}`, {
|
||||||
|
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ compressRole: val }),
|
||||||
|
})
|
||||||
|
}, 300)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="system">作为 System 消息(推荐)</option>
|
||||||
|
<option value="assistant">作为 Assistant 消息</option>
|
||||||
|
</select>
|
||||||
|
<p className="text-[10px] text-muted-foreground">压缩后的摘要将以此角色插入上下文。选择 Assistant 时部分模型可能不会遵守</p>
|
||||||
|
</div>
|
||||||
|
</AccordionContent>
|
||||||
|
</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
|
||||||
{/* System Prompt Preview */}
|
{/* System Prompt Preview */}
|
||||||
{preset.fragments.filter(f => f.enabled).length > 0 && (
|
{preset.fragments.filter(f => f.enabled).length > 0 && (
|
||||||
<details className="text-xs">
|
<details className="text-xs">
|
||||||
|
|||||||
在新工单中引用
屏蔽一个用户