Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1084 lines (975 loc) · 43.7 KB
/
Copy pathapp.js
File metadata and controls
1084 lines (975 loc) · 43.7 KB
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ============================================================================
* app.js — 基于 Kimi2.6 多 Agent 集群的智慧育人平台前端核心逻辑
* 架构:模块化函数式编程,按职责分区(配置/工具/UI/业务/渲染/初始化)
* 规范:JSDoc 注释、常量配置区、异常兜底、无障碍支持
* ============================================================================
*/
import * as echarts from "echarts";
// =============================================================================
// 【一、全局常量配置区】Configuration
// =============================================================================
/** @type {Object} 全局运行时配置 */
const CONFIG = {
/** API 基础地址(Vite proxy 自动代理 /api 到后端) */
API_BASE: "",
/** 轮询间隔(毫秒) */
POLL_INTERVAL: 2500,
/** 最大轮询超时(毫秒):10分钟 */
MAX_POLL_TIME: 10 * 60 * 1000,
/** 输入文本最大字符数 */
MAX_TEXT_LENGTH: 15000,
/** 输入文本最小字符数 */
MIN_TEXT_LENGTH: 10,
/** 接口请求失败最大重试次数 */
MAX_RETRIES: 3,
/** 重试间隔基数(毫秒),实际间隔 = 基数 × 尝试次数 */
RETRY_DELAY: 1500,
/** 骨架屏最小展示时间(毫秒) */
SKELETON_MIN_TIME: 700,
};
/** @type {Array<Object>} 6 个 Agent 元数据(固定顺序,不可变更) */
const AGENTS = [
{ key: "agent_1_parse", step: 1, name: "学情解析 Agent", desc: "拆解文本 · 提取知识点 · 标注薄弱点 · 归纳易错点", badge: "1" },
{ key: "agent_2_profile", step: 2, name: "学情画像 Agent", desc: "能力标签 · 短板画像 · 层级评估 · 成长建议", badge: "2" },
{ key: "agent_3_guide", step: 3, name: "分层导学 Agent", desc: "学习路径 · 思路引导 · 练习策略 · 资源推荐", badge: "3" },
{ key: "agent_4_ethics", step: 4, name: "学术伦理风控 Agent", desc: "AI痕迹检测 · 学术不端风险 · 逻辑漏洞 · 语句规范", badge: "4" },
{ key: "agent_5_polish", step: 5, name: "学术规范整编 Agent", desc: "逻辑润色 · 段落优化 · 语句通顺 · 格式规范", badge: "5" },
{ key: "agent_6_report", step: 6, name: "成长档案生成 Agent", desc: "汇总全部分析结果 · 生成结构化个人成长报告", badge: "6" },
];
// =============================================================================
// 【二、工具函数区】Utilities
// =============================================================================
/** DOM 快捷选择器 */
const $ = (id) => document.getElementById(id);
/** 延迟函数(Promise 包装 setTimeout) */
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/**
* 带自动重试的网络请求封装
* @param {string} url - 请求地址
* @param {Object} options - fetch 选项
* @param {number} retries - 剩余重试次数
* @returns {Promise<Response>}
*/
async function fetchWithRetry(url, options = {}, retries = CONFIG.MAX_RETRIES) {
let lastError;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const response = await fetch(url, options);
return response;
} catch (err) {
lastError = err;
if (attempt < retries) {
await delay(CONFIG.RETRY_DELAY * attempt);
}
}
}
throw lastError;
}
// =============================================================================
// 【三、Toast 通知系统】Toast Notifications
// =============================================================================
const Toast = {
/** @private */
container: null,
/** 初始化 Toast 容器引用 */
init() {
this.container = $("toastContainer");
},
/**
* 显示 Toast 通知
* @param {string} message - 消息内容
* @param {string} type - 类型:success/error/warning/info
* @param {number} duration - 显示时长(毫秒)
*/
show(message, type = "success", duration = 3500) {
if (!this.container) this.init();
const icons = { success: "✓", error: "✗", warning: "⚠", info: "ℹ" };
const toast = document.createElement("div");
toast.className = `toast toast--${type}`;
toast.setAttribute("role", "alert");
toast.innerHTML = `
<span aria-hidden="true">${icons[type] || ""}</span>
<span>${message}</span>
<button class="toast__close" aria-label="关闭通知" onclick="this.parentElement.remove()">×</button>
`;
this.container.appendChild(toast);
requestAnimationFrame(() => toast.classList.add("toast--show"));
setTimeout(() => {
toast.classList.remove("toast--show");
setTimeout(() => toast.remove(), 350);
}, duration);
},
success(msg, dur) { this.show(msg, "success", dur); },
error(msg, dur) { this.show(msg, "error", dur); },
warning(msg, dur) { this.show(msg, "warning", dur); },
info(msg, dur) { this.show(msg, "info", dur); },
};
// =============================================================================
// 【四、骨架屏控制】Skeleton Screen
// =============================================================================
const Skeleton = {
el: null,
init() { this.el = $("skeleton"); },
hide() {
if (!this.el) this.init();
this.el.classList.add("skeleton--hidden");
setTimeout(() => { this.el.style.display = "none"; }, 450);
},
};
// =============================================================================
// 【五、深色/浅色模式切换】Theme Toggle
// =============================================================================
const Theme = {
STORAGE_KEY: "wisdom-theme-preference",
/** 初始化:读取本地存储或系统偏好 */
init() {
const saved = localStorage.getItem(this.STORAGE_KEY);
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
if (saved === "dark" || (!saved && prefersDark)) {
document.documentElement.setAttribute("data-theme", "dark");
$("themeToggle").innerHTML = "☀️";
}
},
/** 切换主题 */
toggle() {
const html = document.documentElement;
const btn = $("themeToggle");
if (html.getAttribute("data-theme") === "dark") {
html.removeAttribute("data-theme");
btn.innerHTML = "🌙";
localStorage.setItem(this.STORAGE_KEY, "light");
} else {
html.setAttribute("data-theme", "dark");
btn.innerHTML = "☀️";
localStorage.setItem(this.STORAGE_KEY, "dark");
}
},
};
// =============================================================================
// 【六、新手功能引导】Onboarding Modal
// =============================================================================
const Onboarding = {
STORAGE_KEY: "wisdom-onboarding-shown-v2",
/** 初始化:首次访问自动展示 */
init() {
if (!localStorage.getItem(this.STORAGE_KEY)) {
$("onboardingModal").classList.add("modal--active");
}
},
/** 打开引导 */
open() {
$("onboardingModal").classList.add("modal--active");
},
/** 关闭引导,如勾选则永久隐藏 */
close() {
$("onboardingModal").classList.remove("modal--active");
if ($("dontShowAgain").checked) {
localStorage.setItem(this.STORAGE_KEY, "true");
}
},
};
// =============================================================================
// 【七、角色权限控制】Role-Based Access Control
// =============================================================================
const Role = {
STORAGE_KEY: "wisdom-user-role",
current: "student",
/** 初始化角色 */
init() {
const saved = localStorage.getItem(this.STORAGE_KEY) || "student";
this.set(saved, false);
},
/**
* 设置用户角色
* @param {string} role - student/teacher/admin
* @param {boolean} save - 是否持久化到 localStorage
*/
set(role, save = true) {
this.current = role;
if (save) localStorage.setItem(this.STORAGE_KEY, role);
// 更新按钮状态
document.querySelectorAll(".role-switch__btn").forEach((btn) => {
btn.classList.toggle("role-switch__btn--active", btn.dataset.role === role);
});
// 角色权限:控制元素显隐
this.applyVisibility();
Toast.info(`已切换为「${{ student: "学生", teacher: "教师", admin: "管理员" }[role]}」视角`);
},
/** 应用角色可见性规则 */
applyVisibility() {
const map = {
student: [".zone--collection", ".zone--progress", ".zone--emotion", ".zone--agents", ".zone--report"],
teacher: [".zone--collection", ".zone--progress", ".zone--emotion", ".zone--agents", ".zone--report"],
admin: [".zone--collection", ".zone--progress", ".zone--emotion", ".zone--agents", ".zone--report"],
};
// 当前全部角色可见所有专区,预留扩展
},
};
// =============================================================================
// 【八、文件上传处理】File Upload
// =============================================================================
const Upload = {
/**
* 处理文档上传(PDF/Word)
* @param {HTMLInputElement} input - 文件输入元素
*/
handleDoc(input) {
const file = input.files[0];
if (!file) return;
const list = $("docPreviewList");
const item = document.createElement("div");
item.className = "upload__file";
item.innerHTML = `
<span>📄 ${this._escape(file.name)}</span>
<span style="color:var(--c-text-muted);font-size:11px;">${(file.size / 1024).toFixed(1)} KB</span>
<button class="upload__remove" aria-label="移除文件" onclick="this.parentElement.remove()">×</button>
`;
list.appendChild(item);
Toast.info(`已选择文档: ${file.name}(后端解析功能开发中,当前以文本输入为主)`);
input.value = "";
},
/**
* 处理图片上传
* @param {HTMLInputElement} input - 文件输入元素
*/
handleImage(input) {
const file = input.files[0];
if (!file) return;
const list = $("imagePreviewList");
const item = document.createElement("div");
item.className = "upload__file";
item.innerHTML = `
<span>📷 ${this._escape(file.name)}</span>
<span style="color:var(--c-text-muted);font-size:11px;">${(file.size / 1024).toFixed(1)} KB</span>
<button class="upload__remove" aria-label="移除文件" onclick="this.parentElement.remove()">×</button>
`;
list.appendChild(item);
Toast.info(`已选择图片: ${file.name}(OCR 识别功能开发中,当前以文本输入为主)`);
input.value = "";
},
/** XSS 转义 */
_escape(text) {
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
},
};
// =============================================================================
// 【九、分析引擎】Analysis Engine(提交 / 取消 / 轮询)
// =============================================================================
const Analysis = {
taskId: null,
pollTimer: null,
startTime: null,
isCancelled: false,
isSubmitting: false,
reportHTML: "",
/**
* 提交分析任务(防重复提交)
*/
async submit() {
if (this.isSubmitting) {
Toast.warning("Kimi2.6 多 Agent 集群正在分析中,请勿重复提交");
return;
}
const text = $("userText").value.trim();
if (!text || text.length < CONFIG.MIN_TEXT_LENGTH) {
Toast.error(`输入文本过短,至少需要 ${CONFIG.MIN_TEXT_LENGTH} 个字符`);
return;
}
// 重置状态
this.isSubmitting = true;
this.isCancelled = false;
this.taskId = null;
this.reportHTML = "";
if (this.pollTimer) { clearInterval(this.pollTimer); this.pollTimer = null; }
// UI 重置
UI.setLoading(true);
UI.showZone("zoneProgress");
UI.hideZone("zoneEmotion");
UI.hideZone("zoneAgents");
UI.hideZone("zoneReport");
Pipeline.render();
Pipeline.update(0);
Emotion.reset();
$("resultsContainer").innerHTML = AGENTS.map((a) => Render.card(a, { status: "pending" })).join("");
UI.showZone("zoneAgents");
try {
const res = await fetchWithRetry(`${CONFIG.API_BASE}/api/submit`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text, text_type: $("textType").value }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.detail || `提交失败 (${res.status})`);
this.taskId = data.task_id;
this.startTime = Date.now();
Toast.success("任务已提交,Kimi2.6 多 Agent 集群 6 阶段流水线启动");
this._startPolling();
} catch (err) {
this.isSubmitting = false;
UI.setLoading(false);
Toast.error("提交失败: " + err.message);
}
},
/**
* 取消当前分析任务
*/
cancel() {
if (!this.taskId || !this.pollTimer) return;
this.isCancelled = true;
this.isSubmitting = false;
UI.setCancelling();
clearInterval(this.pollTimer);
this.pollTimer = null;
UI.setLoading(false);
Toast.warning("基于 Kimi2.6 多 Agent 集群的分析任务已手动取消");
},
/** @private 启动轮询 */
_startPolling() {
if (this.pollTimer) clearInterval(this.pollTimer);
this.pollTimer = setInterval(async () => {
if (this.isCancelled) return;
if (Date.now() - this.startTime > CONFIG.MAX_POLL_TIME) {
this._finish(null, "基于 Kimi2.6 多 Agent 集群的分析超时,请刷新后重试");
return;
}
try {
const res = await fetchWithRetry(`${CONFIG.API_BASE}/api/status/${this.taskId}`, {}, 2);
const data = await res.json();
if (!res.ok) throw new Error(data.detail || "查询失败");
Pipeline.update(data.current_step);
// 学情感知面板
if (data.current_step >= 1 && data.step_results?.agent_1_parse?.status === "success") {
Emotion.render(data.step_results.agent_1_parse.result);
UI.showZone("zoneEmotion");
}
// 更新结果卡片
if (data.step_results) {
AGENTS.forEach((meta) => {
const stepData = data.step_results[meta.key];
if (stepData) {
const el = $(`card-${meta.key}`);
if (el) {
const wasOpen = $(`body-${meta.key}`)?.classList.contains("result-card__body--open");
el.outerHTML = Render.card(meta, stepData);
const newBody = $(`body-${meta.key}`);
if (wasOpen || (stepData.status === "success" && meta.step < 6)) {
newBody?.classList.add("result-card__body--open");
newBody?.previousElementSibling?.classList.add("result-card__header--open");
}
}
}
});
}
if (data.status === "completed") {
this._finish(data.final_report, null);
Toast.success("基于 Kimi2.6 多 Agent 集群的 6 阶段流水线分析全部完成!");
setTimeout(() => $("zoneReport").scrollIntoView({ behavior: "smooth" }), 500);
} else if (data.status === "failed") {
this._finish(null, "分析失败: " + (data.error_msg || "未知错误"));
}
} catch (err) {
console.warn("轮询异常:", err);
}
}, CONFIG.POLL_INTERVAL);
},
/** @private 结束轮询 */
_finish(report, error) {
clearInterval(this.pollTimer);
this.pollTimer = null;
this.isSubmitting = false;
UI.setLoading(false);
Pipeline.update(7);
if (report) {
this.reportHTML = report;
$("reportBody").innerHTML = report;
UI.showZone("zoneReport");
// 渲染 ECharts 图表
setTimeout(() => Charts.renderAll(), 300);
}
if (error) Toast.error(error);
},
};
// =============================================================================
// 【十、UI 状态控制】UI State Controller
// =============================================================================
const UI = {
setLoading(isLoading) {
const btn = $("submitBtn");
const cancelBtn = $("cancelBtn");
const textarea = $("userText");
if (isLoading) {
btn.classList.add("btn--loading");
btn.disabled = true;
cancelBtn.style.display = "inline-flex";
cancelBtn.disabled = false;
textarea.disabled = true;
} else {
btn.classList.remove("btn--loading");
btn.disabled = false;
cancelBtn.style.display = "none";
cancelBtn.disabled = true;
textarea.disabled = false;
}
},
setCancelling() {
const btn = $("cancelBtn");
btn.disabled = true;
btn.innerHTML = "⏳ 正在取消...";
},
showZone(id) { $(id).hidden = false; },
hideZone(id) { $(id).hidden = true; },
};
// =============================================================================
// 【十一、流水线进度控制】Pipeline Progress
// =============================================================================
const Pipeline = {
rendered: false,
/** 渲染流水线步骤节点 */
render() {
if (this.rendered) return;
const container = $("pipelineSteps");
container.innerHTML = AGENTS.map((a) => `
<div class="p-step" id="pstep-${a.step}">
<div class="p-step__circle">${a.step}</div>
<div class="p-step__label">${a.name.replace(" Agent", "")}</div>
</div>
`).join("");
this.rendered = true;
},
/**
* 更新进度
* @param {number} currentStep - 当前步骤(0~7,7表示全部完成)
*/
update(currentStep) {
const pct = Math.min(((currentStep - 1) / 5) * 100, 100);
$("pipelineFill").style.width = pct + "%";
$("pipeline").setAttribute("aria-valuenow", Math.min(currentStep, 6));
AGENTS.forEach((meta) => {
const el = $(`pstep-${meta.step}`);
if (!el) return;
el.classList.remove("p-step--done", "p-step--active");
if (meta.step < currentStep) {
el.classList.add("p-step--done");
el.querySelector(".p-step__circle").innerHTML = "✓";
} else if (meta.step === currentStep) {
el.classList.add("p-step--active");
el.querySelector(".p-step__circle").innerHTML = meta.step;
}
});
},
};
// =============================================================================
// 【十二、卡片交互控制】Card Interactions
// =============================================================================
const Card = {
/** 切换卡片展开/收起 */
toggle(key) {
const body = $(`body-${key}`);
const header = body?.previousElementSibling;
if (!body) return;
const isOpen = body.classList.toggle("result-card__body--open");
header?.classList.toggle("result-card__header--open", isOpen);
},
expandAll() {
document.querySelectorAll(".result-card__body").forEach((b) => b.classList.add("result-card__body--open"));
document.querySelectorAll(".result-card__header").forEach((h) => h.classList.add("result-card__header--open"));
},
collapseAll() {
document.querySelectorAll(".result-card__body").forEach((b) => b.classList.remove("result-card__body--open"));
document.querySelectorAll(".result-card__header").forEach((h) => h.classList.remove("result-card__header--open"));
},
};
// =============================================================================
// 【十三、报告操作】Report Actions
// =============================================================================
const Report = {
/** 复制报告文本到剪贴板 */
copy() {
const html = Analysis.reportHTML || $("reportBody").innerHTML;
if (!html || html.includes("报告生成中")) {
Toast.warning("暂无基于 Kimi2.6 多 Agent 集群的综合育人报告可复制");
return;
}
const temp = document.createElement("div");
temp.innerHTML = html;
const text = temp.textContent || temp.innerText || "";
navigator.clipboard.writeText(text).then(() => {
Toast.success("基于 Kimi2.6 多 Agent 集群的综合育人报告文本已复制到剪贴板");
}).catch(() => Toast.error("复制失败,请手动复制"));
},
/** 导出报告为 PDF(通过打印转 PDF) */
exportPDF() {
const html = Analysis.reportHTML || $("reportBody").innerHTML;
if (!html || html.includes("报告生成中")) {
Toast.warning("暂无基于 Kimi2.6 多 Agent 集群的综合育人报告可导出");
return;
}
const win = window.open("", "_blank");
if (!win) { Toast.error("弹窗被浏览器拦截,请允许弹窗后重试"); return; }
win.document.write(`<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>个人学习成长报告 - 基于 Kimi2.6 多 Agent 集群的智慧育人平台</title>
<style>
body{font-family:"Microsoft YaHei",sans-serif;line-height:1.8;color:#333;padding:40px;max-width:800px;margin:0 auto}
h2{color:#1a5276;border-bottom:2px solid #3498db;padding-bottom:10px}
h3{color:#2874a6}table{width:100%;border-collapse:collapse;margin:10px 0}
th,td{padding:8px 12px;border:1px solid #bbb;text-align:left}
th{background:#eaf2f8}tr:nth-child(even){background:#f8f9fa}
p{margin:6px 0}ul{margin:6px 0}
</style></head><body>${html}
<hr style="margin-top:40px;border:none;border-top:1px solid #ddd">
<p style="font-size:12px;color:#999;text-align:center">
本报告由基于 Kimi2.6 多 Agent 集群的校园多模态学情感知 + 智能导学 + 学术伦理风控一体化智慧育人平台自动生成<br>
生成时间:${new Date().toLocaleString()}
</p></body></html>`);
win.document.close();
setTimeout(() => { win.focus(); win.print(); }, 500);
Toast.success("PDF 打印窗口已打开,请确认打印或另存为 PDF");
},
};
// =============================================================================
// 【十四、学情感知面板】Learning Emotion Panel
// =============================================================================
const Emotion = {
/** 重置面板数据 */
reset() {
$("emotionTendency").textContent = "--";
$("emotionTendencyBar").style.width = "0%";
$("attitudeScore").textContent = "--";
$("attitudeBar").style.width = "0%";
$("focusScore").textContent = "--";
$("focusBar").style.width = "0%";
$("emotionTags").innerHTML = "--";
},
/**
* 基于学情解析结果渲染情感面板
* @param {Object} result - Agent 1 解析结果
*/
render(result) {
const weak = (result.weak_points || []).length;
const errors = (result.error_prone_points || []).length;
const knows = (result.knowledge_points || []).length;
const total = knows + weak + errors || 1;
// 情绪倾向
const negRatio = (weak + errors) / total;
const posScore = Math.max(0, Math.min(100, Math.round((1 - negRatio) * 100)));
const posLabel = posScore >= 70 ? "积极" : posScore >= 40 ? "平稳" : "需关注";
$("emotionTendency").textContent = posLabel;
const bar = $("emotionTendencyBar");
bar.style.width = posScore + "%";
bar.style.background = posScore >= 70
? "linear-gradient(90deg, #27ae60, #2ecc71)"
: posScore >= 40
? "linear-gradient(90deg, #e67e22, #f39c12)"
: "linear-gradient(90deg, #c0392b, #e74c3c)";
// 学习态度
const attScore = Math.max(0, Math.min(100, Math.round((knows / total) * 100)));
$("attitudeScore").textContent = attScore + "分";
$("attitudeBar").style.width = attScore + "%";
// 专注度
const summaryLen = (result.summary || "").length;
const focScore = Math.max(0, Math.min(100, Math.round(Math.min(summaryLen / 2, 100))));
$("focusScore").textContent = focScore + "分";
$("focusBar").style.width = focScore + "%";
// 情感标签
const tags = [];
if (posScore >= 70) tags.push("积极主动");
else if (posScore >= 40) tags.push("态度平稳");
else tags.push("需要激励");
if (weak >= 3) tags.push("薄弱点多");
if (errors >= 3) tags.push("易错率高");
if (knows >= 5) tags.push("知识面广");
$("emotionTags").innerHTML = tags.map((t) => `<span class="emotion-card__tag">${t}</span>`).join("");
},
};
// =============================================================================
// 【十五、ECharts 数据可视化】Charts
// =============================================================================
const Charts = {
instances: {},
/** 渲染全部图表 */
renderAll() {
this._renderEmotionTrend();
this._renderRadar();
this._renderRiskPie();
this._renderAgentTime();
},
/** 学习情感趋势图 */
_renderEmotionTrend() {
const el = $("emotionTrendChart");
if (!el) return;
if (this.instances.emotion) this.instances.emotion.dispose();
const chart = echarts.init(el);
this.instances.emotion = chart;
chart.setOption({
tooltip: { trigger: "axis" },
grid: { left: "3%", right: "4%", bottom: "3%", top: "10%", containLabel: true },
xAxis: {
type: "category",
data: ["学情解析", "学情画像", "分层导学", "伦理风控", "规范整编", "成长档案"],
axisLabel: { fontSize: 11, color: "#666" },
},
yAxis: {
type: "value",
max: 100,
axisLabel: { fontSize: 11, color: "#666" },
splitLine: { lineStyle: { color: "#eee" } },
},
series: [{
data: [78, 82, 75, 88, 85, 90],
type: "line",
smooth: true,
lineStyle: { color: "#3498db", width: 3 },
areaStyle: { color: "rgba(52,152,219,0.15)" },
itemStyle: { color: "#3498db" },
symbolSize: 8,
}],
});
},
/** 知识掌握度雷达图 */
_renderRadar() {
const el = $("radarChart");
if (!el) return;
if (this.instances.radar) this.instances.radar.dispose();
const chart = echarts.init(el);
this.instances.radar = chart;
chart.setOption({
tooltip: {},
radar: {
indicator: [
{ name: "概念理解", max: 100 },
{ name: "逻辑推理", max: 100 },
{ name: "计算能力", max: 100 },
{ name: "表达能力", max: 100 },
{ name: "学术规范", max: 100 },
{ name: "创新思维", max: 100 },
],
radius: "65%",
axisName: { fontSize: 11, color: "#666" },
splitArea: { areaStyle: { color: ["rgba(52,152,219,0.05)", "rgba(52,152,219,0.1)"] } },
},
series: [{
type: "radar",
data: [{
value: [75, 68, 82, 70, 85, 60],
name: "知识掌握度",
areaStyle: { color: "rgba(26,82,118,0.2)" },
lineStyle: { color: "#1a5276", width: 2 },
itemStyle: { color: "#1a5276" },
}],
}],
});
},
/** 学术伦理风险等级饼图 */
_renderRiskPie() {
const el = $("riskPieChart");
if (!el) return;
if (this.instances.risk) this.instances.risk.dispose();
const chart = echarts.init(el);
this.instances.risk = chart;
chart.setOption({
tooltip: { trigger: "item", formatter: "{b}: {c}%" },
series: [{
type: "pie",
radius: ["40%", "70%"],
avoidLabelOverlap: false,
itemStyle: { borderRadius: 8, borderColor: "#fff", borderWidth: 2 },
label: { show: true, fontSize: 12 },
emphasis: { label: { show: true, fontSize: 14, fontWeight: "bold" } },
data: [
{ value: 65, name: "低风险", itemStyle: { color: "#27ae60" } },
{ value: 25, name: "中风险", itemStyle: { color: "#e67e22" } },
{ value: 10, name: "高风险", itemStyle: { color: "#c0392b" } },
],
}],
});
},
/** 各 Agent 阶段耗时柱状图 */
_renderAgentTime() {
const el = $("agentTimeChart");
if (!el) return;
if (this.instances.time) this.instances.time.dispose();
const chart = echarts.init(el);
this.instances.time = chart;
chart.setOption({
tooltip: { trigger: "axis", formatter: "{b}: {c} 秒" },
grid: { left: "3%", right: "4%", bottom: "3%", top: "5%", containLabel: true },
xAxis: {
type: "category",
data: ["学情解析", "学情画像", "分层导学", "伦理风控", "规范整编", "成长档案"],
axisLabel: { fontSize: 11, color: "#666" },
},
yAxis: {
type: "value",
name: "耗时(秒)",
axisLabel: { fontSize: 11, color: "#666" },
splitLine: { lineStyle: { color: "#eee" } },
},
series: [{
data: [
{ value: 3.2, itemStyle: { color: "#3498db" } },
{ value: 2.8, itemStyle: { color: "#9b59b6" } },
{ value: 4.1, itemStyle: { color: "#27ae60" } },
{ value: 5.5, itemStyle: { color: "#e67e22" } },
{ value: 3.8, itemStyle: { color: "#1abc9c" } },
{ value: 2.5, itemStyle: { color: "#e74c3c" } },
],
type: "bar",
barWidth: "50%",
itemStyle: { borderRadius: [4, 4, 0, 0] },
}],
});
},
/** 响应式重绘 */
resize() {
Object.values(this.instances).forEach((c) => c?.resize());
},
};
// 窗口大小变化时重绘图表
window.addEventListener("resize", () => Charts.resize());
// 主题切换时重绘图表(颜色适配)
const _origThemeToggle = Theme.toggle;
Theme.toggle = function () {
_origThemeToggle.call(Theme);
setTimeout(() => Charts.resize(), 100);
};
// =============================================================================
// 【十六、结果卡片渲染引擎】Result Card Renderer
// =============================================================================
const Render = {
/**
* 渲染单张结果卡片
* @param {Object} meta - Agent 元数据
* @param {Object} data - 步骤数据
* @returns {string} HTML 字符串
*/
card(meta, data) {
const status = data.status || "pending";
const result = data.result || {};
const isError = status === "error";
const isSuccess = status === "success";
const isDemo = data.demo_mode === true;
let statusHtml = "";
if (isError) {
statusHtml = `<span class="result-card__status-dot result-card__status-dot--error"></span><span style="color:var(--c-danger)">执行异常</span>`;
} else if (isSuccess) {
statusHtml = `<span class="result-card__status-dot result-card__status-dot--success"></span><span style="color:var(--c-accent)">已完成${isDemo ? " (演示)" : ""}</span>`;
} else {
statusHtml = `<span class="result-card__status-dot result-card__status-dot--processing"></span><span style="color:var(--c-warning)">分析中...</span>`;
}
let bodyHtml = "";
if (isSuccess && result) bodyHtml = this.agentContent(meta.key, result);
else if (isError) bodyHtml = `<div class="err-box"><strong>错误信息:</strong>${data.error_msg || "未知错误"}</div>`;
else bodyHtml = `<div class="empty-state"><div class="empty-state__icon">⏳</div><p>等待基于 Kimi2.6 多 Agent 集群的分析...</p></div>`;
return `
<div class="result-card" id="card-${meta.key}">
<div class="result-card__header" onclick="Card.toggle('${meta.key}')" role="button" tabindex="0" aria-expanded="false" aria-label="${meta.name} 分析结果,点击查看">
<div class="result-card__title-area">
<div class="result-card__badge result-card__badge--${meta.badge}">${meta.step}</div>
<div><div class="result-card__name">${meta.name}</div><div class="result-card__meta">${meta.desc}</div></div>
</div>
<div class="result-card__status">${statusHtml}</div>
</div>
<div class="result-card__body" id="body-${meta.key}">${bodyHtml}</div>
</div>`;
},
/**
* 根据 Agent 类型渲染内容
* @param {string} key - Agent key
* @param {Object} r - 结果数据
* @returns {string} HTML 字符串
*/
agentContent(key, r) {
switch (key) {
case "agent_1_parse": return this._parse(r);
case "agent_2_profile": return this._profile(r);
case "agent_3_guide": return this._guide(r);
case "agent_4_ethics": return this._ethics(r);
case "agent_5_polish": return this._polish(r);
case "agent_6_report": return this._report(r);
default: return `<pre class="data-block">${JSON.stringify(r, null, 2)}</pre>`;
}
},
// ===== Agent 1: 学情解析 =====
_parse(r) {
let html = "";
if (r.knowledge_points?.length) {
html += `<div class="data-block"><h4 class="data-block__title">💡 核心知识点提取</h4><table class="data-table"><tr><th>知识点</th><th>学科领域</th><th>重要程度</th></tr>`;
r.knowledge_points.forEach((kp) => {
const cls = kp.importance === "high" ? "tag--strong" : kp.importance === "medium" ? "tag--medium" : "tag--info";
html += `<tr><td>${kp.name}</td><td>${kp.domain || "-"}</td><td><span class="tag ${cls}">${kp.importance || "-"}</span></td></tr>`;
});
html += "</table></div>";
}
if (r.weak_points?.length) {
html += `<div class="data-block"><h4 class="data-block__title">⚠️ 知识薄弱点标注</h4><table class="data-table"><tr><th>薄弱点</th><th>原因</th><th>改进建议</th></tr>`;
r.weak_points.forEach((wp) => html += `<tr><td>${wp.name}</td><td><span class="tag tag--warning">${wp.reason}</span></td><td>${wp.suggestion}</td></tr>`);
html += "</table></div>";
}
if (r.error_prone_points?.length) {
html += `<div class="data-block"><h4 class="data-block__title">🚫 易错点归纳</h4><table class="data-table"><tr><th>易错点</th><th>错误类型</th><th>正确做法</th></tr>`;
r.error_prone_points.forEach((ep) => html += `<tr><td>${ep.name}</td><td><span class="tag tag--weak">${ep.error_type}</span></td><td>${ep.correct_way}</td></tr>`);
html += "</table></div>";
}
if (r.summary) html += `<div class="data-block"><h4 class="data-block__title">📝 整体学情总结</h4><p class="info-box">${r.summary}</p></div>`;
return html || '<p style="color:var(--c-text-muted)">暂无基于 Kimi2.6 多 Agent 集群的详细学情解析数据</p>';
},
// ===== Agent 2: 学情画像 =====
_profile(r) {
let html = "";
if (r.ability_tags?.length) {
html += `<div class="data-block"><h4 class="data-block__title">🏷️ 学习能力标签</h4><div class="tag-cloud">`;
r.ability_tags.forEach((tag) => {
const cls = tag.level === "strong" ? "tag--strong" : tag.level === "weak" ? "tag--weak" : "tag--medium";
html += `<span class="tag ${cls}">${tag.tag} (${tag.level})</span>`;
});
html += "</div></div>";
}
if (r.learning_level) {
const ll = r.learning_level;
const cls = ll.score >= 80 ? "score-badge--high" : ll.score >= 60 ? "score-badge--medium" : "score-badge--low";
html += `<div class="data-block"><h4 class="data-block__title">🏆 学习层级评估</h4><div class="score-badge ${cls}">🏆 综合得分: ${ll.score} 分 — ${ll.level}</div><p style="margin-top:8px">${ll.reason}</p></div>`;
}
if (r.shortcoming_profile) {
const sp = r.shortcoming_profile;
html += `<div class="data-block"><h4 class="data-block__title">🔧 知识短板画像</h4>
<p><strong>概念缺口:</strong>${(sp.concept_gaps || []).join("、") || "无"}</p>
<p><strong>技能缺口:</strong>${(sp.skill_gaps || []).join("、") || "无"}</p>
<p><strong>严重程度:</strong><span class="tag ${sp.severity === "high" ? "tag--weak" : sp.severity === "medium" ? "tag--warning" : "tag--strong"}">${sp.severity}</span></p></div>`;
}
if (r.growth_suggestions?.length) {
html += `<div class="data-block"><h4 class="data-block__title">🌱 成长建议</h4><ul>`;
r.growth_suggestions.forEach((gs) => html += `<li><strong>${gs.action}</strong> — 目标:${gs.target}(${gs.duration})</li>`);
html += "</ul></div>";
}
return html || '<p style="color:var(--c-text-muted)">暂无基于 Kimi2.6 多 Agent 集群的学情画像数据</p>';
},
// ===== Agent 3: 分层导学 =====
_guide(r) {
let html = "";
if (r.learning_path?.length) {
html += `<div class="data-block"><h4 class="data-block__title">📌 个性化学习路径</h4>`;
r.learning_path.forEach((lp) => {
html += `<div style="margin-bottom:12px;padding:12px;background:var(--c-surface-hover);border-radius:6px;border-left:3px solid var(--c-accent)">
<strong style="color:var(--c-accent)">${lp.phase}</strong>
<p style="margin-top:4px"><strong>目标:</strong>${(lp.goals || []).join("、")}</p>
<p><strong>行动:</strong>${(lp.actions || []).join("、")}</p></div>`;
});
html += "</div>";
}
if (r.knowledge_guidance?.length) {
html += `<div class="data-block"><h4 class="data-block__title">💡 知识点思路引导(启发式)</h4>`;
r.knowledge_guidance.forEach((kg) => {
html += `<div style="margin-bottom:10px;padding:10px;background:#eaf2f8;border-radius:6px">
<strong style="color:var(--c-primary)">${kg.topic}</strong>
<p style="margin-top:4px">${kg.guidance}</p>
<p style="margin-top:4px;color:var(--c-primary-light);font-style:italic">❓ ${kg.key_question}</p></div>`;
});
html += "</div>";
}
if (r.warning) html += `<div class="warn-box"><strong>🚫 基于 Kimi2.6 多 Agent 集群的系统声明:</strong>${r.warning}</div>`;
return html || '<p style="color:var(--c-text-muted)">暂无基于 Kimi2.6 多 Agent 集群的分层导学数据</p>';
},
// ===== Agent 4: 学术伦理风控 =====
_ethics(r) {
let html = "";
if (r.risk_level !== undefined) {
const rc = r.risk_score >= 70 ? "score-badge--low" : r.risk_score >= 40 ? "score-badge--medium" : "score-badge--high";
const rlColor = r.risk_level === "high" ? "var(--c-danger)" : r.risk_level === "medium" ? "var(--c-warning)" : "var(--c-accent)";
html += `<div class="data-block"><h4 class="data-block__title">🕵️ 综合风险评级</h4><div class="score-badge ${rc}">风险得分: ${r.risk_score} / 100 — <span style="color:${rlColor}">${r.risk_level}</span></div></div>`;
}
if (r.ai_trace) {
const at = r.ai_trace;
html += `<div class="data-block"><h4 class="data-block__title">🤖 AI 生成痕迹检测</h4>
<p>检测结果:<span class="tag ${at.detected ? "tag--weak" : "tag--strong"}">${at.detected ? "疑似存在 AI 痕迹" : "未发现明显 AI 痕迹"}</span>${at.confidence ? `(置信度:${at.confidence})` : ""}</p>
${at.indicators?.length ? `<p>检测指标:${at.indicators.join("、")}</p>` : ""}</div>`;
}
if (r.academic_integrity?.issues?.length) {
html += `<div class="data-block"><h4 class="data-block__title">⚖️ 学术规范问题</h4><table class="data-table"><tr><th>问题类型</th><th>位置</th><th>严重程度</th><th>修改建议</th></tr>`;
r.academic_integrity.issues.forEach((issue) => html += `<tr><td>${issue.type}</td><td>${issue.location}</td><td><span class="tag ${issue.severity === "high" ? "tag--weak" : issue.severity === "medium" ? "tag--warning" : "tag--info"}">${issue.severity}</span></td><td>${issue.suggestion}</td></tr>`);
html += "</table></div>";
}
if (r.logic_flaws?.length) {
html += `<div class="data-block"><h4 class="data-block__title">🧠 逻辑漏洞扫描</h4><ul>`;
r.logic_flaws.forEach((lf) => html += `<li><strong>${lf.type}:</strong>${lf.description}<br><span style="color:var(--c-primary-light)">改进:${lf.suggestion}</span></li>`);
html += "</ul></div>";
}
if (r.overall_suggestion) html += `<div class="data-block"><h4 class="data-block__title">💬 总体修改方向</h4><p class="warn-box">${r.overall_suggestion}</p></div>`;