| 1 | /** |
| 2 | * Agent Store - Refs 管理 |
| 3 | * 管理内部引用变量,避免闭包问题 |
| 4 | */ |
| 5 | |
| 6 | import type { IActionContext, IWorkflowStep } from '../agent.types' |
| 7 | |
| 8 | // ============ Ref 类型定义 ============ |
| 9 | |
| 10 | /** 可变引用类型 */ |
| 11 | export interface IRef<T> { |
| 12 | value: T |
| 13 | } |
| 14 | |
| 15 | /** Agent Store 所有 Refs */ |
| 16 | export interface IAgentRefs { |
| 17 | /** 流式文本 */ |
| 18 | streamingText: IRef<string> |
| 19 | /** 当前步骤的工作流步骤 */ |
| 20 | currentStepWorkflow: IRef<IWorkflowStep[]> |
| 21 | /** 当前步骤索引 */ |
| 22 | currentStepIndex: IRef<number> |
| 23 | /** 当前 assistant 消息 ID */ |
| 24 | currentAssistantMessageId: IRef<string> |
| 25 | /** 当前 SSE 连接对应的任务ID(用于防止消息串台) */ |
| 26 | currentSSETaskId: IRef<string> |
| 27 | /** SSE 连接的 abort 函数 */ |
| 28 | sseAbort: IRef<(() => void) | null> |
| 29 | /** 翻译函数 */ |
| 30 | t: IRef<((key: string) => string) | null> |
| 31 | /** Action 上下文 */ |
| 32 | actionContext: IRef<IActionContext | null> |
| 33 | } |
| 34 | |
| 35 | // ============ 创建 Refs ============ |
| 36 | |
| 37 | /** |
| 38 | * 创建 Agent Store 的所有 Refs |
| 39 | */ |
| 40 | export function createAgentRefs(): IAgentRefs { |
| 41 | return { |
| 42 | streamingText: { value: '' }, |
| 43 | currentStepWorkflow: { value: [] }, |
| 44 | currentStepIndex: { value: -1 }, |
| 45 | currentAssistantMessageId: { value: '' }, |
| 46 | currentSSETaskId: { value: '' }, |
| 47 | sseAbort: { value: null }, |
| 48 | t: { value: null }, |
| 49 | actionContext: { value: null }, |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * 重置所有 Refs 到初始状态 |
| 55 | */ |
| 56 | export function resetAgentRefs(refs: IAgentRefs): void { |
| 57 | refs.streamingText.value = '' |
| 58 | refs.currentStepWorkflow.value = [] |
| 59 | refs.currentStepIndex.value = -1 |
| 60 | refs.currentAssistantMessageId.value = '' |
| 61 | refs.currentSSETaskId.value = '' |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * 完全重置所有 Refs(包括 SSE 和上下文) |
| 66 | */ |
| 67 | export function resetAllRefs(refs: IAgentRefs): void { |
| 68 | resetAgentRefs(refs) |
| 69 | refs.sseAbort.value = null |
| 70 | refs.t.value = null |
| 71 | refs.actionContext.value = null |
| 72 | } |
| 73 |