feat: 用缓存处理对话中的项目切换问题

This commit is contained in:
2026-04-02 10:05:29 +08:00
parent b205633d0d
commit 836431788a
15 changed files with 208 additions and 51 deletions

View File

@@ -179,10 +179,10 @@ export class AISelectboxToolManager {
mouseMoveEvent(e) { mouseMoveEvent(e) {
if (!this.targetObject) return; if (!this.targetObject) return;
if (!this.isDragging) return; if (!this.isDragging) return;
var width = e.absolutePointer.x - this.startX let width = e.absolutePointer.x - this.startX
var height = e.absolutePointer.y - this.startY let height = e.absolutePointer.y - this.startY
var left = this.startX let left = this.startX
var top = this.startY let top = this.startY
if (width < 0) { if (width < 0) {
left += width left += width
width = -width width = -width

View File

@@ -17,7 +17,7 @@ fabric.Object.prototype.toObject = function () {
const arr = [...fabric.Object.prototype.customProperties] const arr = [...fabric.Object.prototype.customProperties]
args.forEach(v => (Array.isArray(v) ? arr.push(...v) : arr.push(v))) args.forEach(v => (Array.isArray(v) ? arr.push(...v) : arr.push(v)))
if (this.fill?.source === null) { if (this.fill?.source === null) {
let image = new Image() const image = new Image()
image.crossOrigin = 'anonymous' image.crossOrigin = 'anonymous'
image.src = this.info?.fill?.source image.src = this.info?.fill?.source
this.fill.source = image this.fill.source = image
@@ -65,17 +65,17 @@ export class CanvasManager {
} }
} }
setCanvasViewSize(options) { setCanvasViewSize(options) {
var canvasViewWidth = options.canvasViewWidth || 1920 const canvasViewWidth = options.canvasViewWidth || 1920
var canvasViewHeight = options.canvasViewHeight || 1080 const canvasViewHeight = options.canvasViewHeight || 1080
this.canvas.setWidth(canvasViewWidth) this.canvas.setWidth(canvasViewWidth)
this.canvas.setHeight(canvasViewHeight) this.canvas.setHeight(canvasViewHeight)
} }
/** 初始化画布 */ /** 初始化画布 */
async initCanvas(options: CanvasInitOptions) { async initCanvas(options: CanvasInitOptions) {
this.layerManager = this.stateManager.layerManager this.layerManager = this.stateManager.layerManager
var canvasWidth = options.canvasWidth || 750 let canvasWidth = options.canvasWidth || 750
var canvasHeight = options.canvasHeight || 600 let canvasHeight = options.canvasHeight || 600
var image = null; let image = null;
if (options.url) { if (options.url) {
await new Promise((resolve) => { await new Promise((resolve) => {
fabric.Image.fromURL(options.url, async (img) => { fabric.Image.fromURL(options.url, async (img) => {
@@ -188,8 +188,8 @@ export class CanvasManager {
async updateSubLayerClipPath() { async updateSubLayerClipPath() {
const objects = this.getObjects().filter((v: any) => v.type !== "group" && !!v.info?.id); const objects = this.getObjects().filter((v: any) => v.type !== "group" && !!v.info?.id);
for (let i = 0; i < objects.length; i++) { for (let i = 0; i < objects.length; i++) {
let object = objects[i] const object = objects[i]
let path = this.getObjectById(object.info.parentId)?.clipPath const path = this.getObjectById(object.info.parentId)?.clipPath
object.set({ clipPath: path || null }) object.set({ clipPath: path || null })
} }
this.renderAll() this.renderAll()
@@ -381,7 +381,7 @@ export class CanvasManager {
} }
/** 处理JSON为正常画布 */ /** 处理JSON为正常画布 */
processCanvasDisUrlJSON(obj: { canvas: string, images: Object }) { processCanvasDisUrlJSON(obj: { canvas: string, images: Object }) {
var json = obj.canvas; let json = obj.canvas;
const images = obj.images || {} const images = obj.images || {}
for (const key in images) { for (const key in images) {
json = json.replace(new RegExp(key), images[key]) json = json.replace(new RegExp(key), images[key])

View File

@@ -64,10 +64,10 @@ export class LayerManager {
getLayerById(id) { getLayerById(id) {
function call(arr) { function call(arr) {
for (let i = 0; i < arr.length; i++) { for (let i = 0; i < arr.length; i++) {
let v = arr[i] const v = arr[i]
if (v.info.id === id) return v if (v.info.id === id) return v
if (v.children) { if (v.children) {
let layer = call(v.children) const layer = call(v.children)
if (layer) return layer if (layer) return layer
} }
} }

View File

@@ -220,8 +220,8 @@ export class ObjectManager {
const isWidth = object.hasOwnProperty('width') const isWidth = object.hasOwnProperty('width')
const isHeight = object.hasOwnProperty('height') const isHeight = object.hasOwnProperty('height')
if (isWidth || isHeight) { if (isWidth || isHeight) {
let width = isWidth ? options.width : object.width const width = isWidth ? options.width : object.width
let height = isHeight ? options.height : object.height const height = isHeight ? options.height : object.height
if (type === "polygon") { if (type === "polygon") {
if (object.points.length === 10) {// 五角星 if (object.points.length === 10) {// 五角星
options.points = getStarArr(width, height) options.points = getStarArr(width, height)

View File

@@ -58,10 +58,10 @@ export class ShapeToolManager {
} }
mouseMoveEvent(e) { mouseMoveEvent(e) {
if (!this.isDragging) return; if (!this.isDragging) return;
var width = e.absolutePointer.x - this.startX let width = e.absolutePointer.x - this.startX
var height = e.absolutePointer.y - this.startY let height = e.absolutePointer.y - this.startY
var left = this.startX let left = this.startX
var top = this.startY let top = this.startY
if (width < 0) { if (width < 0) {
left += width left += width
width = -width width = -width

View File

@@ -89,7 +89,7 @@ export class StateManager {
/** 撤回状态 */ /** 撤回状态 */
undoState() { undoState() {
if (this.running.value) return if (this.running.value) return
var index = this.historyIndex.value - 1 const index = this.historyIndex.value - 1
const state = this.historyList.value[index] const state = this.historyList.value[index]
if (!state) return if (!state) return
this.running.value = true this.running.value = true
@@ -103,7 +103,7 @@ export class StateManager {
/** 重做状态 */ /** 重做状态 */
redoState() { redoState() {
if (this.running.value) return if (this.running.value) return
var index = this.historyIndex.value + 1 const index = this.historyIndex.value + 1
const state = this.historyList.value[index] const state = this.historyList.value[index]
if (!state) return if (!state) return
this.running.value = true this.running.value = true

View File

@@ -16,8 +16,8 @@ export const initThree = (threeDom)=>{
/** /**
* 创建渲染器对象 * 创建渲染器对象
*/ */
let width = threeDom.offsetWidth; //窗口宽度 const width = threeDom.offsetWidth; //窗口宽度
let height = threeDom.offsetHeight; //窗口高度 const height = threeDom.offsetHeight; //窗口高度
const renderer = new THREE.WebGLRenderer({ const renderer = new THREE.WebGLRenderer({
antialias: true, antialias: true,
logarithmicDepthBuffer: true,//深度缓存 防止模型闪烁重影 logarithmicDepthBuffer: true,//深度缓存 防止模型闪烁重影
@@ -35,9 +35,9 @@ export const initThree = (threeDom)=>{
// 设置渲染器大小 // 设置渲染器大小
//环境光 //环境光
let ambient = new THREE.AmbientLight(0xffffff,.8); const ambient = new THREE.AmbientLight(0xffffff,.8);
scene.add(ambient); scene.add(ambient);
let controls = new OrbitControls(camera,renderer.domElement)//监听鼠标、键盘事件; const controls = new OrbitControls(camera,renderer.domElement)//监听鼠标、键盘事件;
// controls.minDistance = 500; // 设置相机与焦点的最小距离 // controls.minDistance = 500; // 设置相机与焦点的最小距离
// controls.maxDistance = 4000; // 设置相机与焦点的最大距离 // controls.maxDistance = 4000; // 设置相机与焦点的最大距离
controls.mouseButtons = { controls.mouseButtons = {
@@ -166,14 +166,14 @@ export const addModel = async (
load: any load: any
) => { ) => {
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
var fbxLoader = new GLTFLoader(); const fbxLoader = new GLTFLoader();
let drac = new DRACOLoader() const drac = new DRACOLoader()
drac.setDecoderPath('/draco/') drac.setDecoderPath('/draco/')
fbxLoader.setDRACOLoader(drac) fbxLoader.setDRACOLoader(drac)
fbxLoader.load(url, fbxLoader.load(url,
(obj: any) => { (obj: any) => {
let scene = obj.scene; const scene = obj.scene;
scene.traverse((child: any) => { scene.traverse((child: any) => {
if (child.isMesh) { if (child.isMesh) {
// 如果是基础材质,转换为标准材质 // 如果是基础材质,转换为标准材质

View File

@@ -27,13 +27,13 @@ export class GenerateManager {
async getTasksIdImg() { async getTasksIdImg() {
clearInterval(this.getTaskIdsImgTime) clearInterval(this.getTaskIdsImgTime)
this.getTaskIdsImgTime = setInterval(()=>{ this.getTaskIdsImgTime = setInterval(()=>{
let taskIds = this.taskIds.map((item)=>item.taskId) const taskIds = this.taskIds.map((item)=>item.taskId)
getTaskidResult({taskIds}).then((rv:any)=>{ getTaskidResult({taskIds}).then((rv:any)=>{
//找出成功和失败的任务 //找出成功和失败的任务
let returnedTasks = rv.filter((item)=>item.status == 'RETURNED' || item.status == 'FAILED') const returnedTasks = rv.filter((item)=>item.status == 'RETURNED' || item.status == 'FAILED')
if(returnedTasks.length == 0)return if(returnedTasks.length == 0)return
//剔除调成功的 //剔除调成功的
let taskIds_ = JSON.parse(JSON.stringify(this.taskIds)) const taskIds_ = JSON.parse(JSON.stringify(this.taskIds))
this.taskIds = taskIds_.filter(itemA => this.taskIds = taskIds_.filter(itemA =>
!returnedTasks.some(itemB => itemB.taskId === itemA.taskId) !returnedTasks.some(itemB => itemB.taskId === itemA.taskId)
) )

View File

@@ -142,7 +142,7 @@ export class NodeManager {
copyNodeById(id: string) { copyNodeById(id: string) {
const node = this.stateManager.getNodeById(id) const node = this.stateManager.getNodeById(id)
let copyNode = JSON.parse(JSON.stringify(node)) const copyNode = JSON.parse(JSON.stringify(node))
const flowNode = this.stateManager.flowManager.getNodeById(id) const flowNode = this.stateManager.flowManager.getNodeById(id)
if (!node) return console.warn(`${id}找不到对应节点`) if (!node) return console.warn(`${id}找不到对应节点`)
if (node.data?.disableCopy) return console.warn(`${id}节点已禁用复制`) if (node.data?.disableCopy) return console.warn(`${id}节点已禁用复制`)

View File

@@ -276,7 +276,7 @@ export class StateManager {
} }
/** 撤回状态 */ /** 撤回状态 */
undoState() { undoState() {
var index = this.historyIndex.value - 1 const index = this.historyIndex.value - 1
const state = this.historyList.value[index] const state = this.historyList.value[index]
if (!state) return if (!state) return
this.historyIndex.value = index this.historyIndex.value = index
@@ -285,7 +285,7 @@ export class StateManager {
} }
/** 重做状态 */ /** 重做状态 */
redoState() { redoState() {
var index = this.historyIndex.value + 1 const index = this.historyIndex.value + 1
const state = this.historyList.value[index] const state = this.historyList.value[index]
if (!state) return if (!state) return
this.historyIndex.value = index this.historyIndex.value = index

View File

@@ -5,7 +5,6 @@ import { ref, computed } from 'vue'
import { removeLocal, setLocal } from '@/utils/local' import { removeLocal, setLocal } from '@/utils/local'
import MyEvent from '@/utils/myEvent' import MyEvent from '@/utils/myEvent'
// Agent 项目初始数据 store // Agent 项目初始数据 store
type InitialProjectData = { type InitialProjectData = {
text: string text: string
@@ -13,8 +12,8 @@ type InitialProjectData = {
type: string type: string
area: string area: string
style: string style: string
useReport:boolean useReport: boolean
needSuggestion:boolean needSuggestion: boolean
quoteList: Array<string> quoteList: Array<string>
tempImages: any[] tempImages: any[]
} }
@@ -34,10 +33,94 @@ export const useAgentStore = defineStore('agent', () => {
initialProjectData.value = null initialProjectData.value = null
} }
// 会话缓存管理,最多保存 10 条会话
const conversationCache = new Map<string, any>()
const MAX_CACHE_ENTRIES = 10
const SESSION_KEY_PREFIX = 'agent_session_'
const pruneCache = () => {
const keys = Array.from(conversationCache.keys())
const total = conversationCache.size
if (total <= MAX_CACHE_ENTRIES) return
for (let i = 0; i < total - MAX_CACHE_ENTRIES; i++) {
conversationCache.delete(keys[i])
sessionStorage.removeItem(SESSION_KEY_PREFIX + keys[i])
}
}
const saveCacheConversation = (projectId: string, data: any) => {
if (!projectId) return
const finalData = {
...data,
updatedAt: Date.now()
}
if (conversationCache.has(projectId)) {
conversationCache.delete(projectId)
}
conversationCache.set(projectId, finalData)
try {
sessionStorage.setItem(SESSION_KEY_PREFIX + projectId, JSON.stringify(finalData))
} catch (e) {
console.warn('saveCacheConversation sessionStorage failed', e)
}
pruneCache()
}
const getCacheConversation = (projectId: string) => {
if (!projectId) return null
let data = conversationCache.get(projectId)
if (data) return data
try {
const raw = sessionStorage.getItem(SESSION_KEY_PREFIX + projectId)
if (!raw) return null
data = JSON.parse(raw)
conversationCache.set(projectId, data)
return data
} catch (e) {
console.warn('getCacheConversation failed', e)
return null
}
}
const clearAllCacheConversations = () => {
conversationCache.value.clear()
for (const key in window.sessionStorage) {
if (key.startsWith(SESSION_KEY_PREFIX)) {
sessionStorage.removeItem(key)
}
}
}
const removeCacheConversation = (projectId: string) => {
if (!projectId) return
conversationCache.value.delete(projectId)
sessionStorage.removeItem(SESSION_KEY_PREFIX + projectId)
}
const getCacheStats = () => {
return {
total: conversationCache.value.size,
keys: Array.from(conversationCache.value.keys())
}
}
return { return {
initialProjectData, initialProjectData,
setInitialProjectData, setInitialProjectData,
getInitialProjectData, getInitialProjectData,
clearInitialProjectData clearInitialProjectData,
conversationCache,
saveCacheConversation,
getCacheConversation,
removeCacheConversation,
clearAllCacheConversations,
getCacheStats
} }
}) })

View File

@@ -19,7 +19,7 @@ export const useVersionTreeStore = defineStore('versionTree', () => {
}) })
const setNodeDetail = (v: any) => { const setNodeDetail = (v: any) => {
for(let key in v){ for(const key in v){
state.value.nodeDetail[key] = v[key] state.value.nodeDetail[key] = v[key]
} }
} }

View File

@@ -80,7 +80,55 @@
{ deep: true } { deep: true }
) )
const handleReset = () => { const saveSession = (projectId: string) => {
if (!projectId) return
agentStore.saveCacheConversation(projectId, {
messageList: messageList.value,
sketchList: sketchList.value,
params: {
...params,
projectID: projectId
},
isGenerating: isGenerating.value,
isPaused: isPaused.value
})
}
const restoreSession = (projectId: string) => {
if (!projectId) return false
const payload = agentStore.getCacheConversation(projectId)
if (!payload) return false
messageList.value = payload.messageList || []
sketchList.value = payload.sketchList || []
if (payload.params) {
params.projectID = payload.params.projectID || projectId
params.message = payload.params.message || ''
params.versionID = payload.params.versionID || ''
params.configParams = payload.params.configParams || params.configParams
params.needSuggestion = payload.params.needSuggestion || false
params.useReport = payload.params.useReport || false
params.imageUrlList = payload.params.imageUrlList || []
params.quotaUrl = payload.params.quotaUrl || []
}
isGenerating.value = false
isPaused.value = payload.isPaused || false
return true
}
const clearSession = (projectId: string) => {
if (!projectId) return
agentStore.removeCacheConversation(projectId)
}
const handleReset = (force = false) => {
if (!force && params.projectID) {
saveSession(params.projectID)
}
if (force && params.projectID) {
clearSession(params.projectID)
}
messageList.value = [] messageList.value = []
sketchList.value = [] sketchList.value = []
params.versionID = '' params.versionID = ''
@@ -94,6 +142,7 @@
style: '' style: ''
} }
isGenerating.value = false isGenerating.value = false
isPaused.value = false
} }
// 每次请求时创建新的 AbortController // 每次请求时创建新的 AbortController
@@ -109,6 +158,9 @@
} }
onUnmounted(() => { onUnmounted(() => {
if (params.projectID) {
saveSession(params.projectID)
}
abort?.abort() abort?.abort()
MyEvent.remove('resetAgent', handleReset) MyEvent.remove('resetAgent', handleReset)
}) })
@@ -453,6 +505,9 @@
isPaused.value = true isPaused.value = true
isGenerating.value = false isGenerating.value = false
abort?.abort() abort?.abort()
if (params.projectID) {
saveSession(params.projectID)
}
MyEvent.emit('stopChat') MyEvent.emit('stopChat')
} }
@@ -543,7 +598,7 @@
thinkingText: combinedThinkingText, thinkingText: combinedThinkingText,
text: combinedContent, text: combinedContent,
image_url: combinedImageUrl, image_url: combinedImageUrl,
webAddress: !!webAddress ? JSON.parse(webAddress) : null, webAddress: webAddress ? JSON.parse(webAddress) : null,
isUser: false, isUser: false,
id: result.length + 1, id: result.length + 1,
sessionId: sessionId sessionId: sessionId
@@ -627,7 +682,10 @@
} }
defineExpose({ defineExpose({
setChatInfo setChatInfo,
saveSession,
restoreSession,
clearSession
}) })
</script> </script>

View File

@@ -161,12 +161,14 @@
const quotaList = props.content.image_url ?? [] const quotaList = props.content.image_url ?? []
list.push(...quotaList) list.push(...quotaList)
} }
console.log(imageUrls, '---imageUrls---')
if (!imageUrls || imageUrls.length === 0) return list if (!imageUrls || imageUrls.length === 0) return list
imageUrls.forEach((item) => { imageUrls?.forEach((item) => {
if (typeof item === 'string') { if (typeof item === 'string') {
list.push(item) list.push(item)
} else if (typeof item === 'object' && item.url) { } else if (typeof item === 'object' && item?.url) {
list.push(item.url) list.push(item?.url)
} }
}) })
return list return list

View File

@@ -131,12 +131,26 @@
watch( watch(
() => proJectId.value, () => proJectId.value,
(newVal, oldVal) => { async (newVal, oldVal) => {
if (oldVal && agentRef.value && typeof agentRef.value.saveSession === 'function') {
agentRef.value.saveSession(oldVal as string)
}
projectStore.clearProject() projectStore.clearProject()
if (newVal) { if (newVal) {
handleGetProjectInfoAndHistory() let restored = false
if (agentRef.value && typeof agentRef.value.restoreSession === 'function') {
restored = await agentRef.value.restoreSession(newVal as string)
}
if (!restored) {
handleGetProjectInfoAndHistory()
}
MyEvent.emit('projectChange')
} else {
MyEvent.emit('projectChange') MyEvent.emit('projectChange')
MyEvent.emit('resetAgent')
} }
} }
) )