File size: 25,255 Bytes
4e039c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/* ------------------------------------------------------------------ *
 * 全域狀態(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)