v1.2 优化保存
This commit is contained in:
+116
-15
@@ -20,6 +20,19 @@ import { TASK_KIND_META } from '../constants/task-kinds'
|
||||
*/
|
||||
export type SaveTipState = 'none' | 'ready' | 'saving' | 'done'
|
||||
|
||||
/**
|
||||
* 保存流程占位状态(消息列表末尾的仿「AI 正在生成」占位)。
|
||||
* - idle = 无占位(不设字段)
|
||||
* - ready = save_tip 已执行、等待用户点保存(「策略已就绪…」)
|
||||
* - generating = ① 要逻辑子请求进行中(「正在生成策略…」)
|
||||
* - saving = ② 交付物 + applyStrategy 进行中(「正在保存…」)
|
||||
*
|
||||
* ⚠️ 瞬态字段,不落盘 —— persistSessions 落盘时剔除;idle 时赋 undefined 不留残留。
|
||||
* ⚠️ 与 saveTipState 分工:本字段只管「占位行说什么话」;按钮的显隐 / 禁用 / 图标
|
||||
* 仍由 saveTipState 决定(能不能保存的判定也只在 handleSaveStrategy 里看它)。
|
||||
*/
|
||||
export type SaveFlowPhase = 'idle' | 'ready' | 'generating' | 'saving'
|
||||
|
||||
interface ChatStoreState {
|
||||
sessions: ChatSession[]
|
||||
activeSessionId: string
|
||||
@@ -71,6 +84,20 @@ function sortSessionsByUpdatedAt(sessions: ChatSession[]): ChatSession[] {
|
||||
return [...sessions].sort((first, second) => second.updatedAt - first.updatedAt)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把「生成中」形态的消息落定为 stopped(正文原样保留)。
|
||||
* 两处共用同一变换,保证口径一致:
|
||||
* - 落盘时(persistSessions):磁盘副本永远不能是 in-flight 形态 ——
|
||||
* 流式增量只在内存,否则异常退出后恢复会永远卡「AI 正在生成」。
|
||||
* - 恢复时(state 初始化):旧档 / 异常退出可能带 isLoading:true ⇒ 一律落定,
|
||||
* 不丢任何已产出的文字。
|
||||
*/
|
||||
function settleInFlightMessage(message: ChatMessage): ChatMessage {
|
||||
const inFlight = message.isLoading || message.status === 'pending' || message.status === 'streaming'
|
||||
if (!inFlight) return message
|
||||
return { ...message, isLoading: false, status: 'stopped' }
|
||||
}
|
||||
|
||||
function normalizeImportedMessage(message: Partial<ChatMessage>, index: number, sessionTimestamp: number): ChatMessage | null {
|
||||
if (!message || typeof message.content !== 'string') return null
|
||||
if (message.role !== 'system' && message.role !== 'user' && message.role !== 'assistant') return null
|
||||
@@ -151,11 +178,44 @@ function groupLabel(category: string | undefined | null): string {
|
||||
return trimmed
|
||||
}
|
||||
|
||||
/**
|
||||
* 把策略实例按 sealed 分组分桶(打法策略 / 注码策略)。
|
||||
* 分组依据来自技能清单解析出的「类型名 → 分组」映射(parseStrategyClasses)。
|
||||
* 清单解析失败 / 为空 ⇒ 两个桶都为空(get_policy 会命中 0 条,错误对用户可见)。
|
||||
* loadPolicyContext 与 refreshPolicyContext 共用,保证分桶口径只有这一份。
|
||||
*/
|
||||
function bucketStrategies(
|
||||
strategies: StrategyInstance[],
|
||||
skillList: string | null,
|
||||
): { '打法策略': StrategyInstance[]; '注码策略': StrategyInstance[] } {
|
||||
const bucket = { '打法策略': [] as StrategyInstance[], '注码策略': [] as StrategyInstance[] }
|
||||
try {
|
||||
const classes = parseStrategyClasses(skillList ?? '')
|
||||
const catByKind = new Map<string, string>()
|
||||
for (const c of classes) catByKind.set(c.className, c.category)
|
||||
for (const s of strategies) {
|
||||
const cat = catByKind.get(s.kind)
|
||||
if (cat === '打法策略' || cat === '注码策略') bucket[cat].push(s)
|
||||
// 未识别的 kind 不进任何桶(清单与实例种类对不上时静默丢弃,不阻塞)
|
||||
}
|
||||
} catch {
|
||||
// 清单解析异常 ⇒ 两桶置空(同 loadPolicyContext 的容错口径)
|
||||
}
|
||||
return bucket
|
||||
}
|
||||
|
||||
export const useChatStore = defineStore('chat', {
|
||||
state: (): ChatStoreState => {
|
||||
const storedSessions = loadLocalStorage<ChatSession[]>(STORAGE_KEYS.chatSessions, [])
|
||||
const fallbackSession = createEmptySession()
|
||||
const sessions = storedSessions.length ? sortSessionsByUpdatedAt(storedSessions) : [fallbackSession]
|
||||
// 恢复归一化(A):落盘档里不该有 in-flight 消息(persistSessions 已保证),
|
||||
// 但旧档 / 写入中断可能带 isLoading:true ⇒ 载入时一律落定为 stopped,正文保留。
|
||||
const sessions = storedSessions.length
|
||||
? sortSessionsByUpdatedAt(storedSessions).map((session) => ({
|
||||
...session,
|
||||
messages: Array.isArray(session.messages) ? session.messages.map(settleInFlightMessage) : [],
|
||||
}))
|
||||
: [fallbackSession]
|
||||
const storedActiveSessionId = loadLocalStorage<string>(STORAGE_KEYS.activeSessionId, sessions[0].id)
|
||||
const activeSession = sessions.find((session) => session.id === storedActiveSessionId) || sessions[0]
|
||||
|
||||
@@ -209,6 +269,11 @@ export const useChatStore = defineStore('chat', {
|
||||
const session = state.sessions.find((item) => item.id === state.activeSessionId) || state.sessions[0]
|
||||
return session?.saveTipState ?? 'none'
|
||||
},
|
||||
/** 当前会话的保存流程占位状态(瞬态,不落盘;没设 = idle) */
|
||||
activeSaveFlowPhase(state): SaveFlowPhase {
|
||||
const session = state.sessions.find((item) => item.id === state.activeSessionId) || state.sessions[0]
|
||||
return session?.saveFlowPhase ?? 'idle'
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
persistSessions() {
|
||||
@@ -218,7 +283,19 @@ export const useChatStore = defineStore('chat', {
|
||||
// JSON.stringify 自动丢掉 undefined 字段 ⇒ localStorage 里不含正文。
|
||||
saveLocalStorage(
|
||||
STORAGE_KEYS.chatSessions,
|
||||
this.sessions.map((session) => ({ ...session, loopMessages: undefined, saveTipState: undefined })),
|
||||
this.sessions.map((session) => ({
|
||||
...session,
|
||||
loopMessages: undefined,
|
||||
saveTipState: undefined,
|
||||
// 保存流程占位状态同为瞬态字段,落盘副本一律剔除
|
||||
saveFlowPhase: undefined,
|
||||
// 落盘副本里绝不能有 in-flight 消息(B):isLoading 一律 false、
|
||||
// pending/streaming 落定为 stopped —— 流式增量只在内存,
|
||||
// 磁盘副本永远不是「生成中」形态,恢复时不会卡「AI 正在生成」。
|
||||
messages: Array.isArray(session.messages)
|
||||
? session.messages.map(settleInFlightMessage)
|
||||
: session.messages,
|
||||
})),
|
||||
)
|
||||
saveLocalStorage(STORAGE_KEYS.activeSessionId, this.activeSessionId)
|
||||
this.persistPending = false
|
||||
@@ -446,28 +523,37 @@ export const useChatStore = defineStore('chat', {
|
||||
} catch {
|
||||
this.strategies = []
|
||||
}
|
||||
// 按分组分组缓存:用清单解析出的「类型名 → 分组」映射(已有 parseStrategyClasses)
|
||||
// 拉清单失败时:两个桶置空(不做降级;get_policy 会命中 0 条,错误对用户可见)
|
||||
// 拉技能清单(失败 ⇒ skillList 置 null,分桶随之置空)
|
||||
try {
|
||||
this.skillList = await getAiBridge().getSkills()
|
||||
const classes = parseStrategyClasses(this.skillList)
|
||||
const catByKind = new Map<string, string>()
|
||||
for (const c of classes) catByKind.set(c.className, c.category)
|
||||
const bucket = { '打法策略': [] as StrategyInstance[], '注码策略': [] as StrategyInstance[] }
|
||||
for (const s of this.strategies) {
|
||||
const cat = catByKind.get(s.kind)
|
||||
if (cat === '打法策略' || cat === '注码策略') bucket[cat].push(s)
|
||||
// 未识别的 kind 不进任何桶(清单与实例种类对不上时静默丢弃,不阻塞)
|
||||
}
|
||||
this.strategyCacheByCategory = bucket
|
||||
} catch {
|
||||
this.skillList = null
|
||||
this.strategyCacheByCategory = { '打法策略': [], '注码策略': [] }
|
||||
}
|
||||
// 按分组分桶:抽出的 bucketStrategies(清单解析失败 ⇒ 两桶置空,行为与原内联实现一致)
|
||||
this.strategyCacheByCategory = bucketStrategies(this.strategies, this.skillList)
|
||||
// 实例清单就绪后(或确认拉取失败、列表为空后)重算一次全局选中:
|
||||
// 刷新恢复 / 切会话时 strategies 还没加载完,按 id 解析不到实例,在这里补上
|
||||
this.restoreSelectionForActiveSession()
|
||||
},
|
||||
/**
|
||||
* 保存成功后重拉一次策略实例(走 getPolicyContext()),让 native 新建 / 改写后的
|
||||
* 实例立刻出现在实例下拉里。⚠️ **不**重拉 getSkills —— 技能清单沿用现有缓存
|
||||
* (this.skillList),分桶复用 bucketStrategies。最后重算一次全局选中。
|
||||
* 失败静默降级:strategies 置 [] 且两桶置空(同 loadPolicyContext 的容错口径),
|
||||
* 不报错打扰用户。
|
||||
*/
|
||||
async refreshPolicyContext(): Promise<void> {
|
||||
try {
|
||||
const context = await getAiBridge().getPolicyContext()
|
||||
// 兼容两种契约形态:宽松索引签名(旧)与 { strategies: [...] }(新)。
|
||||
const strategies = (context as { strategies?: StrategyInstance[] }).strategies
|
||||
this.strategies = Array.isArray(strategies) ? strategies : []
|
||||
} catch {
|
||||
this.strategies = []
|
||||
}
|
||||
this.strategyCacheByCategory = bucketStrategies(this.strategies, this.skillList)
|
||||
this.restoreSelectionForActiveSession()
|
||||
},
|
||||
/**
|
||||
* 把内存全局的 selectedStrategy 同步成「当前会话落盘的选中」。
|
||||
* ⚠️ 只同步内存字段,**不改 session.selectedStrategyId** —— strategies 是异步拉的,
|
||||
@@ -529,6 +615,8 @@ export const useChatStore = defineStore('chat', {
|
||||
// none / done ⇒ 回到 ready(首次出现 / 保存后模型再提示,重新出按钮)
|
||||
if (current === 'none' || current === 'done') {
|
||||
session.saveTipState = 'ready'
|
||||
// 占位行同步:显示「策略已就绪,可点击右下角保存」(见 SaveFlowPhase 分工)
|
||||
session.saveFlowPhase = 'ready'
|
||||
}
|
||||
// ready / saving / done ⇒ 不改
|
||||
},
|
||||
@@ -537,6 +625,8 @@ export const useChatStore = defineStore('chat', {
|
||||
const session = this.activeSession
|
||||
if (!session) return
|
||||
session.saveTipState = 'none'
|
||||
// 占位行一并收回(保存流程进行中不动它,由 ChatView 收场时置 idle)
|
||||
if (session.saveFlowPhase === 'ready') session.saveFlowPhase = undefined
|
||||
},
|
||||
/**
|
||||
* 写入会话级技能绑定 `lastSkillName`(落盘)。
|
||||
@@ -590,5 +680,16 @@ export const useChatStore = defineStore('chat', {
|
||||
session.saveTipState = 'ready'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* 置当前会话的保存流程占位状态(瞬态,不落盘)。
|
||||
* - 'generating':① 要逻辑子请求开始(ChatView.handleSaveStrategy)
|
||||
* - 'saving':② 交付物 + applyStrategy 开始
|
||||
* - 'idle':占位消失(成功 / 失败 / 取消收场)—— 赋 undefined,不留落盘字段残留
|
||||
*/
|
||||
setSaveFlowPhase(phase: SaveFlowPhase): void {
|
||||
const session = this.activeSession
|
||||
if (!session) return
|
||||
session.saveFlowPhase = phase === 'idle' ? undefined : phase
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user