dsh-learn-space 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,1740 @@
1
+ /**
2
+ * 学习空间 Client 半边:sidebar 面板图标 + main 面板页。
3
+ * 数据来自 Host 的 /api/learning-space/overview。
4
+ */
5
+ window.__ModuleLoader__.load({
6
+ id: 'dsh-learn-space',
7
+ factory(require) {
8
+ const React = require('react')
9
+ const { useEffect, useState, useCallback, useMemo, useRef } = React
10
+ const h = React.createElement
11
+
12
+ const STATUS_COLOR = {
13
+ done: '#3E6B4F',
14
+ doing: '#3D5A80',
15
+ warn: '#B5432E',
16
+ todo: '#9A968C',
17
+ }
18
+ const STATUS_LABEL = { done: '已确认', doing: '进行中', warn: '待修复', todo: '未学' }
19
+
20
+ // ── 轻量 toast:模块级队列 + 右下角栈,不引第三方运行时 ──
21
+ const toastStore = { items: [], listeners: new Set() }
22
+ let toastSeq = 0
23
+ const emitToasts = () => { for (const l of toastStore.listeners) l(toastStore.items) }
24
+ const dismissToast = id => {
25
+ const t = toastStore.items.find(x => x.id === id)
26
+ if (!t || t.leaving) return
27
+ toastStore.items = toastStore.items.map(x => x.id === id ? { ...x, leaving: true } : x)
28
+ emitToasts()
29
+ setTimeout(() => {
30
+ toastStore.items = toastStore.items.filter(x => x.id !== id)
31
+ emitToasts()
32
+ }, 180)
33
+ }
34
+ const pushToast = (type, title, desc) => {
35
+ const id = ++toastSeq
36
+ toastStore.items = [...toastStore.items, { id, type, title, desc }].slice(-3)
37
+ emitToasts()
38
+ setTimeout(() => dismissToast(id), 3200)
39
+ return id
40
+ }
41
+ const toast = {
42
+ success: (title, desc) => pushToast('success', title, desc),
43
+ error: (title, desc) => pushToast('error', title, desc),
44
+ warning: (title, desc) => pushToast('warning', title, desc),
45
+ info: (title, desc) => pushToast('info', title, desc),
46
+ loading: (title, desc) => pushToast('loading', title, desc),
47
+ }
48
+
49
+ function ToastGlyph({ type }) {
50
+ if (type === 'loading') {
51
+ return h('svg', {
52
+ className: 'ls-spin', viewBox: '0 0 24 24', width: 17, height: 17,
53
+ fill: 'none', stroke: 'currentColor', strokeWidth: 2.6, strokeLinecap: 'round',
54
+ },
55
+ h('circle', { cx: 12, cy: 12, r: 8, strokeOpacity: .3 }),
56
+ h('path', { d: 'M12 4a8 8 0 0 1 8 8' }))
57
+ }
58
+ const stroke = { fill: 'none', stroke: 'currentColor', strokeWidth: 3, strokeLinecap: 'round', strokeLinejoin: 'round' }
59
+ return h('svg', { viewBox: '0 0 24 24', width: 17, height: 17, ...stroke },
60
+ type === 'success' ? h('path', { d: 'M6 12.5l4 4 8-9' })
61
+ : type === 'error' ? h('path', { d: 'M7.5 7.5l9 9M16.5 7.5l-9 9' })
62
+ : type === 'warning' ? h('path', { d: 'M12 6v6.5M12 16.8v.7' })
63
+ : h('path', { d: 'M12 6.2v.7M12 10.5v7' }))
64
+ }
65
+
66
+ function ToastHost() {
67
+ const [items, setItems] = useState(toastStore.items)
68
+ useEffect(() => {
69
+ const fn = list => setItems(list)
70
+ toastStore.listeners.add(fn)
71
+ return () => { toastStore.listeners.delete(fn) }
72
+ }, [])
73
+ return h('div', { className: 'ls-toasts', 'aria-live': 'polite' },
74
+ items.map(t => h('div', { key: t.id, className: 'ls-toast' + (t.leaving ? ' leaving' : ''), 'data-type': t.type },
75
+ h('span', { className: `ls-toast-tile ${t.type}` }, h(ToastGlyph, { type: t.type })),
76
+ h('div', { className: 'ls-toast-body' },
77
+ h('div', { className: 'ls-toast-title' }, t.title),
78
+ t.desc ? h('div', { className: 'ls-toast-desc' }, t.desc) : null),
79
+ h('button', { className: 'ls-toast-x', type: 'button', 'aria-label': '关闭', onClick: () => dismissToast(t.id) }, '×'))))
80
+ }
81
+
82
+ // ── AI 状态行:闪烁文字 + 图标动画 + 秒表(AiStatus 的移植版) ──
83
+ const SPARKLE_PATH = 'M11 5Q12 12 19 13Q12 14 11 21Q10 14 3 13Q10 12 11 5Z'
84
+ const TWINKLE_PATH = 'M18 2Q18.4 4.6 21 5Q18.4 5.4 18 8Q17.6 5.4 15 5Q17.6 4.6 18 2Z'
85
+
86
+ function AiStatus({ state = 'thinking', label, detail, elapsed }) {
87
+ const busy = state === 'thinking' || state === 'tool'
88
+ const [secs, setSecs] = useState(0)
89
+ useEffect(() => {
90
+ if (!busy) return
91
+ const start = Date.now()
92
+ setSecs(0)
93
+ const id = setInterval(() => setSecs(Math.floor((Date.now() - start) / 1000)), 1000)
94
+ return () => clearInterval(id)
95
+ }, [busy])
96
+ const time = elapsed != null ? elapsed : (busy ? secs : null)
97
+ const icon = state === 'done'
98
+ ? h('svg', { viewBox: '0 0 24 24', width: 16, height: 16, fill: 'none', stroke: 'currentColor',
99
+ strokeWidth: 2.4, strokeLinecap: 'round', strokeLinejoin: 'round' },
100
+ h('path', { className: 'ls-ai-check', d: 'M5 12.5L10 17.5L19 7' }))
101
+ : state === 'tool'
102
+ ? h('svg', { viewBox: '0 0 24 24', width: 16, height: 16, fill: 'none', stroke: 'currentColor',
103
+ strokeWidth: 2.6, strokeLinecap: 'round' },
104
+ [6, 12, 18].map(x => h('line', {
105
+ key: x, className: 'ls-ai-bar', x1: x, y1: 18.5, x2: x, y2: 7.5,
106
+ style: { transformBox: 'fill-box', transformOrigin: 'center' },
107
+ })))
108
+ : h('svg', { viewBox: '0 0 24 24', width: 16, height: 16, fill: 'currentColor' },
109
+ h('path', { className: 'ls-ai-spark', d: SPARKLE_PATH }),
110
+ h('path', { className: 'ls-ai-spark2', d: TWINKLE_PATH }))
111
+ return h('div', { className: 'ls-aistatus' + (busy ? ' active' : ''), role: 'status', 'aria-busy': busy },
112
+ h('span', { className: 'ls-aistatus-icon' + (state === 'done' ? ' ls-aistatus-done' : '') }, icon),
113
+ h('span', { className: 'ls-aistatus-label' }, label || (busy ? '思考中' : '完成')),
114
+ detail ? h('span', { className: 'ls-aistatus-detail' }, detail) : null,
115
+ time != null && time > 0 ? h('span', { className: 'ls-aistatus-time' }, `${time}s`) : null)
116
+ }
117
+
118
+ // ── 课程剩余节点铃铛:数字徽标 + 换数时摆铃 + 点开列剩余节点 ──
119
+ const BELL_BODY = 'M3.5 6.5C3.5 3.46279 5.96279 1 9 1C12.0372 1 14.5 3.46279 14.5 6.5V10.75C14.5 11.4408 15.0592 12 15.75 12C16.1642 12 16.5 12.3358 16.5 12.75C16.5 13.1642 16.1642 13.5 15.75 13.5H2.25C1.83579 13.5 1.5 13.1642 1.5 12.75C1.5 12.3358 1.83579 12 2.25 12C2.94079 12 3.5 11.4408 3.5 10.75V6.5Z'
120
+ const BELL_CLAPPER = 'M10.2 15H7.80099C7.64999 15 7.50799 15.068 7.41299 15.185C7.31799 15.302 7.28099 15.456 7.31199 15.603C7.48499 16.425 8.17999 17 9.00099 17C9.82199 17 10.517 16.425 10.69 15.603C10.721 15.456 10.684 15.302 10.589 15.185C10.494 15.068 10.351 15 10.2 15Z'
121
+
122
+ function NotificationBell({ nodes }) {
123
+ const [open, setOpen] = useState(false)
124
+ const [ring, setRing] = useState(0)
125
+ const rootRef = useRef(null)
126
+ const todo = nodes.filter(n => n.status === 'todo')
127
+ const count = todo.length
128
+ const prevRef = useRef(count)
129
+ useEffect(() => {
130
+ if (count !== prevRef.current) { prevRef.current = count; setRing(r => r + 1) }
131
+ }, [count])
132
+ useEffect(() => {
133
+ if (!open) return
134
+ const onDown = e => { if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false) }
135
+ const onKey = e => { if (e.key === 'Escape') setOpen(false) }
136
+ document.addEventListener('pointerdown', onDown)
137
+ document.addEventListener('keydown', onKey)
138
+ return () => {
139
+ document.removeEventListener('pointerdown', onDown)
140
+ document.removeEventListener('keydown', onKey)
141
+ }
142
+ }, [open])
143
+ return h('div', { className: 'ls-bell-wrap', ref: rootRef },
144
+ h('button', {
145
+ className: 'ls-bell' + (open ? ' open' : ''), type: 'button',
146
+ 'aria-expanded': open, 'aria-label': count ? `剩余 ${count} 个节点未学` : '所有节点已确认',
147
+ title: count ? `剩余 ${count} 个节点未学` : '所有节点已确认',
148
+ onClick: e => { e.stopPropagation(); setOpen(v => !v) },
149
+ },
150
+ h('svg', {
151
+ key: ring, className: ring ? 'ls-bell-swing' : '', viewBox: '0 0 18 18',
152
+ width: 17, height: 17, fill: 'currentColor', 'aria-hidden': true,
153
+ },
154
+ h('path', { fillOpacity: .55, d: BELL_BODY }),
155
+ h('path', { d: BELL_CLAPPER })),
156
+ count > 0 ? h('span', { className: 'ls-bell-badge' }, count > 99 ? '99+' : count) : null),
157
+ open ? h('div', { className: 'ls-bell-pop', onClick: e => e.stopPropagation() },
158
+ h('div', { className: 'ls-bell-pop-h' }, count ? `剩余 ${count} 个节点未学` : '所有节点已确认'),
159
+ count ? h('div', { className: 'ls-bell-pop-list' }, todo.map(n =>
160
+ h('div', { key: n.label, className: 'ls-bell-pop-item' },
161
+ h('span', { className: 'ls-dot', style: { background: STATUS_COLOR.todo, flex: 'none' } }),
162
+ cleanLabel(n.label)))) : null) : null)
163
+ }
164
+
165
+ // ── 模型选择:按 provider 分组的搜索式下拉(ModelPicker 的移植版) ──
166
+ function ModelPicker({ models, value, onChange, disabled, placeholder }) {
167
+ const [open, setOpen] = useState(false)
168
+ const [q, setQ] = useState('')
169
+ const [active, setActive] = useState(0)
170
+ const [dropUp, setDropUp] = useState(false)
171
+ const rootRef = useRef(null)
172
+ const triggerRef = useRef(null)
173
+ const inputRef = useRef(null)
174
+ const listRef = useRef(null)
175
+ const selected = models.find(m => m.provider === value.provider && m.modelId === value.model)
176
+ const filtered = useMemo(() => {
177
+ const s = q.trim().toLowerCase()
178
+ return s ? models.filter(m => `${m.name} ${m.providerName}`.toLowerCase().includes(s)) : models
179
+ }, [models, q])
180
+ const sections = []
181
+ filtered.forEach((m, i) => {
182
+ const last = sections[sections.length - 1]
183
+ if (last && last.name === m.providerName) last.items.push({ m, i })
184
+ else sections.push({ name: m.providerName, items: [{ m, i }] })
185
+ })
186
+
187
+ useEffect(() => { if (disabled) setOpen(false) }, [disabled])
188
+ useEffect(() => {
189
+ if (!open) { setQ(''); return }
190
+ const rect = triggerRef.current && triggerRef.current.getBoundingClientRect()
191
+ setDropUp(!!rect && rect.bottom + 300 > window.innerHeight && rect.top > 300)
192
+ setActive(Math.max(0, models.findIndex(m => m.provider === value.provider && m.modelId === value.model)))
193
+ if (inputRef.current) inputRef.current.focus()
194
+ }, [open])
195
+ useEffect(() => {
196
+ if (!open) return
197
+ const onDown = e => { if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false) }
198
+ document.addEventListener('pointerdown', onDown)
199
+ return () => document.removeEventListener('pointerdown', onDown)
200
+ }, [open])
201
+ useEffect(() => {
202
+ if (!open || !listRef.current) return
203
+ const row = listRef.current.querySelector(`[data-i="${active}"]`)
204
+ if (row) row.scrollIntoView({ block: 'nearest' })
205
+ }, [active, open])
206
+
207
+ const pick = m => {
208
+ onChange({ provider: m.provider, model: m.modelId })
209
+ setOpen(false)
210
+ }
211
+ const onKey = e => {
212
+ if (e.key === 'ArrowDown') { e.preventDefault(); setActive(i => (i + 1) % Math.max(1, filtered.length)) }
213
+ else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(i => (i - 1 + filtered.length) % Math.max(1, filtered.length)) }
214
+ else if (e.key === 'Enter') { e.preventDefault(); if (filtered[active]) pick(filtered[active]) }
215
+ else if (e.key === 'Escape') { e.preventDefault(); setOpen(false) }
216
+ }
217
+ return h('div', { className: 'ls-mp' + (open ? ' open' : ''), ref: rootRef },
218
+ h('button', {
219
+ className: 'ls-mp-trigger', type: 'button', disabled, ref: triggerRef,
220
+ 'aria-haspopup': 'listbox', 'aria-expanded': open,
221
+ onClick: () => setOpen(v => !v),
222
+ onKeyDown: e => { if (e.key === 'ArrowDown' || e.key === 'Enter') { e.preventDefault(); if (!disabled) setOpen(true) } },
223
+ },
224
+ h('span', { className: 'ls-mp-icon' }, (selected ? selected.providerName : '?').slice(0, 1)),
225
+ h('span', { className: 'ls-mp-name' }, selected ? selected.name : (placeholder || '选择模型')),
226
+ h('svg', { className: 'ls-mp-chev', viewBox: '0 0 12 12', width: 12, height: 12,
227
+ fill: 'none', stroke: 'currentColor', strokeWidth: 1.6 },
228
+ h('path', { d: 'M3 4.5L6 7.5L9 4.5', strokeLinecap: 'round', strokeLinejoin: 'round' }))),
229
+ open ? h('div', { className: 'ls-mp-panel' + (dropUp ? ' up' : ''), onKeyDown: onKey },
230
+ h('div', { className: 'ls-mp-search' },
231
+ h('svg', { viewBox: '0 0 16 16', width: 14, height: 14, fill: 'none', stroke: 'currentColor', strokeWidth: 1.6 },
232
+ h('circle', { cx: 7, cy: 7, r: 4.5 }), h('path', { d: 'M10.5 10.5L14 14', strokeLinecap: 'round' })),
233
+ h('input', {
234
+ ref: inputRef, value: q, placeholder: '搜索模型', 'aria-label': '搜索模型',
235
+ onChange: e => { setQ(e.target.value); setActive(0) },
236
+ })),
237
+ h('div', { className: 'ls-mp-list', role: 'listbox', ref: listRef },
238
+ sections.length ? sections.map(s => h('div', { key: s.name, role: 'group' },
239
+ h('div', { className: 'ls-mp-group' }, s.name),
240
+ s.items.map(({ m, i }) => {
241
+ const sel = m.provider === value.provider && m.modelId === value.model
242
+ return h('div', {
243
+ key: `${m.provider}-${m.modelId}`, role: 'option', 'aria-selected': sel,
244
+ 'data-i': i, className: 'ls-mp-item' + (i === active ? ' active' : ''),
245
+ onMouseEnter: () => setActive(i),
246
+ onMouseDown: e => e.preventDefault(),
247
+ onClick: () => pick(m),
248
+ },
249
+ h('span', { className: 'ls-mp-icon' }, m.providerName.slice(0, 1)),
250
+ h('span', { className: 'ls-mp-item-name' }, m.name),
251
+ sel ? h('svg', { className: 'ls-check', viewBox: '0 0 16 16', width: 13, height: 13,
252
+ fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round' },
253
+ h('path', { d: 'M3 8.5l3.2 3.2L13 4.5' })) : null)
254
+ }))) : h('div', { className: 'ls-mp-empty' }, '没有匹配的模型'))) : null)
255
+ }
256
+
257
+ function PanelIcon() {
258
+ return h('svg', { viewBox: '0 0 24 24', width: 22, height: 22, 'aria-hidden': true },
259
+ h('path', {
260
+ d: 'M4 4.5A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v16.5a1 1 0 0 1-1 1H6.5A2.5 2.5 0 0 0 4 22z',
261
+ fill: 'none', stroke: 'currentColor', 'stroke-width': '1.6',
262
+ }),
263
+ h('path', {
264
+ d: 'M8 7h8M8 11h8M8 15h5',
265
+ fill: 'none', stroke: 'currentColor', 'stroke-width': '1.6', 'stroke-linecap': 'round',
266
+ }))
267
+ }
268
+
269
+ const css = `
270
+ .ls-panel { padding: 20px 24px; overflow-y: auto; height: 100%;
271
+ color: var(--dsw-alias-label-primary); font-size: 14px; line-height: 1.7; }
272
+ .ls-title { font-size: 20px; font-weight: 700; letter-spacing: 1px; margin: 0 0 2px; }
273
+ .ls-sub { color: var(--dsw-alias-label-secondary); font-size: 13px; margin-bottom: 20px; }
274
+ .ls-section { margin-bottom: 24px; }
275
+ .ls-h { font-size: 13px; letter-spacing: 2px; color: var(--dsw-alias-label-secondary);
276
+ border-bottom: 1px solid var(--dsw-alias-border-l1); padding-bottom: 6px; margin-bottom: 10px; }
277
+ .ls-card { background: var(--dsw-alias-bg-layer-1); border: 1px solid var(--dsw-alias-border-l1);
278
+ border-radius: 8px; padding: 14px 16px; margin-bottom: 12px; cursor: pointer; }
279
+ .ls-card:hover { border-color: var(--dsw-alias-border-l2); }
280
+ .ls-card.open { border-color: var(--dsw-alias-brand-primary); }
281
+ .ls-card-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
282
+ .ls-name { font-size: 15px; font-weight: 600; }
283
+ .ls-frac { font-size: 13px; color: var(--dsw-alias-label-secondary); flex: none; }
284
+ .ls-goal { font-size: 13px; color: var(--dsw-alias-label-secondary); margin-top: 2px; }
285
+ .ls-bar { height: 4px; border-radius: 2px; background: var(--dsw-alias-border-l1); margin-top: 10px; overflow: hidden; }
286
+ .ls-bar-fill { height: 100%; background: var(--dsw-alias-state-success-primary); }
287
+ .ls-badges { display: flex; gap: 12px; margin-top: 8px; font-size: 12px;
288
+ color: var(--dsw-alias-label-secondary); }
289
+ .ls-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 5px; }
290
+ .ls-nodes { list-style: none; margin: 10px 0 0; padding: 0; }
291
+ .ls-node { display: flex; align-items: center; gap: 8px; padding: 3px 0; font-size: 13px; }
292
+ .ls-journal-item { padding: 3px 0; font-size: 13px; color: var(--dsw-alias-label-secondary); }
293
+ .ls-btn { font-family: inherit; font-size: 12px; padding: 3px 12px; cursor: pointer;
294
+ background: var(--dsw-alias-brand-primary); color: var(--dsw-alias-label-primary-foreground, #fff);
295
+ border: none; border-radius: 4px; flex: none; }
296
+ .ls-btn:disabled { opacity: .5; cursor: default; }
297
+ .ls-new { display: flex; gap: 8px; margin-bottom: 14px; flex-wrap: wrap; }
298
+ .ls-input { flex: 1; min-width: 120px; font-family: inherit; font-size: 13px; color: var(--dsw-alias-label-primary);
299
+ background: var(--dsw-alias-bg-layer-1); border: 1px solid var(--dsw-alias-border-l1);
300
+ border-radius: 4px; padding: 6px 10px; }
301
+ .ls-input:focus { outline: none; border-color: var(--dsw-alias-brand-primary); }
302
+ .ls-empty { color: var(--dsw-alias-label-secondary); font-size: 13px; padding: 8px 0; }
303
+ .ls-dag-wrap { margin-top: 12px; overflow-x: auto; }
304
+ .ls-dag text { font-size: 11px; fill: var(--dsw-alias-label-primary); }
305
+ .ls-mermaid-wrap { margin-top: 12px; overflow-x: auto; }
306
+ .ls-mermaid-wrap svg { max-width: none; }
307
+ .ls-mermaid-err { font-size: 12px; color: var(--dsw-alias-state-danger-primary, #B5432E);
308
+ padding: 4px 0; }
309
+ .ls-mermaid-src { margin: 6px 0; padding: 8px 10px; background: var(--dsw-alias-bg-layer-1);
310
+ border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; overflow-x: auto; }
311
+ .ls-mermaid-src code { font-family: Consolas, monospace; font-size: 12px; white-space: pre; }
312
+ .ls-side-head { display: flex; align-items: baseline; justify-content: space-between; }
313
+ .ls-loading { color: var(--dsw-alias-label-secondary); padding: 32px 0; text-align: center; }
314
+ .ls-chat { margin-top: 12px; border-top: 1px solid var(--dsw-alias-border-l1); padding-top: 10px; }
315
+ .ls-chat-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
316
+ .ls-chat-title { font-size: 12px; color: var(--dsw-alias-label-secondary); }
317
+ .ls-chat-list { max-height: 320px; overflow-y: auto; padding: 4px 2px; display: flex; flex-direction: column; gap: 8px; }
318
+ .ls-msg { max-width: 88%; border-radius: 8px; padding: 6px 10px; font-size: 13px; }
319
+ .ls-msg-user { align-self: flex-end; background: var(--dsw-alias-brand-primary);
320
+ color: var(--dsw-alias-label-primary-foreground, #fff); }
321
+ .ls-msg-assistant { align-self: flex-start; background: var(--dsw-alias-bg-layer-2);
322
+ animation: ls-soft-in .24s ease-out; }
323
+ .ls-msg-user .ls-md-code { background: rgba(255,255,255,.25); }
324
+ .ls-md-p { margin: 2px 0; white-space: pre-wrap; word-break: break-word; }
325
+ .ls-md-h { font-size: 13px; font-weight: 700; margin: 6px 0 2px; }
326
+ .ls-md-ul { margin: 2px 0; padding-left: 18px; }
327
+ .ls-md-code { font-family: inherit; background: var(--dsw-alias-bg-layer-1); border-radius: 3px; padding: 0 4px; }
328
+ .ls-md-pre { margin: 4px 0; padding: 8px 10px; background: var(--dsw-alias-bg-layer-1);
329
+ border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; overflow-x: auto; }
330
+ .ls-md-pre code { font-family: Consolas, monospace; font-size: 12px; white-space: pre; }
331
+ .ls-tool { align-self: flex-start; font-size: 12px; color: var(--dsw-alias-label-secondary); }
332
+ .ls-chat-err { font-size: 12px; color: var(--dsw-alias-state-danger-primary, #B5432E); padding: 4px 0; }
333
+ .ls-chat-row { display: flex; gap: 8px; margin-top: 8px; align-items: flex-end; }
334
+ .ls-chat-input { flex: 1; resize: vertical; min-height: 34px; max-height: 120px; }
335
+ .ls-chat-more { font-size: 12px; color: var(--dsw-alias-label-secondary); align-self: center; }
336
+ .ls-ask { align-self: stretch; border: 1px solid var(--dsw-alias-brand-primary); border-radius: 8px;
337
+ padding: 10px 12px; background: var(--dsw-alias-bg-layer-2); }
338
+ .ls-ask-badge { font-size: 12px; font-weight: 700; color: var(--dsw-alias-brand-primary); margin-bottom: 6px; }
339
+ .ls-ask-q { margin-bottom: 8px; }
340
+ .ls-ask-h { font-size: 12px; color: var(--dsw-alias-label-secondary); letter-spacing: 1px; }
341
+ .ls-ask-text { font-size: 13px; font-weight: 600; margin: 2px 0 4px; }
342
+ .ls-ask-opts { display: flex; flex-direction: column; gap: 3px; }
343
+ .ls-ask-opt { font-size: 12px; padding: 3px 8px; border: 1px dashed var(--dsw-alias-border-l2); border-radius: 5px; }
344
+ .ls-ask-opt-label { font-weight: 600; margin-right: 6px; }
345
+ .ls-ask-opt-desc { color: var(--dsw-alias-label-secondary); }
346
+ .ls-ask-go { margin-top: 4px; }
347
+ .ls-layout { display: grid; grid-template-columns: 260px 1fr; gap: 16px; min-height: 0; align-items: start; }
348
+ .ls-side { position: sticky; top: 0; }
349
+ .ls-side-list { display: flex; flex-direction: column; gap: 4px; margin-top: 8px; }
350
+ .ls-side-item { display: flex; align-items: center; gap: 8px; padding: 7px 10px; border-radius: 6px;
351
+ cursor: pointer; font-size: 13px; border-left: 3px solid transparent; word-break: break-all; }
352
+ .ls-side-item:hover { background: var(--dsw-alias-bg-layer-1); }
353
+ .ls-side-item.active { background: var(--dsw-alias-bg-layer-2); border-left-color: var(--dsw-alias-brand-primary); }
354
+ .ls-side-del { flex: none; border: none; background: none; color: var(--dsw-alias-label-secondary);
355
+ cursor: pointer; font-size: 13px; line-height: 1; padding: 2px 4px; border-radius: 4px; visibility: hidden; }
356
+ .ls-side-item:hover .ls-side-del { visibility: visible; }
357
+ .ls-side-del:hover { color: #B5432E; background: var(--dsw-alias-bg-layer-2); }
358
+ .ls-modal-mask { position: fixed; inset: 0; background: rgba(0,0,0,.45); z-index: 100;
359
+ display: flex; align-items: center; justify-content: center; }
360
+ .ls-modal { width: 360px; max-width: 90vw; background: var(--dsw-alias-bg-layer-1);
361
+ border: 1px solid var(--dsw-alias-border-l2); border-radius: 10px; padding: 18px 20px; }
362
+ .ls-modal-title { font-size: 15px; font-weight: 700; margin-bottom: 8px; }
363
+ .ls-modal-body { font-size: 13px; color: var(--dsw-alias-label-secondary); line-height: 1.7; margin-bottom: 14px; }
364
+ .ls-modal-body strong { color: var(--dsw-alias-state-danger-primary, #B5432E); }
365
+ .ls-modal-actions { display: flex; justify-content: flex-end; gap: 8px; }
366
+ .ls-btn-danger { background: #B5432E; color: #fff; }
367
+ .ls-title-row { display: flex; align-items: center; gap: 10px; }
368
+ .ls-title-row .ls-title { margin: 0 0 2px; }
369
+ .ls-gear { border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1);
370
+ color: var(--dsw-alias-label-secondary); border-radius: 6px; cursor: pointer;
371
+ font-size: 14px; line-height: 1; padding: 5px 8px; flex: none; }
372
+ .ls-gear:hover { border-color: var(--dsw-alias-border-l2); color: var(--dsw-alias-label-primary); }
373
+ .ls-select { width: 100%; font-family: inherit; font-size: 13px; color: var(--dsw-alias-label-primary);
374
+ background: var(--dsw-alias-bg-layer-1); border: 1px solid var(--dsw-alias-border-l1);
375
+ border-radius: 4px; padding: 6px 8px; margin-top: 4px; }
376
+ .ls-select:focus { outline: none; border-color: var(--dsw-alias-brand-primary); }
377
+ .ls-select:disabled { opacity: .5; }
378
+ .ls-set-label { font-size: 12px; color: var(--dsw-alias-label-secondary); margin-top: 10px; display: block; }
379
+ .ls-set-check { display: flex; align-items: center; gap: 6px; margin-top: 8px; font-size: 13px; }
380
+ .ls-set-note { font-size: 12px; color: var(--dsw-alias-label-secondary); margin: 8px 0 0; }
381
+ .ls-set-warn { font-size: 12px; color: var(--dsw-alias-state-danger-primary, #B5432E); margin: 8px 0 0; }
382
+ .ls-set-ok { font-size: 12px; color: var(--dsw-alias-state-success-primary); margin: 8px 0 0; }
383
+ .ls-focus { display: grid; grid-template-columns: minmax(280px, 5fr) 7fr; gap: 16px; height: calc(100vh - 140px); }
384
+ .ls-focus-left { overflow-y: auto; padding-right: 4px; }
385
+ .ls-focus-head { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
386
+ .ls-focus-title { font-size: 17px; font-weight: 700; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
387
+ .ls-focus-right { display: flex; flex-direction: column; min-height: 0; border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; padding: 12px 14px; background: var(--dsw-alias-bg-layer-1); }
388
+ .ls-focus-right .ls-chat { margin-top: 0; border-top: none; padding-top: 0; flex: 1; display: flex; flex-direction: column; min-height: 0; }
389
+ .ls-focus-right .ls-chat-list { flex: 1; max-height: none; min-height: 200px; }
390
+ @media (max-width: 900px) { .ls-focus { grid-template-columns: 1fr; height: auto; } .ls-focus-left { max-height: 40vh; } }
391
+ .ls-side-name { flex: 1; min-width: 0; }
392
+ .ls-side-frac { font-size: 12px; color: var(--dsw-alias-label-secondary); flex: none; }
393
+ .ls-detail { background: var(--dsw-alias-bg-layer-1); border: 1px solid var(--dsw-alias-border-l1);
394
+ border-radius: 8px; padding: 16px 18px; min-width: 0; }
395
+ .ls-detail-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-bottom: 4px; }
396
+ .ls-mat-item { display: flex; align-items: center; justify-content: space-between; gap: 10px;
397
+ padding: 4px 0; font-size: 13px; word-break: break-all; }
398
+ .ls-mat-size { color: var(--dsw-alias-label-secondary); font-size: 12px; flex: none; }
399
+ .ls-upload-bar { height: 4px; border-radius: 2px; background: var(--dsw-alias-border-l1); margin: 8px 0 4px; overflow: hidden; }
400
+ .ls-upload-fill { height: 100%; background: var(--dsw-alias-brand-primary); transition: width .15s; }
401
+ .ls-upload-err { font-size: 12px; color: var(--dsw-alias-state-danger-primary, #B5432E); padding: 4px 0; }
402
+ .ls-file-label { display: inline-flex; align-items: center; gap: 6px; }
403
+ .ls-picked { margin-top: 6px; font-size: 12px; color: var(--dsw-alias-label-secondary); }
404
+ .ls-picked-item { display: flex; align-items: center; gap: 6px; padding: 1px 0; word-break: break-all; }
405
+ .ls-picked-x { cursor: pointer; border: none; background: none; color: var(--dsw-alias-label-secondary);
406
+ font-size: 13px; padding: 0 2px; flex: none; }
407
+ .ls-picked-x:hover { color: var(--dsw-alias-state-danger-primary, #B5432E); }
408
+ .ls-rebind { margin-top: 6px; }
409
+ .ls-ws { display: inline-flex; align-items: center; gap: 6px; font-size: 13px;
410
+ color: var(--dsw-alias-label-secondary); cursor: pointer; }
411
+ .ls-quiz { align-self: stretch; border: 1px solid var(--dsw-alias-border-l2); border-radius: 8px;
412
+ padding: 10px 12px; background: var(--dsw-alias-bg-layer-2); }
413
+ .ls-quiz-head { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
414
+ .ls-quiz-no { font-size: 12px; font-weight: 700; color: var(--dsw-alias-brand-primary); }
415
+ .ls-quiz-node { font-size: 12px; color: var(--dsw-alias-label-secondary); }
416
+ .ls-quiz-badge { font-size: 12px; font-weight: 600; margin-left: auto; }
417
+ .ls-quiz-badge.ok { color: var(--dsw-alias-state-success-primary); }
418
+ .ls-quiz-badge.bad { color: var(--dsw-alias-state-danger-primary, #B5432E); }
419
+ .ls-quiz-badge.wait { color: var(--dsw-alias-label-secondary); }
420
+ .ls-quiz-stem { font-size: 13px; margin-bottom: 8px; }
421
+ .ls-quiz-opts { display: flex; flex-direction: column; gap: 4px; }
422
+ .ls-quiz-opt { display: flex; gap: 8px; align-items: baseline; text-align: left; font-family: inherit;
423
+ font-size: 13px; padding: 5px 10px; border: 1px dashed var(--dsw-alias-border-l2); border-radius: 5px;
424
+ background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary); cursor: pointer; }
425
+ .ls-quiz-opt:hover:not(:disabled) { border-color: var(--dsw-alias-brand-primary); }
426
+ .ls-quiz-opt:disabled { cursor: default; opacity: .8; }
427
+ .ls-quiz-opt.chosen { border-style: solid; border-color: var(--dsw-alias-brand-primary);
428
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary) 12%, var(--dsw-alias-bg-layer-1)); }
429
+ .ls-quiz-opt-key { font-weight: 700; flex: none; }
430
+ .ls-qh-list { display: flex; flex-direction: column; gap: 2px; }
431
+ .ls-qh-item { border-left: 2px solid var(--dsw-alias-border-l1); padding: 4px 8px; cursor: pointer;
432
+ font-size: 13px; }
433
+ .ls-qh-item:hover { background: var(--dsw-alias-bg-layer-1); }
434
+ .ls-qh-row { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
435
+ .ls-qh-date { color: var(--dsw-alias-label-secondary); font-size: 12px; }
436
+ .ls-qh-frac { font-size: 12px; }
437
+ .ls-qh-node { font-size: 12px; color: var(--dsw-alias-label-secondary); }
438
+ .ls-qh-ans { font-size: 12px; color: var(--dsw-alias-label-secondary); }
439
+ .ls-qh-detail { margin-top: 4px; padding: 6px 10px; background: var(--dsw-alias-bg-layer-1);
440
+ border-radius: 6px; font-size: 12px; }
441
+ .ls-qh-line { padding: 2px 0; word-break: break-word; }
442
+ @media (max-width: 720px) {
443
+ .ls-layout { grid-template-columns: 1fr; }
444
+ .ls-side { position: static; }
445
+ }
446
+
447
+ /* ── AI 状态行(AiStatus) ───────────────────────── */
448
+ .ls-aistatus { display: inline-flex; align-items: center; gap: 7px; align-self: flex-start;
449
+ height: 24px; font-size: 12px; color: var(--dsw-alias-label-secondary);
450
+ animation: ls-soft-in .24s ease-out; }
451
+ .ls-aistatus-icon { display: inline-grid; place-items: center; width: 16px; height: 16px; flex: none; }
452
+ .ls-aistatus-label { font-weight: 600; letter-spacing: .2px; }
453
+ .ls-aistatus.active .ls-aistatus-label {
454
+ background-image: linear-gradient(90deg,
455
+ var(--dsw-alias-label-secondary) 42%,
456
+ var(--dsw-alias-label-primary) 50%,
457
+ var(--dsw-alias-label-secondary) 58%);
458
+ background-size: 250% 100%; -webkit-background-clip: text; background-clip: text; color: transparent;
459
+ animation: ls-shimmer 1.6s linear infinite; }
460
+ .ls-aistatus-detail, .ls-aistatus-time { color: var(--dsw-alias-label-secondary); opacity: .72; font-weight: 500; }
461
+ .ls-aistatus-time { font-variant-numeric: tabular-nums; }
462
+ .ls-aistatus-done { color: var(--dsw-alias-state-success-primary); }
463
+ .ls-ai-spark { transform-origin: 11px 13px; animation: ls-spark 2.4s ease-in-out infinite; }
464
+ .ls-ai-spark2 { transform-origin: 18px 5px; animation: ls-spark2 1.2s ease-in-out infinite; }
465
+ .ls-ai-bar { animation: ls-bar .9s ease-in-out infinite; }
466
+ .ls-ai-bar:nth-child(2) { animation-delay: .15s; }
467
+ .ls-ai-bar:nth-child(3) { animation-delay: .3s; }
468
+ .ls-ai-check { stroke-dasharray: 22; stroke-dashoffset: 22; animation: ls-draw .45s ease-out .05s forwards; }
469
+ @keyframes ls-shimmer { from { background-position: 100% 0; } to { background-position: 0% 0; } }
470
+ @keyframes ls-soft-in { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } }
471
+ @keyframes ls-spark { 0%, 100% { transform: rotate(0) scale(1); } 50% { transform: rotate(90deg) scale(.82); } }
472
+ @keyframes ls-spark2 { 0%, 100% { transform: scale(.5); opacity: .35; } 50% { transform: scale(1); opacity: 1; } }
473
+ @keyframes ls-bar { 0%, 100% { transform: scaleY(.35); } 50% { transform: scaleY(1); } }
474
+ @keyframes ls-draw { to { stroke-dashoffset: 0; } }
475
+
476
+ /* ── 剩余节点铃铛(NotificationBell) ─────────────── */
477
+ .ls-bell-wrap { position: relative; flex: none; }
478
+ .ls-bell { position: relative; display: grid; place-items: center; width: 30px; height: 30px;
479
+ padding: 0; border: 1px solid var(--dsw-alias-border-l1); border-radius: 50%;
480
+ background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-secondary); cursor: pointer;
481
+ transition: border-color .15s, color .15s, transform .08s; }
482
+ .ls-bell:hover { border-color: var(--dsw-alias-border-l2); color: var(--dsw-alias-label-primary); }
483
+ .ls-bell:active { transform: scale(.94); }
484
+ .ls-bell.open { border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-brand-primary); }
485
+ .ls-bell-badge { position: absolute; top: -4px; right: -4px; min-width: 16px; height: 16px; padding: 0 4px;
486
+ border-radius: 8px; background: #B5432E; color: #fff; font-size: 10px; font-weight: 700;
487
+ line-height: 1; display: grid; place-items: center; animation: ls-badge-pop .3s ease-out; }
488
+ .ls-bell-swing { animation: ls-bell-ring .9s ease-in-out; transform-origin: 50% 12%; }
489
+ .ls-bell-pop { position: absolute; top: calc(100% + 8px); right: 0; width: 240px; z-index: 80;
490
+ padding: 10px 12px; background: var(--dsw-alias-bg-layer-1);
491
+ border: 1px solid var(--dsw-alias-border-l1); border-radius: 10px;
492
+ box-shadow: 0 10px 30px rgba(0,0,0,.16); transform-origin: top right;
493
+ animation: ls-pop-in .22s cubic-bezier(.2,.85,.25,1); }
494
+ .ls-bell-pop-h { font-size: 12px; font-weight: 600; margin-bottom: 6px; }
495
+ .ls-bell-pop-list { display: flex; flex-direction: column; gap: 1px; max-height: 220px; overflow-y: auto; }
496
+ .ls-bell-pop-item { display: flex; align-items: center; gap: 7px; padding: 3px 0;
497
+ font-size: 12px; color: var(--dsw-alias-label-secondary); }
498
+ @keyframes ls-bell-ring {
499
+ 0% { transform: rotate(0); } 15% { transform: rotate(14deg); } 30% { transform: rotate(-12deg); }
500
+ 45% { transform: rotate(9deg); } 60% { transform: rotate(-6deg); } 80% { transform: rotate(3deg); }
501
+ 100% { transform: rotate(0); } }
502
+ @keyframes ls-badge-pop { 0% { transform: scale(.4); opacity: 0; } 60% { transform: scale(1.15); } 100% { transform: scale(1); opacity: 1; } }
503
+ @keyframes ls-pop-in { from { opacity: 0; transform: translateY(-4px) scale(.97); } to { opacity: 1; transform: none; } }
504
+
505
+ /* ── 模型选择(ModelPicker) ─────────────────────── */
506
+ .ls-mp { position: relative; }
507
+ .ls-mp-trigger { display: flex; align-items: center; gap: 8px; width: 100%; height: 34px;
508
+ padding: 0 12px 0 8px; font-family: inherit; font-size: 13px; text-align: left;
509
+ color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-layer-1);
510
+ border: 1px solid var(--dsw-alias-border-l1); border-radius: 17px; cursor: pointer;
511
+ transition: border-color .15s; }
512
+ .ls-mp-trigger:hover:not(:disabled) { border-color: var(--dsw-alias-border-l2); }
513
+ .ls-mp-trigger:disabled { opacity: .5; cursor: default; }
514
+ .ls-mp.open .ls-mp-trigger { border-color: var(--dsw-alias-brand-primary); }
515
+ .ls-mp-icon { display: grid; place-items: center; width: 20px; height: 20px; flex: none;
516
+ border-radius: 6px; background: var(--dsw-alias-bg-layer-2); text-transform: uppercase;
517
+ font-size: 10px; font-weight: 700; color: var(--dsw-alias-label-secondary); }
518
+ .ls-mp-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
519
+ .ls-mp-chev { flex: none; transition: transform .18s; }
520
+ .ls-mp.open .ls-mp-chev { transform: rotate(180deg); }
521
+ .ls-mp-panel { position: absolute; top: calc(100% + 6px); left: 0; width: 100%; min-width: 268px;
522
+ z-index: 90; overflow: hidden; background: var(--dsw-alias-bg-layer-1);
523
+ border: 1px solid var(--dsw-alias-border-l1); border-radius: 12px;
524
+ box-shadow: 0 12px 36px rgba(0,0,0,.18);
525
+ animation: ls-pop-in .22s cubic-bezier(.2,.85,.25,1); }
526
+ .ls-mp-panel.up { top: auto; bottom: calc(100% + 6px); transform-origin: bottom left; }
527
+ .ls-mp-search { display: flex; align-items: center; gap: 7px; height: 38px; padding: 0 12px;
528
+ border-bottom: 1px solid var(--dsw-alias-border-l1); color: var(--dsw-alias-label-secondary); }
529
+ .ls-mp-search input { flex: 1; min-width: 0; border: none; outline: none; background: transparent;
530
+ font-family: inherit; font-size: 12px; color: var(--dsw-alias-label-primary); }
531
+ .ls-mp-list { max-height: 248px; overflow-y: auto; padding: 6px; }
532
+ .ls-mp-group { padding: 6px 8px 3px; font-size: 11px; letter-spacing: .5px;
533
+ color: var(--dsw-alias-label-secondary); }
534
+ .ls-mp-item { display: flex; align-items: center; gap: 8px; height: 34px; padding: 0 8px;
535
+ border-radius: 8px; font-size: 13px; color: var(--dsw-alias-label-primary); cursor: pointer; }
536
+ .ls-mp-item.active { background: var(--dsw-alias-bg-layer-2); }
537
+ .ls-mp-item-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
538
+ .ls-mp-item .ls-check { color: var(--dsw-alias-brand-primary); flex: none; }
539
+ .ls-mp-empty { padding: 14px 8px; text-align: center; font-size: 12px; color: var(--dsw-alias-label-secondary); }
540
+
541
+ /* ── Toast ──────────────────────────────────────── */
542
+ .ls-toasts { position: fixed; right: 18px; bottom: 18px; z-index: 240; display: flex;
543
+ flex-direction: column-reverse; gap: 10px; width: 304px; max-width: calc(100vw - 36px);
544
+ pointer-events: none; }
545
+ .ls-toast { pointer-events: auto; display: flex; align-items: center; gap: 10px; padding: 10px;
546
+ background: var(--dsw-alias-bg-layer-1); border: 1px solid var(--dsw-alias-border-l1);
547
+ border-radius: 14px; box-shadow: 0 6px 24px rgba(0,0,0,.14);
548
+ animation: ls-toast-in .3s cubic-bezier(.2,.85,.25,1); }
549
+ .ls-toast.leaving { animation: ls-toast-out .18s ease-in forwards; }
550
+ .ls-toast-tile { display: grid; place-items: center; width: 34px; height: 34px; flex: none;
551
+ border-radius: 11px; color: #fff; }
552
+ .ls-toast-tile.success { background: var(--dsw-alias-state-success-primary); }
553
+ .ls-toast-tile.error { background: var(--dsw-alias-state-danger-primary, #B5432E); }
554
+ .ls-toast-tile.warning { background: var(--dsw-alias-state-warning-primary, #B7791F); }
555
+ .ls-toast-tile.info { background: var(--dsw-alias-brand-primary);
556
+ color: var(--dsw-alias-label-primary-foreground, #fff); }
557
+ .ls-toast-tile.loading { background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-secondary); }
558
+ .ls-toast-body { flex: 1; min-width: 0; }
559
+ .ls-toast-title { font-size: 13px; font-weight: 600; line-height: 1.35; }
560
+ .ls-toast-desc { margin-top: 1px; font-size: 12px; line-height: 1.5;
561
+ color: var(--dsw-alias-label-secondary); word-break: break-word; }
562
+ .ls-toast-x { flex: none; border: none; background: none; padding: 2px 4px; cursor: pointer;
563
+ font-size: 14px; line-height: 1; color: var(--dsw-alias-label-secondary); }
564
+ .ls-toast-x:hover { color: var(--dsw-alias-label-primary); }
565
+ .ls-spin { animation: ls-spin .9s linear infinite; }
566
+ @keyframes ls-spin { to { transform: rotate(360deg); } }
567
+ @keyframes ls-toast-in { from { opacity: 0; transform: translateY(10px) scale(.96); } to { opacity: 1; transform: none; } }
568
+ @keyframes ls-toast-out { to { opacity: 0; transform: translateX(8px) scale(.97); } }
569
+
570
+ /* 按钮反馈 */
571
+ .ls-btn { transition: background-color .15s, border-color .15s, transform .08s; }
572
+ .ls-btn:active:not(:disabled) { transform: translateY(1px) scale(.99); }
573
+ .ls-btn:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
574
+
575
+ @media (prefers-reduced-motion: reduce) {
576
+ .ls-aistatus, .ls-aistatus-label, .ls-ai-spark, .ls-ai-spark2, .ls-ai-bar, .ls-ai-check,
577
+ .ls-toast, .ls-bell-swing, .ls-bell-badge, .ls-bell-pop, .ls-mp-panel, .ls-spin {
578
+ animation: none !important; }
579
+ }
580
+ `
581
+
582
+ /** 极简 DAG 分层布局:roots 在底,目标在顶 */
583
+ function Dag({ nodes, edges }) {
584
+ if (!nodes.length) return null
585
+ const level = new Map()
586
+ const nexts = new Map(nodes.map(n => [n.id, []]))
587
+ for (const [a, b] of edges) if (nexts.has(a)) nexts.get(a).push(b)
588
+ const depth = id => {
589
+ if (level.has(id)) return level.get(id)
590
+ level.set(id, 0)
591
+ let d = 0
592
+ for (const nx of nexts.get(id) || []) d = Math.max(d, depth(nx) + 1)
593
+ level.set(id, d)
594
+ return d
595
+ }
596
+ nodes.forEach(n => depth(n.id))
597
+ const maxLevel = Math.max(...level.values())
598
+ const byLevel = new Map()
599
+ for (const n of nodes) {
600
+ const l = maxLevel - level.get(n.id) // roots (level0) 放最底一行
601
+ if (!byLevel.has(l)) byLevel.set(l, [])
602
+ byLevel.get(l).push(n)
603
+ }
604
+ const rowH = 46, colW = 150, nodeW = 118, nodeH = 30
605
+ const pos = new Map()
606
+ for (const [l, list] of byLevel) {
607
+ list.forEach((n, i) => pos.set(n.id, { x: colW / 2 + i * colW + l * 18, y: 24 + l * rowH, n }))
608
+ }
609
+ const width = Math.max(...[...pos.values()].map(p => p.x)) + 80
610
+ const height = 24 + (byLevel.size) * rowH
611
+ const key = n => (n.id === n.label ? n.id : `${n.id}`)
612
+ return h('svg', { className: 'ls-dag', width, height, viewBox: `0 0 ${width} ${height}` },
613
+ edges.map(([a, b], i) => {
614
+ const pa = pos.get(a), pb = pos.get(b)
615
+ if (!pa || !pb) return null
616
+ const x1 = pa.x + nodeW / 2, y1 = pa.y + nodeH / 2, x2 = pb.x + nodeW / 2, y2 = pb.y + nodeH / 2
617
+ return h('line', { key: `e${i}`, x1, y1, x2, y2, stroke: 'var(--dsw-alias-border-l2)', strokeWidth: 1 })
618
+ }),
619
+ [...pos.values()].map(({ x, y, n }) => h('g', { key: n.id },
620
+ h('rect', {
621
+ x: x - nodeW / 2, y, width: nodeW, height: nodeH, rx: 5,
622
+ fill: n.status === 'todo' ? 'var(--dsw-alias-bg-layer-2)' : STATUS_COLOR[n.status],
623
+ stroke: n.status === 'todo' ? STATUS_COLOR.todo : 'none',
624
+ strokeDasharray: n.status === 'todo' ? '3 3' : undefined,
625
+ }),
626
+ h('text', {
627
+ x, y: y + nodeH / 2 + 4, textAnchor: 'middle',
628
+ fill: n.status === 'todo' ? 'currentColor' : '#FAF7F0',
629
+ style: { fill: n.status === 'todo' ? undefined : '#FAF7F0' },
630
+ }, n.label.length > 8 ? n.label.slice(0, 7) + '…' : n.label),
631
+ )),
632
+ )
633
+ }
634
+
635
+ /** mermaid UMD 模块级 Promise 单例:动态注入 script,失败记 mermaidFailed 不再重试 */
636
+ let mermaidPromise = null
637
+ let mermaidFailed = false
638
+ function loadMermaid() {
639
+ if (mermaidFailed) return Promise.reject(new Error('mermaid asset failed'))
640
+ if (!mermaidPromise) {
641
+ mermaidPromise = new Promise((resolve, reject) => {
642
+ const s = document.createElement('script')
643
+ s.src = '/api/learning-space/assets/mermaid.min.js'
644
+ s.onload = () => {
645
+ try {
646
+ window.mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'loose' })
647
+ resolve(window.mermaid)
648
+ } catch (e) { mermaidFailed = true; reject(e) }
649
+ }
650
+ s.onerror = () => { mermaidFailed = true; mermaidPromise = null; reject(new Error('mermaid 资产加载失败')) }
651
+ document.head.appendChild(s)
652
+ })
653
+ }
654
+ return mermaidPromise
655
+ }
656
+
657
+ /**
658
+ * 完整 mermaid 渲染:render 成功挂 SVG;失败(语法错/资产 404)提示 + 源码 + 旧 Dag 兜底。
659
+ * planMermaid 字符串未变时跳过重渲染(render 是秒级全量 SVG 重排,不能 15s 轮询盲跑)。
660
+ */
661
+ function MermaidGraph({ src, nodes, edges }) {
662
+ const wrapRef = useRef(null)
663
+ const lastSrcRef = useRef(null)
664
+ const [err, setErr] = useState(null)
665
+ useEffect(() => {
666
+ const el = wrapRef.current
667
+ if (!el) return
668
+ if (!src) { el.innerHTML = ''; lastSrcRef.current = null; setErr(null); return }
669
+ if (lastSrcRef.current === src && !err) return // 轮询未变化:跳过
670
+ let alive = true
671
+ loadMermaid().then(m => {
672
+ if (!alive || !wrapRef.current) return
673
+ return m.render(`ls-mermaid-${Date.now()}`, src).then(({ svg }) => {
674
+ if (!alive) return
675
+ el.innerHTML = svg
676
+ lastSrcRef.current = src
677
+ setErr(null)
678
+ })
679
+ }).catch(e => {
680
+ if (!alive) return
681
+ el.innerHTML = ''
682
+ lastSrcRef.current = null
683
+ setErr(String((e && e.message) || e))
684
+ })
685
+ return () => { alive = false }
686
+ }, [src])
687
+ return h('div', { className: 'ls-dag-wrap' },
688
+ err ? h('div', { className: 'ls-mermaid-err' }, `mermaid 渲染失败(${err}),已降级显示源码与简图`) : null,
689
+ err ? h('pre', { className: 'ls-mermaid-src' }, h('code', null, src)) : null,
690
+ h('div', { className: 'ls-mermaid-wrap', ref: wrapRef }),
691
+ err ? h('div', { className: 'ls-dag-wrap' }, h(Dag, { nodes, edges })) : null,
692
+ )
693
+ }
694
+
695
+ /** 行内 markdown:**加粗** 与 `行内码`,其余按原文本 */
696
+ function inlineNodes(text, keyBase) {
697
+ const out = []
698
+ const re = /(\*\*[^*]+\*\*|`[^`]+`)/g
699
+ let last = 0, m, i = 0
700
+ while ((m = re.exec(text))) {
701
+ if (m.index > last) out.push(text.slice(last, m.index))
702
+ const t = m[0]
703
+ if (t.startsWith('**')) out.push(h('strong', { key: `${keyBase}b${i}` }, t.slice(2, -2)))
704
+ else out.push(h('code', { key: `${keyBase}c${i}`, className: 'ls-md-code' }, t.slice(1, -1)))
705
+ last = m.index + t.length
706
+ i++
707
+ }
708
+ if (last < text.length) out.push(text.slice(last))
709
+ return out
710
+ }
711
+
712
+ /** 极简 markdown → React 元素数组(代码块/标题/列表/加粗/行内码),无法识别的行原样输出 */
713
+ function markdownLite(text) {
714
+ const lines = String(text || '').split(/\r?\n/)
715
+ const els = []
716
+ let code = null
717
+ let list = null
718
+ let k = 0
719
+ const flushCode = () => {
720
+ if (code) { els.push(h('pre', { key: `pre${k++}`, className: 'ls-md-pre' }, h('code', null, code.join('\n')))); code = null }
721
+ }
722
+ const flushList = () => {
723
+ if (list && list.length) { els.push(h('ul', { key: `ul${k++}`, className: 'ls-md-ul' }, list.map((li, i) => h('li', { key: i }, li)))); list = null }
724
+ }
725
+ for (const line of lines) {
726
+ if (/^\s*```/.test(line)) {
727
+ if (code) flushCode()
728
+ else { flushList(); code = [] }
729
+ continue
730
+ }
731
+ if (code) { code.push(line); continue }
732
+ const hm = /^(#{1,3})\s+(.*)$/.exec(line)
733
+ if (hm) {
734
+ flushList()
735
+ els.push(h(`h${hm[1].length + 3}`, { key: `h${k++}`, className: 'ls-md-h' }, inlineNodes(hm[2], `i${k}`)))
736
+ continue
737
+ }
738
+ if (/^\s*[-*]\s+/.test(line)) {
739
+ if (!list) list = []
740
+ list.push(inlineNodes(line.replace(/^\s*[-*]\s+/, ''), `l${k++}`))
741
+ continue
742
+ }
743
+ flushList()
744
+ if (line.trim()) els.push(h('p', { key: `p${k++}`, className: 'ls-md-p' }, inlineNodes(line, `i${k}`)))
745
+ }
746
+ flushCode()
747
+ flushList()
748
+ return els
749
+ }
750
+
751
+ /** 选择题卡片:题干 + 可点选项;点选即发送字母(复用 sendText 与发送锁) */
752
+ function QuizCard({ quiz, sending, onAnswer }) {
753
+ const [localAnswer, setLocalAnswer] = useState(null)
754
+ const answered = quiz.state === 'answered' || quiz.state === 'graded' || localAnswer
755
+ const chosen = quiz.answer || localAnswer
756
+ const disabled = !!answered || sending
757
+ return h('div', { className: 'ls-quiz' },
758
+ h('div', { className: 'ls-quiz-head' },
759
+ h('span', { className: 'ls-quiz-no' }, `第 ${quiz.index} / ${quiz.total} 题`),
760
+ quiz.node ? h('span', { className: 'ls-quiz-node' }, quiz.node) : null,
761
+ quiz.state === 'graded'
762
+ ? h('span', { className: 'ls-quiz-badge' + (quiz.correct ? ' ok' : ' bad') }, quiz.correct ? '✅ 答对' : '❌ 答错')
763
+ : answered ? h('span', { className: 'ls-quiz-badge wait' }, '已作答,等待反馈') : null),
764
+ quiz.stem ? h('div', { className: 'ls-quiz-stem' }, quiz.stem) : null,
765
+ h('div', { className: 'ls-quiz-opts' },
766
+ (quiz.options || []).map(o =>
767
+ h('button', {
768
+ key: o.key, type: 'button',
769
+ className: 'ls-quiz-opt' + (chosen === o.key ? ' chosen' : ''),
770
+ disabled,
771
+ // 发送失败(含非 409 错误)时回滚 localAnswer,允许重点重试
772
+ onClick: () => { Promise.resolve(onAnswer(o.key)).then(ok => setLocalAnswer(ok ? o.key : null)) },
773
+ },
774
+ h('span', { className: 'ls-quiz-opt-key' }, o.key),
775
+ h('span', null, o.text)))),
776
+ )
777
+ }
778
+
779
+ /** 答题历史:quizlog 时间线,点击展开题面与反馈;refreshKey 变化时重拉(答完题联动刷新) */
780
+ function QuizHistory({ topic, refreshKey }) {
781
+ const [records, setRecords] = useState(null)
782
+ const [openSeq, setOpenSeq] = useState(null)
783
+ useEffect(() => {
784
+ let alive = true
785
+ fetch(`/api/learning-space/quizlog?topic=${encodeURIComponent(topic)}`)
786
+ .then(r => r.json())
787
+ .then(j => { if (alive && j.ok) setRecords(j.records || []) })
788
+ .catch(() => { if (alive) setRecords([]) })
789
+ return () => { alive = false }
790
+ }, [topic, refreshKey])
791
+ if (!records || !records.length) return null
792
+ return h('div', { className: 'ls-section' },
793
+ h('div', { className: 'ls-h' }, `答题历史(${records.length})`),
794
+ h('div', { className: 'ls-qh-list' }, records.map((r, i) =>
795
+ h('div', { key: `${r.fbSeq}-${i}`, className: 'ls-qh-item' + (openSeq === r.fbSeq ? ' open' : ''),
796
+ onClick: () => setOpenSeq(openSeq === r.fbSeq ? null : r.fbSeq) },
797
+ h('div', { className: 'ls-qh-row' },
798
+ h('span', { className: 'ls-qh-mark ' + (r.correct ? 'ok' : 'bad') }, r.correct ? '✅' : '❌'),
799
+ h('span', { className: 'ls-qh-date' }, r.date),
800
+ h('span', { className: 'ls-qh-frac' }, `第 ${r.index} / ${r.total} 题`),
801
+ r.node ? h('span', { className: 'ls-qh-node' }, r.node) : null,
802
+ h('span', { className: 'ls-qh-ans' }, `答 ${r.answer}`)),
803
+ openSeq === r.fbSeq ? h('div', { className: 'ls-qh-detail' },
804
+ h('div', { className: 'ls-qh-line' }, `题面:${r.stem}`),
805
+ h('div', { className: 'ls-qh-line' }, `选项:${r.options}`),
806
+ h('div', { className: 'ls-qh-line' }, `反馈:${r.feedback}`)) : null))),
807
+ )
808
+ }
809
+
810
+ /** 内嵌对话窗:轮询收消息 + 发消息 + 兜底跳转;phase=1 摸底 / 2 学习(默认 2 兼容存量) */
811
+ function ChatWindow({ topic, phase = 2, sessionId: initialSessionId, onOpenInSession, onQuizGraded }) {
812
+ const [messages, setMessages] = useState([])
813
+ const [input, setInput] = useState('')
814
+ const [sending, setSending] = useState(false)
815
+ const [err, setErr] = useState(null)
816
+ const [running, setRunning] = useState(false)
817
+ const [hasMore, setHasMore] = useState(false)
818
+ const [sessionId, setSessionId] = useState(initialSessionId || null)
819
+ const [needRebind, setNeedRebind] = useState(false)
820
+ const lastSeqRef = useRef(null)
821
+ const inFlightRef = useRef(false)
822
+ const pendingIdRef = useRef(0)
823
+ const listRef = useRef(null)
824
+ const [doneInfo, setDoneInfo] = useState(null)
825
+ const prevRunningRef = useRef(false)
826
+ const runStartRef = useRef(null)
827
+
828
+ const poll = useCallback(async () => {
829
+ if (inFlightRef.current) return
830
+ inFlightRef.current = true
831
+ try {
832
+ const afterSeq = lastSeqRef.current
833
+ const qs = `topic=${encodeURIComponent(topic)}&phase=${phase}` + (afterSeq != null ? `&afterSeq=${afterSeq}` : '')
834
+ const r = await fetch(`/api/learning-space/session/messages?${qs}`)
835
+ const j = await r.json()
836
+ if (!j.ok) {
837
+ setErr(j.error)
838
+ if (j.error === 'no session') setNeedRebind(true)
839
+ return
840
+ }
841
+ setErr(null)
842
+ setSessionId(j.sessionId)
843
+ setRunning(j.running)
844
+ setHasMore(!!j.hasMore)
845
+ const incoming = Array.isArray(j.messages) ? j.messages : []
846
+ const updates = Array.isArray(j.toolUpdates) ? j.toolUpdates : []
847
+ if (incoming.length || updates.length) {
848
+ // 新到达的 assistant 消息首字符是 ✅/❌ 即视为判分反馈,触发答题历史刷新
849
+ if (onQuizGraded && incoming.some(m => m.role === 'assistant' && /^\s*[✅❌]/.test(m.text || ''))) onQuizGraded()
850
+ setMessages(prev => {
851
+ // 乐观消息(pending)保持追加在末尾,真实消息到达后按文本确认并移除
852
+ const real = prev.filter(m => !m.pending)
853
+ const optimistic = prev.filter(m => m.pending)
854
+ const seen = new Set(real.map(m => m.seq))
855
+ for (const m of incoming) if (!seen.has(m.seq)) { seen.add(m.seq); real.push(m) }
856
+ const stateByCall = new Map(updates.map(u => [u.callId, u.state]))
857
+ const withState = stateByCall.size
858
+ ? real.map(m => m.role === 'tool' && m.callId && stateByCall.has(m.callId)
859
+ ? { ...m, state: stateByCall.get(m.callId) } : m)
860
+ : real
861
+ // 只把发送之后才出现的同文本用户消息当作乐观消息的确认,避免重发相同文本时误删
862
+ return [...withState, ...optimistic.filter(p =>
863
+ !withState.some(m => m.role === 'user' && m.text === p.text && m.seq > p.afterSeq))]
864
+ })
865
+ }
866
+ if (typeof j.cursor === 'number') {
867
+ lastSeqRef.current = lastSeqRef.current == null
868
+ ? j.cursor : Math.max(lastSeqRef.current, j.cursor)
869
+ }
870
+ } catch (e) { setErr(String(e)) } finally { inFlightRef.current = false }
871
+ }, [topic, phase])
872
+
873
+ useEffect(() => { poll(); const t = setInterval(poll, 2500); return () => clearInterval(t) }, [poll])
874
+ // running 由 true→false 视为一轮结束:记下用时并短暂展示完成态
875
+ useEffect(() => {
876
+ if (running && !prevRunningRef.current) runStartRef.current = Date.now()
877
+ if (!running && prevRunningRef.current && runStartRef.current) {
878
+ const sec = Math.max(1, Math.round((Date.now() - runStartRef.current) / 1000))
879
+ runStartRef.current = null
880
+ setDoneInfo({ sec })
881
+ prevRunningRef.current = running
882
+ const t = setTimeout(() => setDoneInfo(null), 2600)
883
+ return () => clearTimeout(t)
884
+ }
885
+ prevRunningRef.current = running
886
+ }, [running])
887
+ useEffect(() => { if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight }, [messages, running, doneInfo])
888
+
889
+ // 发文本(输入框与 QuizCard 点选共用):失败里 409 = 绑定会话已失效
890
+ const sendText = async (text) => {
891
+ if (!text || sending) return false
892
+ setSending(true); setErr(null)
893
+ try {
894
+ const r = await fetch('/api/learning-space/session/send', {
895
+ method: 'POST',
896
+ headers: { 'content-type': 'application/json' },
897
+ body: JSON.stringify({ topic, text, phase }),
898
+ })
899
+ const j = await r.json()
900
+ if (j.ok) {
901
+ pendingIdRef.current += 1
902
+ const afterSeq = lastSeqRef.current == null ? -1 : lastSeqRef.current
903
+ setMessages(prev => [...prev, {
904
+ seq: -pendingIdRef.current, role: 'user', text, pending: true, afterSeq,
905
+ }])
906
+ poll()
907
+ return true
908
+ }
909
+ if (j.error === 'session gone, start first') {
910
+ setErr('会话已失效'); setNeedRebind(true); toast.warning('会话已失效', '点「重新绑定」即可继续'); return false
911
+ }
912
+ setErr(j.error); toast.error('发送失败', j.error); return false
913
+ } catch (e) { setErr(String(e)); toast.error('发送失败', String(e)); return false }
914
+ finally { setSending(false) }
915
+ }
916
+
917
+ const send = async () => {
918
+ const text = input.trim()
919
+ if (!text || sending) return
920
+ if (await sendText(text)) setInput('')
921
+ }
922
+
923
+ // 重新绑定:调 /session/start {rebind:true, phase} 只重建当前 phase 的会话,重置轮询
924
+ const rebind = async () => {
925
+ setNeedRebind(false)
926
+ setErr(null)
927
+ try {
928
+ const r = await fetch('/api/learning-space/session/start', {
929
+ method: 'POST',
930
+ headers: { 'content-type': 'application/json' },
931
+ body: JSON.stringify({ topic, rebind: true, phase }),
932
+ })
933
+ const j = await r.json()
934
+ if (j.ok && j.sessionId) {
935
+ setSessionId(j.sessionId)
936
+ setMessages([])
937
+ lastSeqRef.current = null
938
+ poll()
939
+ toast.success('会话已重新绑定')
940
+ } else setErr(j.error || '重新绑定失败')
941
+ } catch (e) { setErr(String(e)) }
942
+ }
943
+
944
+ const last = messages[messages.length - 1]
945
+ const toolMsg = running && last && last.role === 'tool' && last.state !== 'done' && last.state !== 'error' ? last : null
946
+ const statusNode = doneInfo && !running
947
+ ? h(AiStatus, { state: 'done', label: '完成', elapsed: doneInfo.sec })
948
+ : toolMsg
949
+ ? h(AiStatus, { state: 'tool', label: '正在调用工具', detail: toolMsg.toolName || '工具' })
950
+ : running && (!last || last.role !== 'assistant')
951
+ ? h(AiStatus, { state: 'thinking', label: '思考中' })
952
+ : null
953
+ return h('div', {
954
+ className: 'ls-chat',
955
+ // 点击对话窗(输入框/按钮/滚动)不冒泡到卡片折叠区,否则一点输入框整块就收起
956
+ onClick: e => e.stopPropagation(),
957
+ },
958
+ h('div', { className: 'ls-chat-head' },
959
+ h('span', { className: 'ls-chat-title' }, phase === 1 ? '摸底对话' : '学习对话'),
960
+ h('button', {
961
+ className: 'ls-btn', type: 'button',
962
+ disabled: !sessionId || !onOpenInSession,
963
+ onClick: () => onOpenInSession && onOpenInSession(sessionId),
964
+ }, '在会话中打开 ↗')),
965
+ h('div', { className: 'ls-chat-list', ref: listRef },
966
+ hasMore ? h('span', { className: 'ls-chat-more' }, '更早消息可在会话中查看') : null,
967
+ messages.map((m, i) => {
968
+ if (m.role === 'tool') {
969
+ // ask_user_question 待作答时渲染提示卡片:问题+选项只读展示,作答跳转完整会话
970
+ if (m.ask && m.state === 'running') {
971
+ return h('div', { key: `q${m.seq}`, className: 'ls-ask' },
972
+ h('div', { className: 'ls-ask-badge' }, '❓ AI 想问你'),
973
+ m.ask.map((q, qi) => h('div', { key: qi, className: 'ls-ask-q' },
974
+ q.header ? h('div', { className: 'ls-ask-h' }, q.header) : null,
975
+ h('div', { className: 'ls-ask-text' }, q.question || ''),
976
+ Array.isArray(q.options) && q.options.length
977
+ ? h('div', { className: 'ls-ask-opts' }, q.options.map((o, oi) =>
978
+ h('div', { key: oi, className: 'ls-ask-opt' },
979
+ h('span', { className: 'ls-ask-opt-label' }, o.label || ''),
980
+ o.description ? h('span', { className: 'ls-ask-opt-desc' }, o.description) : null)))
981
+ : null,
982
+ q.multi_select ? h('div', { className: 'ls-ask-opt-desc' }, '(可多选)') : null)),
983
+ h('button', {
984
+ className: 'ls-btn ls-ask-go', type: 'button',
985
+ disabled: !sessionId || !onOpenInSession,
986
+ onClick: () => onOpenInSession && onOpenInSession(sessionId),
987
+ }, '去回答 ↗'))
988
+ }
989
+ return h('div', { key: m.seq < 0 ? `t${i}${m.seq}` : m.seq, className: 'ls-tool' },
990
+ `🛠 ${m.toolName || '工具'} `,
991
+ m.state === 'done' ? '✓' : m.state === 'error' ? '✗' : '…')
992
+ }
993
+ return h('div', { key: m.seq < 0 ? `m${m.seq}` : m.seq, className: `ls-msg ls-msg-${m.role}` },
994
+ m.role === 'assistant' && m.quiz
995
+ ? h(QuizCard, { quiz: m.quiz, sending, onAnswer: sendText })
996
+ : m.role === 'assistant' ? markdownLite(m.text) : m.text)
997
+ }),
998
+ running || doneInfo ? statusNode : null),
999
+ err ? h('div', { className: 'ls-chat-err' }, `出错:${err},可点「在会话中打开」继续`) : null,
1000
+ needRebind ? h('button', { className: 'ls-btn ls-rebind', type: 'button', onClick: rebind }, '会话已失效,重新绑定') : null,
1001
+ h('div', { className: 'ls-chat-row' },
1002
+ h('textarea', {
1003
+ className: 'ls-input ls-chat-input',
1004
+ value: input,
1005
+ placeholder: '输入问题,Enter 发送,Shift+Enter 换行',
1006
+ onChange: e => setInput(e.target.value),
1007
+ onKeyDown: e => {
1008
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send() }
1009
+ },
1010
+ }),
1011
+ h('button', { className: 'ls-btn', type: 'button', disabled: sending || !input.trim(), onClick: send },
1012
+ sending ? '发送中…' : '发送')),
1013
+ )
1014
+ }
1015
+
1016
+ /** 材料扩展名白名单(与 Host 上传路由一致),供 file input 的 accept */
1017
+ const ACCEPT = '.pdf,.md,.txt,.docx,.pptx,.xlsx,.csv,.json,.epub,.png,.jpg,.jpeg,.gif,.webp,.zip'
1018
+
1019
+ /** XHR 上传(fetch 无上传进度):FormData + xhr.upload.onprogress 回传百分比 */
1020
+ function uploadFiles(topic, fileList, onProgress) {
1021
+ return new Promise((resolve, reject) => {
1022
+ const fd = new FormData()
1023
+ fd.append('topic', topic)
1024
+ for (const f of fileList) fd.append('file', f)
1025
+ const xhr = new XMLHttpRequest()
1026
+ xhr.open('POST', '/api/learning-space/materials/upload')
1027
+ if (xhr.upload && onProgress) {
1028
+ xhr.upload.onprogress = e => { if (e.lengthComputable) onProgress(e.loaded / e.total) }
1029
+ }
1030
+ xhr.onload = () => {
1031
+ let j = null
1032
+ try { j = JSON.parse(xhr.responseText) } catch { /* 非 JSON */ }
1033
+ if (xhr.status >= 200 && xhr.status < 300 && j && j.ok) resolve(j)
1034
+ else reject(new Error((j && j.error) || `上传失败(HTTP ${xhr.status})`))
1035
+ }
1036
+ xhr.onerror = () => reject(new Error('网络错误,上传失败'))
1037
+ xhr.send(fd)
1038
+ })
1039
+ }
1040
+
1041
+ /** 隐藏 file input + 样式化按钮触发,选中即回调 */
1042
+ function FilePickButton({ onFiles, label, disabled }) {
1043
+ const ref = useRef(null)
1044
+ return h('span', { className: 'ls-file-label' },
1045
+ h('input', {
1046
+ ref, type: 'file', multiple: true, accept: ACCEPT, style: { display: 'none' },
1047
+ onChange: e => { if (e.target.files && e.target.files.length) onFiles(e.target.files); e.target.value = '' },
1048
+ }),
1049
+ h('button', {
1050
+ className: 'ls-btn', type: 'button', disabled,
1051
+ onClick: () => ref.current && ref.current.click(),
1052
+ }, label || '导入材料'),
1053
+ )
1054
+ }
1055
+
1056
+ /** 人类可读文件大小 */
1057
+ function fmtSize(n) {
1058
+ if (n == null) return ''
1059
+ if (n < 1024) return `${n} B`
1060
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
1061
+ return `${(n / 1024 / 1024).toFixed(1)} MB`
1062
+ }
1063
+
1064
+ /** 材料列表 + 导入按钮 + 上传进度 + 错误展示 */
1065
+ function MaterialList({ topic, onRefresh }) {
1066
+ const [uploading, setUploading] = useState(false)
1067
+ const [pct, setPct] = useState(0)
1068
+ const [err, setErr] = useState(null)
1069
+ // 材料列表折叠态:默认收起,与「导入材料」按钮同行展示数量
1070
+ const [open, setOpen] = useState(false)
1071
+ const materials = (topic && topic.materials) || []
1072
+ const doUpload = async files => {
1073
+ setUploading(true); setPct(0); setErr(null)
1074
+ try {
1075
+ const res = await uploadFiles(topic.name, files, p => setPct(Math.round(p * 100)))
1076
+ toast.success('材料已导入', `${(res && res.files ? res.files.length : files.length) || files.length} 个文件`)
1077
+ onRefresh()
1078
+ } catch (e) {
1079
+ const msg = String(e.message || e)
1080
+ setErr(msg); toast.error('上传失败', msg)
1081
+ }
1082
+ finally { setUploading(false) }
1083
+ }
1084
+ return h('div', { className: 'ls-section' },
1085
+ h('div', { className: 'ls-side-head', style: { marginBottom: 0, flexWrap: 'wrap', rowGap: 6 } },
1086
+ h('span', {
1087
+ className: 'ls-h', style: { border: 'none', padding: 0, margin: 0, cursor: 'pointer', userSelect: 'none' },
1088
+ onClick: () => setOpen(!open),
1089
+ }, `${open ? '▾' : '▸'} 学习材料${materials.length ? `(${materials.length})` : ''}`),
1090
+ h(FilePickButton, { onFiles: doUpload, disabled: uploading, label: uploading ? '上传中…' : '导入材料' })),
1091
+ open ? (materials.length === 0
1092
+ ? h('div', { className: 'ls-empty' }, '暂无材料')
1093
+ : materials.map(m => h('div', { key: m.name, className: 'ls-mat-item' },
1094
+ h('span', null, m.name),
1095
+ h('span', { className: 'ls-mat-size' }, fmtSize(m.size))))) : null,
1096
+ uploading ? h('div', { className: 'ls-upload-bar' },
1097
+ h('div', { className: 'ls-upload-fill', style: { width: pct + '%' } })) : null,
1098
+ uploading ? h('div', { className: 'ls-empty' }, `上传中 ${pct}%…`) : null,
1099
+ err ? h('div', { className: 'ls-upload-err' }, err) : null,
1100
+ )
1101
+ }
1102
+
1103
+ /** 阶段卡:阶段一(摸底 + 计划生成)/ 计划已生成 两态;阶段二不渲染(详情区回归现有布局) */
1104
+ function PhaseCard({ topic, onStartPhase1, onStartPhase2, onToggleWebSearch, starting }) {
1105
+ if (topic.phase !== 1) return null
1106
+ return h('div', { className: 'ls-section' },
1107
+ h('div', { className: 'ls-h' }, topic.planReady ? '计划已生成' : '摸底 + 学习计划生成'),
1108
+ !topic.planReady
1109
+ ? h('div', null,
1110
+ h('div', { className: 'ls-empty' }, '可先把学习材料导入下方「学习材料」,AI 摸底与计划生成会参考'),
1111
+ h('label', { className: 'ls-ws' },
1112
+ h('input', {
1113
+ type: 'checkbox',
1114
+ checked: topic.webSearch !== false,
1115
+ onChange: e => onToggleWebSearch(topic.name, e.target.checked),
1116
+ }),
1117
+ ' 允许联网检索(对下一次新会话生效)'),
1118
+ h('div', { style: { marginTop: 8 } },
1119
+ h('button', {
1120
+ className: 'ls-btn', type: 'button', disabled: starting,
1121
+ onClick: () => onStartPhase1(topic.name),
1122
+ }, starting ? '创建中…' : '开始摸底对话 →')))
1123
+ : h('div', { style: { display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' } },
1124
+ h('a', {
1125
+ className: 'ls-btn', download: '',
1126
+ href: `/api/learning-space/export/plan?topic=${encodeURIComponent(topic.name)}`,
1127
+ style: { textDecoration: 'none', lineHeight: '20px' },
1128
+ }, '导出学习计划'),
1129
+ h('span', { className: 'ls-frac' }, '计划已就绪,开始学习?'),
1130
+ h('button', {
1131
+ className: 'ls-btn', type: 'button', disabled: starting,
1132
+ onClick: () => onStartPhase2(topic.name),
1133
+ }, starting ? '创建中…' : '开始学习 →')),
1134
+ )
1135
+ }
1136
+
1137
+ /** 学习记录:studyLog 条目(倒序,最新在前)+ 下载 study-log.md 原文 */
1138
+ function StudyLogList({ topic }) {
1139
+ const entries = (topic && topic.studyLog) || []
1140
+ return h('div', { className: 'ls-section' },
1141
+ h('div', { className: 'ls-side-head', style: { marginBottom: 8 } },
1142
+ h('span', { className: 'ls-h', style: { border: 'none', padding: 0, margin: 0 } }, `学习记录(${entries.length})`),
1143
+ entries.length ? h('a', {
1144
+ className: 'ls-btn', download: '',
1145
+ href: `/api/learning-space/studylog?topic=${encodeURIComponent(topic.name)}`,
1146
+ style: { textDecoration: 'none', lineHeight: '20px' },
1147
+ }, '下载学习记录') : null),
1148
+ entries.length === 0
1149
+ ? h('div', { className: 'ls-empty' }, '暂无学习记录(每教完一个节点 AI 应自动写入;长时间没有时可在对话里提醒它调用 learn_update 的 study_log)')
1150
+ : entries.map((e, i) => h('div', {
1151
+ key: `${e.date}-${i}`, className: 'ls-journal-item', style: { wordBreak: 'break-word' },
1152
+ }, `${e.date} · ${e.node}${e.mastery ? ` · ${e.mastery}` : ''} — ${e.summary}`)),
1153
+ )
1154
+ }
1155
+
1156
+ /** 学习方案(节点列表 + 依赖图):可折叠;阶段二默认收起,点标题或箭头展开 */
1157
+ function PlanSection({ topic, defaultOpen, nodeStatus }) {
1158
+ const [open, setOpen] = useState(!!defaultOpen)
1159
+ const total = topic.nodes.length || topic.order.length || 0
1160
+ const done = topic.counts.done || 0
1161
+ return h('div', { className: 'ls-section' },
1162
+ h('div', {
1163
+ className: 'ls-side-head',
1164
+ style: { marginBottom: open ? 8 : 0, cursor: 'pointer', userSelect: 'none' },
1165
+ onClick: () => setOpen(!open),
1166
+ },
1167
+ h('span', {
1168
+ className: 'ls-h', style: { border: 'none', padding: 0, margin: 0, flex: 1 },
1169
+ }, `${open ? '▾' : '▸'} 学习方案(${done}/${total})`)),
1170
+ open ? h('div', null,
1171
+ h('ul', { className: 'ls-nodes' },
1172
+ (topic.order.length ? topic.order : topic.nodes.map(n => n.label)).map(label =>
1173
+ h('li', { className: 'ls-node', key: label },
1174
+ h('span', { className: 'ls-dot', style: { background: STATUS_COLOR[nodeStatus.get(label) || 'todo'] } }),
1175
+ cleanLabel(label)))),
1176
+ h(MermaidGraph, { src: topic.planMermaid || '', nodes: topic.nodes, edges: topic.edges }),
1177
+ ) : null,
1178
+ )
1179
+ }
1180
+
1181
+ /** 选中课程详情:按 phase 组装——phase1 = PhaseCard + 摸底对话窗;phase2 = 现有布局 + 学习记录 + 学习对话窗 */
1182
+ function TopicDetail({ topic, onStart, starting, chat, onOpenInSession, onRefresh, onToggleWebSearch }) {
1183
+ const [quizTick, setQuizTick] = useState(0)
1184
+ const phase = topic.phase === 1 ? 1 : 2
1185
+ const total = topic.nodes.length || topic.order.length || 0
1186
+ const done = topic.counts.done || 0
1187
+ const pct = total ? Math.round((done / total) * 100) : 0
1188
+ const nodeStatus = new Map(topic.nodes.map(n => [n.label, n.status]))
1189
+ return h('div', { className: 'ls-detail' },
1190
+ h('div', { className: 'ls-detail-head' },
1191
+ h('span', { className: 'ls-name' }, topic.name),
1192
+ h('span', { style: { display: 'flex', gap: 10, alignItems: 'center' } },
1193
+ h('span', { className: 'ls-frac' }, phase === 1 ? '阶段一 · 摸底' : `${done}/${total} 已确认`),
1194
+ h('a', {
1195
+ className: 'ls-btn', href: `/api/learning-space/export?topic=${encodeURIComponent(topic.name)}`,
1196
+ download: '', style: { textDecoration: 'none', lineHeight: '20px' },
1197
+ }, '导出报告'),
1198
+ h('button', {
1199
+ className: 'ls-btn',
1200
+ disabled: starting,
1201
+ onClick: () => onStart(topic.name, phase),
1202
+ }, starting ? '创建中…' : phase === 2 ? '继续学习 →' : '开始摸底对话 →'),
1203
+ phase === 2 ? h('button', {
1204
+ className: 'ls-btn', title: '新建学习会话,从学习方案开头重新教;旧会话保留在会话列表',
1205
+ disabled: starting,
1206
+ onClick: () => onStart(topic.name, 2, true),
1207
+ }, starting ? '…' : '重新学习 ↻') : null,
1208
+ topic.nodes.length ? h(NotificationBell, { nodes: topic.nodes }) : null)),
1209
+ topic.goal ? h('div', { className: 'ls-goal' }, topic.goal) : null,
1210
+ h('div', { className: 'ls-bar' }, h('div', { className: 'ls-bar-fill', style: { width: pct + '%' } })),
1211
+ h('div', { className: 'ls-badges' },
1212
+ ['done', 'doing', 'warn', 'todo'].filter(s => topic.counts[s]).map(s =>
1213
+ h('span', { key: s },
1214
+ h('span', { className: 'ls-dot', style: { background: STATUS_COLOR[s] } }),
1215
+ `${STATUS_LABEL[s]} ${topic.counts[s]}`)),
1216
+ topic.mistakes.length
1217
+ ? h('span', null, `错题 ${topic.mistakes.length}`) : null),
1218
+ h(PhaseCard, {
1219
+ topic,
1220
+ starting,
1221
+ onStartPhase1: name => onStart(name, 1),
1222
+ onStartPhase2: name => onStart(name, 2),
1223
+ onToggleWebSearch,
1224
+ }),
1225
+ h(PlanSection, { topic, defaultOpen: phase === 1, nodeStatus }),
1226
+ h(MaterialList, { topic, onRefresh }),
1227
+ h(QuizHistory, { topic: topic.name, refreshKey: quizTick }),
1228
+ phase === 2 ? h(StudyLogList, { topic }) : null,
1229
+ chat ? h(ChatWindow, {
1230
+ key: `${topic.name}-${phase}`, // phase 切换时重挂载,重置轮询游标,避免双会话消息串窗
1231
+ topic: topic.name,
1232
+ phase,
1233
+ sessionId: phase === 1 ? topic.phase1SessionId : topic.phase2SessionId,
1234
+ onOpenInSession,
1235
+ onQuizGraded: () => setQuizTick(t => t + 1),
1236
+ }) : null,
1237
+ )
1238
+ }
1239
+
1240
+ /** 节点标签清洗:去掉 mermaid 里带的 <br/> 换行标记(显示层处理,源数据不动) */
1241
+ const cleanLabel = s => String(s || '').replace(/<br\s*\/?>/gi, ' ').replace(/\s{2,}/g, ' ').trim()
1242
+
1243
+ /** 专注页左栏:节点手风琴——点节点展开该节点的教学笔记(notes/<节点>.md) */
1244
+ function NodeAccordion({ topic }) {
1245
+ const [openNode, setOpenNode] = useState(null)
1246
+ const [notes, setNotes] = useState({}) // label -> content(含 '' 已确认为无笔记)
1247
+ const nodes = topic.nodes.length ? topic.nodes : (topic.order || []).map(l => ({ id: l, label: l, status: 'todo' }))
1248
+ const label = n => cleanLabel(n.label || n.id)
1249
+ const toggle = async label => {
1250
+ if (openNode === label) { setOpenNode(null); return }
1251
+ setOpenNode(label)
1252
+ if (notes[label] === undefined) {
1253
+ try {
1254
+ const r = await fetch(`/api/learning-space/node-note?topic=${encodeURIComponent(topic.name)}&node=${encodeURIComponent(label)}`)
1255
+ const j = await r.json()
1256
+ setNotes(prev => ({ ...prev, [label]: j.ok ? j.content : null }))
1257
+ } catch { setNotes(prev => ({ ...prev, [label]: null })) }
1258
+ }
1259
+ }
1260
+ return h('div', { className: 'ls-section' },
1261
+ h('div', { className: 'ls-side-head', style: { marginBottom: 8 } },
1262
+ h('span', { className: 'ls-h', style: { border: 'none', padding: 0, margin: 0 } }, '知识节点(点击看教学内容)')),
1263
+ h('div', { className: 'ls-side-list' }, nodes.map(n => {
1264
+ const label = n.label || n.id // 原始标签:fetch/匹配 notes 文件用
1265
+ const disp = cleanLabel(label) // 显示用:去 <br/>
1266
+ const open = openNode === label
1267
+ const content = notes[label]
1268
+ return h('div', { key: label, style: { marginBottom: 2 } },
1269
+ h('div', {
1270
+ className: 'ls-side-item' + (open ? ' active' : ''),
1271
+ onClick: () => toggle(label),
1272
+ style: { cursor: 'pointer' },
1273
+ },
1274
+ h('span', { className: 'ls-dot', style: { background: STATUS_COLOR[n.status] || STATUS_COLOR.todo, flex: 'none' } }),
1275
+ h('span', { className: 'ls-side-name' }, `${open ? '▾' : '▸'} ${disp}`)),
1276
+ open ? h('div', {
1277
+ className: 'ls-md-p',
1278
+ style: { padding: '8px 10px 8px 24px', fontSize: 13, lineHeight: 1.8 },
1279
+ },
1280
+ content === undefined ? '加载中…'
1281
+ : content === null ? '(读取失败,稍后再试)'
1282
+ : content.trim() ? markdownLite(content)
1283
+ : '(还没有这个节点的教学笔记——学到这里时 AI 会写入 notes/<节点>.md)')
1284
+ : null,
1285
+ )
1286
+ })),
1287
+ )
1288
+ }
1289
+
1290
+ /** 专注学习页:左 = 教的知识(方案/学习记录/材料),右 = 问答对话窗,头部带返回 */
1291
+ function StudyFocusView({ topic, onBack, onOpenInSession, onRefresh }) {
1292
+ const [quizTick, setQuizTick] = useState(0)
1293
+ const phase = topic.phase === 1 ? 1 : 2
1294
+ const total = topic.nodes.length || topic.order.length || 0
1295
+ const done = topic.counts.done || 0
1296
+ const nodeStatus = new Map(topic.nodes.map(n => [n.label, n.status]))
1297
+ return h('div', { className: 'ls-focus' },
1298
+ h('div', { className: 'ls-focus-left' },
1299
+ h('div', { className: 'ls-focus-head' },
1300
+ h('button', { className: 'ls-btn', type: 'button', onClick: onBack }, '← 返回'),
1301
+ h('span', { className: 'ls-focus-title', title: topic.name }, topic.name),
1302
+ h('span', { className: 'ls-frac' }, `${done}/${total} 已确认`),
1303
+ topic.nodes.length ? h(NotificationBell, { nodes: topic.nodes }) : null),
1304
+ h(NodeAccordion, { topic }),
1305
+ h(MaterialList, { topic, onRefresh })),
1306
+ h('div', { className: 'ls-focus-right' },
1307
+ h(ChatWindow, {
1308
+ key: `${topic.name}-${phase}`,
1309
+ topic: topic.name,
1310
+ phase,
1311
+ sessionId: phase === 1 ? topic.phase1SessionId : topic.phase2SessionId,
1312
+ onOpenInSession,
1313
+ onQuizGraded: () => setQuizTick(t => t + 1),
1314
+ })),
1315
+ )
1316
+ }
1317
+
1318
+ /** 左栏:新建入口 + 课程列表(进度摘要 + 状态色点 + 选中态) */
1319
+ function TopicSidebar({ topics, selected, onSelect, onCreated, onDelete }) {
1320
+ return h('div', { className: 'ls-side' },
1321
+ h('div', { className: 'ls-side-head' },
1322
+ h('span', { className: 'ls-h', style: { flex: 1 } }, '课程'),
1323
+ topics.length ? h('a', {
1324
+ className: 'ls-btn', href: '/api/learning-space/export?all=1', download: '',
1325
+ style: { textDecoration: 'none', lineHeight: '20px' },
1326
+ }, '导出全部') : null),
1327
+ h(NewTopicForm, { onCreated }),
1328
+ topics.length === 0
1329
+ ? h('div', { className: 'ls-empty' }, '还没有课程')
1330
+ : h('div', { className: 'ls-side-list' }, topics.map(t => {
1331
+ const total = t.nodes.length || t.order.length || 0
1332
+ const color = t.counts.warn > 0 ? STATUS_COLOR.warn
1333
+ : t.counts.doing > 0 ? STATUS_COLOR.doing
1334
+ : t.counts.done > 0 ? STATUS_COLOR.done : STATUS_COLOR.todo
1335
+ return h('div', {
1336
+ key: t.name,
1337
+ className: 'ls-side-item' + (selected === t.name ? ' active' : ''),
1338
+ onClick: () => onSelect(t.name),
1339
+ },
1340
+ h('span', { className: 'ls-dot', style: { background: color, flex: 'none' } }),
1341
+ h('span', { className: 'ls-side-name' }, t.name),
1342
+ h('span', { className: 'ls-side-frac' }, `${t.counts.done || 0}/${total}`),
1343
+ h('button', {
1344
+ className: 'ls-side-del', type: 'button', title: '删除课程',
1345
+ onClick: e => { e.stopPropagation(); onDelete(t) },
1346
+ }, '✕'))
1347
+ })),
1348
+ )
1349
+ }
1350
+
1351
+ /** 删除课程确认弹窗:警告不可恢复,会话保留说明 */
1352
+ function DeleteTopicDialog({ topic, busy, onCancel, onConfirm }) {
1353
+ const total = topic.nodes.length || topic.order.length || 0
1354
+ return h('div', { className: 'ls-modal-mask', onClick: busy ? undefined : onCancel },
1355
+ h('div', { className: 'ls-modal', onClick: e => e.stopPropagation() },
1356
+ h('div', { className: 'ls-modal-title' }, `删除课程「${topic.name}」?`),
1357
+ h('div', { className: 'ls-modal-body' },
1358
+ h('p', { style: { margin: '0 0 6px' } },
1359
+ `当前进度 ${topic.counts.done || 0}/${total} 已确认,材料 ${((topic.materials) || []).length} 个。`),
1360
+ h('p', { style: { margin: 0 } },
1361
+ h('strong', null, '删除后学习计划、错题本、学习记录、答题记录和上传材料均不可恢复。'),
1362
+ '摸底/学习会话会保留在会话列表中,可自行归档。')),
1363
+ h('div', { className: 'ls-modal-actions' },
1364
+ h('button', { className: 'ls-btn', type: 'button', disabled: busy, onClick: onCancel }, '取消'),
1365
+ h('button', {
1366
+ className: 'ls-btn ls-btn-danger', type: 'button', disabled: busy, onClick: onConfirm,
1367
+ }, busy ? '删除中…' : '确认删除'))))
1368
+ }
1369
+
1370
+ /**
1371
+ * 模型设置弹窗:跟随宿主默认开关 + provider/model 级联下拉 + 立即应用勾选。
1372
+ * 每次打开都重新 GET(目录按当前实况渲染);已存模型不在目录时回显跟默认态并提示。
1373
+ */
1374
+ function ModelSettingsDialog({ currentTopic, onClose }) {
1375
+ const [catalog, setCatalog] = useState(undefined) // undefined=加载中 null=目录失败
1376
+ const [catalogError, setCatalogError] = useState(null)
1377
+ const [followDefault, setFollowDefault] = useState(true)
1378
+ const [provider, setProvider] = useState('')
1379
+ const [model, setModel] = useState('')
1380
+ const [savedStale, setSavedStale] = useState(false) // 已存模型不在当前目录
1381
+ const [applyNow, setApplyNow] = useState(false)
1382
+ const [busy, setBusy] = useState(false)
1383
+ const [err, setErr] = useState(null)
1384
+ const [applyNotice, setApplyNotice] = useState(null)
1385
+
1386
+ useEffect(() => {
1387
+ let alive = true
1388
+ fetch('/api/learning-space/settings/model').then(r => r.json()).then(j => {
1389
+ if (!alive) return
1390
+ const cat = j.ok ? j.catalog : null
1391
+ const savedSel = j.ok && j.saved ? j.saved.model : null
1392
+ let follow = true, prov = '', mdl = '', stale = false
1393
+ if (savedSel && cat && Array.isArray(cat.groups)) {
1394
+ const g = cat.groups.find(x => x.id === savedSel.provider)
1395
+ const m = g && (g.models || []).find(x => x.id === savedSel.model)
1396
+ if (g && m) { follow = false; prov = g.id; mdl = m.id }
1397
+ else stale = true // 已存选择不在当前目录:回显跟默认 + 提示
1398
+ }
1399
+ if (!follow && !prov && cat && Array.isArray(cat.groups) && cat.groups.length) {
1400
+ prov = cat.groups[0].id
1401
+ mdl = (cat.groups[0].models || [])[0] ? cat.groups[0].models[0].id : ''
1402
+ }
1403
+ setCatalog(cat || null)
1404
+ setCatalogError(j.ok ? (j.error || null) : (j.error || '加载失败'))
1405
+ setFollowDefault(follow); setProvider(prov); setModel(mdl); setSavedStale(stale)
1406
+ }).catch(e => { if (alive) { setCatalog(null); setCatalogError(String(e)) } })
1407
+ return () => { alive = false }
1408
+ }, [])
1409
+
1410
+ const groups = (catalog && Array.isArray(catalog.groups)) ? catalog.groups : []
1411
+ const group = groups.find(g => g.id === provider)
1412
+ const models = group ? (group.models || []) : []
1413
+ const pickerModels = useMemo(() => groups.flatMap(g => (g.models || []).map(m => ({
1414
+ provider: g.id,
1415
+ providerName: g.name || g.id,
1416
+ modelId: m.id,
1417
+ name: m.name || m.id,
1418
+ }))), [catalog])
1419
+
1420
+ const save = async () => {
1421
+ if (busy) return
1422
+ setBusy(true); setErr(null); setApplyNotice(null)
1423
+ let sel = null
1424
+ if (!followDefault) {
1425
+ if (!provider || !model) { setErr('请先选择模型'); setBusy(false); return }
1426
+ sel = { provider, model }
1427
+ // effort 不做 UI:目录里该模型有 defaultEffort 就随保存带上
1428
+ const m = models.find(x => x.id === model)
1429
+ if (m && m.reasoning && m.reasoning.defaultEffort) sel.reasoningEffort = m.reasoning.defaultEffort
1430
+ }
1431
+ try {
1432
+ const r = await fetch('/api/learning-space/settings/model', {
1433
+ method: 'POST', headers: { 'content-type': 'application/json' },
1434
+ body: JSON.stringify({ model: sel,
1435
+ applyToTopic: applyNow && currentTopic ? currentTopic : undefined }),
1436
+ })
1437
+ const j = await r.json()
1438
+ if (!j.ok) { setErr(j.error || '保存失败'); toast.error('保存失败', j.error || ''); return }
1439
+ if (j.applyError) {
1440
+ const msg = `已保存,但应用到会话失败:${j.applyError}`
1441
+ setApplyNotice(msg); toast.warning('已保存', msg); return
1442
+ }
1443
+ toast.success('模型设置已保存', sel ? `${sel.provider} / ${sel.model}` : '跟随宿主默认')
1444
+ onClose(true)
1445
+ } catch (e) { setErr(String(e)) }
1446
+ finally { setBusy(false) }
1447
+ }
1448
+
1449
+ const catalogDown = catalog === null
1450
+ return h('div', { className: 'ls-modal-mask', onClick: busy ? undefined : onClose },
1451
+ h('div', { className: 'ls-modal', onClick: e => e.stopPropagation() },
1452
+ h('div', { className: 'ls-modal-title' }, '模型设置'),
1453
+ h('div', { className: 'ls-modal-body' },
1454
+ catalog === undefined ? h('div', { className: 'ls-empty' }, '加载模型目录…') : [
1455
+ h('label', { key: 'follow', className: 'ls-set-check' },
1456
+ h('input', { type: 'checkbox', checked: followDefault,
1457
+ onChange: e => {
1458
+ const on = e.target.checked
1459
+ setFollowDefault(on)
1460
+ // 取消跟随默认且尚未选过:落到目录里的第一个模型,避免空选
1461
+ if (!on && !provider && pickerModels.length) {
1462
+ setProvider(pickerModels[0].provider)
1463
+ setModel(pickerModels[0].modelId)
1464
+ }
1465
+ } }),
1466
+ '跟随宿主默认模型'),
1467
+ followDefault && catalog && catalog.default
1468
+ ? h('div', { key: 'def', className: 'ls-set-note' },
1469
+ `当前默认:${catalog.default.provider} / ${catalog.default.model}`)
1470
+ : null,
1471
+ h('label', { key: 'mdl', className: 'ls-set-label' }, '模型'),
1472
+ h(ModelPicker, {
1473
+ key: 'picker',
1474
+ models: pickerModels,
1475
+ value: { provider, model },
1476
+ disabled: followDefault || catalogDown,
1477
+ placeholder: catalogDown ? '模型目录不可用' : '选择模型',
1478
+ onChange: sel => { setProvider(sel.provider); setModel(sel.model) },
1479
+ }),
1480
+ h('label', { key: 'apply', className: 'ls-set-check' },
1481
+ h('input', { type: 'checkbox', checked: applyNow, disabled: !currentTopic,
1482
+ onChange: e => setApplyNow(e.target.checked) }),
1483
+ `同时应用到当前课程的学习会话${currentTopic ? `(${currentTopic})` : '(未选择课程)'}`),
1484
+ applyNow && followDefault
1485
+ ? h('div', { key: 'an', className: 'ls-set-note' }, '跟随默认不会改动已有会话。')
1486
+ : null,
1487
+ h('p', { key: 'doc', className: 'ls-set-note' },
1488
+ '选择会保存到项目根 .learning-space.json,新建的教学会话将使用该模型;',
1489
+ '宿主会同时把它记为部署默认偏好(DSH 设置里可改回)。'),
1490
+ savedStale ? h('div', { key: 'stale', className: 'ls-set-warn' }, '已保存的模型当前不可用,暂按跟随默认显示。') : null,
1491
+ catalogError ? h('div', { key: 'cerr', className: 'ls-set-warn' }, catalogError) : null,
1492
+ applyNotice ? h('div', { key: 'anotice', className: 'ls-set-warn' }, applyNotice) : null,
1493
+ err ? h('div', { key: 'err', className: 'ls-set-warn' }, err) : null,
1494
+ ]),
1495
+ h('div', { className: 'ls-modal-actions' },
1496
+ h('button', { className: 'ls-btn', type: 'button', disabled: busy, onClick: onClose }, '取消'),
1497
+ h('button', {
1498
+ className: 'ls-btn', type: 'button', disabled: busy || catalog === undefined,
1499
+ onClick: save,
1500
+ }, busy ? '保存中…' : '保存'))))
1501
+ }
1502
+
1503
+ /** 新建课程(可带文件):create 成功后紧接着对所选文件调上传,两步全成才算完成 */
1504
+ function NewTopicForm({ onCreated }) {
1505
+ const [name, setName] = useState('')
1506
+ const [goal, setGoal] = useState('')
1507
+ const [files, setFiles] = useState([])
1508
+ const [busy, setBusy] = useState(false)
1509
+ const [err, setErr] = useState(null)
1510
+ const fileRef = useRef(null)
1511
+ const submit = async e => {
1512
+ e.preventDefault()
1513
+ const t = name.trim()
1514
+ if (!t || busy) return
1515
+ setBusy(true); setErr(null)
1516
+ try {
1517
+ // 第一步:建课
1518
+ const r = await fetch('/api/learning-space/topic/create', {
1519
+ method: 'POST', headers: { 'content-type': 'application/json' },
1520
+ body: JSON.stringify({ topic: t, goal: goal.trim() }),
1521
+ })
1522
+ const j = await r.json()
1523
+ if (!j.ok) { setErr(j.error || '创建失败'); toast.error('创建失败', j.error || ''); return }
1524
+ // 第二步:对所选文件上传(失败有补救路径:课程已建成,详情区可再导入)
1525
+ if (files.length) {
1526
+ try { await uploadFiles(t, files) }
1527
+ catch (e2) {
1528
+ const msg = `课程已创建,但材料上传失败:${e2.message || e2}`
1529
+ setErr(msg); toast.warning('材料上传失败', msg)
1530
+ }
1531
+ }
1532
+ setName(''); setGoal(''); setFiles([])
1533
+ onCreated(t)
1534
+ toast.success('课程已创建', files.length ? `${t} · ${files.length} 个材料` : t)
1535
+ } catch (e2) {
1536
+ setErr(String(e2)); toast.error('创建失败', String(e2))
1537
+ }
1538
+ finally { setBusy(false) }
1539
+ }
1540
+ return h('form', { className: 'ls-new', onSubmit: submit, style: { flexDirection: 'column' } },
1541
+ err ? h('div', { className: 'ls-upload-err' }, err) : null,
1542
+ h('input', { className: 'ls-input', placeholder: '课程名,如:傅里叶变换', value: name,
1543
+ onChange: e => setName(e.target.value) }),
1544
+ h('input', { className: 'ls-input', placeholder: '学习目标(可选)', value: goal,
1545
+ onChange: e => setGoal(e.target.value) }),
1546
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
1547
+ h(FilePickButton, {
1548
+ onFiles: fl => setFiles(prev => [...prev, ...Array.from(fl)]),
1549
+ disabled: busy, label: files.length ? `+ 追加材料(${files.length})` : '+ 附带材料',
1550
+ }),
1551
+ h('button', { className: 'ls-btn', type: 'submit', disabled: busy || !name.trim() },
1552
+ busy ? '创建中…' : '+ 新建课程'),
1553
+ ),
1554
+ files.length ? h('div', { className: 'ls-picked' }, files.map((f, i) =>
1555
+ h('div', { key: `${f.name}${i}`, className: 'ls-picked-item' },
1556
+ h('span', null, `${f.name}(${fmtSize(f.size)})`),
1557
+ h('button', {
1558
+ className: 'ls-picked-x', type: 'button', title: '移除',
1559
+ onClick: () => setFiles(prev => prev.filter((_, j) => j !== i)),
1560
+ }, '×')),
1561
+ )) : null,
1562
+ )
1563
+ }
1564
+
1565
+ function LearningPanel() {
1566
+ const [data, setData] = useState(null)
1567
+ const [error, setError] = useState(null)
1568
+ const [selectedTopic, setSelectedTopic] = useState(null)
1569
+ const [starting, setStarting] = useState(null)
1570
+ const [chatTopic, setChatTopic] = useState(null)
1571
+ // 待删除课程 { name, topic, busy },非空时渲染确认弹窗
1572
+ const [deleting, setDeleting] = useState(null)
1573
+ // 专注学习页:课程名非空时整面板切换为左知识右问答视图
1574
+ const [studyView, setStudyView] = useState(null)
1575
+ // 模型设置弹窗:非空时渲染 ModelSettingsDialog
1576
+ const [modelSettings, setModelSettings] = useState(false)
1577
+
1578
+ const load = useCallback(() => {
1579
+ fetch('/api/learning-space/overview').then(r => r.json())
1580
+ .then(j => { if (j.ok) { setData(j); setError(null) } else setError(j.error) })
1581
+ .catch(e => setError(String(e)))
1582
+ }, [])
1583
+ useEffect(() => { load(); const t = setInterval(load, 15000); return () => clearInterval(t) }, [load])
1584
+
1585
+ // 默认选中第一门课;已选课程被删则回退
1586
+ useEffect(() => {
1587
+ if (data && data.topics.length) {
1588
+ if (!selectedTopic || !data.topics.some(t => t.name === selectedTopic)) {
1589
+ setSelectedTopic(data.topics[0].name)
1590
+ }
1591
+ } else if (selectedTopic !== null) setSelectedTopic(null)
1592
+ }, [data])
1593
+
1594
+ // rebind=true:抛弃旧绑定强制新建会话并重注 seed(「重新学习」用;旧会话保留在会话列表)
1595
+ const startLearning = useCallback(async (topic, phase, rebind) => {
1596
+ setStarting(topic)
1597
+ try {
1598
+ const r = await fetch('/api/learning-space/session/start', {
1599
+ method: 'POST',
1600
+ headers: { 'content-type': 'application/json' },
1601
+ body: JSON.stringify(rebind ? { topic, phase, rebind: true } : { topic, phase }),
1602
+ })
1603
+ const j = await r.json()
1604
+ if (j.ok && j.sessionId) {
1605
+ setSelectedTopic(topic) // 切到该课程详情
1606
+ setChatTopic(topic) // 详情区展开内嵌对话窗(单窗互斥;窗内按 topic.phase 路由)
1607
+ setStudyView(topic) // 直接进入专注学习页(左知识右问答,可返回)
1608
+ toast.success(phase === 1 ? '摸底会话已创建' : '学习会话已创建', topic)
1609
+ load()
1610
+ } else {
1611
+ setError(j.error || '创建会话失败')
1612
+ toast.error('创建会话失败', j.error || '')
1613
+ }
1614
+ } catch (e) {
1615
+ setError(String(e)); toast.error('创建会话失败', String(e))
1616
+ }
1617
+ finally { setStarting(null) }
1618
+ }, [load])
1619
+
1620
+ // 联网开关:只改 session.json 的 webSearch 字段(对下一次新建会话生效)
1621
+ const toggleWebSearch = useCallback(async (topic, enabled) => {
1622
+ try {
1623
+ const r = await fetch('/api/learning-space/session/websearch', {
1624
+ method: 'POST',
1625
+ headers: { 'content-type': 'application/json' },
1626
+ body: JSON.stringify({ topic, enabled }),
1627
+ })
1628
+ const j = await r.json()
1629
+ if (!j.ok) { setError(j.error || '设置失败'); toast.error('设置失败', j.error || ''); return }
1630
+ toast.info(enabled ? '已开启联网检索' : '已关闭联网检索', '对下一次新建会话生效')
1631
+ load()
1632
+ } catch (e) { setError(String(e)) }
1633
+ }, [load])
1634
+
1635
+ // 删除课程:确认后调 /topic/delete,成功后刷新并清掉选中/对话窗状态
1636
+ const confirmDeleteTopic = useCallback(async () => {
1637
+ if (!deleting) return
1638
+ setDeleting(d => ({ ...d, busy: true }))
1639
+ try {
1640
+ const r = await fetch('/api/learning-space/topic/delete', {
1641
+ method: 'POST',
1642
+ headers: { 'content-type': 'application/json' },
1643
+ body: JSON.stringify({ topic: deleting.name }),
1644
+ })
1645
+ const j = await r.json()
1646
+ if (j.ok) {
1647
+ const name = deleting.name
1648
+ setDeleting(null)
1649
+ if (selectedTopic === deleting.name) { setSelectedTopic(null); setChatTopic(null) }
1650
+ toast.success('课程已删除', name)
1651
+ load()
1652
+ } else {
1653
+ setError(j.error || '删除失败')
1654
+ toast.error('删除失败', j.error || '')
1655
+ }
1656
+ } catch (e) {
1657
+ setError(String(e)); toast.error('删除失败', String(e))
1658
+ }
1659
+ finally { setDeleting(d => d && { ...d, busy: false }) }
1660
+ }, [deleting, selectedTopic, load])
1661
+
1662
+ const selected = data && data.topics.find(t => t.name === selectedTopic)
1663
+ // 专注学习页:课程还在就整面板切换(overview 刷新后 topic 对象取最新)
1664
+ const studyTopic = studyView && data ? data.topics.find(t => t.name === studyView) : null
1665
+ if (studyTopic) return h('div', { className: 'ls-panel' },
1666
+ h('style', null, css),
1667
+ h(ToastHost),
1668
+ error ? h('div', { className: 'ls-empty' }, `出错:${error}`) : null,
1669
+ h(StudyFocusView, {
1670
+ topic: studyTopic,
1671
+ onBack: () => setStudyView(null),
1672
+ onOpenInSession: sid => panelCtx && panelCtx.uiWorkspace && panelCtx.uiWorkspace.openSession(sid),
1673
+ onRefresh: load,
1674
+ }),
1675
+ )
1676
+ return h('div', { className: 'ls-panel' },
1677
+ h('style', null, css),
1678
+ h(ToastHost),
1679
+ h('div', { className: 'ls-title-row' },
1680
+ h('h1', { className: 'ls-title' }, '学习空间'),
1681
+ h('button', {
1682
+ className: 'ls-gear', type: 'button', 'aria-label': '模型设置', title: '模型设置',
1683
+ onClick: () => setModelSettings(true),
1684
+ }, '⚙')),
1685
+ h('p', { className: 'ls-sub' }, '左侧管理课程,右侧看进度、依赖图和错题,材料可导入给教学会话'),
1686
+ error ? h('div', { className: 'ls-empty' }, `出错:${error}`) : null,
1687
+ !data && !error ? h('div', { className: 'ls-loading' }, '加载中…') : null,
1688
+ data ? h('div', { className: 'ls-layout' },
1689
+ h(TopicSidebar, {
1690
+ topics: data.topics,
1691
+ selected: selectedTopic,
1692
+ onSelect: name => setSelectedTopic(name),
1693
+ onCreated: name => { setSelectedTopic(name); load() },
1694
+ onDelete: t => setDeleting({ name: t.name, topic: t, busy: false }),
1695
+ }),
1696
+ selected
1697
+ ? h(TopicDetail, {
1698
+ key: selected.name,
1699
+ topic: selected,
1700
+ starting: starting === selected.name,
1701
+ chat: chatTopic === selected.name,
1702
+ onStart: startLearning,
1703
+ onToggleWebSearch: toggleWebSearch,
1704
+ onOpenInSession: sid => panelCtx && panelCtx.uiWorkspace && panelCtx.uiWorkspace.openSession(sid),
1705
+ onRefresh: load,
1706
+ })
1707
+ : h('div', { className: 'ls-empty' }, '在左侧新建或选择一门课程'),
1708
+ ) : null,
1709
+ data && data.journal.length ? h('div', { className: 'ls-section' },
1710
+ h('div', { className: 'ls-h' }, '最近日志'),
1711
+ data.journal.map((line, i) => h('div', { key: i, className: 'ls-journal-item' }, line)),
1712
+ ) : null,
1713
+ deleting ? h(DeleteTopicDialog, {
1714
+ topic: deleting.topic,
1715
+ busy: deleting.busy,
1716
+ onCancel: () => { if (!deleting.busy) setDeleting(null) },
1717
+ onConfirm: confirmDeleteTopic,
1718
+ }) : null,
1719
+ modelSettings ? h(ModelSettingsDialog, {
1720
+ currentTopic: selectedTopic,
1721
+ onClose: () => setModelSettings(false),
1722
+ }) : null,
1723
+ )
1724
+ }
1725
+
1726
+ let panelCtx = null
1727
+ return {
1728
+ inject: ['slots', 'uiWorkspace'],
1729
+ apply(ctx) {
1730
+ panelCtx = ctx
1731
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register(
1732
+ { name: 'sidebar.panellist', id: 'learning-space', order: 60, label: '学习空间' },
1733
+ PanelIcon))
1734
+ ctx.slots.inject('main', () => ctx.slots.register(
1735
+ { name: 'main', key: 'learning-space' },
1736
+ LearningPanel))
1737
+ },
1738
+ }
1739
+ },
1740
+ })