| 41 | } |
| 42 | |
| 43 | export function useChatCore({ pageId }: UseChatCoreOptions): UseChatCoreResult { |
| 44 | const { pages } = usePagesStore() |
| 45 | const { cache, load } = useMessagesStore() |
| 46 | const { settings } = useSettingsStore() |
| 47 | |
| 48 | const page = useMemo(() => pages.find((p) => p.id === pageId), [pages, pageId]) |
| 49 | const record = cache[pageId] |
| 50 | const messages = useMemo(() => record?.messages ?? [], [record?.messages]) |
| 51 | const isLoading = !record |
| 52 | |
| 53 | // 加载消息 |
| 54 | useEffect(() => { |
| 55 | if (!record && pageId) { |
| 56 | load(pageId) |
| 57 | } |
| 58 | }, [pageId, record, load]) |
| 59 | |
| 60 | const currentPath = useMemo(() => { |
| 61 | if (!record) return [] |
| 62 | return messagesService.getMessagePath(record.messages, record.leafMessageId) |
| 63 | }, [record]) |
| 64 | |
| 65 | // Topics |
| 66 | const topics = useMemo(() => record?.topics ?? [], [record?.topics]) |
| 67 | |
| 68 | // Topic 分组和大纲计算 |
| 69 | const topicGroups = useMemo(() => { |
| 70 | return messagesService.computeTopicGroups(topics, currentPath) |
| 71 | }, [topics, currentPath]) |
| 72 | |
| 73 | const outline = useMemo(() => { |
| 74 | return messagesService.computeOutline(topicGroups, currentPath) |
| 75 | }, [topicGroups, currentPath]) |
| 76 | |
| 77 | // 获取默认配置 |
| 78 | const getConfigs = useCallback((): ChatConfigs | null => { |
| 79 | const llmConfig = settings.llmConfigs.items.find((c) => c.id === settings.defaultLLMId) |
| 80 | if (!llmConfig) return null |
| 81 | |
| 82 | const modelConfig = settings.modelConfigs.items.find( |
| 83 | (c) => c.id === settings.defaultModelConfigId |
| 84 | ) |
| 85 | |
| 86 | return { llmConfig, modelConfig } |
| 87 | }, [settings]) |
| 88 | |
| 89 | // 获取配置(支持覆盖) |
| 90 | const getConfigsWithOverride = useCallback( |
| 91 | (llmId?: string, modelConfigId?: string): ChatConfigs | null => { |
| 92 | const targetLLMId = llmId ?? settings.defaultLLMId |
| 93 | const llmConfig = settings.llmConfigs.items.find((c) => c.id === targetLLMId) |
| 94 | if (!llmConfig) return null |
| 95 | |
| 96 | const targetModelConfigId = modelConfigId ?? settings.defaultModelConfigId |
| 97 | const modelConfig = settings.modelConfigs.items.find((c) => c.id === targetModelConfigId) |
| 98 | |
| 99 | return { llmConfig, modelConfig } |
| 100 | }, |