Merge branch 'bug-fix'

This commit is contained in:
RockYang
2025-09-08 15:19:01 +08:00
23 changed files with 623 additions and 397 deletions

View File

@@ -70,17 +70,18 @@ type SdTaskParams struct {
// DallTask DALL-E task
type DallTask struct {
ModelId uint `json:"model_id"`
ModelName string `json:"model_name"`
Id uint `json:"id"`
UserId uint `json:"user_id"`
Prompt string `json:"prompt"`
N int `json:"n"`
Quality string `json:"quality"`
Size string `json:"size"`
Style string `json:"style"`
Power int `json:"power"`
TranslateModelId int `json:"translate_model_id"` // 提示词翻译模型ID
ModelId uint `json:"model_id"`
ModelName string `json:"model_name"`
Image []string `json:"image,omitempty"`
Id uint `json:"id"`
UserId uint `json:"user_id"`
Prompt string `json:"prompt"`
N int `json:"n"`
Quality string `json:"quality"`
Size string `json:"size"`
Style string `json:"style"`
Power int `json:"power"`
TranslateModelId int `json:"translate_model_id"` // 提示词翻译模型ID
}
type SunoTask struct {

View File

@@ -244,7 +244,16 @@ func (h *ModerationHandler) UpdateModeration(c *gin.Context) {
return
}
err := h.DB.Where("name", types.ConfigKeyModeration).FirstOrCreate(&model.Config{Name: types.ConfigKeyModeration, Value: utils.JsonEncode(data)}).Error
var config model.Config
err := h.DB.Where("name", types.ConfigKeyModeration).First(&config).Error
if err != nil {
config.Name = types.ConfigKeyModeration
config.Value = utils.JsonEncode(data)
err = h.DB.Create(&config).Error
} else {
config.Value = utils.JsonEncode(data)
err = h.DB.Updates(&config).Error
}
if err != nil {
resp.ERROR(c, err.Error())
return

View File

@@ -194,7 +194,7 @@ func (h *ChatHandler) sendMessage(ctx context.Context, input ChatInput, c *gin.C
}
if userVo.Power < input.ChatModel.Power {
return fmt.Errorf("您当前剩余算力 %d 已不足以支付当前模型的单次对话需要消耗的算力 %d[立即购买](/member)。", userVo.Power, input.ChatModel.Power)
return fmt.Errorf("您的算力不足,请购买算力。")
}
if userVo.ExpiredTime > 0 && userVo.ExpiredTime <= time.Now().Unix() {
@@ -338,16 +338,14 @@ func (h *ChatHandler) sendMessage(ctx context.Context, input ChatInput, c *gin.C
},
})
} else {
// 如果不是逆向模型,则提取文件内容
modelValue := input.ChatModel.Value
if !(strings.Contains(modelValue, "-all") || strings.HasPrefix(modelValue, "gpt-4-gizmo") || strings.HasPrefix(modelValue, "claude")) {
content, err := utils.ReadFileContent(file.URL, h.App.Config.TikaHost)
if err != nil {
logger.Error("error with read file: ", err)
continue
} else {
fileContents = append(fileContents, fmt.Sprintf("%s 文件内容:%s", file.Name, content))
}
// 处理文件,提取文件内容
content, err := utils.ReadFileContent(file.URL, h.App.Config.TikaHost)
if err != nil {
logger.Error("error with read file: ", err)
continue
} else {
fileContents = append(fileContents, fmt.Sprintf("%s 文件内容:%s", file.Name, content))
logger.Debugf("fileContents: %s", fileContents)
}
}
}

View File

@@ -118,6 +118,7 @@ func (h *DallJobHandler) Image(c *gin.Context) {
UserId: uint(userId),
ModelId: chatModel.Id,
ModelName: chatModel.Value,
Image: data.Image,
Prompt: data.Prompt,
Quality: data.Quality,
Size: data.Size,

View File

@@ -112,8 +112,8 @@ func (h *UserHandler) Register(c *gin.Context) {
return
}
// 如果注册方式不是账号密码,则需要验证
if h.captchaService.GetConfig().Enabled && data.RegWay != "username" {
// 人机验证
if h.captchaService.GetConfig().Enabled {
var check bool
if data.X != 0 {
check = h.captchaService.SlideCheck(data)

View File

@@ -16,6 +16,7 @@ import (
"geekai/store"
"geekai/store/model"
"geekai/utils"
"strings"
"time"
"github.com/go-redis/redis/v8"
@@ -94,12 +95,14 @@ func (s *Service) Run() {
}
type imgReq struct {
Model string `json:"model"`
Prompt string `json:"prompt"`
N int `json:"n,omitempty"`
Size string `json:"size,omitempty"`
Quality string `json:"quality,omitempty"`
Style string `json:"style,omitempty"`
Model string `json:"model"`
Image []string `json:"image,omitempty"`
Prompt string `json:"prompt"`
N int `json:"n,omitempty"`
Size string `json:"size,omitempty"`
Quality string `json:"quality,omitempty"`
Style string `json:"style,omitempty"`
ResponseFormat string `json:"response_format,omitempty"`
}
type imgRes struct {
@@ -157,6 +160,11 @@ func (s *Service) Image(task types.DallTask, sync bool) (string, error) {
Style: task.Style,
Quality: task.Quality,
}
// 图片编辑
if len(task.Image) > 0 {
reqBody.Prompt = fmt.Sprintf("%s, %s", strings.Join(task.Image, " "), task.Prompt)
}
logger.Infof("Channel:%s, API KEY:%s, BODY: %+v", apiURL, apiKey.Value, reqBody)
r, err := s.httpClient.R().SetHeader("Body-Type", "application/json").
SetHeader("Authorization", "Bearer "+apiKey.Value).

View File

@@ -7,8 +7,8 @@ package sms
// * @Author yangjian102621@163.com
// * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
const Ali = "ALI"
const Bao = "BAO"
const Ali = "aliyun"
const Bao = "bao"
type Service interface {
SendVerifyCode(mobile string, code int) error

View File

@@ -49,6 +49,77 @@
}
}
}
// .file-preview-list {
// display: flex;
// flex-wrap: wrap;
// padding: 6px 10px 0 10px;
// gap: 8px;
// .file-preview-item {
// position: relative;
// display: inline-flex;
// align-items: center;
// border: 1px solid #e8e8e8;
// background: var(--van-cell-background);
// border-radius: 8px;
// padding: 6px 26px 6px 6px;
// overflow: hidden;
// .thumb {
// width: 56px;
// height: 56px;
// border-radius: 6px;
// overflow: hidden;
// .img {
// width: 56px;
// height: 56px;
// }
// .size {
// position: absolute;
// left: 6px;
// bottom: 6px;
// background: rgba(0, 0, 0, 0.5);
// color: #fff;
// font-size: 10px;
// padding: 1px 4px;
// border-radius: 3px;
// }
// }
// .doc {
// display: inline-flex;
// align-items: center;
// gap: 6px;
// max-width: 220px;
// .icon {
// width: 24px;
// height: 24px;
// }
// .name {
// white-space: nowrap;
// text-overflow: ellipsis;
// overflow: hidden;
// max-width: 180px;
// }
// .size {
// color: #8c8c8c;
// font-size: 12px;
// margin-left: 6px;
// }
// }
// .remove {
// position: absolute;
// right: 6px;
// top: 6px;
// font-size: 14px;
// color: #999;
// }
// }
// }
}
}

View File

@@ -232,6 +232,7 @@ const copyContent = (text) => {
flex-flow: row;
margin-right: 10px;
position: relative;
justify-content: start;
.el-image {
border: 1px solid #e3e3e3;
@@ -365,6 +366,7 @@ const copyContent = (text) => {
flex-flow: row;
margin-right: 10px;
position: relative;
justify-content: end;
.el-image {
border: 1px solid #e3e3e3;

View File

@@ -81,6 +81,7 @@ const removeFile = (file) => {
border: 1px solid #e3e3e3;
padding: 6px;
margin-right: 10px;
max-height: 54px;
.icon {
.el-image {
@@ -91,10 +92,10 @@ const removeFile = (file) => {
.body {
margin-left: 5px;
font-size: 14px;
font-size: 12px;
.title {
line-height: 24px;
// line-height: 20px;
color: #0d0d0d;
}

View File

@@ -85,7 +85,7 @@
<el-icon :size="40" class="el-icon--upload"><UploadFilled /></el-icon>
<div class="el-upload__text">拖拽图片到此处 <em>点击上传</em></div>
<template #tip>
<div class="el-upload__tip text-center">
<div class="el-upload__tip text-gray-500 text-sm">
支持 JPGPNG 格式最多上传 {{ maxCount }} 单张最大 5MB
</div>
</template>

View File

@@ -398,7 +398,7 @@ const activeName = ref('')
const wxImg = ref('/images/wx.png')
const captchaRef = ref(null)
// eslint-disable-next-line no-undef
const emits = defineEmits(['hide', 'success'])
const emits = defineEmits(['hide', 'success', 'changeActive'])
const action = ref('login')
const enableCaptcha = ref(false)
const captchaType = ref('')
@@ -411,6 +411,13 @@ const showPrivacy = ref(false)
const agreementHtml = ref('')
const privacyHtml = ref('')
watch(
() => login.value,
(newValue) => {
emits('changeActive', newValue)
}
)
onMounted(() => {
getSystemInfo()
.then((res) => {
@@ -649,7 +656,7 @@ const submitRegister = () => {
if (!agreeChecked.value) {
return ElMessage.error('请先阅读并同意《用户协议》和《隐私政策》')
}
if (enableCaptcha.value && activeName.value === 'username') {
if (enableCaptcha.value) {
captchaRef.value.loadCaptcha()
action.value = 'register'
} else {

View File

@@ -4,15 +4,14 @@
{{ btnText }}
</el-button>
<captcha @success="doSendMsg" ref="captchaRef" />
<captcha @success="doSendMsg" ref="captchaRef" :type="captchaType" />
</el-container>
</template>
<script setup>
// 发送短信验证码组件
import Captcha from '@/components/Captcha.vue'
import { getSystemInfo } from '@/store/cache'
import { httpPost } from '@/utils/http'
import { httpGet, httpPost } from '@/utils/http'
import { validateEmail, validateMobile } from '@/utils/validate'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
@@ -29,10 +28,12 @@ const props = defineProps({
const btnText = ref('发送验证码')
const canSend = ref(true)
const captchaRef = ref(null)
const enableVerify = ref(false)
const enableCaptcha = ref(false)
const captchaType = ref('')
getSystemInfo().then((res) => {
enableVerify.value = res.data['enabled_verify']
httpGet('/api/captcha/config').then((res) => {
enableCaptcha.value = res.data['enabled']
captchaType.value = res.data['type']
})
const sendMsg = () => {
@@ -43,7 +44,7 @@ const sendMsg = () => {
return ElMessage.error('请输入合法的邮箱地址')
}
if (enableVerify.value) {
if (enableCaptcha.value) {
captchaRef.value.loadCaptcha()
} else {
doSendMsg({})

View File

@@ -1,12 +1,17 @@
<template>
<div class="mobile-message-prompt">
<div class="chat-item">
<div ref="contentRef" :data-clipboard-text="content" class="content" v-html="content"></div>
<div class="triangle"></div>
<div class="mb-2">
<MobileFileList :files="files" direction="col" />
</div>
<div class="flex justify-end">
<div class="chat-item">
<div ref="contentRef" :data-clipboard-text="content" class="content" v-html="content"></div>
<div class="triangle"></div>
</div>
<div class="chat-icon">
<van-image :src="icon" />
<div class="chat-icon">
<van-image :src="icon" />
</div>
</div>
</div>
</template>
@@ -15,6 +20,7 @@
import Clipboard from 'clipboard'
import { showNotify } from 'vant'
import { onMounted, ref } from 'vue'
import MobileFileList from '@/components/mobile/MobileFileList.vue'
// eslint-disable-next-line no-unused-vars,no-undef
const props = defineProps({
@@ -34,6 +40,7 @@ const contentRef = ref(null)
const content = computed(() => {
return props.content.text
})
const files = computed(() => props.content.files || [])
onMounted(() => {
const clipboard = new Clipboard(contentRef.value)
clipboard.on('success', () => {
@@ -47,9 +54,6 @@ onMounted(() => {
<style lang="scss">
.mobile-message-prompt {
display: flex;
justify-content: flex-end;
.chat-icon {
margin-left: 5px;
@@ -67,6 +71,51 @@ onMounted(() => {
padding: 0 5px 0 0;
overflow: hidden;
.file-list {
margin: 0 0 6px 0;
.image {
.img {
width: 120px;
height: 120px;
border-radius: 6px;
margin-bottom: 6px;
}
}
.doc {
display: flex;
align-items: center;
gap: 6px;
background: #ffffff;
border: 1px solid #e8e8e8;
border-radius: 8px;
padding: 6px 8px;
margin-bottom: 6px;
.icon {
width: 24px;
height: 24px;
}
.meta {
display: flex;
align-items: center;
gap: 6px;
.name {
max-width: 180px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.size {
color: #8c8c8c;
font-size: 12px;
}
}
}
}
.triangle {
width: 0;
height: 0;

View File

@@ -7,25 +7,52 @@
<div class="chat-item">
<div class="triangle"></div>
<div class="content-box" ref="contentRef">
<div
:data-clipboard-text="orgContent"
class="content content-mobile"
v-html="content"
v-if="content"
></div>
<div v-if="content" class="content content-mobile" v-html="content"></div>
<div v-else-if="error">
<div class="content content-mobile !text-red-500">{{ error }}</div>
</div>
<div class="content content-mobile flex justify-start items-center" v-else>
<span class="mr-2">AI 思考中</span> <Thinking :duration="1.5" />
</div>
</div>
<!-- 操作按钮区域 -->
<div class="action-buttons" v-if="showActions && orgContent">
<van-button
size="mini"
type="primary"
plain
@click="handleRegenerate"
:disabled="isGenerating"
>
{{ isGenerating ? '生成中...' : '重新生成' }}
</van-button>
<van-button
size="mini"
type="success"
:data-clipboard-text="orgContent"
class="copy-answer"
plain
>
复制回答
</van-button>
</div>
</div>
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { showImagePreview } from 'vant'
import Thinking from '../Thinking.vue'
import hl from 'highlight.js'
import MarkdownIt from 'markdown-it'
import emoji from 'markdown-it-emoji'
import mathjaxPlugin from 'markdown-it-mathjax3'
import { processContent } from '@/utils/libs'
import Clipboard from 'clipboard'
import { showNotify } from 'vant'
const props = defineProps({
content: {
type: Object,
@@ -42,12 +69,66 @@ const props = defineProps({
type: String,
default: '/images/gpt-icon.png',
},
showActions: {
type: Boolean,
default: true,
},
isGenerating: {
type: Boolean,
default: false,
},
messageId: {
type: [String, Number],
default: '',
},
error: {
type: String,
default: '',
},
})
const content = computed(() => {
return props.content.text
const emits = defineEmits(['regenerate'])
const md = new MarkdownIt({
breaks: true,
html: true,
linkify: true,
typographer: true,
highlight: function (str, lang) {
const codeIndex = parseInt(Date.now()) + Math.floor(Math.random() * 10000000)
// 显示复制代码按钮
const copyBtn = `<span class="copy-code-mobile" data-clipboard-action="copy" data-clipboard-target="#copy-target-${codeIndex}">复制</span>
<textarea style="position: absolute;top: -9999px;left: -9999px;z-index: -9999;" id="copy-target-${codeIndex}">${str.replace(
/<\/textarea>/g,
'&lt;/textarea>'
)}</textarea>`
if (lang && hl.getLanguage(lang)) {
const langHtml = `<span class="lang-name">${lang}</span>`
// 处理代码高亮
const preCode = hl.highlight(str, { language: lang }).value
// 将代码包裹在 pre 中
return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code>${copyBtn} ${langHtml}</pre>`
}
// 处理代码高亮
const preCode = md.utils.escapeHtml(str)
// 将代码包裹在 pre 中
return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code>${copyBtn}</pre>`
},
})
md.use(mathjaxPlugin)
md.use(emoji)
const content = computed(() => {
return md.render(processContent(props.content.text))
})
const contentRef = ref(null)
// 处理重新生成
const handleRegenerate = () => {
emits('regenerate', props.messageId)
}
const clipboard = ref(null)
onMounted(() => {
const imgs = contentRef.value.querySelectorAll('img')
for (let i = 0; i < imgs.length; i++) {
@@ -59,6 +140,18 @@ onMounted(() => {
showImagePreview([imgs[i].src])
})
}
clipboard.value = new Clipboard('.copy-answer,.copy-code-mobile')
clipboard.value.on('success', () => {
showNotify({ type: 'success', message: '复制成功', duration: 1000 })
})
clipboard.value.on('error', () => {
showNotify({ type: 'danger', message: '复制失败', duration: 2000 })
})
})
onUnmounted(() => {
clipboard.value.destroy()
})
</script>
@@ -201,6 +294,17 @@ onMounted(() => {
}
}
}
.action-buttons {
margin-top: 8px;
padding-left: 5px;
.van-button {
font-size: 12px;
height: 24px;
padding: 0 8px;
}
}
}
}

View File

@@ -0,0 +1,68 @@
<template>
<div v-if="items.length" :class="[containerClass, direction === 'col' ? '!items-end' : '']">
<div
v-for="(f, idx) in items"
:key="f.url || idx"
:class="[
'relative inline-flex items-center border border-gray-200 rounded-xl bg-white dark:bg-[#2b2b2b] dark:border-gray-700',
isImage(f.ext) ? 'p-0' : 'p-2',
]"
>
<div v-if="isImage(f.ext)" class="relative w-[56px] h-[56px] overflow-hidden rounded-lg">
<img :src="f.url" alt="img" class="w-full h-full object-cover" />
</div>
<div v-else :class="['flex items-center', direction === 'col' ? 'w-full' : 'max-w-[240px]']">
<img :src="GetFileIcon(f.ext)" class="w-10 h-10 mr-2" />
<div class="min-w-0 flex flex-col items-center gap-1 text-sm">
<a
:href="f.url"
target="_blank"
class="truncate block"
:class="direction === 'col' ? 'text-base max-w-full' : 'max-w-[180px]'"
>{{ f.name }}</a
>
<div class="text-xs flex w-full justify-start text-gray-500">
{{ extUpper(f.ext) }} · {{ FormatFileSize(f.size || 0) }}
</div>
</div>
</div>
<button
v-if="removable"
class="absolute -right-2 -top-2 w-5 h-5 rounded-full bg-rose-600 text-white flex items-center justify-center text-[10px]"
@click="onRemove(f, idx)"
>
×
</button>
</div>
</div>
</template>
<script setup>
import { FormatFileSize, GetFileIcon } from '@/store/system'
import { isImage } from '@/utils/libs'
const props = defineProps({
files: {
type: Array,
default: () => [],
},
removable: {
type: Boolean,
default: false,
},
direction: {
type: String,
default: 'row',
},
})
const emits = defineEmits(['remove'])
const items = computed(() => props.files || [])
const onRemove = (f, idx) => emits('remove', { file: f, index: idx })
const direction = computed(() => props.direction)
const containerClass = computed(() =>
props.direction === 'col' ? 'flex flex-col gap-2' : 'flex flex-wrap gap-2 px-2 pt-2'
)
const extUpper = (ext) => (ext || '').replace('.', '').toUpperCase() || 'FILE'
</script>
<style scoped></style>

View File

@@ -134,7 +134,7 @@ const routes = [
name: 'register',
path: '/register',
meta: { title: '用户注册' },
component: () => import('@/views/Register.vue'),
component: () => import('@/views/Login.vue'),
},
{
name: 'resetpassword',

View File

@@ -384,7 +384,7 @@ import FileSelect from '@/components/FileSelect.vue'
import Welcome from '@/components/Welcome.vue'
import { checkSession, getClientId, getSystemInfo } from '@/store/cache'
import { useSharedStore } from '@/store/sharedata'
import { closeLoading, showLoading, showMessageError } from '@/utils/dialog'
import { closeLoading, showLoading, showMessageError, showMessageInfo } from '@/utils/dialog'
import { httpGet, httpPost } from '@/utils/http'
import { isMobile, randString, removeArrayItem, UUID } from '@/utils/libs'
import {
@@ -789,6 +789,7 @@ const sendSSERequest = async (message) => {
}
}
// 回答完毕,更新完整的消息内容
if (data.type === 'complete') {
chatData.value[chatData.value.length - 1] = data.body
}
@@ -1161,7 +1162,7 @@ const stopGenerate = function () {
isGenerating.value = false
httpGet('/api/chat/stop?session_id=' + getClientId())
.then(() => {
console.log('会话已中断')
showMessageInfo('会话已中断')
})
.catch((e) => {
showMessageError('中断对话失败:' + e.message)

View File

@@ -101,6 +101,13 @@
<span v-else>生成中...</span>
</el-button>
</div>
<div class="mt-2 mb-2">
<label class="text-gray-700 font-semibold">参考图(可选)</label>
<div class="py-2">
<ImageUpload v-model="params.image" :max-count="5" :multiple="true" />
</div>
</div>
</el-form>
</div>
<div class="py-4">
@@ -295,6 +302,7 @@ import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, onUnmounted, ref } from 'vue'
import { LazyImg, Waterfall } from 'vue-waterfall-plugin-next'
import 'vue-waterfall-plugin-next/dist/style.css'
import ImageUpload from '@/components/ImageUpload.vue'
const listBoxHeight = ref(0)
// const paramBoxHeight = ref(0)

View File

@@ -22,15 +22,22 @@
class="text-3xl font-semibold m-0 mb-2 tracking-tight"
style="color: var(--login-title-color)"
>
欢迎登录
{{ title }}
</h1>
<p class="text-base m-0 leading-relaxed" style="color: var(--login-subtitle-color)">
登录您的账户以继续使用服务
{{ subtitle }}
</p>
</div>
<div class="login-content">
<login-dialog :show="true" @success="handleLoginSuccess" ref="loginDialogRef" />
<div class="register-content">
<login-dialog
:show="true"
:active="active"
:inviteCode="inviteCode"
@success="handleRegisterSuccess"
@changeActive="handleChangeActive"
ref="loginDialogRef"
/>
</div>
</div>
@@ -42,22 +49,22 @@
<script setup>
import FooterBar from '@/components/FooterBar.vue'
import LoginDialog from '@/components/LoginDialog.vue'
import { setUserToken } from '@/store/session'
import { isMobile } from '@/utils/libs'
import { onMounted, ref } from 'vue'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const loginDialogRef = ref(null)
const token = router.currentRoute.value.query.token
const inviteCode = ref(router.currentRoute.value.query.invite_code || '')
const isRegister = ref(router.currentRoute.value.path === '/register')
const active = ref(isRegister.value ? 'register' : 'login')
const title = computed(() => (isRegister.value ? '用户注册' : '用户登录'))
const subtitle = computed(() =>
isRegister.value ? '创建您的账户以开始使用服务' : '登录您的账户以继续使用服务'
)
if (token) {
setUserToken(token)
router.push('/chat')
}
// 处理登录成功
const handleLoginSuccess = () => {
// 处理注册成功
const handleRegisterSuccess = () => {
if (isMobile()) {
router.push('/mobile')
} else {
@@ -65,10 +72,14 @@ const handleLoginSuccess = () => {
}
}
const handleChangeActive = (newValue) => {
isRegister.value = !newValue
}
onMounted(() => {
// 确保默认显示登录状态
// 确保默认显示注册状态
if (loginDialogRef.value) {
loginDialogRef.value.login = true
loginDialogRef.value.login = !isRegister
}
})
</script>

View File

@@ -1,129 +0,0 @@
<template>
<div
class="min-h-screen flex items-center justify-center p-5 relative overflow-auto"
style="background: var(--login-bg)"
>
<router-link
to="/"
class="fixed top-5 left-5 z-50 flex items-center justify-center w-11 h-11 border border-transparent rounded-xl text-white no-underline shadow-lg backdrop-blur-sm transition-all duration-300 hover:-translate-y-0.5 hover:shadow-xl"
style="background: var(--btnColor)"
title="返回首页"
>
<i class="iconfont icon-home text-xl"></i>
</router-link>
<div class="w-full max-w-md mx-auto">
<div
class="rounded-3xl p-10 shadow-2xl backdrop-blur-sm relative overflow-hidden"
style="background: var(--login-card-bg); border: 1px solid var(--login-card-border)"
>
<div class="absolute top-0 left-0 right-0 h-1" style="background: var(--btnColor)"></div>
<div class="text-center mb-8">
<h1
class="text-3xl font-semibold m-0 mb-2 tracking-tight"
style="color: var(--login-title-color)"
>
用户注册
</h1>
<p class="text-base m-0 leading-relaxed" style="color: var(--login-subtitle-color)">
创建您的账户以开始使用服务
</p>
</div>
<div class="register-content">
<login-dialog
:show="true"
active="register"
:inviteCode="inviteCode"
@success="handleRegisterSuccess"
ref="loginDialogRef"
/>
</div>
</div>
<footer-bar />
</div>
</div>
</template>
<script setup>
import FooterBar from '@/components/FooterBar.vue'
import LoginDialog from '@/components/LoginDialog.vue'
import { isMobile } from '@/utils/libs'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const loginDialogRef = ref(null)
const inviteCode = ref(router.currentRoute.value.query.invite_code || '')
// 处理注册成功
const handleRegisterSuccess = () => {
if (isMobile()) {
router.push('/mobile')
} else {
router.push('/chat')
}
}
onMounted(() => {
// 确保默认显示注册状态
if (loginDialogRef.value) {
loginDialogRef.value.login = false
}
})
</script>
<style scoped>
/* 移动端适配 */
@media (max-width: 768px) {
.min-h-screen {
padding: 1rem;
}
.fixed.top-5.left-5 {
top: 1rem;
left: 1rem;
width: 2.5rem;
height: 2.5rem;
}
.fixed.top-5.left-5 .iconfont {
font-size: 1.125rem;
}
.max-w-md {
margin-top: 3.75rem;
}
.p-10 {
padding: 2rem 1.5rem;
}
.rounded-3xl {
border-radius: 1rem;
}
.text-3xl {
font-size: 1.5rem;
}
.text-base {
font-size: 0.875rem;
}
}
/* 小屏幕手机适配 */
@media (max-width: 480px) {
.p-10 {
padding: 1.5rem 1.25rem;
}
.text-3xl {
font-size: 1.25rem;
}
.text-base {
font-size: 0.875rem;
}
}
</style>

View File

@@ -104,8 +104,12 @@ checkSession()
.then((user) => {
loginUser.value = user
isLogin.value = true
})
.finally(() => {
loading.value = false
finished.value = true
// 加载角色列表
httpGet(`/api/app/list/user`)
httpGet(`/api/app/list`)
.then((res) => {
if (res.data) {
const items = res.data
@@ -139,44 +143,6 @@ checkSession()
showFailToast('加载模型失败: ' + e.message)
})
})
.catch(() => {
loading.value = false
finished.value = true
// 加载角色列表
httpGet('/api/app/list/user')
.then((res) => {
if (res.data) {
const items = res.data
for (let i = 0; i < items.length; i++) {
// console.log(items[i])
roles.value.push({
text: items[i].name,
value: items[i].id,
icon: items[i].icon,
helloMsg: items[i].hello_msg,
})
}
}
})
.catch(() => {
showFailToast('加载聊天角色失败')
})
// 加载模型
httpGet('/api/model/list')
.then((res) => {
if (res.data) {
const items = res.data
for (let i = 0; i < items.length; i++) {
models.value.push({ text: items[i].name, value: items[i].id })
}
}
})
.catch((e) => {
showFailToast('加载模型失败: ' + e.message)
})
})
const onLoad = () => {
checkSession()

View File

@@ -20,8 +20,6 @@
</template>
</van-nav-bar>
<!-- 移除分享面板 -->
<div class="chat-list-wrapper">
<div id="message-list-box" :style="{ height: winHeight + 'px' }" class="message-list-box">
<van-list
@@ -41,6 +39,11 @@
:content="item.content"
:icon="item.icon"
:org-content="item.orgContent"
:message-id="item.id"
:is-generating="isGenerating"
:show-actions="item.showAction"
:error="item.error"
@regenerate="handleRegenerate"
/>
</van-cell>
</van-list>
@@ -50,43 +53,44 @@
<div class="chat-box-wrapper">
<van-sticky ref="bottomBarRef" :offset-bottom="0" position="bottom">
<van-cell-group inset style="--van-cell-background: var(--van-cell-background-light)">
<!-- <div class="flex flex-row p-2">
<file-list :files="[{ url: 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png', name: 'test.png', ext: 'png', size: 1024 }]" />
</div> -->
<van-field v-model="prompt" center clearable placeholder="输入你的问题">
<van-field
v-model="prompt"
center
clearable
placeholder="输入你的问题"
type="textarea"
rows="1"
:autosize="{ maxHeight: 100, minHeight: 20 }"
show-word-limit
@keyup.enter="sendMessage"
>
<template #left-icon>
<!-- <div class="flex flex-row">
<span class="rounded-full size-6 flex items-center justify-center"><i class="iconfont icon-attachment-cl"></i></span>
</div> -->
<van-uploader
:after-read="afterRead"
:max-count="6"
:multiple="true"
:preview-image="false"
accept=".doc,.docx,.jpg,.jpeg,.png,.gif,.bmp,.webp,.svg,.ico,.xls,.xlsx,.ppt,.pptx,.pdf,.mp4,.mp3,.txt,.md,.csv,.html"
>
<van-icon name="photo" />
</van-uploader>
</template>
<template #button>
<van-button size="small" type="primary" @click="sendMessage">发送</van-button>
<van-button size="small" type="primary" v-if="!isGenerating" @click="sendMessage"
>发送</van-button
>
</template>
<template #extra>
<div class="icon-box">
<van-icon v-if="showStopGenerate" name="stop-circle-o" @click="stopGenerate" />
<van-icon v-if="showReGenerate" name="play-circle-o" @click="reGenerate" />
<van-icon v-if="isGenerating" name="stop-circle-o" @click="stopGenerate" />
</div>
</template>
</van-field>
</van-cell-group>
</van-sticky>
<MobileFileList :files="files" removable @remove="onRemovePreview" />
</div>
</div>
<!-- <van-overlay :show="showMic" z-index="100">-->
<!-- <div class="mic-wrapper">-->
<!-- <div class="image">-->
<!-- <van-image-->
<!-- width="100"-->
<!-- height="100"-->
<!-- src="/images/mic.gif"-->
<!-- />-->
<!-- </div>-->
<!-- <van-button type="success" @click="stopVoice">说完了</van-button>-->
<!-- </div>-->
<!-- </van-overlay>-->
</div>
<van-popup v-model:show="showPicker" position="bottom" class="popup">
@@ -114,19 +118,17 @@ import ChatReply from '@/components/mobile/ChatReply.vue'
import { checkSession } from '@/store/cache'
import { getUserToken } from '@/store/session'
import { useSharedStore } from '@/store/sharedata'
import { showMessageError } from '@/utils/dialog'
import { httpGet } from '@/utils/http'
import { showMessageError, showLoading, closeLoading } from '@/utils/dialog'
import { httpGet, httpPost } from '@/utils/http'
import MobileFileList from '@/components/mobile/MobileFileList.vue'
import { processContent, randString, renderInputText, UUID } from '@/utils/libs'
import { fetchEventSource } from '@microsoft/fetch-event-source'
// 移除 Clipboard.js 相关内容
import hl from 'highlight.js'
import 'highlight.js/styles/a11y-dark.css'
import MarkdownIt from 'markdown-it'
import emoji from 'markdown-it-emoji'
import mathjaxPlugin from 'markdown-it-mathjax3'
import { showImagePreview, showNotify, showToast } from 'vant'
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { getClientId } from '@/store/cache'
const winHeight = ref(0)
const navBarRef = ref(null)
@@ -142,7 +144,6 @@ const modelValue = ref('')
const title = ref(router.currentRoute.value.query['title'])
const chatId = ref(router.currentRoute.value.query['chat_id'])
const loginUser = ref(null)
// const showMic = ref(false)
const showPicker = ref(false)
const columns = ref([roles.value, models.value])
const selectedValues = ref([roleId.value, modelId.value])
@@ -218,44 +219,10 @@ const finished = ref(false)
const error = ref(false)
const store = useSharedStore()
const url = ref(location.protocol + '//' + location.host + '/chat/export?chat_id=' + chatId.value)
const md = new MarkdownIt({
breaks: true,
html: true,
linkify: true,
typographer: true,
highlight: function (str, lang) {
const codeIndex = parseInt(Date.now()) + Math.floor(Math.random() * 10000000)
// 显示复制代码按钮
const copyBtn = `<span class="copy-code-mobile" data-clipboard-action="copy" data-clipboard-target="#copy-target-${codeIndex}">复制</span>
<textarea style="position: absolute;top: -9999px;left: -9999px;z-index: -9999;" id="copy-target-${codeIndex}">${str.replace(
/<\/textarea>/g,
'&lt;/textarea>'
)}</textarea>`
if (lang && hl.getLanguage(lang)) {
const langHtml = `<span class="lang-name">${lang}</span>`
// 处理代码高亮
const preCode = hl.highlight(lang, str, true).value
// 将代码包裹在 pre 中
return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code>${copyBtn} ${langHtml}</pre>`
}
// 处理代码高亮
const preCode = md.utils.escapeHtml(str)
// 将代码包裹在 pre 中
return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code>${copyBtn}</pre>`
},
})
md.use(mathjaxPlugin)
md.use(emoji)
onMounted(() => {
winHeight.value =
window.innerHeight - navBarRef.value.$el.offsetHeight - bottomBarRef.value.$el.offsetHeight - 70
// 移除 Clipboard.js 相关内容
})
onUnmounted(() => {
// Remove WebSocket handler cleanup
})
const newChat = (item) => {
@@ -272,10 +239,7 @@ const newChat = (item) => {
}
const onLoad = () => {
// checkSession().then(() => {
// connect()
// }).catch(() => {
// })
// 加载更多消息的逻辑可以在这里实现
}
const loadChatHistory = () => {
@@ -294,6 +258,7 @@ const loadChatHistory = () => {
text: role.hello_msg,
},
orgContent: role.hello_msg,
showAction: false,
})
return
}
@@ -303,19 +268,12 @@ const loadChatHistory = () => {
chatData.value.push(data[i])
continue
}
data[i].orgContent = data[i].content
data[i].content.text = md.render(processContent(data[i].content.text))
data[i].showAction = true
data[i].orgContent = data[i].content.text
chatData.value.push(data[i])
}
nextTick(() => {
hl.configure({ ignoreUnescapedHTML: true })
const blocks = document.querySelector('#message-list-box').querySelectorAll('pre code')
blocks.forEach((block) => {
hl.highlightElement(block)
})
scrollListBox()
})
})
@@ -326,13 +284,12 @@ const loadChatHistory = () => {
// 创建 socket 连接
const prompt = ref('')
const showStopGenerate = ref(false) // 停止生成
const showReGenerate = ref(false) // 重新生成
const previousText = ref('') // 上一次提问
const lineBuffer = ref('') // 输出缓冲行
const canSend = ref(true)
const isGenerating = ref(false)
const isNewMsg = ref(true)
const stream = ref(store.chatStream)
const abortController = new AbortController()
watch(
() => store.chatStream,
(newValue) => {
@@ -340,18 +297,6 @@ watch(
}
)
const disableInput = (force) => {
canSend.value = false
showReGenerate.value = false
showStopGenerate.value = !force
}
const enableInput = () => {
canSend.value = true
showReGenerate.value = previousText.value !== ''
showStopGenerate.value = false
}
// 将聊天框的滚动条滑动到最底部
const scrollListBox = () => {
document
@@ -359,9 +304,27 @@ const scrollListBox = () => {
.scrollTo(0, document.getElementById('message-list-box').scrollHeight + 46)
}
// 滚动到输入区域,确保预览文件可见
const scrollToBottomBar = () => {
try {
// 优先让底部输入区域进入视野
bottomBarRef.value &&
bottomBarRef.value.$el &&
bottomBarRef.value.$el.scrollIntoView({
behavior: 'smooth',
block: 'end',
})
} catch (e) {}
// 再兜底滚动到页面底部
try {
window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'smooth' })
} catch (e) {}
}
// 发送 SSE 请求
const sendSSERequest = async (message) => {
try {
isGenerating.value = true
await fetchEventSource('/api/chat/message', {
method: 'POST',
headers: {
@@ -369,6 +332,13 @@ const sendSSERequest = async (message) => {
},
body: JSON.stringify(message),
openWhenHidden: true,
// 重试机制,避免连接断开后一直重试
retry: 3000,
// 设置重试延迟为0确保不重试
retryDelay: 3000,
// 设置最大重试次数为0
maxRetries: 3,
signal: abortController.signal,
onopen(response) {
if (response.ok && response.status === 200) {
console.log('SSE connection opened')
@@ -380,13 +350,13 @@ const sendSSERequest = async (message) => {
try {
const data = JSON.parse(msg.data)
if (data.type === 'error') {
showMessageError(data.body)
enableInput()
chatData.value[chatData.value.length - 1].error = data.body
isGenerating.value = false
return
}
if (data.type === 'end') {
enableInput()
isGenerating.value = false
lineBuffer.value = '' // 清空缓冲
isNewMsg.value = true
return
@@ -404,15 +374,9 @@ const sendSSERequest = async (message) => {
lineBuffer.value += data.body
const reply = chatData.value[chatData.value.length - 1]
reply['orgContent'] = lineBuffer.value
reply['content']['text'] = md.render(processContent(lineBuffer.value))
reply['content']['text'] = lineBuffer.value
nextTick(() => {
hl.configure({ ignoreUnescapedHTML: true })
const lines = document.querySelectorAll('.message-line')
const blocks = lines[lines.length - 1].querySelectorAll('pre code')
blocks.forEach((block) => {
hl.highlightElement(block)
})
scrollListBox()
const items = document.querySelectorAll('.message-line')
@@ -429,32 +393,49 @@ const sendSSERequest = async (message) => {
})
}
}
// 回答完毕,更新完整的消息内容
if (data.type === 'complete') {
data.body.showAction = true
data.body.orgContent = data.body.content.text
chatData.value[chatData.value.length - 1] = data.body
}
} catch (error) {
console.error('Error processing message:', error)
enableInput()
isGenerating.value = false
showMessageError('消息处理出错,请重试')
}
},
onerror(err) {
console.error('SSE Error:', err)
enableInput()
try {
abortController && abortController.abort()
} catch (e) {
console.error('AbortController abort error:', e)
}
isGenerating.value = false
showMessageError('连接已断开,请重试')
},
onclose() {
console.log('SSE connection closed')
enableInput()
isGenerating.value = false
},
})
} catch (error) {
try {
abortController && abortController.abort()
} catch (e) {
console.error('AbortController abort error:', e)
}
console.error('Failed to send message:', error)
enableInput()
isGenerating.value = false
showMessageError('发送消息失败,请重试')
}
}
// 发送消息
const sendMessage = () => {
if (canSend.value === false) {
if (isGenerating.value) {
showToast('AI 正在作答中,请稍后...')
return
}
@@ -469,9 +450,78 @@ const sendMessage = () => {
type: 'prompt',
id: randString(32),
icon: loginUser.value.avatar,
content: { text: renderInputText(prompt.value) },
content: { text: renderInputText(prompt.value), files: files.value },
created_at: new Date().getTime(),
})
// 添加空回复消息
const _role = getRoleById(roleId.value)
chatData.value.push({
chat_id: chatId,
role_id: roleId.value,
type: 'reply',
id: randString(32),
icon: _role['icon'],
content: {
text: '',
files: [],
},
})
nextTick(() => {
scrollListBox()
})
// 发送 SSE 请求
sendSSERequest({
user_id: loginUser.value.id,
role_id: roleId.value,
model_id: modelId.value,
chat_id: chatId.value,
prompt: prompt.value,
stream: stream.value,
files: files.value,
})
previousText.value = prompt.value
prompt.value = ''
files.value = []
return true
}
// 停止生成
const stopGenerate = function () {
if (abortController) {
abortController.abort()
isGenerating.value = false
httpGet('/api/chat/stop?session_id=' + getClientId())
.then(() => {
showToast('会话已中断')
})
.catch((e) => {
showMessageError('中断对话失败:' + e.message)
})
}
}
// 处理从ChatReply组件触发的重新生成
const handleRegenerate = (messageId) => {
if (isGenerating.value) {
showToast('AI 正在作答中,请稍后...')
return
}
console.log('messageId', messageId)
console.log('chatData.value', chatData.value)
// 判断 messageId 是整数
if (messageId !== '' && isNaN(messageId)) {
showToast('消息 ID 不合法,无法重新生成')
return
}
chatData.value = chatData.value.filter((item) => item.id < messageId && !item.isHello)
const userPrompt = chatData.value.pop()
// 添加空回复消息
const _role = getRoleById(roleId.value)
chatData.value.push({
@@ -485,52 +535,19 @@ const sendMessage = () => {
},
})
nextTick(() => {
scrollListBox()
})
disableInput(false)
// 发送 SSE 请求
sendSSERequest({
user_id: loginUser.value.id,
role_id: roleId.value,
model_id: modelId.value,
chat_id: chatId.value,
prompt: prompt.value,
stream: stream.value,
})
previousText.value = prompt.value
prompt.value = ''
return true
}
// 重新生成
const reGenerate = () => {
disableInput(false)
const text = '重新生成上述问题的答案:' + previousText.value
// 追加消息
chatData.value.push({
type: 'prompt',
id: randString(32),
icon: loginUser.value.avatar,
content: renderInputText(text),
})
// 发送 SSE 请求
sendSSERequest({
user_id: loginUser.value.id,
role_id: roleId.value,
model_id: modelId.value,
chat_id: chatId.value,
prompt: previousText.value,
last_msg_id: messageId,
prompt: userPrompt.content.text,
stream: stream.value,
files: [],
})
}
// 移除 showShare、shareOptions、shareChat 相关内容
const getRoleById = function (rid) {
for (let i = 0; i < roles.value.length; i++) {
if (roles.value[i]['id'] === rid) {
@@ -571,6 +588,38 @@ const copyShareUrl = async () => {
showNotify({ type: 'danger', message: '复制失败', duration: 2000 })
}
}
// 文件上传与管理
const files = ref([])
const isHttpUrl = (url) => url.startsWith('http://') || url.startsWith('https://')
const toAbsUrl = (url) => (isHttpUrl(url) ? url : location.protocol + '//' + location.host + url)
const afterRead = async (fileItem) => {
showLoading('文件上传中...')
try {
const file = Array.isArray(fileItem) ? fileItem[0].file : fileItem.file || fileItem
const formData = new FormData()
formData.append('file', file, file.name)
const res = await httpPost('/api/upload', formData)
const f = res.data || {}
f.url = toAbsUrl(f.url || '')
files.value = [f, ...files.value]
// 确保上传后文件预览立即可见
nextTick(() => {
scrollToBottomBar()
})
} catch (e) {
showNotify({ type: 'danger', message: '文件上传失败:' + (e.message || '网络错误') })
} finally {
closeLoading()
}
}
const removeFile = (f, idx) => {
files.value.splice(idx, 1)
}
const onRemovePreview = ({ file, index }) => {
files.value.splice(index, 1)
}
</script>
<style lang="scss" scoped>