| 1 | // 当前工作区/知识库上下文:均可切换且 localStorage 记忆;工作区无 KB 时自动创建 "General"。 |
| 2 | import { useSyncExternalStore } from "react"; |
| 3 | import { useQuery, useQueryClient } from "@tanstack/react-query"; |
| 4 | import { api, type Kb, type Workspace } from "./api"; |
| 5 | import { kbStore, wsStore } from "./wsStore"; |
| 6 | |
| 7 | export function useKb(): { |
| 8 | kb: Kb | null; |
| 9 | kbs: Kb[]; |
| 10 | workspace: Workspace | null; |
| 11 | workspaces: Workspace[]; |
| 12 | setWorkspace: (id: string) => void; |
| 13 | setKb: (id: string) => void; |
| 14 | } { |
| 15 | const queryClient = useQueryClient(); |
| 16 | const selectedId = useSyncExternalStore(wsStore.subscribe, wsStore.get); |
| 17 | const selectedKbId = useSyncExternalStore(kbStore.subscribe, kbStore.get); |
| 18 | |
| 19 | const workspaces = useQuery({ queryKey: ["workspaces"], queryFn: api.workspaces }); |
| 20 | const list = workspaces.data ?? []; |
| 21 | const ws = list.find((w) => w.id === selectedId) ?? list[0] ?? null; |
| 22 | |
| 23 | const kbs = useQuery({ |
| 24 | queryKey: ["kbs", ws?.id], |
| 25 | queryFn: async () => { |
| 26 | const existing = await api.kbs(ws!.id); |
| 27 | if (existing.length > 0) return existing; |
| 28 | // 空工作区自动创建 General——建库现在是管理员动作,非管理员会 403: |
| 29 | // 静默等管理员来创建(现实中首个用户即管理员,General 总在) |
| 30 | try { |
| 31 | const created = await api.createKb(ws!.id, { name: "General" }); |
| 32 | queryClient.invalidateQueries({ queryKey: ["kbs", ws!.id] }); |
| 33 | return [created]; |
| 34 | } catch { |
| 35 | return []; |
| 36 | } |
| 37 | }, |
| 38 | enabled: !!ws, |
| 39 | }); |
| 40 | |
| 41 | const kbList = kbs.data ?? []; |
| 42 | const kb = kbList.find((k) => k.id === selectedKbId) ?? kbList[0] ?? null; |
| 43 | |
| 44 | return { |
| 45 | kb, |
| 46 | kbs: kbList, |
| 47 | workspace: ws, |
| 48 | workspaces: list, |
| 49 | setWorkspace: wsStore.set, |
| 50 | setKb: kbStore.set, |
| 51 | }; |
| 52 | } |