增量提交

This commit is contained in:
zqm
2026-04-21 13:46:20 +08:00
parent f64209cb04
commit 09eb6fb1bd
44 changed files with 4411 additions and 931 deletions

View File

@@ -1,4 +1,4 @@
// 聊天页面
// 聊天页面
const { API, WebSocketManager, util, constants } = require('../../utils/api.js')
const { formatRelativeTime } = util
const { MESSAGE_TYPE, WS_MESSAGE_TYPE } = constants
@@ -13,18 +13,157 @@ Page({
websocketManager: null,
lastMessageId: '',
isConnected: false,
currentPage: 1
currentPage: 1,
userInfo: null,
showUserInfoCard: false,
locationInfo: null,
deviceInfo: null,
networkType: '',
showAuthPrompt: false,
authType: 'userInfo'
},
onLoad() {
this.initWebSocket()
this._initWebSocket()
this.loadChatHistory()
this.addWelcomeMessage()
this.checkUserAuth()
// 通知 tab-bar 进入聊天模式
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
currentTab: 1,
showChatPanel: true
})
}
},
// 检查用户授权状态
checkUserAuth() {
const app = getApp()
const userInfo = app.globalData.userInfo
if (userInfo) {
this.setData({ userInfo })
this.showUserInfoCard()
this.getUserAdditionalInfo()
} else {
this.requestUserAuth()
}
},
// 请求用户授权
requestUserAuth() {
const app = getApp()
app.getUserInfo((userInfo) => {
if (userInfo) {
this.setData({ userInfo })
this.showUserInfoCard()
this.getUserAdditionalInfo()
} else {
// 未授权,显示授权提示组件
this.setData({
showAuthPrompt: true,
authType: 'userInfo'
})
}
})
},
// 获取用户附加信息
getUserAdditionalInfo() {
const app = getApp()
// 获取地理位置信息
app.getLocation((locationInfo) => {
if (locationInfo) {
this.setData({ locationInfo })
}
})
// 获取设备信息
const deviceInfo = app.getDeviceInfo()
if (deviceInfo) {
this.setData({ deviceInfo })
}
// 获取网络状态
app.getNetworkType((networkType) => {
if (networkType) {
this.setData({ networkType })
}
})
},
// 显示用户信息卡片
showUserInfoCard() {
const { userInfo, locationInfo, deviceInfo, networkType } = this.data
// 获取UnionID
let userId = this.getUnionId()
// 获取手机号
const phoneNumber = wx.getStorageSync('phoneNumber')
let userInfoContent = `你好,${userInfo.nickName}\n`
userInfoContent += `UnionID${userId}\n`
if (phoneNumber) {
userInfoContent += `手机号:${phoneNumber}\n`
}
if (userInfo.gender === 1) {
userInfoContent += '性别:男\n'
} else if (userInfo.gender === 2) {
userInfoContent += '性别:女\n'
}
if (userInfo.city) {
userInfoContent += `地区:${userInfo.country} ${userInfo.province} ${userInfo.city}\n`
}
if (locationInfo) {
userInfoContent += `位置:${locationInfo.latitude.toFixed(2)}, ${locationInfo.longitude.toFixed(2)}\n`
}
if (deviceInfo) {
userInfoContent += `设备:${deviceInfo.model}\n`
userInfoContent += `系统:${deviceInfo.system}\n`
}
if (networkType) {
userInfoContent += `网络:${networkType}`
}
const userInfoMessage = {
id: util.generateUniqueId(),
content: userInfoContent,
type: MESSAGE_TYPE.TEXT,
isMe: false,
nickname: '系统',
avatar: '/assets/images/system-avatar.png',
time: formatRelativeTime(new Date())
}
this.addMessage(userInfoMessage)
this.setData({ showUserInfoCard: true })
},
onShow() {
// 更新自定义 TabBar 选中态 & 强制聊天模式
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
currentTab: 1,
showChatPanel: true
})
}
// 每次显示页面时检查授权状态
this.checkUserAuth()
},
onUnload() {
if (this.data.websocketManager) {
this.data.websocketManager.disconnect()
if (this.wsManager) {
this.wsManager.disconnect()
this.wsManager = null
}
},
@@ -32,7 +171,7 @@ Page({
addWelcomeMessage() {
const welcomeMessage = {
id: util.generateUniqueId(),
content: '你好我是智控未来的AI助手有什么可以帮你的吗',
content: '你好我是智控未来的AI助手有什么可以帮你的吗?',
type: MESSAGE_TYPE.TEXT,
isMe: false,
nickname: '智控未来',
@@ -42,25 +181,14 @@ Page({
this.addMessage(welcomeMessage)
},
// 初始化WebSocket连接
initWebSocket() {
const manager = new WebSocketManager()
// 初始化 WebSocket 连接(小程序 WebSocket
_initWebSocket() {
if (this.wsManager && this.wsManager.isConnected) return
const app = getApp()
manager.onMessage(WS_MESSAGE_TYPE.MESSAGE, (data) => {
this.handleNewMessage(data)
})
manager.onMessage(WS_MESSAGE_TYPE.SYSTEM, (data) => {
this.handleSystemMessage(data)
})
manager.connect(app.globalData.websocketUrl || 'wss://pactgo.cn/api/v1/ws/control')
this.setData({
websocketManager: manager,
isConnected: true
})
const wsUrl = app.globalData.websocketUrl || 'wss://pactgo.cn/api/v1/ws/miniprogram'
this.wsManager = new WebSocketManager()
this.wsManager.connect(wsUrl)
this.setData({ isConnected: true })
},
// 加载聊天记录
@@ -82,7 +210,7 @@ Page({
// 加载更多历史消息
loadMoreHistory() {
if (this.data.currentPage < 3) { // 模拟加载3页历史
if (this.data.currentPage < 3) {
this.setData({ currentPage: this.data.currentPage + 1 })
const moreHistory = this.getMockHistoryMessages(this.data.currentPage)
if (moreHistory.length > 0) {
@@ -98,7 +226,7 @@ Page({
if (page === 1) {
messages.push({
id: 'history-1',
content: '你好我是智控未来的AI助手',
content: '你好我是智控未来的AI助手,有什么可以帮助你的吗?',
type: MESSAGE_TYPE.TEXT,
isMe: false,
nickname: '智控未来',
@@ -116,7 +244,7 @@ Page({
})
messages.push({
id: 'history-3',
content: '我可以帮你解答问题、提供信息、生成内容等。请问有什么具体需求吗?',
content: '我可以帮你解答问题、提供信息、生成内容等。请问有什么具体需求吗?',
type: MESSAGE_TYPE.TEXT,
isMe: false,
nickname: '智控未来',
@@ -135,7 +263,7 @@ Page({
})
messages.push({
id: 'history-5',
content: '<p>学习编程的步骤:</p><ol><li>选择一门编程语言如Python、JavaScript等</li><li>学习基础语法和概念</li><li>实践项目,积累经验</li><li>参与社区,学习他人的代码</li></ol>',
content: '<p>学习编程的步骤:</p><ol><li>选择一门编程语言如Python、JavaScript等</li><li>学习基础语法和概念</li><li>动手项目,积累经验</li><li>参与社区,学习他人的代码</li></ol>',
type: MESSAGE_TYPE.richText,
isMe: false,
nickname: '智控未来',
@@ -149,7 +277,7 @@ Page({
// 处理新消息
handleNewMessage(data) {
this.setData({ isTyping: false })
// 模拟不同类型的消息
if (data.content.includes('代码')) {
const codeMessage = {
@@ -181,7 +309,7 @@ Page({
} else if (data.content.includes('富文本')) {
const richTextMessage = {
id: data.id || util.generateUniqueId(),
content: '<h3>标题</h3><p>这是一段<b>加粗</b>的文,包含<ul><li>无序列表项1</li><li>无序列表项2</li></ul></p>',
content: '<h3>标题</h3><p>这是一段<b>加粗</b>的文,包含<ul><li>无序列表项</li><li>无序列表项</li></ul></p>',
type: 'richText',
isMe: false,
nickname: '智控未来',
@@ -239,26 +367,20 @@ Page({
}, 100)
},
// 输入变化
// 输入变化
onInputChange(e) {
this.setData({
inputValue: e.detail.value
})
},
// 发送消息
async sendMessage() {
const content = this.data.inputValue.trim()
if (!content || this.data.sending) {
return
}
this.setData({
sending: true,
isTyping: true
})
// 添加用户消息到界面
// 发送消息(走 SSE → Gateway → SmartClaw → LMStudio
async sendMessage(text) {
const content = text ? text.trim() : this.data.inputValue.trim()
if (!content || this.data.sending) return
this.setData({ sending: true, isTyping: true })
const userMessage = {
id: util.generateUniqueId(),
content: content,
@@ -268,58 +390,144 @@ Page({
avatar: '/assets/images/user-avatar.png',
time: formatRelativeTime(new Date())
}
this.addMessage(userMessage)
try {
// 模拟AI回复
setTimeout(() => {
const aiResponse = {
id: util.generateUniqueId(),
content: this.getMockAIResponse(content),
type: MESSAGE_TYPE.TEXT,
isMe: false,
nickname: '智控未来',
avatar: '/assets/images/ai-avatar.png',
time: formatRelativeTime(new Date())
}
this.handleNewMessage(aiResponse)
}, 1500)
this.setData({
inputValue: '',
sending: false
})
} catch (error) {
console.error('发送消息失败:', error)
util.showError('发送失败,请重试')
this.setData({
sending: false,
isTyping: false
})
this.setData({ inputValue: '' })
// 创建 AI 占位消息(打字机效果)
const aiMsgId = util.generateUniqueId()
const aiMsg = {
id: aiMsgId, content: '', type: MESSAGE_TYPE.TEXT,
isMe: false, nickname: '智控未来',
avatar: '/assets/images/ai-avatar.png',
time: formatRelativeTime(new Date()), isStreaming: true
}
this.addMessage(aiMsg)
try {
const app = getApp()
const gatewayUrl = app.globalData.gatewayUrl || 'http://localhost:8000'
// 构建 SSE 请求数据
const requestData = {
model: "qwen2.5-vl-7b-instruct",
messages: [
{
role: "user",
content: content
}
],
stream: true,
temperature: 0.7,
max_tokens: 500
}
// 发送 SSE 请求
const self = this
let fullResponse = ''
// 使用 wx.request 发送请求并处理 SSE 流
wx.request({
url: `${gatewayUrl}/v1/chat/completions`,
method: 'POST',
header: {
'Content-Type': 'application/json'
},
data: requestData,
responseType: 'text',
success: function(res) {
// 处理 SSE 响应
const lines = res.data.split('\n')
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.substring(6)
if (data === '[DONE]') {
// SSE 流结束
self._typewriterAppend(aiMsgId, fullResponse, true)
break
}
try {
const json = JSON.parse(data)
if (json.choices && json.choices[0] && json.choices[0].delta && json.choices[0].delta.content) {
const chunk = json.choices[0].delta.content
fullResponse += chunk
self._typewriterAppend(aiMsgId, fullResponse)
}
} catch (e) {
console.error('解析 SSE 数据失败:', e)
}
}
}
},
fail: function(err) {
console.error('SSE 请求失败:', err)
self._typewriterAppend(aiMsgId, self.getMockAIResponse(content), true)
}
})
// 8 秒超时:降级为模拟回复
setTimeout(() => {
const msgs = self.data.messages
const aiM = msgs.find(m => m.id === aiMsgId)
if (aiM && aiM.isStreaming) {
aiM.isStreaming = false
self._typewriterAppend(aiMsgId, self.getMockAIResponse(content), true)
}
}, 8000)
} catch (err) {
console.error('发送失败:', err)
const aiResponse = {
id: aiMsgId,
content: this.getMockAIResponse(content),
type: MESSAGE_TYPE.TEXT,
isMe: false,
nickname: '智控未来',
avatar: '/assets/images/ai-avatar.png',
time: formatRelativeTime(new Date())
}
this.handleNewMessage(aiResponse)
}
this.setData({ sending: false })
},
// 打字机效果
_typewriterAppend(msgId, fullContent, isFinal = false) {
const msgs = this.data.messages
const idx = msgs.findIndex(m => m.id === msgId)
if (idx === -1) return
const cur = msgs[idx].content || ''
if (isFinal || cur.length >= fullContent.length) {
msgs[idx] = { ...msgs[idx], content: fullContent, isStreaming: false }
this.setData({ messages: [...msgs], isTyping: false })
return
}
const next = fullContent[cur.length]
msgs[idx] = { ...msgs[idx], content: cur + next, isStreaming: true }
this.setData({ messages: [...msgs] })
setTimeout(() => { this._typewriterAppend(msgId, fullContent) }, 30)
},
// 模拟AI回复
getMockAIResponse(content) {
const responses = {
'你好': '你好很高兴为你服务。',
'你好': '你好很高兴为你服务。',
'今天天气怎么样': '今天天气晴朗,适合户外活动。',
'如何学习编程': '学习编程需要持之以恒,建议从基础语法开始,多动手实践。',
'代码': 'def hello():\n print("Hello, World!")',
'卡片': '这是一个卡片消息',
'卡片': '这是一个卡片消息',
'富文本': '这是一段富文本消息,包含<b>加粗</b>和<u>下划线</u>。',
'今天是几月几': '今天是' + new Date().toLocaleDateString('zh-CN'),
'今天是几月几': '今天是 ' + new Date().toLocaleDateString('zh-CN'),
'你是谁': '我是智控未来的AI助手由LMStudio提供支持。'
}
return responses[content] || '感谢你的提问,我会为你提供准确的答。'
return responses[content] || '感谢你的提问,我会为你提供准确的答。'
},
// 长按消息
onMessageLongPress(e) {
const messageId = e.currentTarget.dataset.messageId
const message = this.data.messages.find(msg => msg.id === messageId)
if (message && message.type === MESSAGE_TYPE.TEXT) {
wx.showActionSheet({
itemList: ['复制消息', '删除消息'],
@@ -386,7 +594,7 @@ Page({
onCardButtonTap(e) {
const action = e.currentTarget.dataset.action
wx.showToast({
title: `你点击了${action}`,
title: '你点击了' + action,
icon: 'none'
})
},
@@ -404,10 +612,7 @@ Page({
messages: [],
lastMessageId: ''
})
// 清空本地存储
wx.removeStorageSync('chatHistory')
wx.showToast({
title: '已清空',
icon: 'success'
@@ -415,5 +620,89 @@ Page({
}
}
})
},
// 授权成功回调
onAuthSuccess(e) {
const { authType, data } = e.detail
console.log('授权成功:', authType, data)
const app = getApp()
switch (authType) {
case 'userInfo':
app.globalData.userInfo = data
wx.setStorageSync('userInfo', data)
this.setData({ userInfo: data })
this.showUserInfoCard()
this.getUserAdditionalInfo()
break
case 'location':
const locationInfo = {
latitude: data.latitude,
longitude: data.longitude,
speed: data.speed,
accuracy: data.accuracy
}
wx.setStorageSync('locationInfo', locationInfo)
this.setData({ locationInfo })
break
}
},
// 授权失败回调
onAuthFail(e) {
const { authType, error } = e.detail
console.error('授权失败:', authType, error)
wx.showToast({
title: '授权失败,请重试',
icon: 'none'
})
},
// 取消授权回调
onAuthCancel(e) {
const { authType } = e.detail
console.log('取消授权:', authType)
// 如果是用户信息授权,使用默认信息
if (authType === 'userInfo') {
this.setData({
userInfo: {
nickName: '游客',
avatarUrl: '/assets/images/user-avatar.png',
gender: 0,
city: '',
province: '',
country: ''
}
})
this.showUserInfoCard()
}
},
// 打开设置回调
onSettingsOpen(e) {
const { authType, settings } = e.detail
console.log('打开设置:', authType, settings)
},
// 获取UnionID
getUnionId() {
// 从本地存储获取
let unionId = wx.getStorageSync('globalUserId')
if (!unionId) {
const app = getApp()
// 如果本地没有调用app方法获取
app.getGlobalUserId((id) => {
unionId = id
})
// 同时返回一个临时ID确保页面正常显示
unionId = '获取中...'
}
return unionId
}
})
})

View File

@@ -1,7 +1 @@
{
"navigationBarTitleText": "智控未来",
"navigationBarBackgroundColor": "#ffffff",
"navigationBarTextStyle": "black",
"enablePullDownRefresh": false,
"backgroundTextStyle": "light"
}
{"navigationBarTitleText": "设备", "navigationBarBackgroundColor": "#1a1a1a", "navigationBarTextStyle": "white", "enablePullDownRefresh": false, "backgroundTextStyle": "light", "usingComponents": {"message": "../../components/message/message", "auth-prompt": "../../components/auth-prompt/auth-prompt"}}

View File

@@ -100,8 +100,8 @@
</view>
</scroll-view>
<!-- 输入区域 -->
<view class="input-container">
<!-- 输入区域tab-bar 聊天模式时由 tab-bar 接管,此处隐藏) -->
<view class="input-container" wx:if="{{false}}">
<view class="input-wrapper">
<input
class="message-input"
@@ -123,4 +123,14 @@
</button>
</view>
</view>
<!-- 授权提示组件 -->
<auth-prompt
show="{{showAuthPrompt}}"
auth-type="{{authType}}"
bind:authSuccess="onAuthSuccess"
bind:authFail="onAuthFail"
bind:authCancel="onAuthCancel"
bind:settingsOpen="onSettingsOpen"
/>
</view>

View File

@@ -1,11 +1,11 @@
/* 聊天页面样式 */
/* 聊天页面样式 - 深色主题 */
@import '../../utils/constant.wxss';
.chat-container {
display: flex;
flex-direction: column;
height: 100vh;
background-color: #f7f7f7;
background-color: #0d0d0d;
}
.message-list {
@@ -20,12 +20,12 @@
justify-content: center;
align-items: center;
height: 400rpx;
color: #999;
color: #555555;
}
.empty-text {
font-size: 28rpx;
color: #999;
color: #555555;
}
.history-tip {
@@ -37,8 +37,8 @@
.history-tip text {
font-size: 24rpx;
color: #999;
background-color: #f0f0f0;
color: #666666;
background-color: #1a1a1a;
padding: 5rpx 20rpx;
border-radius: 20rpx;
}
@@ -85,7 +85,7 @@
.message-nickname {
font-size: 24rpx;
color: #999;
color: #666666;
font-weight: 500;
}
@@ -96,15 +96,15 @@
}
.message-left .message-body {
background-color: white;
background-color: #1e1e1e;
border-radius: 16rpx 16rpx 16rpx 4rpx;
box-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.05);
border: 2rpx solid rgba(255,255,255,0.06);
}
.message-right .message-body {
background-color: #1677FF;
border-radius: 16rpx 16rpx 4rpx 16rpx;
box-shadow: 0 1rpx 2rpx rgba(22, 119, 255, 0.1);
box-shadow: 0 4rpx 16rpx rgba(22,119,255,0.25);
}
.message-text-container {
@@ -117,7 +117,7 @@
}
.message-left .message-text {
color: #333;
color: #e8e8e8;
}
.message-right .message-text {
@@ -132,7 +132,7 @@
.message-time {
font-size: 20rpx;
color: #ccc;
color: #444444;
margin-right: 16rpx;
}
@@ -143,12 +143,13 @@
margin: 4rpx 0;
}
/* 代码块样式 */
/* 代码块样式 - 深色 */
.message-code {
background-color: #f5f5f5;
background-color: #141414;
border-radius: 12rpx;
overflow: hidden;
margin: 8rpx 0;
border: 2rpx solid #252525;
}
.code-header {
@@ -156,8 +157,8 @@
justify-content: space-between;
align-items: center;
padding: 12rpx 16rpx;
background-color: #e8e8e8;
border-bottom: 1rpx solid #ddd;
background-color: #1a1a1a;
border-bottom: 2rpx solid #252525;
}
.code-language {
@@ -188,30 +189,30 @@
padding: 16rpx;
max-height: 400rpx;
overflow-y: auto;
background-color: #f5f5f5;
background-color: #0d0d0d;
}
.code-text {
font-size: 24rpx;
line-height: 1.4;
color: #333;
color: #a8dadc;
font-family: 'Courier New', Courier, monospace;
white-space: pre-wrap;
}
/* 按钮卡片样式 */
/* 按钮卡片样式 - 深色 */
.message-button-card {
background-color: white;
background-color: #1e1e1e;
border-radius: 12rpx;
padding: 20rpx;
box-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.05);
margin: 8rpx 0;
border: 2rpx solid rgba(255,255,255,0.06);
}
.card-title {
font-size: 26rpx;
font-weight: 500;
color: #333;
color: #ffffff;
margin-bottom: 16rpx;
}
@@ -222,8 +223,8 @@
}
.card-button {
background-color: #f8f8f8;
border: 1rpx solid #e0e0e0;
background-color: #141414;
border: 2rpx solid #252525;
border-radius: 8rpx;
padding: 16rpx;
font-size: 26rpx;
@@ -266,7 +267,7 @@
.typing-text {
font-size: 24rpx;
color: #999;
color: #666666;
}
@keyframes typing-bounce {
@@ -278,17 +279,16 @@
}
}
/* 输入区域 */
/* 输入区域 - 深色 */
.input-container {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: white;
border-top: 1rpx solid #e0e0e0;
background: linear-gradient(180deg, #1a1a1a 0%, #141414 100%);
border-top: 2rpx solid rgba(255,255,255,0.06);
padding: 20rpx;
z-index: 1000;
box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.input-wrapper {
@@ -299,11 +299,12 @@
.message-input {
flex: 1;
border: 1rpx solid #e0e0e0;
border: 2rpx solid #252525;
border-radius: 28rpx;
padding: 20rpx 28rpx;
font-size: 28rpx;
background-color: #f8f8f8;
background-color: #0d0d0d;
color: #ffffff;
min-height: 80rpx;
max-height: 200rpx;
overflow-y: auto;
@@ -343,7 +344,7 @@
transform: none;
}
/* 富文本样式 */
/* 富文本样式 - 深色主题 */
rich-text {
line-height: 1.5;
}
@@ -361,17 +362,17 @@ rich-text :deep(h3) {
rich-text :deep(h1) {
font-size: 32rpx;
color: #333;
color: #ffffff;
}
rich-text :deep(h2) {
font-size: 28rpx;
color: #444;
color: #e5e5e5;
}
rich-text :deep(h3) {
font-size: 26rpx;
color: #555;
color: #cccccc;
}
rich-text :deep(ul),
@@ -383,6 +384,7 @@ rich-text :deep(ol) {
rich-text :deep(li) {
margin: 8rpx 0;
line-height: 1.5;
color: #d0d0d0;
}
rich-text :deep(strong) {