Download src/store/useStore.js from cheumk/studio: direct link, hf CLI and curl.
- Browser
- Download file 25.3 kB
-
https://huggingface.co/spaces/cheumk/studio/resolve/main/src/store/useStore.js
- Command line
-
hf download hf://spaces/cheumk/studio/src/store/useStore.js
-
curl -L -o useStore.js https://huggingface.co/spaces/cheumk/studio/resolve/main/src/store/useStore.js
25.3 kB
| /* ------------------------------------------------------------------ * | |
| * 全域狀態(zustand + localStorage 持久化) | |
| * | |
| * 結構以「專案」為主軸: | |
| * 專案 → 多個對話 + 專案指示(system prompt)+ 專案筆記 + 預設 Agent / 模型 | |
| * ------------------------------------------------------------------ */ | |
| import { create } from 'zustand' | |
| import { persist, createJSONStorage } from 'zustand/middleware' | |
| import { BUILTIN_AGENTS } from '../lib/agents' | |
| import { PROVIDER_PRESETS, makeProvider, uid } from '../lib/providers' | |
| import { streamChat } from '../lib/llm' | |
| import { resolveTools, toOpenAITools, executeToolCall } from '../lib/tools' | |
| const now = () => new Date().toISOString() | |
| const controllers = new Map() // convId → AbortController(不持久化) | |
| /* 寫入 localStorage 做節流,避免串流時每個 token 都整包序列化 */ | |
| function debouncedStorage(delay = 600) { | |
| const timers = {} | |
| const pending = {} | |
| const flush = (name) => { | |
| if (pending[name] === undefined) return | |
| try { localStorage.setItem(name, pending[name]) } catch (e) { console.error('localStorage 寫入失敗(可能超過容量)', e) } | |
| delete pending[name] | |
| } | |
| if (typeof window !== 'undefined') { | |
| window.addEventListener('beforeunload', () => Object.keys(pending).forEach(flush)) | |
| } | |
| return { | |
| getItem: (name) => localStorage.getItem(name), | |
| setItem: (name, value) => { | |
| pending[name] = value | |
| clearTimeout(timers[name]) | |
| timers[name] = setTimeout(() => flush(name), delay) | |
| }, | |
| removeItem: (name) => localStorage.removeItem(name), | |
| } | |
| } | |
| function makeProject(name = '我的第一個專案', extra = {}) { | |
| return { | |
| id: uid(), | |
| name, | |
| description: '', | |
| instructions: '', | |
| defaultAgentId: 'assistant', | |
| defaultProviderId: '', | |
| defaultModel: '', | |
| notes: [], | |
| createdAt: now(), | |
| ...extra, | |
| } | |
| } | |
| function initialState() { | |
| const provider = makeProvider(PROVIDER_PRESETS[0]) | |
| // 沿用舊版(v1)存在 localStorage 的單一設定 | |
| try { | |
| const old = JSON.parse(localStorage.getItem('agentStudioConfig') || 'null') | |
| if (old?.supplier) { | |
| provider.baseUrl = old.supplier | |
| provider.apiKey = old.apiKey || '' | |
| if (old.model && !provider.models.includes(old.model)) provider.models.unshift(old.model) | |
| } | |
| } catch { /* ignore */ } | |
| const project = makeProject('我的第一個專案', { defaultProviderId: provider.id, defaultModel: provider.models[0] || '' }) | |
| return { | |
| settings: { | |
| theme: localStorage.getItem('theme') || 'dark', | |
| maxSteps: 10, | |
| temperature: '', | |
| tavilyKey: '', | |
| jinaKey: '', | |
| }, | |
| providers: [provider], | |
| agents: BUILTIN_AGENTS.map((a) => ({ ...a, builtin: true })), | |
| customTools: [], | |
| projects: [project], | |
| conversations: {}, | |
| activeProjectId: project.id, | |
| activeConversationId: null, | |
| } | |
| } | |
| /* ------------------------------ 送進 API 的訊息 ------------------------------ */ | |
| function buildSystemPrompt(agent, project) { | |
| const parts = [] | |
| if (agent?.systemPrompt) parts.push(agent.systemPrompt) | |
| if (project) { | |
| parts.push(`\n【目前專案】${project.name}${project.description ? `:${project.description}` : ''}`) | |
| if (project.instructions?.trim()) parts.push(`【專案指示】\n${project.instructions.trim()}`) | |
| if (project.notes?.length) { | |
| const list = project.notes.map((n) => `- ${n.title}:${String(n.content).slice(0, 300)}`).join('\n') | |
| parts.push(`【專案筆記】(摘要,完整內容可用 read_notes 工具讀取)\n${list.slice(0, 3000)}`) | |
| } | |
| } | |
| parts.push(`【目前時間】${new Date().toString()}`) | |
| return parts.join('\n') | |
| } | |
| /** 清理歷史:移除錯誤訊息、只保留有對應結果的 tool_calls(避免中止後 API 回 400) */ | |
| function toApiMessages(messages, systemPrompt) { | |
| const valid = messages.filter((m) => !m.error && !m.info) | |
| const resultIds = new Set(valid.filter((m) => m.role === 'tool').map((m) => m.tool_call_id)) | |
| const keptCallIds = new Set() | |
| const out = [{ role: 'system', content: systemPrompt }] | |
| for (const m of valid) { | |
| if (m.role === 'user') out.push({ role: 'user', content: m.content }) | |
| else if (m.role === 'assistant') { | |
| const calls = (m.tool_calls || []).filter((c) => resultIds.has(c.id)) | |
| calls.forEach((c) => keptCallIds.add(c.id)) | |
| if (!calls.length && !m.content) continue | |
| const msg = { role: 'assistant', content: m.content || (calls.length ? null : '') } | |
| if (calls.length) { | |
| msg.tool_calls = calls.map((c) => ({ | |
| id: c.id, type: 'function', function: { name: c.function.name, arguments: c.function.arguments || '{}' }, | |
| })) | |
| } | |
| out.push(msg) | |
| } else if (m.role === 'tool' && keptCallIds.has(m.tool_call_id)) { | |
| out.push({ role: 'tool', tool_call_id: m.tool_call_id, content: String(m.content ?? '') }) | |
| } | |
| } | |
| return out | |
| } | |
| /* ------------------------------ Store ------------------------------ */ | |
| export const useStore = create( | |
| persist( | |
| (set, get) => { | |
| const patchConv = (convId, fn) => | |
| set((s) => { | |
| const c = s.conversations[convId] | |
| if (!c) return {} | |
| return { conversations: { ...s.conversations, [convId]: { ...c, ...fn(c), updatedAt: now() } } } | |
| }) | |
| const pushMsg = (convId, msg) => patchConv(convId, (c) => ({ messages: [...c.messages, msg] })) | |
| const patchMsg = (convId, msgId, patch) => | |
| patchConv(convId, (c) => ({ messages: c.messages.map((m) => (m.id === msgId ? { ...m, ...patch } : m)) })) | |
| return { | |
| ...initialState(), | |
| running: {}, // convId → 目前步數(不持久化) | |
| sidebarOpen: false, // 行動版側邊欄(不持久化) | |
| /* ---------- UI ---------- */ | |
| setSidebarOpen: (v) => set({ sidebarOpen: v }), | |
| updateSettings: (patch) => set((s) => ({ settings: { ...s.settings, ...patch } })), | |
| /* ---------- 供應商 ---------- */ | |
| addProvider: (preset) => { | |
| const p = makeProvider(preset) | |
| set((s) => ({ providers: [...s.providers, p] })) | |
| return p.id | |
| }, | |
| updateProvider: (id, patch) => | |
| set((s) => ({ providers: s.providers.map((p) => (p.id === id ? { ...p, ...patch } : p)) })), | |
| removeProvider: (id) => set((s) => ({ providers: s.providers.filter((p) => p.id !== id) })), | |
| /* ---------- Agent ---------- */ | |
| saveAgent: (agent) => | |
| set((s) => { | |
| const exists = s.agents.some((a) => a.id === agent.id) | |
| return { agents: exists ? s.agents.map((a) => (a.id === agent.id ? { ...a, ...agent } : a)) : [...s.agents, agent] } | |
| }), | |
| removeAgent: (id) => set((s) => ({ agents: s.agents.filter((a) => a.id !== id) })), | |
| resetBuiltinAgents: () => | |
| set((s) => ({ | |
| agents: [...BUILTIN_AGENTS.map((a) => ({ ...a, builtin: true })), ...s.agents.filter((a) => !a.builtin)], | |
| })), | |
| /* ---------- 自訂工具 ---------- */ | |
| saveCustomTool: (tool) => | |
| set((s) => { | |
| const exists = s.customTools.some((t) => t.name === tool.name) | |
| return { customTools: exists ? s.customTools.map((t) => (t.name === tool.name ? tool : t)) : [...s.customTools, tool] } | |
| }), | |
| removeCustomTool: (name) => set((s) => ({ customTools: s.customTools.filter((t) => t.name !== name) })), | |
| /* ---------- 專案 ---------- */ | |
| createProject: (name) => { | |
| const s = get() | |
| const cur = s.projects.find((p) => p.id === s.activeProjectId) | |
| const p = makeProject(name || '新專案', { | |
| defaultProviderId: cur?.defaultProviderId || s.providers[0]?.id || '', | |
| defaultModel: cur?.defaultModel || s.providers[0]?.models?.[0] || '', | |
| }) | |
| set((st) => ({ projects: [...st.projects, p], activeProjectId: p.id, activeConversationId: null })) | |
| return p.id | |
| }, | |
| updateProject: (id, patch) => | |
| set((s) => ({ projects: s.projects.map((p) => (p.id === id ? { ...p, ...patch } : p)) })), | |
| removeProject: (id) => | |
| set((s) => { | |
| const projects = s.projects.filter((p) => p.id !== id) | |
| const conversations = Object.fromEntries(Object.entries(s.conversations).filter(([, c]) => c.projectId !== id)) | |
| const fallback = projects[0] || makeProject() | |
| return { | |
| projects: projects.length ? projects : [fallback], | |
| conversations, | |
| activeProjectId: s.activeProjectId === id ? fallback.id : s.activeProjectId, | |
| activeConversationId: conversations[s.activeConversationId] ? s.activeConversationId : null, | |
| } | |
| }), | |
| selectProject: (id) => { | |
| const convs = Object.values(get().conversations).filter((c) => c.projectId === id) | |
| convs.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)) | |
| set({ activeProjectId: id, activeConversationId: convs[0]?.id || null }) | |
| }, | |
| /* ---------- 專案筆記 ---------- */ | |
| addNote: (projectId, { title, content }) => | |
| set((s) => ({ | |
| projects: s.projects.map((p) => | |
| p.id === projectId | |
| ? { ...p, notes: [...(p.notes || []), { id: uid(), title, content, createdAt: now(), updatedAt: now() }] } | |
| : p), | |
| })), | |
| updateNote: (projectId, noteId, patch) => | |
| set((s) => ({ | |
| projects: s.projects.map((p) => | |
| p.id === projectId | |
| ? { ...p, notes: p.notes.map((n) => (n.id === noteId ? { ...n, ...patch, updatedAt: now() } : n)) } | |
| : p), | |
| })), | |
| removeNote: (projectId, noteId) => | |
| set((s) => ({ | |
| projects: s.projects.map((p) => (p.id === projectId ? { ...p, notes: p.notes.filter((n) => n.id !== noteId) } : p)), | |
| })), | |
| /* ---------- 對話 ---------- */ | |
| createConversation: () => { | |
| const s = get() | |
| const project = s.projects.find((p) => p.id === s.activeProjectId) || s.projects[0] | |
| const providerId = s.providers.some((p) => p.id === project.defaultProviderId) | |
| ? project.defaultProviderId | |
| : s.providers[0]?.id || '' | |
| const provider = s.providers.find((p) => p.id === providerId) | |
| const conv = { | |
| id: uid(), | |
| projectId: project.id, | |
| title: '新對話', | |
| agentId: project.defaultAgentId || 'assistant', | |
| providerId, | |
| model: project.defaultModel || provider?.models?.[0] || '', | |
| messages: [], | |
| createdAt: now(), | |
| updatedAt: now(), | |
| } | |
| set((st) => ({ conversations: { ...st.conversations, [conv.id]: conv }, activeConversationId: conv.id })) | |
| return conv.id | |
| }, | |
| selectConversation: (id) => set({ activeConversationId: id, sidebarOpen: false }), | |
| updateConversation: (id, patch) => patchConv(id, () => patch), | |
| removeConversation: (id) => { | |
| get().stop(id) | |
| set((s) => { | |
| const conversations = { ...s.conversations } | |
| delete conversations[id] | |
| return { conversations, activeConversationId: s.activeConversationId === id ? null : s.activeConversationId } | |
| }) | |
| }, | |
| clearConversation: (id) => { if (!get().running[id]) patchConv(id, () => ({ messages: [] })) }, | |
| deleteMessage: (convId, msgId) => patchConv(convId, (c) => ({ messages: c.messages.filter((m) => m.id !== msgId) })), | |
| /* ---------- 執行 ---------- */ | |
| stop: (convId) => controllers.get(convId)?.abort(), | |
| async send(convId, text) { | |
| const conv = get().conversations[convId] | |
| if (!conv || get().running[convId]) return | |
| const content = text.trim() | |
| if (!content) return | |
| if (!conv.messages.some((m) => m.role === 'user')) { | |
| patchConv(convId, () => ({ title: content.replace(/\s+/g, ' ').slice(0, 30) })) | |
| } | |
| pushMsg(convId, { id: uid(), role: 'user', content, createdAt: now() }) | |
| await get().runLoop(convId) | |
| }, | |
| async regenerate(convId) { | |
| const conv = get().conversations[convId] | |
| if (!conv || get().running[convId]) return | |
| const lastUser = conv.messages.map((m) => m.role).lastIndexOf('user') | |
| if (lastUser < 0) return | |
| patchConv(convId, (c) => ({ messages: c.messages.slice(0, lastUser + 1) })) | |
| await get().runLoop(convId) | |
| }, | |
| async runLoop(convId) { | |
| const s = get() | |
| const conv = s.conversations[convId] | |
| const project = s.projects.find((p) => p.id === conv.projectId) | |
| const agent = s.agents.find((a) => a.id === conv.agentId) || s.agents[0] | |
| const provider = s.providers.find((p) => p.id === conv.providerId) | |
| const fail = (msg) => pushMsg(convId, { id: uid(), role: 'assistant', content: `⚠️ ${msg}`, error: true, createdAt: now() }) | |
| if (!provider) return fail('這個對話沒有選擇供應商,請在側邊欄「目前對話」選一個') | |
| if (!provider.baseUrl?.trim()) return fail(`供應商「${provider.name}」沒有設定 API URL`) | |
| if (!provider.noKey && !provider.apiKey?.trim()) return fail(`供應商「${provider.name}」尚未填 API Key(側邊欄 → 模型)`) | |
| if (!conv.model?.trim()) return fail('尚未選擇模型') | |
| const tools = resolveTools(agent?.tools, s.customTools) | |
| const apiTools = toOpenAITools(tools) | |
| const temp = s.settings.temperature === '' ? undefined : Number(s.settings.temperature) | |
| const maxSteps = Math.max(1, Number(s.settings.maxSteps) || 10) | |
| const controller = new AbortController() | |
| controllers.set(convId, controller) | |
| set((st) => ({ running: { ...st.running, [convId]: 1 } })) | |
| try { | |
| let finished = false | |
| for (let step = 1; step <= maxSteps; step++) { | |
| set((st) => ({ running: { ...st.running, [convId]: step } })) | |
| const cur = get().conversations[convId] | |
| if (!cur) return | |
| const curProject = get().projects.find((p) => p.id === cur.projectId) || project | |
| const messages = toApiMessages(cur.messages, buildSystemPrompt(agent, curProject)) | |
| const msgId = uid() | |
| pushMsg(convId, { | |
| id: msgId, role: 'assistant', content: '', reasoning: '', tool_calls: [], | |
| streaming: true, model: conv.model, agentId: agent?.id, createdAt: now(), | |
| }) | |
| let result | |
| try { | |
| result = await streamChat({ | |
| provider, model: conv.model, messages, tools: apiTools, temperature: temp, | |
| signal: controller.signal, | |
| onDelta: (d) => patchMsg(convId, msgId, d), | |
| }) | |
| } catch (e) { | |
| const aborted = e.name === 'AbortError' | |
| const partial = get().conversations[convId]?.messages.find((m) => m.id === msgId) | |
| if (aborted) { | |
| patchMsg(convId, msgId, { streaming: false, stopped: true, tool_calls: [] }) | |
| if (!partial?.content) patchMsg(convId, msgId, { content: '⏹ 已停止', info: true }) | |
| } else { | |
| patchMsg(convId, msgId, { | |
| streaming: false, error: true, tool_calls: [], | |
| content: `${partial?.content ? `${partial.content}\n\n` : ''}⚠️ ${e.message}`, | |
| }) | |
| } | |
| finished = true | |
| break | |
| } | |
| patchMsg(convId, msgId, { | |
| streaming: false, | |
| content: result.content, | |
| reasoning: result.reasoning, | |
| tool_calls: result.tool_calls, | |
| }) | |
| if (!result.tool_calls.length) { | |
| if (!result.content && !result.reasoning) { | |
| patchMsg(convId, msgId, { content: '⚠️ 模型沒有回傳任何內容', error: true }) | |
| } | |
| finished = true | |
| break | |
| } | |
| const ctx = { | |
| settings: get().settings, | |
| project: get().projects.find((p) => p.id === conv.projectId), | |
| addNote: get().addNote, | |
| signal: controller.signal, | |
| } | |
| for (const call of result.tool_calls) { | |
| const toolMsgId = uid() | |
| pushMsg(convId, { | |
| id: toolMsgId, role: 'tool', tool_call_id: call.id, name: call.function?.name, | |
| arguments: call.function?.arguments, content: '', pending: true, createdAt: now(), | |
| }) | |
| const output = controller.signal.aborted ? '已中止' : await executeToolCall(call, tools, ctx) | |
| ctx.project = get().projects.find((p) => p.id === conv.projectId) | |
| patchMsg(convId, toolMsgId, { content: output, pending: false }) | |
| } | |
| if (controller.signal.aborted) { | |
| pushMsg(convId, { id: uid(), role: 'assistant', content: '⏹ 已停止', info: true, createdAt: now() }) | |
| finished = true | |
| break | |
| } | |
| } | |
| if (!finished) { | |
| pushMsg(convId, { | |
| id: uid(), role: 'assistant', info: true, createdAt: now(), | |
| content: `⏸ 已達步數上限(${maxSteps} 步)。可輸入「繼續」讓 Agent 接著做,或在設定調高上限。`, | |
| }) | |
| } | |
| } finally { | |
| controllers.delete(convId) | |
| set((st) => { | |
| const running = { ...st.running } | |
| delete running[convId] | |
| return { running } | |
| }) | |
| } | |
| }, | |
| /* ---------- 匯入 / 匯出 ---------- */ | |
| exportData(scope = 'all', { includeKeys = true, id } = {}) { | |
| const s = get() | |
| const strip = (providers) => providers.map((p) => (includeKeys ? p : { ...p, apiKey: '' })) | |
| const settings = includeKeys ? s.settings : { ...s.settings, tavilyKey: '', jinaKey: '' } | |
| const base = { app: 'agent-studio', version: 2, type: scope, exportedAt: now() } | |
| if (scope === 'settings') { | |
| return { ...base, data: { settings, providers: strip(s.providers), agents: s.agents, customTools: s.customTools } } | |
| } | |
| if (scope === 'project') { | |
| const project = s.projects.find((p) => p.id === id) | |
| const conversations = Object.values(s.conversations).filter((c) => c.projectId === id) | |
| return { ...base, data: { projects: [project], conversations } } | |
| } | |
| if (scope === 'conversation') { | |
| return { ...base, data: { conversations: [s.conversations[id]] } } | |
| } | |
| return { | |
| ...base, | |
| type: 'all', | |
| data: { | |
| settings, providers: strip(s.providers), agents: s.agents, customTools: s.customTools, | |
| projects: s.projects, conversations: Object.values(s.conversations), | |
| activeProjectId: s.activeProjectId, activeConversationId: s.activeConversationId, | |
| }, | |
| } | |
| }, | |
| /** mode: 'merge'(合併,同 id 覆蓋)| 'replace'(整個取代)。回傳摘要字串 */ | |
| importData(json, mode = 'merge') { | |
| let file = json | |
| // 相容 v1 匯出格式 { messages: [...] } | |
| if (Array.isArray(file?.messages) && !file.data) { | |
| file = { | |
| type: 'conversation', | |
| data: { | |
| conversations: [{ | |
| id: uid(), title: `匯入:${file.source || '舊版對話'}`, agentId: 'assistant', | |
| messages: file.messages.map((m) => ({ ...m, id: uid() })), createdAt: now(), updatedAt: now(), | |
| }], | |
| }, | |
| } | |
| } | |
| const d = file?.data | |
| if (!d) throw new Error('檔案格式不正確(找不到 data 欄位)') | |
| const s = get() | |
| const summary = [] | |
| if (mode === 'replace' && file.type === 'all') { | |
| const projects = d.projects?.length ? d.projects : [makeProject()] | |
| const conversations = Object.fromEntries((d.conversations || []).map((c) => [c.id, c])) | |
| set({ | |
| settings: { ...initialState().settings, ...(d.settings || {}) }, | |
| providers: d.providers || [], | |
| agents: d.agents?.length ? d.agents : BUILTIN_AGENTS.map((a) => ({ ...a, builtin: true })), | |
| customTools: d.customTools || [], | |
| projects, | |
| conversations, | |
| activeProjectId: projects.some((p) => p.id === d.activeProjectId) ? d.activeProjectId : projects[0].id, | |
| activeConversationId: conversations[d.activeConversationId] ? d.activeConversationId : null, | |
| }) | |
| return `已取代全部資料:${projects.length} 個專案、${Object.keys(conversations).length} 個對話` | |
| } | |
| const mergeById = (cur, inc, key = 'id') => { | |
| const map = new Map(cur.map((x) => [x[key], x])) | |
| inc.forEach((x) => { | |
| const prev = map.get(x[key]) | |
| // 匯入的設定沒帶金鑰時保留本機原有金鑰 | |
| if (prev && 'apiKey' in x && !x.apiKey && prev.apiKey) x = { ...x, apiKey: prev.apiKey } | |
| map.set(x[key], x) | |
| }) | |
| return [...map.values()] | |
| } | |
| const patch = {} | |
| if (d.settings) { | |
| const inc = { ...d.settings } | |
| if (!inc.tavilyKey) delete inc.tavilyKey | |
| if (!inc.jinaKey) delete inc.jinaKey | |
| patch.settings = { ...s.settings, ...inc } | |
| summary.push('設定') | |
| } | |
| if (d.providers) { patch.providers = mergeById(s.providers, d.providers); summary.push(`${d.providers.length} 個供應商`) } | |
| if (d.agents) { patch.agents = mergeById(s.agents, d.agents); summary.push(`${d.agents.length} 個 Agent`) } | |
| if (d.customTools) { patch.customTools = mergeById(s.customTools, d.customTools, 'name'); summary.push(`${d.customTools.length} 個自訂工具`) } | |
| let projects = patch.projects || s.projects | |
| if (d.projects) { | |
| projects = mergeById(projects, d.projects.filter(Boolean)) | |
| patch.projects = projects | |
| summary.push(`${d.projects.length} 個專案`) | |
| } | |
| if (d.conversations) { | |
| const conversations = { ...s.conversations } | |
| const projectIds = new Set(projects.map((p) => p.id)) | |
| d.conversations.filter(Boolean).forEach((c) => { | |
| // 對話所屬專案不存在時,掛到目前專案 | |
| const conv = { ...c, projectId: projectIds.has(c.projectId) ? c.projectId : s.activeProjectId } | |
| if (!conv.providerId || !(patch.providers || s.providers).some((p) => p.id === conv.providerId)) { | |
| const prov = (patch.providers || s.providers)[0] | |
| conv.providerId = prov?.id || '' | |
| if (!conv.model) conv.model = prov?.models?.[0] || '' | |
| } | |
| conversations[conv.id] = conv | |
| }) | |
| patch.conversations = conversations | |
| summary.push(`${d.conversations.length} 個對話`) | |
| if (d.conversations.length === 1 && file.type === 'conversation') { | |
| const c = conversations[d.conversations[0].id] | |
| patch.activeProjectId = c.projectId | |
| patch.activeConversationId = c.id | |
| } | |
| } | |
| set(patch) | |
| return `已匯入:${summary.join('、') || '(沒有可匯入的內容)'}` | |
| }, | |
| resetAll() { | |
| Object.keys(get().running).forEach((id) => get().stop(id)) | |
| set({ ...initialState(), running: {} }) | |
| }, | |
| } | |
| }, | |
| { | |
| name: 'agentStudio.v2', | |
| storage: createJSONStorage(() => debouncedStorage()), | |
| partialize: (s) => ({ | |
| settings: s.settings, | |
| providers: s.providers, | |
| agents: s.agents, | |
| customTools: s.customTools, | |
| projects: s.projects, | |
| conversations: s.conversations, | |
| activeProjectId: s.activeProjectId, | |
| activeConversationId: s.activeConversationId, | |
| }), | |
| // 重新整理時若有串流中斷的訊息,把狀態收尾 | |
| onRehydrateStorage: () => (state) => { | |
| if (!state) return | |
| Object.values(state.conversations || {}).forEach((c) => { | |
| c.messages = (c.messages || []).map((m) => (m.streaming || m.pending ? { ...m, streaming: false, pending: false, stopped: true } : m)) | |
| }) | |
| }, | |
| }, | |
| ), | |
| ) | |
| /* ---------- 選取器 ---------- */ | |
| export const useActiveProject = () => | |
| useStore((s) => s.projects.find((p) => p.id === s.activeProjectId) || s.projects[0]) | |
| export const useActiveConversation = () => useStore((s) => s.conversations[s.activeConversationId] || null) | |