dsh-stm32 0.1.7 → 0.1.8

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.
Files changed (41) hide show
  1. package/README.md +256 -363
  2. package/README_EN.md +257 -357
  3. package/client/client.js +4340 -1
  4. package/docs/reading-guide.md +62 -0
  5. package/lib/client.js +4340 -1
  6. package/lib/engine/artifacts.js +123 -0
  7. package/lib/engine/breakpoint-hits.js +73 -0
  8. package/lib/engine/build.js +73 -3
  9. package/lib/engine/channel-tap.js +227 -0
  10. package/lib/engine/channels.js +48 -0
  11. package/lib/engine/clocks.js +192 -0
  12. package/lib/engine/debug-session.js +46 -1
  13. package/lib/engine/event-bus.js +158 -0
  14. package/lib/engine/event-log.js +335 -0
  15. package/lib/engine/fault-hints.js +146 -0
  16. package/lib/engine/interrupts.js +247 -0
  17. package/lib/engine/ioc-diff.js +369 -0
  18. package/lib/engine/ioc-sync.js +58 -0
  19. package/lib/engine/msys2-install.js +31 -6
  20. package/lib/engine/panel-actions.js +103 -0
  21. package/lib/engine/pinout.js +140 -0
  22. package/lib/engine/probe-info.js +95 -0
  23. package/lib/engine/progress.js +99 -0
  24. package/lib/engine/project-conf.js +199 -0
  25. package/lib/engine/session-context.js +19 -0
  26. package/lib/engine/source-slice.js +59 -0
  27. package/lib/engine/tool-events.js +119 -0
  28. package/lib/engine/watch-admin.js +101 -0
  29. package/lib/engine/watch-record.js +39 -0
  30. package/lib/engine/watch-recorder.js +116 -0
  31. package/lib/engine/web-api.js +886 -4
  32. package/lib/engine/web-routes.js +18 -1
  33. package/lib/engine/workspace-memo.js +41 -0
  34. package/lib/index.js +67 -24
  35. package/lib/tools/ioc-apply.js +9 -0
  36. package/lib/tools/project-create.js +28 -0
  37. package/lib/tools/project-dir.js +7 -1
  38. package/lib/tools/rtt.js +8 -0
  39. package/lib/tools/serial.js +22 -0
  40. package/lib/tools/watch.js +24 -2
  41. package/package.json +1 -1
package/lib/client.js CHANGED
@@ -650,9 +650,4331 @@ window.__ModuleLoader__.load({
650
650
  );
651
651
  }
652
652
 
653
+ /* ------------------------------ 调试台 ------------------------------ */
654
+
655
+ /*
656
+ * 调试台(conversation.view 标签,id: stm32-debug)。
657
+ *
658
+ * 数据只有一个来源:宿主侧事件总线的 SSE 流 /dsh-stm32/api/events。
659
+ * 面板自己不留第二份账本,重连时按 lastSeq 续播,断线不会丢段。
660
+ *
661
+ * 布局是停靠网格:左时间线、中详情、右通道,面板可收起进抽屉、可拖分隔条改宽,
662
+ * 宽度与收起状态存 localStorage,下次打开保持原样。
663
+ */
664
+
665
+ const DEBUG_LAYOUT_KEY = "dsh-stm32.debug.layout.v1";
666
+ /** 工程选择的记忆键:一个会话一份,换会话不串(S82)。 */
667
+ const DEBUG_PROJECT_KEY = (session) => "dsh-stm32.debug.project.v1:" + (session === "" ? "unbound" : session);
668
+ const DEBUG_EVENT_CAP = 2000;
669
+ const DEBUG_RECONNECT_MS = 1500;
670
+
671
+ /**
672
+ * 视觉基调(S89):瑞士国际主义。
673
+ *
674
+ * 版式取自 guizang-ppt-skill 风格 B:全无衬线、单一强调色、直角、发丝线、
675
+ * 等宽大写小标、极大的字号对比。底色与文字色一律取宿主设计令牌,深的浅的
676
+ * 都交给宿主切换,面板不写死任何底色(用户 m07178)。
677
+ */
678
+ const D32_FONT_CODE = "var(--ds-font-family-code, ui-monospace, SFMono-Regular, Menlo, monospace)";
679
+ /** 警告色:宿主 light/dark 各自有对应值(S88)。 */
680
+ const D32_WARN = "var(--dsw-alias-state-warn-primary)";
681
+ /** 强调色(S89):只用于选中的页签、关键数值、焦点环与选中行。 */
682
+ const D32_ACCENT = "var(--d32-accent)";
683
+ const D32_HAIR = "1px solid var(--dsw-alias-border-l2)";
684
+ /** 等宽大写小标:栏目标题、状态项、元数据(S89)。 */
685
+ const D32_LABEL_MONO = {
686
+ fontFamily: D32_FONT_CODE,
687
+ fontSize: "10.5px",
688
+ letterSpacing: "0.14em",
689
+ lineHeight: "16px",
690
+ textTransform: "uppercase",
691
+ };
692
+ const debugStyles = {
693
+ page: {
694
+ display: "flex",
695
+ flexDirection: "column",
696
+ height: "100%",
697
+ minHeight: "420px",
698
+ gap: "10px",
699
+ padding: "14px 16px 16px",
700
+ color: "var(--dsw-alias-label-primary)",
701
+ fontSize: "13px",
702
+ lineHeight: "1.5",
703
+ boxSizing: "border-box",
704
+ },
705
+ /** 报头:等宽大写小标 + 发丝线收尾(S89)。 */
706
+ brand: Object.assign({}, D32_LABEL_MONO, {
707
+ paddingRight: "12px",
708
+ marginRight: "12px",
709
+ borderRight: D32_HAIR,
710
+ color: "var(--dsw-alias-label-primary)",
711
+ fontWeight: 600,
712
+ }),
713
+ /** 状态行:一条发丝线到底,不套卡片(S89)。 */
714
+ statusBar: {
715
+ display: "flex",
716
+ alignItems: "center",
717
+ flexWrap: "wrap",
718
+ gap: "0",
719
+ padding: "0 0 9px",
720
+ borderBottom: D32_HAIR,
721
+ },
722
+ chip: Object.assign({}, D32_LABEL_MONO, {
723
+ display: "inline-flex",
724
+ alignItems: "center",
725
+ gap: "6px",
726
+ padding: "0 12px",
727
+ borderLeft: D32_HAIR,
728
+ color: "var(--dsw-alias-label-tertiary)",
729
+ letterSpacing: "0.1em",
730
+ }),
731
+ dot: { width: "5px", height: "5px", background: D32_ACCENT, flex: "0 0 auto" },
732
+ spacer: { flex: "1 1 auto" },
733
+ grid: { display: "flex", flex: "1 1 auto", gap: "10px", minHeight: "0" },
734
+ panel: {
735
+ display: "flex",
736
+ flexDirection: "column",
737
+ minWidth: "0",
738
+ minHeight: "0",
739
+ border: D32_HAIR,
740
+ background: "var(--dsw-alias-bg-layer-1)",
741
+ overflow: "hidden",
742
+ },
743
+ panelHead: Object.assign({}, D32_LABEL_MONO, {
744
+ display: "flex",
745
+ alignItems: "center",
746
+ gap: "8px",
747
+ padding: "8px 12px",
748
+ borderBottom: D32_HAIR,
749
+ color: "var(--dsw-alias-label-tertiary)",
750
+ cursor: "default",
751
+ userSelect: "none",
752
+ }),
753
+ panelBody: { flex: "1 1 auto", overflow: "auto", minHeight: "0" },
754
+ divider: { flex: "0 0 6px", cursor: "col-resize", background: "transparent", position: "relative" },
755
+ /** 事件行:发丝线分隔 + 左侧方角状态条(S89)。 */
756
+ row: {
757
+ display: "flex",
758
+ gap: "10px",
759
+ padding: "7px 12px",
760
+ cursor: "pointer",
761
+ borderBottom: "0.5px solid var(--dsw-alias-border-l3)",
762
+ alignItems: "baseline",
763
+ },
764
+ rowTime: {
765
+ color: "var(--dsw-alias-label-tertiary)",
766
+ fontVariantNumeric: "tabular-nums",
767
+ flex: "0 0 auto",
768
+ fontFamily: D32_FONT_CODE,
769
+ fontSize: "11px",
770
+ },
771
+ rowKind: {
772
+ color: "var(--dsw-alias-label-secondary)",
773
+ fontFamily: D32_FONT_CODE,
774
+ fontSize: "11px",
775
+ letterSpacing: "0.02em",
776
+ flex: "0 0 auto",
777
+ maxWidth: "150px",
778
+ overflow: "hidden",
779
+ textOverflow: "ellipsis",
780
+ whiteSpace: "nowrap",
781
+ },
782
+ rowText: { flex: "1 1 auto", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
783
+ empty: {
784
+ padding: "22px 14px",
785
+ color: "var(--dsw-alias-label-tertiary)",
786
+ textAlign: "center",
787
+ fontFamily: D32_FONT_CODE,
788
+ fontSize: "11px",
789
+ letterSpacing: "0.08em",
790
+ },
791
+ mono: { fontFamily: D32_FONT_CODE, fontSize: "11px" },
792
+ pre: {
793
+ margin: 0,
794
+ padding: "10px 12px",
795
+ whiteSpace: "pre-wrap",
796
+ wordBreak: "break-word",
797
+ fontFamily: D32_FONT_CODE,
798
+ fontSize: "11px",
799
+ lineHeight: "1.7",
800
+ color: "var(--dsw-alias-label-secondary)",
801
+ background: "var(--dsw-alias-bg-layer-2)",
802
+ border: "1px solid var(--dsw-alias-border-l2)",
803
+ },
804
+ input: {
805
+ padding: "4px 8px",
806
+ font: "inherit",
807
+ fontSize: "12px",
808
+ color: "var(--dsw-alias-label-primary)",
809
+ background: "transparent",
810
+ border: D32_HAIR,
811
+ minWidth: "140px",
812
+ outline: "none",
813
+ },
814
+ button: {
815
+ padding: "5px 12px",
816
+ font: "inherit",
817
+ fontSize: "12px",
818
+ color: "var(--dsw-alias-label-primary)",
819
+ background: "transparent",
820
+ border: D32_HAIR,
821
+ cursor: "pointer",
822
+ },
823
+ drawer: {
824
+ display: "flex",
825
+ alignItems: "center",
826
+ gap: "8px",
827
+ padding: "8px 12px",
828
+ border: "1px solid var(--dsw-alias-border-l3)",
829
+ background: "var(--dsw-alias-bg-layer-1)",
830
+ flexWrap: "wrap",
831
+ },
832
+ };
833
+
834
+ /**
835
+ * 面板样式表(S85 建、S88 对齐编队页、S89 改瑞士国际主义)。
836
+ *
837
+ * 内联样式做不了 hover、焦点环、页签下划线、直角与滚动条;
838
+ * `--d32-accent` 在这里落到宿主强调色上,深浅色由宿主给值。
839
+ */
840
+ const DEBUG_CSS = [
841
+ ".d32-page { --d32-accent: var(--dsw-alias-state-business-primary); }",
842
+ "/* 瑞士国际主义:面板内一律直角,圆角由语言决定,不留给单个组件(S89)。 */",
843
+ ".d32-page, .d32-page * { border-radius: 0 !important; }",
844
+ ".d32-page button, .d32-page input, .d32-page select { transition: background-color .12s ease, border-color .12s ease, color .12s ease; }",
845
+ ".d32-page button:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover) !important; border-color: var(--dsw-alias-border-l3) !important; color: var(--dsw-alias-label-primary) !important; }",
846
+ ".d32-page button:active:not(:disabled) { background: var(--dsw-alias-interactive-bg-active) !important; }",
847
+ ".d32-page button:focus-visible, .d32-page input:focus-visible, .d32-page select:focus-visible { outline: 2px solid var(--d32-accent); outline-offset: 1px; }",
848
+ ".d32-page button:disabled { opacity: .45; cursor: default; }",
849
+ ".d32-page input:hover, .d32-page select:hover { border-color: var(--dsw-alias-border-l3) !important; }",
850
+ ".d32-page input:focus, .d32-page select:focus { border-color: var(--d32-accent) !important; }",
851
+ "/* 页签:文字 + 选中项下划线,不做填充式分段控件(S89)。 */",
852
+ ".d32-tabs { position: sticky; top: 0; z-index: 2; display: flex; gap: 0; padding: 0 !important; background: transparent !important; border: 0 !important; border-bottom: 1px solid var(--dsw-alias-border-l2) !important; backdrop-filter: blur(8px); overflow-x: auto; scrollbar-width: thin; }",
853
+ ".d32-tab { border: 0 !important; border-bottom: 2px solid transparent !important; background: transparent !important; border-radius: 0 !important; color: var(--dsw-alias-label-tertiary) !important; font-family: " + D32_FONT_CODE + " !important; font-size: 11px !important; letter-spacing: 0.08em !important; padding: 8px 13px 7px !important; margin-bottom: -1px; }",
854
+ ".d32-tab:hover:not(:disabled) { background: transparent !important; color: var(--dsw-alias-label-primary) !important; }",
855
+ ".d32-tab[data-active=\"1\"] { background: transparent !important; border-bottom-color: var(--d32-accent) !important; color: var(--dsw-alias-label-primary) !important; font-weight: 500; }",
856
+ ".d32-row:hover { background: var(--dsw-alias-interactive-bg-hover) !important; }",
857
+ ".d32-row[data-status=\"fail\"] { box-shadow: inset 2px 0 0 var(--dsw-alias-state-error-primary); }",
858
+ ".d32-row[data-status=\"ok\"] { box-shadow: inset 2px 0 0 var(--dsw-alias-state-success-primary); }",
859
+ ".d32-row[data-status=\"start\"] { box-shadow: inset 2px 0 0 var(--d32-accent); }",
860
+ ".d32-page ::-webkit-scrollbar { width: 9px; height: 9px; }",
861
+ ".d32-page ::-webkit-scrollbar-thumb { background: color-mix(in srgb, var(--dsw-alias-label-tertiary) 50%, transparent); }",
862
+ ".d32-page ::-webkit-scrollbar-thumb:hover { background: color-mix(in srgb, var(--dsw-alias-label-secondary) 60%, transparent); }",
863
+ ".d32-page ::-webkit-scrollbar-track { background: transparent; }",
864
+ ].join("\n");
865
+
866
+ /** 样式表只插一次;标签页切来切去不会重复追加。 */
867
+ function ensureDebugStyleTag() {
868
+ if (typeof document !== "object" || document === null) return;
869
+ if (document.getElementById("dsh-stm32-debug-css") !== null) return;
870
+ const style = document.createElement("style");
871
+ style.id = "dsh-stm32-debug-css";
872
+ style.textContent = DEBUG_CSS;
873
+ document.head.appendChild(style);
874
+ }
875
+
876
+ function debugStorage() {
877
+ try {
878
+ return typeof window === "object" && window !== null ? window.localStorage : null;
879
+ } catch {
880
+ return null;
881
+ }
882
+ }
883
+
884
+ function readDebugLayout() {
885
+ const store = debugStorage();
886
+ const fallback = { left: 300, right: 300, collapsed: {} };
887
+ if (store === null) return fallback;
888
+ try {
889
+ const raw = store.getItem(DEBUG_LAYOUT_KEY);
890
+ if (raw === null) return fallback;
891
+ const parsed = JSON.parse(raw);
892
+ const left = Number(parsed.left);
893
+ const right = Number(parsed.right);
894
+ return {
895
+ left: Number.isFinite(left) && left >= 180 ? Math.min(left, 720) : fallback.left,
896
+ right: Number.isFinite(right) && right >= 180 ? Math.min(right, 720) : fallback.right,
897
+ collapsed: parsed.collapsed !== null && typeof parsed.collapsed === "object" ? parsed.collapsed : {},
898
+ };
899
+ } catch {
900
+ return fallback;
901
+ }
902
+ }
903
+
904
+ function writeDebugLayout(layout) {
905
+ const store = debugStorage();
906
+ if (store === null) return;
907
+ try {
908
+ store.setItem(DEBUG_LAYOUT_KEY, JSON.stringify(layout));
909
+ } catch {
910
+ // 隐私模式或配额满:布局存不下不影响使用。
911
+ }
912
+ }
913
+
914
+ function clockText(iso) {
915
+ const date = new Date(iso);
916
+ if (Number.isNaN(date.getTime())) return String(iso);
917
+ const pad = (value, width) => String(value).padStart(width, "0");
918
+ return pad(date.getHours(), 2) + ":" + pad(date.getMinutes(), 2) + ":" + pad(date.getSeconds(), 2) + "." + pad(date.getMilliseconds(), 3);
919
+ }
920
+
921
+ const DEBUG_STATUS_SIGN = { start: "▶", ok: "✔", fail: "✘", info: "·" };
922
+ const DEBUG_LABELS = { timeline: "时间线", detail: "事件详情", events: "事件", channels: "实时通道", overview: "概览", pinout: "引脚", clocks: "时钟", interrupts: "中断", faults: "故障", artifacts: "产物", changes: "变更" };
923
+
924
+ /** 一条事件的对话引用:单行,贴进对话后模型能对上调试台的序号。 */
925
+ function eventRefLine(event) {
926
+ return "- #" + String(event.seq) + " " + clockText(event.time) + " " + String(event.kind) + " " + String(event.status) + ":" + String(event.summary);
927
+ }
928
+
929
+ /** 多条事件的引用块:首行给条数,其余每行一条,顺序按传入顺序(时间线自上而下)。 */
930
+ function eventRefBlock(events) {
931
+ if (!Array.isArray(events) || events.length === 0) return "";
932
+ return ["调试台事件(" + String(events.length) + " 条):"].concat(events.map(eventRefLine)).join("\n");
933
+ }
934
+
935
+ /** 事件流地址:带上会话键,多标签页同时开着时只收本会话的事件。 */
936
+ function debugEventsPath(lastSeq, sessionId) {
937
+ const since = "events?since=" + String(lastSeq);
938
+ if (typeof sessionId !== "string" || sessionId === "") return since;
939
+ return since + "&session=" + encodeURIComponent(sessionId);
940
+ }
941
+
942
+ /** SSE 订阅:首连只补发本会话快照,断线按 lastSeq 续播。 */
943
+ function useDebugEvents(sessionId) {
944
+ const [events, setEvents] = useState([]);
945
+ const [connection, setConnection] = useState("connecting");
946
+ useEffect(() => {
947
+ let closed = false;
948
+ let source = null;
949
+ let timer = null;
950
+ let lastSeq = 0;
951
+ const scheduleReconnect = () => {
952
+ if (closed) return;
953
+ setConnection("retry");
954
+ timer = setTimeout(connect, DEBUG_RECONNECT_MS);
955
+ };
956
+ const connect = () => {
957
+ if (closed) return;
958
+ if (typeof EventSource !== "function") {
959
+ setConnection("unsupported");
960
+ return;
961
+ }
962
+ setConnection(lastSeq === 0 ? "connecting" : "retry");
963
+ source = new EventSource(apiUrl(debugEventsPath(lastSeq, sessionId)));
964
+ source.onopen = () => {
965
+ if (!closed) setConnection("open");
966
+ };
967
+ source.onmessage = (message) => {
968
+ if (closed) return;
969
+ let event;
970
+ try {
971
+ event = JSON.parse(message.data);
972
+ } catch {
973
+ return;
974
+ }
975
+ if (event === null || typeof event !== "object" || typeof event.seq !== "number") return;
976
+ lastSeq = event.seq;
977
+ setEvents((previous) => {
978
+ const next = previous.concat([event]);
979
+ return next.length > DEBUG_EVENT_CAP ? next.slice(next.length - DEBUG_EVENT_CAP) : next;
980
+ });
981
+ };
982
+ source.onerror = () => {
983
+ if (source !== null) source.close();
984
+ source = null;
985
+ scheduleReconnect();
986
+ };
987
+ };
988
+ connect();
989
+ return () => {
990
+ closed = true;
991
+ if (timer !== null) clearTimeout(timer);
992
+ if (source !== null) source.close();
993
+ };
994
+ }, [sessionId]);
995
+ return { events, connection };
996
+ }
997
+
998
+ function DebugPanel(props) {
999
+ const header = e(
1000
+ "div",
1001
+ { style: debugStyles.panelHead },
1002
+ props.title,
1003
+ e("span", { style: debugStyles.spacer }),
1004
+ props.onCollapse === undefined
1005
+ ? null
1006
+ : e(
1007
+ "button",
1008
+ {
1009
+ style: debugStyles.button,
1010
+ title: "收起到抽屉",
1011
+ onClick: (event) => {
1012
+ event.stopPropagation();
1013
+ props.onCollapse();
1014
+ },
1015
+ },
1016
+ "–",
1017
+ ),
1018
+ );
1019
+ return e(
1020
+ "div",
1021
+ { style: Object.assign({}, debugStyles.panel, { flex: props.flex === undefined ? "1 1 auto" : props.flex }) },
1022
+ header,
1023
+ e("div", { style: debugStyles.panelBody }, props.children),
1024
+ );
1025
+ }
1026
+
1027
+ function StatusBar(props) {
1028
+ const connectionText = {
1029
+ connecting: "连接中",
1030
+ open: "已连接",
1031
+ retry: "重连中",
1032
+ unsupported: "浏览器不支持事件流",
1033
+ }[props.connection] ?? props.connection;
1034
+ const lastEvent = props.events.length === 0 ? null : props.events[props.events.length - 1];
1035
+ const self = props.status === null || props.status === undefined ? null : (props.status.self ?? null);
1036
+ // lib 比进程新说明磁盘上是新构建、内存里跑的仍是旧模块:路由与面板都不会出现。
1037
+ const staleLib = self !== null && Number(self.libMtimeMs) > Number(self.startedAt) + 1000;
1038
+ return e(
1039
+ "div",
1040
+ { style: debugStyles.statusBar },
1041
+ e("strong", { style: debugStyles.brand }, "调试台"),
1042
+ e("span", { style: debugStyles.chip }, e("span", { style: debugStyles.dot }), connectionText),
1043
+ e("span", { style: debugStyles.chip }, "事件 " + String(props.events.length)),
1044
+ lastEvent === null
1045
+ ? null
1046
+ : e("span", { style: debugStyles.chip }, "序号 " + String(lastEvent.seq)),
1047
+ props.status === null || props.status === undefined
1048
+ ? null
1049
+ : e(
1050
+ "span",
1051
+ {
1052
+ style: Object.assign({}, debugStyles.chip, { maxWidth: "320px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }),
1053
+ title: String(props.status.evidenceRoot) + (props.status.evidenceOverride === true ? "(由 DSH_STM32_EVIDENCE 覆盖)" : ""),
1054
+ },
1055
+ "证据 " + String(props.status.evidenceRoot),
1056
+ ),
1057
+ self === null
1058
+ ? null
1059
+ : e(
1060
+ "span",
1061
+ {
1062
+ style: Object.assign({}, debugStyles.chip, staleLib ? { color: D32_WARN } : {}),
1063
+ title:
1064
+ "插件 v" + self.version + " · " + String(self.routeCount) + " 条路由\nlib 构建 " + clockText(self.libMtimeMs) +
1065
+ "\n进程启动 " + clockText(self.startedAt) +
1066
+ (staleLib ? "\nlib 比进程新:完全退出 DSH 再启动才会加载新路由与新面板。" : ""),
1067
+ },
1068
+ "v" + self.version + " · " + String(self.routeCount) + " 路由" + (staleLib ? "(有新构建)" : ""),
1069
+ ),
1070
+ e("span", { style: debugStyles.spacer }),
1071
+ e(
1072
+ "span",
1073
+ { style: Object.assign({}, D32_LABEL_MONO, { color: "var(--dsw-alias-label-tertiary)", letterSpacing: "0.08em" }) },
1074
+ "只读 · 事件自动落盘到证据目录",
1075
+ ),
1076
+ );
1077
+ }
1078
+
1079
+ /** 按 kind 统计出现次数(S57):用来点工具名快速筛一类事件。 */
1080
+ function kindCounts(events, limit) {
1081
+ const counts = new Map();
1082
+ for (const event of events) {
1083
+ const kind = String(event.kind ?? "");
1084
+ if (kind === "") continue;
1085
+ counts.set(kind, (counts.get(kind) ?? 0) + 1);
1086
+ }
1087
+ return [...counts.entries()]
1088
+ .sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0]))
1089
+ .slice(0, limit)
1090
+ .map((pair) => ({ kind: pair[0], count: pair[1] }));
1091
+ }
1092
+
1093
+ /** 超过这个耗时的工具调用在时间线上标黄(S47)。 */
1094
+ const TOOL_SLOW_MS = 5000;
1095
+
1096
+ /**
1097
+ * 按 callId 把 start 与 ok/fail 配成一对,算每次调用的耗时。
1098
+ *
1099
+ * 面板不另记计时器:事件里已经有时间戳,重连后补发的历史也能算出来。
1100
+ */
1101
+ function toolDurations(events) {
1102
+ const starts = new Map();
1103
+ const done = new Map();
1104
+ for (const event of events) {
1105
+ const callId = event.payload !== null && typeof event.payload === "object" && typeof event.payload.callId === "string" ? event.payload.callId : "";
1106
+ if (callId === "") continue;
1107
+ const at = Date.parse(String(event.time));
1108
+ if (!Number.isFinite(at)) continue;
1109
+ if (event.status === "start") {
1110
+ starts.set(callId, at);
1111
+ } else if (event.status === "ok" || event.status === "fail") {
1112
+ const start = starts.get(callId);
1113
+ if (start === undefined) continue;
1114
+ const ms = at - start;
1115
+ done.set(callId, { ms: ms >= 0 ? ms : 0, slow: ms >= TOOL_SLOW_MS });
1116
+ }
1117
+ }
1118
+ return done;
1119
+ }
1120
+
1121
+ function durationText(ms) {
1122
+ return ms >= 1000 ? (ms / 1000).toFixed(1) + " s" : String(Math.round(ms)) + " ms";
1123
+ }
1124
+
1125
+ function Timeline(props) {
1126
+ const body = props.events.length === 0
1127
+ ? e("div", { style: debugStyles.empty }, props.connection === "open" ? "尚无事件。调用任一 stm32_* 工具后在此出现。" : "等待事件流连接。")
1128
+ : props.events.map((event) =>
1129
+ e(
1130
+ "div",
1131
+ {
1132
+ key: String(event.seq),
1133
+ className: "d32-row",
1134
+ "data-status": String(event.status),
1135
+ style: Object.assign(
1136
+ {},
1137
+ debugStyles.row,
1138
+ (props.selectedSeq === event.seq ? { background: "color-mix(in srgb, " + D32_ACCENT + " 10%, transparent)" } : {}),
1139
+ props.pickedSet && props.pickedSet.has(event.seq) ? { outline: "1px solid " + D32_ACCENT } : {},
1140
+ ),
1141
+ onClick: () => props.onSelect(event),
1142
+ },
1143
+ e("input", {
1144
+ type: "checkbox",
1145
+ checked: props.pickedSet ? props.pickedSet.has(event.seq) : false,
1146
+ title: "勾选后可以批量复制引用",
1147
+ style: { margin: "0 2px 0 0" },
1148
+ onClick: (ev) => {
1149
+ if (typeof ev.stopPropagation === "function") ev.stopPropagation();
1150
+ },
1151
+ onChange: () => props.onPick(event),
1152
+ }),
1153
+ e("span", { style: debugStyles.rowTime }, clockText(event.time)),
1154
+ e("span", { style: debugStyles.rowKind }, (DEBUG_STATUS_SIGN[event.status] ?? "·") + " " + String(event.kind)),
1155
+ e("span", { style: debugStyles.rowText, title: String(event.summary) }, String(event.summary)),
1156
+ (() => {
1157
+ const callId = event.payload !== null && typeof event.payload === "object" && typeof event.payload.callId === "string" ? event.payload.callId : "";
1158
+ const timing = callId === "" || props.durations === null ? undefined : props.durations.get(callId);
1159
+ if (timing === undefined) return null;
1160
+ return e(
1161
+ "span",
1162
+ {
1163
+ style: Object.assign({}, debugStyles.rowTime, timing.slow ? { color: D32_WARN, opacity: 1 } : { opacity: 0.55 }),
1164
+ title: timing.slow ? "超过 " + String(TOOL_SLOW_MS / 1000) + " 秒的调用" : "本次调用耗时",
1165
+ },
1166
+ (timing.slow ? "慢 " : "") + durationText(timing.ms),
1167
+ );
1168
+ })(),
1169
+ ),
1170
+ );
1171
+ return e(DebugPanel, { title: DEBUG_LABELS.timeline, flex: "1 1 0", onCollapse: props.onCollapse }, body);
1172
+ }
1173
+
1174
+ /** 编译错误列表:每条可点开源码上下文;解析不出「文件:行:列」的按纯文本列出。 */
1175
+ function CompileErrors(props) {
1176
+ const errors = Array.isArray(props.errors) ? props.errors : [];
1177
+ const [picked, setPicked] = useState(null);
1178
+ const [slice, setSlice] = useState(null);
1179
+ const [error, setError] = useState("");
1180
+ if (errors.length === 0) return null;
1181
+ const open = async (index, parsed) => {
1182
+ if (parsed === null) return;
1183
+ setPicked(index);
1184
+ setError("");
1185
+ const result = await fetchSource(props.projectDir, parsed.file, parsed.line, 2);
1186
+ if (result.ok) setSlice(result.value.source);
1187
+ else {
1188
+ setSlice(null);
1189
+ setError(String(result.error ?? "读取源码失败"));
1190
+ }
1191
+ };
1192
+ return e(
1193
+ "div",
1194
+ { style: { padding: "0 12px 8px", display: "flex", flexDirection: "column", gap: "2px" } },
1195
+ e("div", { style: { opacity: 0.65 } }, "编译错误(" + String(errors.length) + ")"),
1196
+ errors.map((line, index) => {
1197
+ const parsed = parseCompileError(line);
1198
+ return e(
1199
+ "div",
1200
+ {
1201
+ key: String(index),
1202
+ style: {
1203
+ fontFamily: "ui-monospace, monospace",
1204
+ fontSize: "11px",
1205
+ whiteSpace: "pre-wrap",
1206
+ wordBreak: "break-word",
1207
+ cursor: parsed === null ? "default" : "pointer",
1208
+ opacity: picked === index ? 0.95 : 0.8,
1209
+ },
1210
+ title: parsed === null ? String(line) : "点击看源码:" + parsed.file + ":" + String(parsed.line),
1211
+ onClick: () => open(index, parsed),
1212
+ },
1213
+ String(line),
1214
+ );
1215
+ }),
1216
+ error === "" ? null : e("div", { style: { fontSize: "11px", opacity: 0.7 } }, error),
1217
+ e(SourceBlock, { slice: slice }),
1218
+ );
1219
+ }
1220
+
1221
+ /** 编译警告清单(S75):与错误同一套跳源码,标题与配色区分开。 */
1222
+ function CompileWarnings(props) {
1223
+ const warnings = Array.isArray(props.warnings) ? props.warnings : [];
1224
+ const [picked, setPicked] = useState(null);
1225
+ const [slice, setSlice] = useState(null);
1226
+ const [error, setError] = useState("");
1227
+ if (warnings.length === 0) return null;
1228
+ const open = async (index, parsed) => {
1229
+ if (parsed === null) return;
1230
+ setPicked(index);
1231
+ setError("");
1232
+ const result = await fetchSource(props.projectDir, parsed.file, parsed.line, 2);
1233
+ if (result.ok) setSlice(result.value.source);
1234
+ else {
1235
+ setSlice(null);
1236
+ setError(String(result.error ?? "读取源码失败"));
1237
+ }
1238
+ };
1239
+ return e(
1240
+ "div",
1241
+ { style: { padding: "0 12px 8px", display: "flex", flexDirection: "column", gap: "2px" } },
1242
+ e("div", { style: { opacity: 0.65, color: D32_WARN } }, "编译警告(" + String(warnings.length) + ")"),
1243
+ warnings.map((line, index) => {
1244
+ const parsed = parseCompileError(line);
1245
+ return e(
1246
+ "div",
1247
+ {
1248
+ key: String(index),
1249
+ style: {
1250
+ fontFamily: "ui-monospace, monospace",
1251
+ fontSize: "11px",
1252
+ whiteSpace: "pre-wrap",
1253
+ wordBreak: "break-word",
1254
+ cursor: parsed === null ? "default" : "pointer",
1255
+ opacity: picked === index ? 0.95 : 0.8,
1256
+ },
1257
+ title: parsed === null ? String(line) : "点击看源码:" + parsed.file + ":" + String(parsed.line),
1258
+ onClick: () => open(index, parsed),
1259
+ },
1260
+ String(line),
1261
+ );
1262
+ }),
1263
+ error === "" ? null : e("div", { style: { fontSize: "11px", opacity: 0.7 } }, error),
1264
+ e(SourceBlock, { slice: slice }),
1265
+ );
1266
+ }
1267
+
1268
+ function Detail(props) {
1269
+ const event = props.event;
1270
+ if (event === null) {
1271
+ return e(DebugPanel, { title: DEBUG_LABELS.detail, onCollapse: props.onCollapse }, e("div", { style: debugStyles.empty }, "在左侧选择一条事件查看参数与结果。"));
1272
+ }
1273
+ const refs = Array.isArray(event.refs) && event.refs.length > 0
1274
+ ? e(
1275
+ "div",
1276
+ { style: { padding: "0 12px 10px" } },
1277
+ e("div", { style: { opacity: 0.65, marginBottom: "4px" } }, "关联"),
1278
+ event.refs.map((ref, index) =>
1279
+ e("div", { key: String(index), style: debugStyles.mono }, [ref.file, ref.line === undefined ? "" : ":" + String(ref.line), ref.hash === undefined ? "" : " #" + String(ref.hash).slice(0, 12)].join("")),
1280
+ ),
1281
+ )
1282
+ : null;
1283
+ const payloadText =
1284
+ event.payload === undefined || event.payload === null ? "" : JSON.stringify(event.payload, null, 2);
1285
+ const copyPayload = () => {
1286
+ if (payloadText === "") return;
1287
+ const clipboard = typeof navigator === "object" && navigator !== null ? navigator.clipboard : null;
1288
+ if (clipboard !== null && clipboard !== undefined && typeof clipboard.writeText === "function") {
1289
+ clipboard.writeText(payloadText).catch(() => undefined);
1290
+ }
1291
+ };
1292
+ const copyRef = () => {
1293
+ const text = "[调试台事件 #" + String(event.seq) + "] " + String(event.kind) + " " + String(event.status) + ":" + String(event.summary);
1294
+ const clipboard = typeof navigator === "object" && navigator !== null ? navigator.clipboard : null;
1295
+ if (clipboard !== null && clipboard !== undefined && typeof clipboard.writeText === "function") {
1296
+ clipboard.writeText(text).catch(() => undefined);
1297
+ }
1298
+ };
1299
+ return e(
1300
+ DebugPanel,
1301
+ { title: DEBUG_LABELS.detail, onCollapse: props.onCollapse },
1302
+ e(
1303
+ "div",
1304
+ { style: { padding: "10px 12px 6px", display: "flex", flexDirection: "column", gap: "4px" } },
1305
+ e("div", null, "序号 " + String(event.seq) + " · " + clockText(event.time) + " · " + String(event.kind)),
1306
+ e("div", null, "来源 " + String(event.source) + " · 状态 " + String(event.status)),
1307
+ e("div", { style: { opacity: 0.85 } }, String(event.summary)),
1308
+ event.truncated === true ? e("div", { style: { opacity: 0.65 } }, "payload 超过上限,仅保留预览。") : null,
1309
+ ),
1310
+ refs,
1311
+ e(CompileErrors, {
1312
+ errors: event.payload !== null && typeof event.payload === "object" && event.payload.result !== null && typeof event.payload.result === "object" ? event.payload.result.errors : undefined,
1313
+ projectDir: event.payload !== null && typeof event.payload === "object" && event.payload.result !== null && typeof event.payload.result === "object" && typeof event.payload.result.projectDir === "string" ? event.payload.result.projectDir : (typeof props.projectDir === "string" ? props.projectDir : ""),
1314
+ }),
1315
+ e(CompileWarnings, {
1316
+ warnings: event.payload !== null && typeof event.payload === "object" && event.payload.result !== null && typeof event.payload.result === "object" ? event.payload.result.warnings : undefined,
1317
+ projectDir: event.payload !== null && typeof event.payload === "object" && event.payload.result !== null && typeof event.payload.result === "object" && typeof event.payload.result.projectDir === "string" ? event.payload.result.projectDir : (typeof props.projectDir === "string" ? props.projectDir : ""),
1318
+ }),
1319
+ payloadText === ""
1320
+ ? null
1321
+ : e(
1322
+ "div",
1323
+ { style: { padding: "0 12px 8px" } },
1324
+ e("div", { style: { opacity: 0.65, marginBottom: "4px" } }, "参数与结果"),
1325
+ e(
1326
+ "pre",
1327
+ {
1328
+ style: {
1329
+ margin: 0,
1330
+ padding: "6px 8px",
1331
+ maxHeight: "200px",
1332
+ overflow: "auto",
1333
+ fontSize: "11px",
1334
+ lineHeight: "1.45",
1335
+ whiteSpace: "pre-wrap",
1336
+ wordBreak: "break-word",
1337
+ border: "1px solid color-mix(in srgb, currentColor 18%, transparent)",
1338
+ borderRadius: "4px",
1339
+ },
1340
+ },
1341
+ payloadText,
1342
+ ),
1343
+ ),
1344
+ e(
1345
+ "div",
1346
+ { style: { padding: "0 12px 8px", display: "flex", gap: "6px", flexWrap: "wrap" } },
1347
+ e("button", { style: debugStyles.button, onClick: copyRef }, "复制引用(贴到对话里)"),
1348
+ payloadText === "" ? null : e("button", { style: debugStyles.button, onClick: copyPayload }, "复制 payload"),
1349
+ ),
1350
+ e("pre", { style: debugStyles.pre }, event.payload === undefined ? "(无 payload)" : JSON.stringify(event.payload, null, 2)),
1351
+ );
1352
+ }
1353
+
1354
+ /** 会话卡一行:名称与值左右对齐。 */
1355
+ function metaRow(label, value) {
1356
+ return e(
1357
+ "div",
1358
+ { style: { display: "flex", gap: "8px", alignItems: "baseline" } },
1359
+ e("span", { style: { opacity: 0.6, flex: "0 0 auto" } }, label),
1360
+ e("span", { style: { flex: "1 1 auto", wordBreak: "break-all" } }, value),
1361
+ );
1362
+ }
1363
+
1364
+ /** 调试会话状态:面板里与「当前会话」相关的块共用一次轮询。 */
1365
+ function useDebugStatus(intervalMs) {
1366
+ const [debug, setDebug] = useState(null);
1367
+ const [error, setError] = useState("");
1368
+ const [tick, setTick] = useState(0);
1369
+ useEffect(() => {
1370
+ let closed = false;
1371
+ const load = async () => {
1372
+ const result = await callApi("GET", "debug");
1373
+ if (closed) return;
1374
+ if (result.ok) {
1375
+ setDebug(result.value.debug);
1376
+ setError("");
1377
+ } else {
1378
+ setError(result.error);
1379
+ }
1380
+ };
1381
+ load();
1382
+ const timer = setInterval(load, intervalMs);
1383
+ return () => {
1384
+ closed = true;
1385
+ clearInterval(timer);
1386
+ };
1387
+ }, [tick]);
1388
+ return { debug, error, reload: () => setTick((value) => value + 1) };
1389
+ }
1390
+
1391
+ /** 调试会话摘要:只读呈现 /debug 的结果,不触发探针动作。 */
1392
+ function SessionCard(props) {
1393
+ const [copyNote, setCopyNote] = useState("");
1394
+ const [closing, setClosing] = useState(false);
1395
+ const debug = props.debug ?? null;
1396
+ const error = props.error ?? "";
1397
+ const quota = (value) => (value !== null && typeof value === "object" && value.used !== undefined ? String(value.used) + "/" + String(value.budget) : "—");
1398
+ const body = [];
1399
+ if (error !== "") {
1400
+ body.push(e("div", { key: "error", style: { opacity: 0.7 } }, "读取调试会话失败:" + error));
1401
+ } else if (debug === null) {
1402
+ body.push(e("div", { key: "loading", style: { opacity: 0.6 } }, "读取调试会话…"));
1403
+ } else if (debug.active !== true) {
1404
+ body.push(e("div", { key: "idle", style: { opacity: 0.7 } }, "当前没有调试会话(探针空闲)。"));
1405
+ } else {
1406
+ body.push(metaRow("状态", "进行中 · 剩余 " + String(Math.ceil(Number(debug.remainingMs) / 1000)) + " s"));
1407
+ body.push(metaRow("会话", String(debug.sessionId)));
1408
+ body.push(metaRow("端口", "gdb " + String(debug.port) + " · tcl " + String(debug.tclPort)));
1409
+ body.push(metaRow("工程", String(debug.projectDir)));
1410
+ body.push(metaRow("符号", String(debug.elfPath)));
1411
+ body.push(metaRow("断点", quota(debug.breakpoints)));
1412
+ body.push(metaRow("观察点", quota(debug.watchpoints)));
1413
+ const traces = Array.isArray(debug.outputs) ? debug.outputs.slice(-3).reverse() : [];
1414
+ if (traces.length > 0) {
1415
+ body.push(
1416
+ e(
1417
+ "div",
1418
+ { key: "outputs", style: { display: "flex", flexDirection: "column", gap: "2px" } },
1419
+ e(
1420
+ "div",
1421
+ { style: { display: "flex", alignItems: "baseline", gap: "8px", opacity: 0.7 } },
1422
+ e("span", {}, "最近 gdb 输出"),
1423
+ e(
1424
+ "button",
1425
+ {
1426
+ style: Object.assign({}, debugStyles.button, { fontSize: "11px", padding: "1px 6px" }),
1427
+ title: "复制最近一次 eval 的完整输出",
1428
+ onClick: () => {
1429
+ void navigator.clipboard.writeText(String(traces[0].output ?? ""));
1430
+ setCopyNote("已复制最近一次 gdb 输出");
1431
+ },
1432
+ },
1433
+ "复制",
1434
+ ),
1435
+ copyNote === "" ? null : e("span", { style: { fontSize: "11px", opacity: 0.6 } }, copyNote),
1436
+ ),
1437
+ traces.map((trace) =>
1438
+ e(
1439
+ "pre",
1440
+ {
1441
+ key: "trace-" + String(trace.at),
1442
+ title: String(trace.command),
1443
+ style: {
1444
+ margin: 0,
1445
+ maxHeight: "120px",
1446
+ overflow: "auto",
1447
+ fontSize: "11px",
1448
+ whiteSpace: "pre-wrap",
1449
+ wordBreak: "break-word",
1450
+ padding: "4px 6px",
1451
+ border: "1px solid color-mix(in srgb, currentColor 12%, transparent)",
1452
+ borderRadius: "4px",
1453
+ opacity: trace.ok === true ? 0.85 : 1,
1454
+ },
1455
+ },
1456
+ clockText(trace.at) + (trace.ok === true ? "" : "(失败)") + "\n" + String(trace.output ?? ""),
1457
+ ),
1458
+ ),
1459
+ ),
1460
+ );
1461
+ }
1462
+ const closeSession = async () => {
1463
+ setClosing(true);
1464
+ const result = await props.onClose?.();
1465
+ setClosing(false);
1466
+ if (result !== undefined) setCopyNote(result);
1467
+ };
1468
+ body.push(
1469
+ e(
1470
+ "div",
1471
+ { key: "touch", style: { display: "flex", alignItems: "center", gap: "6px" } },
1472
+ e(
1473
+ "button",
1474
+ {
1475
+ style: debugStyles.button,
1476
+ title: "重置空闲计时,总时长上限不变",
1477
+ onClick: () => props.onTouch?.(),
1478
+ },
1479
+ "续期",
1480
+ ),
1481
+ e(
1482
+ "button",
1483
+ {
1484
+ style: Object.assign({}, debugStyles.button, { color: D32_WARN }),
1485
+ title: "关闭调试会话,释放 gdb、openocd 与探针;观察点会一起清空",
1486
+ disabled: closing === true,
1487
+ onClick: () => void closeSession(),
1488
+ },
1489
+ closing === true ? "关闭中…" : "关闭会话",
1490
+ ),
1491
+ props.touchMessage === ""
1492
+ ? null
1493
+ : e("span", { style: { opacity: 0.6, fontSize: "11px" } }, props.touchMessage),
1494
+ ),
1495
+ );
1496
+ }
1497
+ return e(
1498
+ "div",
1499
+ {
1500
+ style: {
1501
+ display: "flex",
1502
+ flexDirection: "column",
1503
+ gap: "4px",
1504
+ padding: "6px 10px",
1505
+ borderBottom: "1px solid color-mix(in srgb, currentColor 8%, transparent)",
1506
+ fontSize: "12px",
1507
+ },
1508
+ },
1509
+ body,
1510
+ );
1511
+ }
1512
+
1513
+ /** 读一段源码:给断点命中与编译错误共用,只读,越界由服务端拒绝。 */
1514
+ async function fetchSource(projectDir, file, line, context) {
1515
+ return callApi(
1516
+ "GET",
1517
+ "source?projectDir=" + encodeURIComponent(projectDir) +
1518
+ "&file=" + encodeURIComponent(file) +
1519
+ "&line=" + String(line) +
1520
+ "&context=" + String(context ?? 3),
1521
+ );
1522
+ }
1523
+
1524
+ /** 源码片段:行号在左,焦点行加底色。 */
1525
+ function SourceBlock(props) {
1526
+ const slice = props.slice;
1527
+ if (slice === null || slice === undefined) return null;
1528
+ return e(
1529
+ "div",
1530
+ { style: { display: "flex", flexDirection: "column", gap: "1px", paddingTop: "2px" } },
1531
+ e(
1532
+ "div",
1533
+ { style: { fontSize: "11px", opacity: 0.7, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, title: slice.file },
1534
+ slice.file + ":" + String(slice.line) + "(共 " + String(slice.totalLines) + " 行)",
1535
+ ),
1536
+ slice.lines.map((item) =>
1537
+ e(
1538
+ "div",
1539
+ {
1540
+ key: String(item.line),
1541
+ style: {
1542
+ display: "flex",
1543
+ gap: "6px",
1544
+ fontFamily: "ui-monospace, monospace",
1545
+ fontSize: "11px",
1546
+ whiteSpace: "pre",
1547
+ overflow: "hidden",
1548
+ background: item.line === slice.line ? "color-mix(in srgb, currentColor 10%, transparent)" : "transparent",
1549
+ },
1550
+ },
1551
+ e("span", { style: { flex: "0 0 34px", textAlign: "right", opacity: 0.5 } }, String(item.line)),
1552
+ e("span", { style: { flex: "1 1 auto", overflow: "hidden", textOverflow: "ellipsis" } }, item.text),
1553
+ ),
1554
+ ),
1555
+ );
1556
+ }
1557
+
1558
+ /**
1559
+ * 从 gcc 的报错里取「文件:行:列」。
1560
+ *
1561
+ * 常见形状:`Core/Src/main.c:67:5: error: 'x' undeclared`;
1562
+ * 也有 `core/Src/main.c: In function 'main':` 这种无行号的,返回 null。
1563
+ */
1564
+ function parseCompileError(line) {
1565
+ const match = /^\s*(.+?):(\d+):(\d+):\s*(.*)$/u.exec(String(line ?? ""));
1566
+ if (match === null) return null;
1567
+ return { file: match[1], line: Number.parseInt(match[2], 10), column: Number.parseInt(match[3], 10), message: match[4] };
1568
+ }
1569
+
1570
+ /**
1571
+ * 从 gdb 的停点文本里取「文件:行」。
1572
+ *
1573
+ * 真实文本形如 `Breakpoint 2 at 0x8000314: file stm32f1xx_hal.c, line 373.` 或
1574
+ * `... stm32f1xx_hal.c:373`;从右往左找最后一个「带扩展名:数字」,避免把地址当成行号。
1575
+ */
1576
+ function parseHitLocation(text) {
1577
+ const source = String(text ?? "");
1578
+ const pattern = /([A-Za-z0-9_.\/-]+\.(?:c|h|cc|cpp|hpp|s|S))(?::|, line )(\d+)/gu;
1579
+ let found = null;
1580
+ let match = pattern.exec(source);
1581
+ while (match !== null) {
1582
+ found = { file: match[1], line: Number.parseInt(match[2], 10) };
1583
+ match = pattern.exec(source);
1584
+ }
1585
+ return found;
1586
+ }
1587
+
1588
+ /** 断点面板:只发 add / remove / list 三种动作,location 与 id 由服务端再校验一遍。 */
1589
+ function BreakpointPanel(props) {
1590
+ const active = props.debug !== null && typeof props.debug === "object" && props.debug.active === true;
1591
+ const [location, setLocation] = useState("");
1592
+ const [removeId, setRemoveId] = useState("");
1593
+ const [output, setOutput] = useState("");
1594
+ const [busy, setBusy] = useState(false);
1595
+ const [slice, setSlice] = useState(null);
1596
+ const [sliceError, setSliceError] = useState("");
1597
+ const hits = Array.isArray(props.debug?.hits) ? props.debug.hits.slice().reverse() : [];
1598
+ const projectDir = typeof props.debug?.projectDir === "string" ? props.debug.projectDir : "";
1599
+ const openHit = async (hit) => {
1600
+ const at = parseHitLocation(hit.text);
1601
+ if (at === null) {
1602
+ setSliceError("这条停点里没有源码位置。");
1603
+ setSlice(null);
1604
+ return;
1605
+ }
1606
+ setSliceError("");
1607
+ const result = await callApi(
1608
+ "GET",
1609
+ "source?projectDir=" + encodeURIComponent(projectDir) +
1610
+ "&file=" + encodeURIComponent(at.file) +
1611
+ "&line=" + String(at.line) +
1612
+ "&context=3",
1613
+ );
1614
+ if (result.ok) setSlice(result.value.source);
1615
+ else {
1616
+ setSlice(null);
1617
+ setSliceError(String(result.error ?? "读取源码失败"));
1618
+ }
1619
+ };
1620
+ const run = async (body) => {
1621
+ if (busy) return;
1622
+ setBusy(true);
1623
+ const result = await callApi("POST", "debug/breakpoints", body);
1624
+ setBusy(false);
1625
+ if (result.ok) {
1626
+ const payload = result.value.breakpoints;
1627
+ const text = String(payload.output ?? "").trim();
1628
+ setOutput(text === "" ? String(payload.message ?? "") : text);
1629
+ if (typeof props.onChanged === "function") props.onChanged();
1630
+ } else {
1631
+ setOutput(String(result.error ?? "请求失败"));
1632
+ }
1633
+ };
1634
+ const disabled = busy === true || active !== true;
1635
+ const button = (label, onClick) => e("button", { style: debugStyles.button, disabled, onClick }, label);
1636
+ return e(
1637
+ "div",
1638
+ {
1639
+ style: {
1640
+ display: "flex",
1641
+ flexDirection: "column",
1642
+ gap: "4px",
1643
+ padding: "6px 10px",
1644
+ borderBottom: "1px solid color-mix(in srgb, currentColor 8%, transparent)",
1645
+ fontSize: "12px",
1646
+ },
1647
+ },
1648
+ e(
1649
+ "div",
1650
+ { style: { display: "flex", alignItems: "center", gap: "6px" } },
1651
+ e("strong", null, "断点"),
1652
+ e("span", { style: { opacity: 0.55 } }, active ? "会话进行中" : "无会话"),
1653
+ e("span", { style: debugStyles.spacer }),
1654
+ button("列出", () => run({ action: "list" })),
1655
+ ),
1656
+ e(
1657
+ "div",
1658
+ { style: { display: "flex", gap: "6px" } },
1659
+ e("input", {
1660
+ style: Object.assign({}, debugStyles.input, { flex: "1 1 auto" }),
1661
+ placeholder: "符号名或 文件:行,例如 main",
1662
+ value: location,
1663
+ onChange: (event) => setLocation(event.target.value),
1664
+ }),
1665
+ button("添加", () => run({ action: "add", location: location.trim() })),
1666
+ ),
1667
+ e(
1668
+ "div",
1669
+ { style: { display: "flex", gap: "6px" } },
1670
+ e("input", {
1671
+ style: Object.assign({}, debugStyles.input, { flex: "0 0 90px" }),
1672
+ placeholder: "编号",
1673
+ value: removeId,
1674
+ onChange: (event) => setRemoveId(event.target.value),
1675
+ }),
1676
+ button("移除", () => run({ action: "remove", id: Number(removeId) })),
1677
+ ),
1678
+ output === ""
1679
+ ? null
1680
+ : e("pre", { style: Object.assign({}, debugStyles.pre, { padding: 0, maxHeight: "140px", overflow: "auto" }) }, output),
1681
+ e("div", { style: { display: "flex", alignItems: "center", gap: "6px", opacity: 0.7 } }, "命中历史(" + String(hits.length) + ")"),
1682
+ hits.length === 0
1683
+ ? e("div", { style: { fontSize: "11px", opacity: 0.5 } }, "还没有停点记录:跑一次 continue / next 后这里会出现停在哪。")
1684
+ : hits.map((hit) =>
1685
+ e(
1686
+ "div",
1687
+ {
1688
+ key: String(hit.time) + ":" + String(hit.id) + ":" + hit.text,
1689
+ style: { fontFamily: "ui-monospace, monospace", fontSize: "11px", opacity: 0.8, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", cursor: "pointer" },
1690
+ title: "点击看源码上下文:" + hit.text,
1691
+ onClick: () => openHit(hit),
1692
+ },
1693
+ clockText(hit.time) + " #" + String(hit.id) + " " + hit.text,
1694
+ ),
1695
+ ),
1696
+ sliceError === ""
1697
+ ? null
1698
+ : e("div", { style: { fontSize: "11px", opacity: 0.7 } }, sliceError),
1699
+ e(SourceBlock, { slice: slice }),
1700
+ );
1701
+ }
1702
+
1703
+ const WATCH_POINT_LIMIT = 120;
1704
+
1705
+ /** 从 channel:watch 事件的结构化样本里取数字序列,按表达式分桶。 */
1706
+ function collectWatchSeries(events) {
1707
+ const series = {};
1708
+ for (const event of events) {
1709
+ if (event.kind !== "channel:watch") continue;
1710
+ const payload = event.payload !== null && typeof event.payload === "object" ? event.payload : null;
1711
+ const meta = payload !== null && payload.meta !== null && typeof payload.meta === "object" ? payload.meta : null;
1712
+ const samples = meta !== null && Array.isArray(meta.samples) ? meta.samples : [];
1713
+ for (const sample of samples) {
1714
+ if (sample === null || typeof sample !== "object" || sample.ok !== true) continue;
1715
+ const numeric = Number(String(sample.value).trim());
1716
+ if (!Number.isFinite(numeric)) continue;
1717
+ const key = String(sample.expression);
1718
+ if (series[key] === undefined) series[key] = [];
1719
+ series[key].push(numeric);
1720
+ if (series[key].length > WATCH_POINT_LIMIT) series[key].shift();
1721
+ }
1722
+ }
1723
+ return series;
1724
+ }
1725
+
1726
+ /** 监视采样明细(S67):带时间与增量,供导出 CSV;曲线本身只要数值。 */
1727
+ function collectWatchRows(events) {
1728
+ const rows = [];
1729
+ for (const event of events) {
1730
+ if (event.kind !== "channel:watch") continue;
1731
+ const payload = event.payload !== null && typeof event.payload === "object" ? event.payload : null;
1732
+ const meta = payload !== null && payload.meta !== null && typeof payload.meta === "object" ? payload.meta : null;
1733
+ const samples = meta !== null && Array.isArray(meta.samples) ? meta.samples : [];
1734
+ for (const sample of samples) {
1735
+ if (sample === null || typeof sample !== "object" || sample.ok !== true) continue;
1736
+ rows.push({
1737
+ time: String(event.time),
1738
+ expression: String(sample.expression),
1739
+ value: sample.value,
1740
+ delta: sample.delta === null || sample.delta === undefined ? "" : sample.delta,
1741
+ });
1742
+ }
1743
+ }
1744
+ return rows;
1745
+ }
1746
+
1747
+ /** 把监视采样明细导成 CSV(S67):表头中文,UTF-8 带 BOM。 */
1748
+ function exportWatchCsv(rows) {
1749
+ const header = ["时间", "表达式", "值", "增量"];
1750
+ const body = rows.map((row) => [row.time, row.expression, row.value, row.delta].map(csvCell).join(","));
1751
+ const text = "\ufeff" + [header.join(",")].concat(body).join("\r\n") + "\r\n";
1752
+ const blob = new Blob([text], { type: "text/csv;charset=utf-8" });
1753
+ const url = URL.createObjectURL(blob);
1754
+ const link = document.createElement("a");
1755
+ link.href = url;
1756
+ link.download = "stm32-watch-" + new Date().toISOString().replace(/[:.]/gu, "-") + ".csv";
1757
+ document.body.appendChild(link);
1758
+ link.click();
1759
+ document.body.removeChild(link);
1760
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
1761
+ }
1762
+
1763
+ /** 采样序列折线:宽度固定,纵向按本次序列的最小最大值铺满。 */
1764
+ function sparklinePath(values, width, height) {
1765
+ const min = Math.min(...values);
1766
+ const max = Math.max(...values);
1767
+ const span = max - min === 0 ? 1 : max - min;
1768
+ const step = values.length > 1 ? width / (values.length - 1) : 0;
1769
+ return values
1770
+ .map((value, index) => {
1771
+ const x = values.length > 1 ? index * step : width / 2;
1772
+ const y = height - 1 - ((value - min) / span) * (height - 2);
1773
+ return (index === 0 ? "M" : "L") + x.toFixed(1) + " " + y.toFixed(1);
1774
+ })
1775
+ .join(" ");
1776
+ }
1777
+
1778
+ /** 监视历史曲线:数值采样画走势;结构体、指针等非数值只留在通道行里。 */
1779
+ function WatchCurves(props) {
1780
+ const series = collectWatchSeries(props.events);
1781
+ const keys = Object.keys(series).sort();
1782
+ const recording = props.recording ?? null;
1783
+ const header = e(
1784
+ "div",
1785
+ { style: { display: "flex", alignItems: "center", gap: "8px", padding: "6px 10px" } },
1786
+ e("span", { style: { flex: "1 1 auto", fontSize: "12px" } }, "监视采样"),
1787
+ e(
1788
+ "span",
1789
+ { style: { fontSize: "11px", opacity: 0.6 }, title: recording?.lastError ?? "" },
1790
+ recording?.active === true ? "自动采样中 · 每 " + String(recording.intervalMs) + " ms" : "手动",
1791
+ ),
1792
+ e(
1793
+ "button",
1794
+ {
1795
+ type: "button",
1796
+ onClick: recording?.active === true ? props.onStop : props.onStart,
1797
+ style: { fontSize: "11px", padding: "1px 8px" },
1798
+ },
1799
+ recording?.active === true ? "停止" : "自动采样",
1800
+ ),
1801
+ e(
1802
+ "button",
1803
+ {
1804
+ type: "button",
1805
+ disabled: (props.events ?? []).length === 0,
1806
+ onClick: () => exportWatchCsv(collectWatchRows(props.events ?? [])),
1807
+ style: Object.assign({}, debugStyles.button, { fontSize: "11px", padding: "1px 8px" }, (props.events ?? []).length === 0 ? { opacity: 0.5 } : {}),
1808
+ title: "把当前会话的监视采样明细导成 CSV(时间、表达式、值、增量)",
1809
+ },
1810
+ "导出 CSV",
1811
+ ),
1812
+ );
1813
+ if (keys.length === 0) {
1814
+ return e(
1815
+ "div",
1816
+ { style: { padding: "0 0 6px 0" } },
1817
+ header,
1818
+ e("div", { style: { padding: "0 10px 6px 10px", opacity: 0.55, fontSize: "12px" } }, "暂无数值型监视采样。"),
1819
+ );
1820
+ }
1821
+ return e(
1822
+ "div",
1823
+ {
1824
+ style: {
1825
+ display: "flex",
1826
+ flexDirection: "column",
1827
+ gap: "4px",
1828
+ padding: "0 0 6px 0",
1829
+ borderBottom: "1px solid color-mix(in srgb, currentColor 8%, transparent)",
1830
+ fontSize: "12px",
1831
+ },
1832
+ },
1833
+ header,
1834
+ keys.map((key) => {
1835
+ const values = series[key];
1836
+ const last = values[values.length - 1];
1837
+ const min = Math.min(...values);
1838
+ const max = Math.max(...values);
1839
+ return e(
1840
+ "div",
1841
+ { key: key, style: { display: "flex", alignItems: "center", gap: "8px" } },
1842
+ e("span", { title: key, style: { flex: "0 0 40%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, key),
1843
+ e(
1844
+ "svg",
1845
+ { width: 110, height: 26, viewBox: "0 0 110 26", style: { flex: "0 0 auto", opacity: 0.9 } },
1846
+ e("path", { d: sparklinePath(values, 110, 26), fill: "none", stroke: "currentColor", strokeWidth: 1.2 }),
1847
+ ),
1848
+ e(
1849
+ "span",
1850
+ { style: { flex: "1 1 auto", textAlign: "right", fontVariantNumeric: "tabular-nums" } },
1851
+ String(last) + "(" + String(values.length) + " 点," + String(min) + "…" + String(max) + ")",
1852
+ ),
1853
+ );
1854
+ }),
1855
+ );
1856
+ }
1857
+
1858
+ /** 引脚表:读工程 .ioc 的分组结果;切到引脚标签时立即拉一次,之后 10 秒刷新。 */
1859
+ function usePinout(projectDir, intervalMs) {
1860
+ const [pinout, setPinout] = useState(null);
1861
+ const [error, setError] = useState("");
1862
+ const [tick, setTick] = useState(0);
1863
+ useEffect(() => {
1864
+ let closed = false;
1865
+ if (typeof projectDir !== "string" || projectDir === "") {
1866
+ setPinout(null);
1867
+ setError("");
1868
+ return () => {
1869
+ closed = true;
1870
+ };
1871
+ }
1872
+ const load = async () => {
1873
+ const result = await callApi("GET", "pinout?projectDir=" + encodeURIComponent(projectDir));
1874
+ if (closed) return;
1875
+ if (result.ok) {
1876
+ setPinout(result.value.pinout);
1877
+ setError("");
1878
+ } else {
1879
+ setError(result.error);
1880
+ }
1881
+ };
1882
+ load();
1883
+ const timer = setInterval(load, intervalMs);
1884
+ return () => {
1885
+ closed = true;
1886
+ clearInterval(timer);
1887
+ };
1888
+ }, [projectDir, tick]);
1889
+ return { pinout, error, reload: () => setTick((value) => value + 1) };
1890
+ }
1891
+
1892
+ /** 构建与烧录:人在面板上直接触发,结果按 stm32_build / stm32_flash 事件进时间线。 */
1893
+ function BuildCard(props) {
1894
+ const [busy, setBusy] = useState("");
1895
+ const [note, setNote] = useState("");
1896
+ const [errors, setErrors] = useState([]);
1897
+ const run = async (path, body, label) => {
1898
+ setBusy(label);
1899
+ setNote(label + "中…这期间页面不要关。");
1900
+ setErrors([]);
1901
+ const result = await callApi("POST", path, body);
1902
+ setBusy("");
1903
+ if (!result.ok) {
1904
+ setNote(result.error);
1905
+ return;
1906
+ }
1907
+ const report = path === "build" ? result.value.build : result.value.flash;
1908
+ setNote(report.message);
1909
+ setErrors(Array.isArray(report.errors) ? report.errors.slice(0, 5) : []);
1910
+ };
1911
+ const projectDir = typeof props.projectDir === "string" ? props.projectDir : "";
1912
+ const disabled = busy !== "" || projectDir === "";
1913
+ const button = (key, label, onClick) =>
1914
+ e(
1915
+ "button",
1916
+ { key: key, type: "button", disabled: disabled, onClick: onClick, style: Object.assign({}, debugStyles.button, disabled ? { opacity: 0.5 } : {}) },
1917
+ label,
1918
+ );
1919
+ return e(
1920
+ "div",
1921
+ { style: { padding: "6px 10px", borderBottom: "1px solid color-mix(in srgb, currentColor 8%, transparent)", fontSize: "12px" } },
1922
+ e(
1923
+ "div",
1924
+ { style: { display: "flex", alignItems: "center", gap: "6px" } },
1925
+ e("span", { style: { flex: "1 1 auto" } }, "构建与烧录"),
1926
+ button("build", "构建", () => run("build", { projectDir: projectDir }, "构建")),
1927
+ button("clean", "清理构建", () => run("build", { projectDir: projectDir, clean: true }, "清理构建")),
1928
+ button("flash", "烧录", () => run("flash", { projectDir: projectDir }, "烧录")),
1929
+ ),
1930
+ note === "" ? null : e("div", { style: { padding: "3px 0 0", opacity: 0.75 } }, note),
1931
+ errors.length === 0 ? null : e("div", { style: { padding: "2px 0 0", opacity: 0.85, fontFamily: "ui-monospace, monospace", whiteSpace: "pre-wrap" } }, errors.join("\n")),
1932
+ e("div", { style: { padding: "3px 0 0", opacity: 0.5, fontSize: "11px" } }, "构建与烧录同时记进时间线;烧录会占用探针,调试会话开着时先关。"),
1933
+ );
1934
+ }
1935
+
1936
+ /** .ioc 与生成代码是否同步:只读两个文件的修改时间,不跑 CubeMX。 */
1937
+ function useIocSync(projectDir, intervalMs) {
1938
+ const [sync, setSync] = useState(null);
1939
+ useEffect(() => {
1940
+ let closed = false;
1941
+ if (typeof projectDir !== "string" || projectDir === "") {
1942
+ setSync(null);
1943
+ return () => {
1944
+ closed = true;
1945
+ };
1946
+ }
1947
+ const load = async () => {
1948
+ const result = await callApi("GET", "ioc-sync?projectDir=" + encodeURIComponent(projectDir));
1949
+ if (closed) return;
1950
+ setSync(result.ok ? result.value.iocSync : null);
1951
+ };
1952
+ load();
1953
+ const timer = setInterval(load, intervalMs);
1954
+ return () => {
1955
+ closed = true;
1956
+ clearInterval(timer);
1957
+ };
1958
+ }, [projectDir]);
1959
+ return sync;
1960
+ }
1961
+
1962
+ /** 监视登记表:与 stm32_watch 共用同一份状态,面板加一项下一次 sample 就读到它。 */
1963
+ function useWatches(intervalMs) {
1964
+ const [watch, setWatch] = useState(null);
1965
+ const [error, setError] = useState("");
1966
+ const [tick, setTick] = useState(0);
1967
+ useEffect(() => {
1968
+ let closed = false;
1969
+ const load = async () => {
1970
+ const result = await callApi("GET", "watch");
1971
+ if (closed) return;
1972
+ if (result.ok) {
1973
+ setWatch(result.value.watch);
1974
+ setError("");
1975
+ } else {
1976
+ setError(result.error);
1977
+ }
1978
+ };
1979
+ load();
1980
+ const timer = setInterval(load, intervalMs);
1981
+ return () => {
1982
+ closed = true;
1983
+ clearInterval(timer);
1984
+ };
1985
+ }, [tick]);
1986
+ return { watch, error, reload: () => setTick((value) => value + 1) };
1987
+ }
1988
+
1989
+ const WATCH_KIND_OPTIONS = [
1990
+ { key: "value", label: "值采样" },
1991
+ { key: "write", label: "写观察点" },
1992
+ { key: "read", label: "读观察点" },
1993
+ { key: "access", label: "读写观察点" },
1994
+ ];
1995
+
1996
+ /** 监视登记表:表达式、类型、最近一次的值,可加可删。 */
1997
+ function WatchAdmin(props) {
1998
+ const state = useWatches(5000);
1999
+ const [expression, setExpression] = useState("");
2000
+ const [kind, setKind] = useState("value");
2001
+ const [note, setNote] = useState("");
2002
+ const post = async (body) => {
2003
+ const result = await callApi("POST", "watch", body);
2004
+ if (!result.ok) setNote(result.error);
2005
+ else {
2006
+ setNote(result.value?.watch?.message ?? "");
2007
+ state.reload();
2008
+ }
2009
+ };
2010
+ const add = () => {
2011
+ const text = expression.trim();
2012
+ if (text === "") return;
2013
+ post({ action: "add", kind: kind, expressions: [text] }).then(() => setExpression(""));
2014
+ };
2015
+ const entries = state.watch?.entries ?? [];
2016
+ const head = e(
2017
+ "div",
2018
+ { style: { display: "flex", alignItems: "center", gap: "6px", padding: "6px 10px 2px" } },
2019
+ e("span", { style: { flex: "1 1 auto", fontSize: "12px" } }, "监视登记表"),
2020
+ e(
2021
+ "span",
2022
+ { style: { fontSize: "11px", opacity: 0.6 }, title: state.watch === null ? state.error : "" },
2023
+ "观察点 " + String(state.watch?.budget?.used ?? 0) + "/" + String(state.watch?.budget?.limit ?? 0),
2024
+ ),
2025
+ e("button", { type: "button", onClick: () => post({ action: "clear" }), style: { fontSize: "11px", padding: "1px 8px" } }, "清空"),
2026
+ );
2027
+ const rows = entries.map((entry) =>
2028
+ e(
2029
+ "div",
2030
+ { key: String(entry.id), style: { display: "flex", alignItems: "center", gap: "6px", padding: "1px 10px", fontSize: "12px" } },
2031
+ e("span", { style: { flex: "0 0 6%", opacity: 0.55, fontVariantNumeric: "tabular-nums" } }, "#" + String(entry.id)),
2032
+ e("span", { style: { flex: "1 1 auto", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, title: entry.lastError }, entry.expression),
2033
+ e("span", { style: { flex: "0 0 auto", opacity: 0.6 } }, entry.kindLabel),
2034
+ e("span", { style: { flex: "0 0 22%", textAlign: "right", opacity: 0.8, fontVariantNumeric: "tabular-nums" } }, entry.lastValue === "" ? "—" : entry.lastValue),
2035
+ e("button", { type: "button", onClick: () => post({ action: "remove", ids: [entry.id] }), style: { fontSize: "11px", padding: "0 6px" } }, "移除"),
2036
+ ),
2037
+ );
2038
+ const form = e(
2039
+ "div",
2040
+ { style: { display: "flex", gap: "6px", padding: "4px 10px 6px" } },
2041
+ e("input", {
2042
+ value: expression,
2043
+ placeholder: "表达式,例如 g_tick_1k 或 *(unsigned int *)0x4001100C",
2044
+ onChange: (event) => setExpression(event.target.value),
2045
+ onKeyDown: (event) => {
2046
+ if (event.key === "Enter") add();
2047
+ },
2048
+ style: Object.assign({}, debugStyles.input, { flex: "1 1 auto" }),
2049
+ }),
2050
+ e(
2051
+ "select",
2052
+ { value: kind, onChange: (event) => setKind(event.target.value), style: { fontSize: "11px" } },
2053
+ WATCH_KIND_OPTIONS.map((option) => e("option", { key: option.key, value: option.key }, option.label)),
2054
+ ),
2055
+ e("button", { type: "button", onClick: add, style: { fontSize: "11px", padding: "1px 8px" } }, "添加"),
2056
+ );
2057
+ return e(
2058
+ "div",
2059
+ { style: { padding: "0 0 4px 0", borderBottom: "1px solid color-mix(in srgb, currentColor 8%, transparent)" } },
2060
+ head,
2061
+ entries.length === 0 ? e("div", { style: { padding: "0 10px 4px", fontSize: "12px", opacity: 0.55 } }, "登记表是空的:加一个表达式后,下一次采样会出现在曲线里。") : rows,
2062
+ form,
2063
+ note === "" ? null : e("div", { style: { padding: "0 10px 4px", fontSize: "11px", opacity: 0.7 } }, note),
2064
+ );
2065
+ }
2066
+
2067
+ const PIN_KIND_LABEL = { gpio: "GPIO", debug: "调试", clock: "时钟", virtual: "虚拟", other: "其它" };
2068
+
2069
+ function PinRow(props) {
2070
+ const pin = props.pin;
2071
+ const parts = [];
2072
+ if (pin.label !== "") parts.push("标号 " + pin.label);
2073
+ if (pin.mode !== "") parts.push(pin.mode);
2074
+ if (pin.signal !== "") parts.push(pin.signal);
2075
+ return e(
2076
+ "div",
2077
+ { style: { display: "flex", gap: "8px", padding: "1px 0", fontSize: "12px" } },
2078
+ e("span", { style: { flex: "0 0 26%", fontVariantNumeric: "tabular-nums" } }, pin.pin),
2079
+ e(
2080
+ "span",
2081
+ { style: { flex: "1 1 auto", opacity: 0.8, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, title: parts.join(" · ") },
2082
+ parts.join(" · ") === "" ? "(未配置)" : parts.join(" · "),
2083
+ ),
2084
+ e("span", { style: { flex: "0 0 auto", opacity: 0.55 } }, PIN_KIND_LABEL[pin.kind] ?? pin.kind),
2085
+ pin.locked === true ? e("span", { style: { flex: "0 0 auto", opacity: 0.55 }, title: "在 CubeMX 里锁定" }, "锁") : null,
2086
+ props.onShowKeys === undefined
2087
+ ? null
2088
+ : e(
2089
+ "button",
2090
+ {
2091
+ type: "button",
2092
+ style: Object.assign({}, debugStyles.button, { flex: "0 0 auto", fontSize: "11px", padding: "0 5px" }),
2093
+ title: "看这个引脚在 .ioc 里的键(只读)",
2094
+ onClick: (ev) => {
2095
+ if (typeof ev.stopPropagation === "function") ev.stopPropagation();
2096
+ props.onShowKeys(pin.pin);
2097
+ },
2098
+ },
2099
+ "ioc",
2100
+ ),
2101
+ );
2102
+ }
2103
+
2104
+ const PIN_PORT_PATTERN = /^P([A-Z])(\d+)$/u;
2105
+
2106
+ /** 按端口把引脚排成小格:一行一个端口,格子里是脚名与信号;用于快速看哪一路占了哪些脚。 */
2107
+ function pinMapRows(pins) {
2108
+ const ports = new Map();
2109
+ for (const pin of pins) {
2110
+ const matched = PIN_PORT_PATTERN.exec(pin.pin);
2111
+ const port = matched === null ? "其它" : "P" + matched[1];
2112
+ const order = matched === null ? 999 : Number(matched[2]);
2113
+ if (!ports.has(port)) ports.set(port, []);
2114
+ ports.get(port).push({ pin: pin, order: order });
2115
+ }
2116
+ return Array.from(ports.keys())
2117
+ .sort((a, b) => (a === "其它" ? 1 : b === "其它" ? -1 : a.localeCompare(b)))
2118
+ .map((port) => ({ port: port, cells: ports.get(port).sort((a, b) => a.order - b.order) }));
2119
+ }
2120
+
2121
+ /**
2122
+ * 按 LQFP 封装把脚位摊到方框四边(S77)。
2123
+ *
2124
+ * 规则:1 脚在左上角,逆时针走——左侧自上而下 1..quarter,下边自左向右,
2125
+ * 右边自下而上,上边自右向左。只依赖 CubeMX db 里的 Position,不猜。
2126
+ */
2127
+ function pinBoxSides(physical) {
2128
+ const count = physical !== null && typeof physical.pinCount === "number" ? physical.pinCount : 0;
2129
+ const quarter = Math.max(1, Math.ceil(count / 4));
2130
+ const byPosition = new Map();
2131
+ for (const item of physical === null || !Array.isArray(physical.positions) ? [] : physical.positions) {
2132
+ if (item !== null && typeof item.position === "number") byPosition.set(item.position, item.pin);
2133
+ }
2134
+ const cell = (position) => ({ position: position, pin: byPosition.get(position) ?? null });
2135
+ const sides = { left: [], bottom: [], right: [], top: [] };
2136
+ for (let position = 1; position <= quarter; position += 1) sides.left.push(cell(position));
2137
+ for (let position = quarter + 1; position <= quarter * 2; position += 1) sides.bottom.push(cell(position));
2138
+ for (let position = quarter * 2 + 1; position <= quarter * 3; position += 1) sides.right.unshift(cell(position));
2139
+ for (let position = quarter * 3 + 1; position <= count; position += 1) sides.top.unshift(cell(position));
2140
+ return sides;
2141
+ }
2142
+
2143
+ /** 物理引脚方框:四边是脚号,格子里是该脚在 .ioc 里的名字;点格子复制引用。 */
2144
+ function PinBox(props) {
2145
+ const physical = props.physical;
2146
+ if (physical === null || physical === undefined || physical.available !== true) {
2147
+ const reason = physical === null || physical === undefined ? "" : physical.reason;
2148
+ return e(
2149
+ "div",
2150
+ { style: { padding: "6px 0", opacity: 0.7, fontSize: "12px" } },
2151
+ reason === "" ? "缺少封装引脚事实:装 CubeMX 后这里按方框显示物理脚位。" : reason,
2152
+ );
2153
+ }
2154
+ const sides = pinBoxSides(physical);
2155
+ const cellView = (item) =>
2156
+ e(
2157
+ "button",
2158
+ {
2159
+ key: String(item.position),
2160
+ type: "button",
2161
+ title: item.pin === null ? "第 " + String(item.position) + " 脚:.ioc 里没有用这个脚" : "第 " + String(item.position) + " 脚 " + item.pin + "(点击复制引用)",
2162
+ style: {
2163
+ minWidth: "46px",
2164
+ padding: "1px 3px",
2165
+ fontSize: "9px",
2166
+ lineHeight: "1.2",
2167
+ textAlign: "center",
2168
+ border: "1px solid color-mix(in srgb, currentColor " + (item.pin === null ? "8%" : "22%") + ", transparent)",
2169
+ borderRadius: "3px",
2170
+ background: item.pin === null ? "transparent" : "color-mix(in srgb, currentColor 6%, transparent)",
2171
+ opacity: item.pin === null ? 0.45 : 1,
2172
+ whiteSpace: "nowrap",
2173
+ overflow: "hidden",
2174
+ textOverflow: "ellipsis",
2175
+ },
2176
+ disabled: item.pin === null,
2177
+ onClick: item.pin === null ? undefined : () => props.onCopy(item.pin),
2178
+ },
2179
+ e("div", { style: { opacity: 0.55, fontSize: "8px" } }, String(item.position)),
2180
+ e("div", {}, item.pin === null ? "—" : item.pin),
2181
+ );
2182
+ const sideRow = (items, key, vertical) =>
2183
+ e(
2184
+ "div",
2185
+ { key: key, style: { display: "flex", flexDirection: vertical ? "column" : "row", gap: "2px", flex: vertical ? "0 0 auto" : "1 1 auto", justifyContent: "center" } },
2186
+ items.map(cellView),
2187
+ );
2188
+ return e(
2189
+ "div",
2190
+ { style: { display: "flex", flexDirection: "column", gap: "4px", padding: "4px 0 8px", fontSize: "11px" } },
2191
+ e("div", { style: { display: "flex", alignItems: "center", gap: "6px" } },
2192
+ e("span", { style: { opacity: 0.6, flex: "0 0 auto" } }, physical.packageName || "封装未知"),
2193
+ sideRow(sides.top, "top", false),
2194
+ ),
2195
+ e("div", { style: { display: "flex", alignItems: "stretch", gap: "6px" } },
2196
+ sideRow(sides.left, "left", true),
2197
+ e(
2198
+ "div",
2199
+ {
2200
+ style: {
2201
+ flex: "1 1 auto",
2202
+ minHeight: "90px",
2203
+ display: "flex",
2204
+ alignItems: "center",
2205
+ justifyContent: "center",
2206
+ border: "1px solid color-mix(in srgb, currentColor 22%, transparent)",
2207
+ borderRadius: "4px",
2208
+ fontSize: "10px",
2209
+ opacity: 0.7,
2210
+ textAlign: "center",
2211
+ },
2212
+ },
2213
+ physical.packageName + " · " + String(physical.pinCount) + " 脚",
2214
+ ),
2215
+ sideRow(sides.right, "right", true),
2216
+ ),
2217
+ e("div", { style: { display: "flex", alignItems: "center", gap: "6px" } },
2218
+ e("span", { style: { opacity: 0.6, flex: "0 0 auto" } }, "1 脚在左上,逆时针"),
2219
+ sideRow(sides.bottom, "bottom", false),
2220
+ ),
2221
+ );
2222
+ }
2223
+
2224
+ function PinMap(props) {
2225
+ const rows = pinMapRows(props.pins);
2226
+ if (rows.length === 0) {
2227
+ return e("div", { style: { padding: "6px 0", opacity: 0.6, fontSize: "12px" } }, "还没有可显示的引脚。");
2228
+ }
2229
+ return e(
2230
+ "div",
2231
+ { style: { display: "flex", flexDirection: "column", gap: "4px", padding: "2px 0 6px" } },
2232
+ rows.map((row) =>
2233
+ e(
2234
+ "div",
2235
+ { key: row.port, style: { display: "flex", alignItems: "center", gap: "6px" } },
2236
+ e("span", { style: { flex: "0 0 34px", fontSize: "11px", opacity: 0.6, fontVariantNumeric: "tabular-nums" } }, row.port),
2237
+ e(
2238
+ "div",
2239
+ { style: { display: "flex", flexWrap: "wrap", gap: "4px" } },
2240
+ row.cells.map((cell) => {
2241
+ const pin = cell.pin;
2242
+ const text = pin.signal !== "" ? pin.signal : pin.label !== "" ? pin.label : pin.mode !== "" ? pin.mode : "";
2243
+ const tone = pin.kind === "debug" ? 0.95 : pin.kind === "gpio" ? 0.7 : 0.5;
2244
+ return e(
2245
+ "button",
2246
+ {
2247
+ key: pin.pin + ":" + pin.signal,
2248
+ type: "button",
2249
+ title: pin.pin + (text === "" ? "" : " " + text) + "(点击复制引用)",
2250
+ onClick: () => props.onCopy(pin),
2251
+ style: {
2252
+ width: "76px",
2253
+ padding: "2px 4px",
2254
+ textAlign: "left",
2255
+ fontSize: "10px",
2256
+ lineHeight: "1.25",
2257
+ borderRadius: "4px",
2258
+ border: "1px solid color-mix(in srgb, currentColor " + String(Math.round(tone * 30)) + "%, transparent)",
2259
+ background: pin.signal === "" ? "transparent" : "color-mix(in srgb, currentColor 6%, transparent)",
2260
+ color: "inherit",
2261
+ cursor: "pointer",
2262
+ overflow: "hidden",
2263
+ },
2264
+ },
2265
+ e("div", { style: { fontWeight: 600, opacity: 0.9 } }, pin.pin),
2266
+ e("div", { style: { opacity: 0.65, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, text === "" ? "未配置" : text),
2267
+ );
2268
+ }),
2269
+ ),
2270
+ ),
2271
+ ),
2272
+ );
2273
+ }
2274
+
2275
+ /** 引脚面板:芯片、时钟与按外设分组的引脚表。只读 .ioc,不触发 CubeMX。 */
2276
+ function PinoutPanel(props) {
2277
+ const projectDir = typeof props.projectDir === "string" ? props.projectDir : "";
2278
+ const state = usePinout(projectDir, 10000);
2279
+ const sync = useIocSync(projectDir, 10000);
2280
+ const pinout = state.pinout;
2281
+ const [copiedPin, setCopiedPin] = useState("");
2282
+ const [mode, setMode] = useState("table");
2283
+ const [pinKeys, setPinKeys] = useState(null);
2284
+ const [needle, setNeedle] = useState("");
2285
+ const showKeys = async (pinName) => {
2286
+ const result = await callApi("GET", "ioc-keys?projectDir=" + encodeURIComponent(projectDir) + "&pin=" + encodeURIComponent(pinName));
2287
+ if (result.ok) setPinKeys({ report: result.value.iocKeys, error: "" });
2288
+ else setPinKeys({ report: null, error: result.error });
2289
+ };
2290
+ const copyPin = async (pin) => {
2291
+ const text = pin.signal === "" ? pin.pin : pin.pin + " " + pin.signal;
2292
+ try {
2293
+ await navigator.clipboard.writeText(text);
2294
+ setCopiedPin(pin.pin);
2295
+ } catch {
2296
+ setCopiedPin("");
2297
+ }
2298
+ };
2299
+ /** 按引脚名、信号名、标号模糊匹配(S53);空白表示不过滤。 */
2300
+ const pinMatches = (pin) => {
2301
+ const wanted = needle.trim().toLowerCase();
2302
+ if (wanted === "") return true;
2303
+ const text = [pin.pin, pin.signal, pin.label ?? ""].join(" ").toLowerCase();
2304
+ return text.includes(wanted);
2305
+ };
2306
+ /* 下面这几项 head 里就要用(导出按钮的可用态、命中计数、分组行),必须先算:
2307
+ 放到 return 前面会触发「Cannot access 'x' before initialization」(S84d)。 */
2308
+ const allGroups = pinout === null || state.error !== "" ? [] : (pinout.groups ?? []);
2309
+ const groups = allGroups
2310
+ .map((group) => Object.assign({}, group, { pins: group.pins.filter(pinMatches) }))
2311
+ .filter((group) => group.pins.length > 0);
2312
+ const totalPins = (pinout === null ? [] : (pinout.pins ?? [])).length;
2313
+ const hitPins = groups.reduce((sum, group) => sum + group.pins.length, 0);
2314
+ const head = [];
2315
+ if (projectDir === "") {
2316
+ head.push(e("div", { key: "no-project", style: { padding: "6px 0", opacity: 0.6 } }, "当前没有可用的工程目录:在工具栏「工程」里选一个,或先打开调试会话。"));
2317
+ } else if (state.error !== "") {
2318
+ head.push(e("div", { key: "error", style: { padding: "6px 0", opacity: 0.75 } }, state.error));
2319
+ } else if (pinout === null) {
2320
+ head.push(e("div", { key: "loading", style: { padding: "6px 0", opacity: 0.6 } }, "读取引脚表…"));
2321
+ } else {
2322
+ const clocks = pinout.clocks ?? {};
2323
+ const mhz = (hz) => (typeof hz === "number" && hz > 0 ? String(Math.round(hz / 1000000)) + " MHz" : "—");
2324
+ head.push(
2325
+ e("div", { key: "head", style: { padding: "4px 0 6px", display: "flex", flexWrap: "wrap", gap: "10px", fontSize: "12px", opacity: 0.85 } },
2326
+ e("span", null, pinout.mcu?.cpn || "未知型号"),
2327
+ e("span", null, "SYSCLK " + mhz(clocks.sysclkHz)),
2328
+ e("span", null, "APB1 " + mhz(clocks.apb1Hz)),
2329
+ e("span", null, "APB2 " + mhz(clocks.apb2Hz)),
2330
+ e("span", null, "中断 " + String(pinout.nvicCount ?? 0)),
2331
+ e("span", null, "引脚 " + String((pinout.pins ?? []).length)),
2332
+ (pinout.debug?.serialWire ?? false) ? e("span", { title: "SWD 可用于烧录与调试" }, "SWD 开") : e("span", { style: { opacity: 0.9 } }, "SWD 关"),
2333
+ e("span", { style: { opacity: 0.55 }, title: "复制形如 PA9 USART1_TX 的引用,可直接贴进对话" }, "点行复制引用"),
2334
+ sync === null
2335
+ ? null
2336
+ : e("span", { title: sync.message, style: sync.stale === true ? { color: D32_WARN } : { opacity: 0.7 } },
2337
+ sync.stale === true ? "待重新生成" : "已同步"),
2338
+ ),
2339
+ );
2340
+ head.push(
2341
+ e("div", { key: "mode", style: { display: "flex", gap: "6px", padding: "0 0 4px" } },
2342
+ e("button", { type: "button", onClick: () => setMode("table"), style: Object.assign({}, debugStyles.button, mode === "table" ? { background: "color-mix(in srgb, currentColor 14%, transparent)" } : {}) }, "表"),
2343
+ e("button", { type: "button", onClick: () => setMode("map"), style: Object.assign({}, debugStyles.button, mode === "map" ? { background: "color-mix(in srgb, currentColor 14%, transparent)" } : {}) }, "图"),
2344
+ e("button", { type: "button", onClick: () => setMode("box"), style: Object.assign({}, debugStyles.button, mode === "box" ? { background: "color-mix(in srgb, currentColor 14%, transparent)" } : {}) }, "方框"),
2345
+ e("input", {
2346
+ value: needle,
2347
+ onChange: (event) => setNeedle(event.target.value),
2348
+ placeholder: "筛选引脚 / 信号 / 标号",
2349
+ style: { fontSize: "11px", padding: "1px 6px", flex: "0 0 34%" },
2350
+ }),
2351
+ e(
2352
+ "button",
2353
+ {
2354
+ type: "button",
2355
+ style: Object.assign({}, debugStyles.button, totalPins === 0 ? { opacity: 0.5 } : {}),
2356
+ disabled: totalPins === 0,
2357
+ title: "导出当前筛选结果的引脚表(CSV,含表头)",
2358
+ onClick: () => exportPinsCsv((pinout === null ? [] : (pinout.pins ?? [])).filter(pinMatches)),
2359
+ },
2360
+ "导出 CSV",
2361
+ ),
2362
+ e("span", { style: { fontSize: "11px", opacity: 0.5, alignSelf: "center" } },
2363
+ needle.trim() === ""
2364
+ ? (mode === "map" ? "按端口排布;点格子复制引用" : mode === "box" ? "按封装脚位排布;点格子复制引用" : "按外设分组")
2365
+ : "命中 " + String(hitPins) + " / " + String(totalPins)),
2366
+ ),
2367
+ );
2368
+ const warnings = pinout.warnings ?? [];
2369
+ if (warnings.length > 0) {
2370
+ head.push(
2371
+ e("div", { key: "warn", style: { padding: "2px 0 6px", fontSize: "12px", opacity: 0.8 } },
2372
+ warnings.slice(0, 3).map((warning, index) => e("div", { key: "w" + String(index) }, "注意:" + warning)),
2373
+ ),
2374
+ );
2375
+ }
2376
+ }
2377
+ return e(
2378
+ "div",
2379
+ { style: { display: "flex", flexDirection: "column", padding: "0 10px 8px" } },
2380
+ head,
2381
+ mode === "map"
2382
+ ? e(PinMap, { key: "map", pins: (pinout === null ? [] : (pinout.pins ?? [])).filter(pinMatches), onCopy: copyPin })
2383
+ : null,
2384
+ mode === "box" ? e(PinBox, { key: "box", physical: pinout === null ? null : pinout.physical, onCopy: copyPin }) : null,
2385
+ mode === "map" || mode === "box"
2386
+ ? null
2387
+ : groups.length === 0 && needle.trim() !== ""
2388
+ ? e("div", { style: { padding: "6px 0", opacity: 0.6 } }, "没有匹配的引脚。")
2389
+ : groups.map((group) =>
2390
+ e(
2391
+ "div",
2392
+ { key: group.name, style: { padding: "4px 0", borderTop: "1px solid color-mix(in srgb, currentColor 8%, transparent)" } },
2393
+ e(
2394
+ "div",
2395
+ { style: { fontSize: "12px", opacity: 0.7, paddingBottom: "2px" } },
2396
+ group.name + "(" + String(group.pins.length) + ")",
2397
+ ),
2398
+ group.pins.map((pin) =>
2399
+ e(PinRow, { key: pin.pin + ":" + pin.signal, pin: pin, copied: copiedPin === pin.pin, onCopy: copyPin, onShowKeys: showKeys }),
2400
+ ),
2401
+ ),
2402
+ ),
2403
+ pinKeys === null
2404
+ ? null
2405
+ : e(
2406
+ "div",
2407
+ {
2408
+ key: "pin-keys",
2409
+ style: {
2410
+ marginTop: "6px",
2411
+ padding: "6px 8px",
2412
+ border: "1px solid color-mix(in srgb, currentColor 12%, transparent)",
2413
+ borderRadius: "6px",
2414
+ fontSize: "11px",
2415
+ fontFamily: "ui-monospace, monospace",
2416
+ maxHeight: "180px",
2417
+ overflow: "auto",
2418
+ },
2419
+ },
2420
+ e(
2421
+ "div",
2422
+ { style: { display: "flex", gap: "8px", alignItems: "baseline", paddingBottom: "4px", fontFamily: "inherit" } },
2423
+ e("span", { style: { opacity: 0.7 } },
2424
+ pinKeys.error !== "" ? "读 .ioc 失败" : "ioc 键 · " + String(pinKeys.report?.pin ?? "") + "(" + String(pinKeys.report?.entries?.length ?? 0) + ")"),
2425
+ e("button", { type: "button", style: Object.assign({}, debugStyles.button, { fontSize: "11px", padding: "0 5px" }), onClick: () => setPinKeys(null) }, "关闭"),
2426
+ ),
2427
+ pinKeys.error !== ""
2428
+ ? e("div", { style: { opacity: 0.8 } }, pinKeys.error)
2429
+ : (pinKeys.report?.entries ?? []).map((entry) =>
2430
+ e("div", { key: entry.key, style: { whiteSpace: "pre-wrap", wordBreak: "break-all" } }, entry.key + "=" + entry.value),
2431
+ ),
2432
+ ),
2433
+ );
2434
+ }
2435
+
2436
+ /** 中断表:读 .ioc 的 NVIC.*,只显示使能状态与两级优先级。 */
2437
+ function useInterrupts(projectDir, intervalMs) {
2438
+ const [report, setReport] = useState(null);
2439
+ const [error, setError] = useState("");
2440
+ useEffect(() => {
2441
+ let closed = false;
2442
+ const load = async () => {
2443
+ const result = await callApi("GET", "interrupts?projectDir=" + encodeURIComponent(projectDir));
2444
+ if (closed) return;
2445
+ if (result.ok) {
2446
+ setReport(result.value.interrupts);
2447
+ setError("");
2448
+ } else {
2449
+ setError(result.error);
2450
+ }
2451
+ };
2452
+ load();
2453
+ const timer = setInterval(load, intervalMs);
2454
+ return () => {
2455
+ closed = true;
2456
+ clearInterval(timer);
2457
+ };
2458
+ }, [projectDir, intervalMs]);
2459
+ return { report, error };
2460
+ }
2461
+
2462
+ function InterruptPanel(props) {
2463
+ const projectDir = typeof props.projectDir === "string" ? props.projectDir : "";
2464
+ const state = useInterrupts(projectDir, 10000);
2465
+ const report = state.report;
2466
+ const [editing, setEditing] = useState("");
2467
+ const [preemptText, setPreemptText] = useState("");
2468
+ const [subText, setSubText] = useState("");
2469
+ const [message, setMessage] = useState("");
2470
+ const [saving, setSaving] = useState(false);
2471
+ const [needle, setNeedle] = useState("");
2472
+ const [order, setOrder] = useState("priority");
2473
+ const [selected, setSelected] = useState([]);
2474
+ const [batchPreempt, setBatchPreempt] = useState("2");
2475
+ const [batchSub, setBatchSub] = useState("0");
2476
+ const [batchSaving, setBatchSaving] = useState(false);
2477
+ const toggleSelect = (name) => {
2478
+ setSelected(selected.includes(name) ? selected.filter((item) => item !== name) : selected.concat([name]));
2479
+ };
2480
+ const applyBatch = async () => {
2481
+ if (selected.length === 0) return;
2482
+ setBatchSaving(true);
2483
+ const result = await callApi("POST", "interrupts/priorities", {
2484
+ projectDir: projectDir,
2485
+ names: selected,
2486
+ preempt: Number(batchPreempt),
2487
+ sub: Number(batchSub),
2488
+ });
2489
+ setBatchSaving(false);
2490
+ if (result.ok) {
2491
+ const report = result.value.interruptPriorities;
2492
+ const skipped = Array.isArray(report.errors) ? report.errors.length : 0;
2493
+ setMessage("批量改了 " + String(report.applied.length) + " 路" + (skipped > 0 ? "(跳过 " + String(skipped) + " 路)" : "") + ":抢 " + String(batchPreempt) + " / 子 " + String(batchSub) + "(已备份)");
2494
+ setSelected([]);
2495
+ state.reload();
2496
+ } else {
2497
+ setMessage("批量改优先级失败:" + result.error);
2498
+ }
2499
+ };
2500
+ const beginEdit = (entry) => {
2501
+ setEditing(entry.name);
2502
+ setPreemptText(String(entry.preempt));
2503
+ setSubText(String(entry.sub));
2504
+ setMessage("");
2505
+ };
2506
+ const saveEdit = async (entry) => {
2507
+ setSaving(true);
2508
+ const result = await callApi("POST", "interrupts/priority", {
2509
+ projectDir: projectDir,
2510
+ name: entry.name,
2511
+ preempt: Number(preemptText),
2512
+ sub: Number(subText),
2513
+ });
2514
+ setSaving(false);
2515
+ if (result.ok) {
2516
+ const written = result.value.interruptPriority;
2517
+ setMessage("已改 " + String(written.name) + ":抢 " + String(written.before.preempt) + " / 子 " + String(written.before.sub) + " → 抢 " + String(written.after.preempt) + " / 子 " + String(written.after.sub) + "(已备份)");
2518
+ setEditing("");
2519
+ state.reload();
2520
+ } else {
2521
+ setMessage("改优先级失败:" + result.error);
2522
+ }
2523
+ };
2524
+ const row = (entry) =>
2525
+ editing === entry.name
2526
+ ? e(
2527
+ "div",
2528
+ { key: entry.name, style: { display: "flex", gap: "4px", padding: "1px 0", fontSize: "12px", alignItems: "center" } },
2529
+ e("span", { style: { flex: "1 1 auto", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, entry.name),
2530
+ e("input", { style: { width: "38px" }, value: preemptText, onChange: (change) => setPreemptText(change.target.value), title: "抢占优先级 0–15" }),
2531
+ e("input", { style: { width: "38px" }, value: subText, onChange: (change) => setSubText(change.target.value), title: "子优先级 0–15" }),
2532
+ e("button", { style: { fontSize: "10px", padding: "1px 6px" }, disabled: saving === true, onClick: () => saveEdit(entry) }, saving === true ? "保存中…" : "保存"),
2533
+ e("button", { style: { fontSize: "10px", padding: "1px 6px" }, disabled: saving === true, onClick: () => setEditing("") }, "取消"),
2534
+ )
2535
+ : e(
2536
+ "div",
2537
+ { key: entry.name, style: { display: "flex", gap: "8px", padding: "1px 0", fontSize: "12px", alignItems: "center" } },
2538
+ e("input", {
2539
+ type: "checkbox",
2540
+ checked: selected.includes(entry.name),
2541
+ onChange: () => toggleSelect(entry.name),
2542
+ title: "选这一路,批量设优先级",
2543
+ }),
2544
+ e("span", { style: { flex: "0 0 46%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, entry.name),
2545
+ e("button", { style: { fontSize: "10px", padding: "1px 6px", opacity: 0.8 }, title: "点这里改这一路的优先级", onClick: () => beginEdit(entry) }, "抢 " + String(entry.preempt) + " / 子 " + String(entry.sub)),
2546
+ e("span", { style: { flex: "0 0 auto", opacity: entry.enabled ? 0.85 : 0.45 } }, entry.enabled ? "开" : "关"),
2547
+ );
2548
+ if (projectDir === "") return e("div", { style: { padding: "6px 10px", opacity: 0.6, fontSize: "12px" } }, "当前没有可用的工程目录:在工具栏「工程」里选一个,或先打开调试会话。");
2549
+ if (state.error !== "") return e("div", { style: { padding: "6px 10px", opacity: 0.75, fontSize: "12px" } }, state.error);
2550
+ if (report === null) return e("div", { style: { padding: "6px 10px", opacity: 0.6, fontSize: "12px" } }, "读取中断表…");
2551
+ const entries = Array.isArray(report.entries) ? report.entries : [];
2552
+ /** 按中断名模糊匹配(S55);空白表示不过滤。 */
2553
+ const wanted = needle.trim().toLowerCase();
2554
+ const filtered = wanted === "" ? entries : entries.filter((entry) => String(entry.name).toLowerCase().includes(wanted));
2555
+ /* 排序只影响显示顺序(S63):服务端给的是「抢占 → 子 → 名字」,按名字排便于找某一路。 */
2556
+ const shown =
2557
+ order === "name"
2558
+ ? filtered.slice().sort((left, right) => String(left.name).localeCompare(String(right.name)))
2559
+ : filtered;
2560
+ return e(
2561
+ "div",
2562
+ { style: { display: "flex", flexDirection: "column", padding: "0 10px 8px" } },
2563
+ e(
2564
+ "div",
2565
+ { style: { padding: "4px 0 6px", fontSize: "12px", opacity: 0.85, display: "flex", gap: "8px", alignItems: "center" } },
2566
+ e("span", null, report.iocName + ":使能 " + String(report.enabledCount) + " / " + String(entries.length) + " 路"),
2567
+ e("span", { style: debugStyles.spacer }),
2568
+ e("input", {
2569
+ value: needle,
2570
+ onChange: (event) => setNeedle(event.target.value),
2571
+ placeholder: "筛选中断名",
2572
+ style: { fontSize: "11px", padding: "1px 6px", flex: "0 0 34%" },
2573
+ }),
2574
+ wanted === "" ? null : e("span", { style: { fontSize: "11px", opacity: 0.55 } }, "命中 " + String(shown.length)),
2575
+ e(
2576
+ "button",
2577
+ {
2578
+ type: "button",
2579
+ style: Object.assign({}, debugStyles.button, order === "priority" ? { fontWeight: 600 } : { opacity: 0.7 }),
2580
+ title: "按抢占优先级排序(默认)",
2581
+ onClick: () => setOrder("priority"),
2582
+ },
2583
+ "按优先级",
2584
+ ),
2585
+ e(
2586
+ "button",
2587
+ {
2588
+ type: "button",
2589
+ style: Object.assign({}, debugStyles.button, order === "name" ? { fontWeight: 600 } : { opacity: 0.7 }),
2590
+ title: "按中断名排序,便于查某一路",
2591
+ onClick: () => setOrder("name"),
2592
+ },
2593
+ "按名字",
2594
+ ),
2595
+ ),
2596
+ selected.length === 0
2597
+ ? null
2598
+ : e(
2599
+ "div",
2600
+ { style: { display: "flex", gap: "6px", alignItems: "center", fontSize: "11px", paddingBottom: "4px" } },
2601
+ e("span", { style: { opacity: 0.7 } }, "已选 " + String(selected.length) + " 路,设为"),
2602
+ e("input", { style: { width: "34px" }, value: batchPreempt, onChange: (change) => setBatchPreempt(change.target.value), title: "抢占优先级 0–15" }),
2603
+ e("span", { style: { opacity: 0.6 } }, "抢"),
2604
+ e("input", { style: { width: "34px" }, value: batchSub, onChange: (change) => setBatchSub(change.target.value), title: "子优先级 0–15" }),
2605
+ e("span", { style: { opacity: 0.6 } }, "子"),
2606
+ e(
2607
+ "button",
2608
+ { type: "button", style: debugStyles.button, disabled: batchSaving === true, onClick: () => applyBatch() },
2609
+ batchSaving === true ? "写入中…" : "批量应用",
2610
+ ),
2611
+ e("button", { type: "button", style: debugStyles.button, disabled: batchSaving === true, onClick: () => setSelected([]) }, "清除选择"),
2612
+ ),
2613
+ message === "" ? null : e("div", { style: { fontSize: "11px", opacity: 0.8, padding: "0 0 4px" } }, message),
2614
+ entries.length === 0
2615
+ ? e("div", { style: { opacity: 0.6, fontSize: "12px" } }, "这个 .ioc 里没有 NVIC 中断配置。")
2616
+ : shown.length === 0
2617
+ ? e("div", { style: { opacity: 0.6, fontSize: "12px" } }, "没有匹配的中断名。")
2618
+ : shown.map(row),
2619
+ );
2620
+ }
2621
+
2622
+ /** 时钟树:读工程 .ioc 里已写下的 RCC 频率;与引脚页同一套刷新口径。 */
2623
+ function useClockTree(projectDir, intervalMs) {
2624
+ const [clocks, setClocks] = useState(null);
2625
+ const [error, setError] = useState("");
2626
+ const [tick, setTick] = useState(0);
2627
+ useEffect(() => {
2628
+ let closed = false;
2629
+ if (typeof projectDir !== "string" || projectDir === "") {
2630
+ setClocks(null);
2631
+ setError("");
2632
+ return () => {
2633
+ closed = true;
2634
+ };
2635
+ }
2636
+ const load = async () => {
2637
+ const result = await callApi("GET", "clocks?projectDir=" + encodeURIComponent(projectDir));
2638
+ if (closed) return;
2639
+ if (result.ok) {
2640
+ setClocks(result.value.clocks);
2641
+ setError("");
2642
+ } else {
2643
+ setError(result.error);
2644
+ }
2645
+ };
2646
+ load();
2647
+ const timer = setInterval(load, intervalMs);
2648
+ return () => {
2649
+ closed = true;
2650
+ clearInterval(timer);
2651
+ };
2652
+ }, [projectDir, tick]);
2653
+ return { clocks, error, reload: () => setTick((value) => value + 1) };
2654
+ }
2655
+
2656
+ /** Hz → MHz 文本;0 与 null 都写成 —。 */
2657
+ function mhzText(hz) {
2658
+ if (typeof hz !== "number" || hz <= 0) return "—";
2659
+ const mhz = hz / 1000000;
2660
+ return (Number.isInteger(mhz) ? String(mhz) : mhz.toFixed(2)) + " MHz";
2661
+ }
2662
+
2663
+ /**
2664
+ * 时钟页:按树顺序画一条横向比例条,一眼看出哪一路被分频压下来。
2665
+ * 比例按最高频归一,不取对数——分频是整数倍,线性更符合直觉。
2666
+ */
2667
+ /** 时钟树层级:按名字把节点挂到父节点下,用于图模式;认不出的节点平铺在最外层。 */
2668
+ function clockFlowRows(nodes) {
2669
+ const find = (pattern) => nodes.find((node) => pattern.test(String(node.label)));
2670
+ const parentOf = (label) => {
2671
+ if (/^PCLK1/u.test(label)) return "SYSCLK";
2672
+ if (/^PCLK2/u.test(label)) return "SYSCLK";
2673
+ if (/^TIM \(APB1\)/u.test(label)) return "PCLK1";
2674
+ if (/^TIM \(APB2\)/u.test(label)) return "PCLK2";
2675
+ if (/^HCLK/u.test(label) || /^Cortex/u.test(label) || /^SysTick/u.test(label) || /^ADC/u.test(label) || /^USB/u.test(label) || /^MCO/u.test(label)) return "SYSCLK";
2676
+ return "";
2677
+ };
2678
+ const byParent = new Map();
2679
+ for (const node of nodes) {
2680
+ const label = String(node.label);
2681
+ const parent = /^SYSCLK/u.test(label) ? "" : parentOf(label);
2682
+ if (!byParent.has(parent)) byParent.set(parent, []);
2683
+ byParent.get(parent).push(node);
2684
+ }
2685
+ for (const list of byParent.values()) {
2686
+ list.sort((a, b) => (typeof b.hz === "number" ? b.hz : 0) - (typeof a.hz === "number" ? a.hz : 0));
2687
+ }
2688
+ const rows = [];
2689
+ const walk = (parent, depth) => {
2690
+ for (const node of byParent.get(parent) ?? []) {
2691
+ rows.push({ node: node, depth: depth });
2692
+ walk(node.label, depth + 1);
2693
+ }
2694
+ };
2695
+ walk("", 0);
2696
+ return rows;
2697
+ }
2698
+
2699
+ /**
2700
+ * 时钟流向图(S38 定义,S76 补回):缩进表示层级,条宽按最高频归一。
2701
+ *
2702
+ * 不画 SVG 连线:窄侧栏里手工排线会压字,层级只有三层,缩进加竖线足够读。
2703
+ */
2704
+ function ClockFlow(props) {
2705
+ const rows = clockFlowRows(Array.isArray(props.nodes) ? props.nodes : []);
2706
+ const peak = typeof props.peak === "number" && props.peak > 0 ? props.peak : 0;
2707
+ if (rows.length === 0) {
2708
+ return e("div", { style: { padding: "6px 0", opacity: 0.6, fontSize: "12px" } }, "没有可画的频率节点。");
2709
+ }
2710
+ return e(
2711
+ "div",
2712
+ { style: { display: "flex", flexDirection: "column", gap: "2px", padding: "4px 0" } },
2713
+ rows.map((row, index) => {
2714
+ const node = row.node;
2715
+ const width = peak > 0 && typeof node.hz === "number" ? Math.max(2, Math.round((node.hz / peak) * 100)) : 0;
2716
+ return e(
2717
+ "div",
2718
+ { key: "flow-" + String(index), style: { display: "flex", gap: "6px", alignItems: "center", paddingLeft: String(row.depth * 16) + "px", fontSize: "12px" } },
2719
+ e("span", { style: { opacity: 0.45 } }, "└"),
2720
+ e(
2721
+ "span",
2722
+ { style: { flex: "0 0 88px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", opacity: row.depth === 0 ? 0.95 : 0.75 }, title: node.key },
2723
+ String(node.label),
2724
+ ),
2725
+ e(
2726
+ "span",
2727
+ { style: { flex: "1 1 auto", height: "6px", borderRadius: "2px", background: "color-mix(in srgb, currentColor 8%, transparent)" } },
2728
+ e("span", {
2729
+ style: { display: "block", height: "100%", width: width + "%", borderRadius: "2px", background: "color-mix(in srgb, currentColor " + (row.depth === 0 ? "50%" : "32%") + ", transparent)" },
2730
+ }),
2731
+ ),
2732
+ e(
2733
+ "span",
2734
+ { style: { flex: "0 0 84px", textAlign: "right", fontVariantNumeric: "tabular-nums", color: node.overLimit === true ? D32_WARN : "inherit", fontWeight: node.overLimit === true ? 600 : 400 } },
2735
+ mhzText(node.hz) + (node.overLimit === true ? " 超" : ""),
2736
+ ),
2737
+ node.overLimit === true && typeof node.suggest === "string" && node.suggest !== ""
2738
+ ? e("span", { style: { flex: "1 1 auto", fontSize: "11px", color: D32_WARN, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }, title: "按手册上限给出的分频建议;改配置仍走 stm32_ioc_plan" }, node.suggest)
2739
+ : null,
2740
+ );
2741
+ }),
2742
+ );
2743
+ }
2744
+
2745
+ function ClockPanel(props) {
2746
+ const projectDir = typeof props.projectDir === "string" ? props.projectDir : "";
2747
+ /* 钩子必须在任何早退之前(S84e):否则「读取中 → 数据到达」那一帧钩子数量变化,
2748
+ React 直接抛错,整块面板变空白。 */
2749
+ const [mode, setMode] = useState("table");
2750
+ const state = useClockTree(projectDir, 10000);
2751
+ const clocks = state.clocks;
2752
+ if (projectDir === "") {
2753
+ return e("div", { style: { padding: "12px", opacity: 0.6, fontSize: "12px" } }, "当前没有可用的工程目录:在工具栏「工程」里选一个,或先打开调试会话。");
2754
+ }
2755
+ if (state.error !== "") {
2756
+ return e("div", { style: { padding: "12px", opacity: 0.75, fontSize: "12px" } }, state.error);
2757
+ }
2758
+ if (clocks === null) {
2759
+ return e("div", { style: { padding: "12px", opacity: 0.6, fontSize: "12px" } }, "读取时钟树…");
2760
+ }
2761
+ const nodes = clocks.nodes ?? [];
2762
+ const peak = nodes.reduce((max, node) => (typeof node.hz === "number" && node.hz > max ? node.hz : max), 0);
2763
+ const row = (node) =>
2764
+ e(
2765
+ "div",
2766
+ { key: node.key, style: { display: "flex", alignItems: "center", gap: "8px", padding: "2px 0", fontSize: "12px" } },
2767
+ e("span", { style: { flex: "0 0 30%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, title: node.key }, node.label),
2768
+ e(
2769
+ "span",
2770
+ { style: { flex: "1 1 auto", height: "8px", background: "color-mix(in srgb, currentColor 8%, transparent)", borderRadius: "2px" } },
2771
+ e("span", {
2772
+ style: {
2773
+ display: "block",
2774
+ height: "100%",
2775
+ width: (peak > 0 && typeof node.hz === "number" ? Math.max(2, Math.round((node.hz / peak) * 100)) : 0) + "%",
2776
+ background: "color-mix(in srgb, currentColor 45%, transparent)",
2777
+ borderRadius: "2px",
2778
+ },
2779
+ }),
2780
+ ),
2781
+ e(
2782
+ "span",
2783
+ {
2784
+ style: {
2785
+ flex: "0 0 84px",
2786
+ textAlign: "right",
2787
+ fontVariantNumeric: "tabular-nums",
2788
+ color: node.overLimit === true ? D32_WARN : "inherit",
2789
+ fontWeight: node.overLimit === true ? 600 : 400,
2790
+ },
2791
+ title: node.overLimit === true ? "超过手册上限 " + mhzText(node.limitHz) : "",
2792
+ },
2793
+ mhzText(node.hz) + (node.overLimit === true ? " 超" : ""),
2794
+ ),
2795
+ e(
2796
+ "span",
2797
+ { style: { flex: "0 0 40px", opacity: 0.6, fontSize: "11px" } },
2798
+ node.limitHz === null || node.limitHz === undefined ? node.divider : node.divider + " 限" + mhzText(node.limitHz),
2799
+ ),
2800
+ node.overLimit === true && typeof node.suggest === "string" && node.suggest !== ""
2801
+ ? e(
2802
+ "span",
2803
+ {
2804
+ style: { flex: "1 1 auto", fontSize: "11px", color: D32_WARN, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" },
2805
+ title: "按手册上限给出的分频建议;改配置仍走 stm32_ioc_plan",
2806
+ },
2807
+ node.suggest,
2808
+ )
2809
+ : null,
2810
+ );
2811
+ return e(
2812
+ "div",
2813
+ { style: { display: "flex", flexDirection: "column", padding: "6px 10px 10px" } },
2814
+ e(
2815
+ "div",
2816
+ { style: { display: "flex", flexWrap: "wrap", gap: "10px", fontSize: "12px", opacity: 0.85, paddingBottom: "6px" } },
2817
+ e("span", null, clocks.cpn || "未知型号"),
2818
+ e("span", null, "SYSCLK ← " + (clocks.sysclkSourceLabel || "—")),
2819
+ e("span", null, "PLL ← " + (clocks.pll?.sourceLabel || "—") + " " + (clocks.pll?.mulLabel || "")),
2820
+ clocks.limits === null || clocks.limits === undefined
2821
+ ? e("span", { style: { opacity: 0.55 }, title: "该族不在总线上限表里,不做超限判断" }, "上限:未收录")
2822
+ : e(
2823
+ "span",
2824
+ { style: { opacity: 0.7 }, title: "来自 clock-db 的总线上限(按芯片族)" },
2825
+ clocks.limits.family + " 上限 APB1 " + mhzText(clocks.limits.apb1Hz) + " · APB2 " + mhzText(clocks.limits.apb2Hz) + " · ADC " + mhzText(clocks.limits.adcHz),
2826
+ ),
2827
+ (nodes.some((node) => node.overLimit === true)
2828
+ ? e("span", { style: { color: D32_WARN, fontWeight: 600 } }, "有 " + String(nodes.filter((node) => node.overLimit === true).length) + " 路超限")
2829
+ : null),
2830
+ e("span", { style: { flex: "1 1 auto" } }),
2831
+ e("button", { type: "button", onClick: () => setMode("table"), style: Object.assign({}, debugStyles.button, mode === "table" ? { background: "color-mix(in srgb, currentColor 14%, transparent)" } : {}) }, "表"),
2832
+ e("button", { type: "button", onClick: () => setMode("flow"), style: Object.assign({}, debugStyles.button, mode === "flow" ? { background: "color-mix(in srgb, currentColor 14%, transparent)" } : {}) }, "图"),
2833
+ ),
2834
+ mode === "flow" ? e(ClockFlow, { key: "flow", nodes: nodes, peak: peak }) : nodes.map(row),
2835
+ (clocks.others ?? []).length > 0
2836
+ ? e(
2837
+ "div",
2838
+ { key: "others", style: { paddingTop: "8px", fontSize: "11px", opacity: 0.6 } },
2839
+ "其它 RCC 频率:" + clocks.others.map((node) => node.label + " " + mhzText(node.hz)).join(";"),
2840
+ )
2841
+ : null,
2842
+ );
2843
+ }
2844
+
2845
+ /** 故障页:读取本会话失败事件的解码结果;进页拉一次,失败事件变化时再刷。 */
2846
+ function useFaults(sessionId, intervalMs) {
2847
+ const [faults, setFaults] = useState(null);
2848
+ const [groups, setGroups] = useState([]);
2849
+ const [error, setError] = useState("");
2850
+ const [tick, setTick] = useState(0);
2851
+ useEffect(() => {
2852
+ let closed = false;
2853
+ const load = async () => {
2854
+ const suffix = typeof sessionId === "string" && sessionId !== "" ? "&session=" + encodeURIComponent(sessionId) : "";
2855
+ const result = await callApi("GET", "faults?limit=100" + suffix);
2856
+ if (closed) return;
2857
+ if (result.ok) {
2858
+ setFaults(result.value.faults ?? []);
2859
+ setGroups(result.value.groups ?? []);
2860
+ setError("");
2861
+ } else {
2862
+ setError(result.error);
2863
+ }
2864
+ };
2865
+ load();
2866
+ const timer = setInterval(load, intervalMs);
2867
+ return () => {
2868
+ closed = true;
2869
+ clearInterval(timer);
2870
+ };
2871
+ }, [sessionId, tick]);
2872
+ return { faults, groups, error, reload: () => setTick((value) => value + 1) };
2873
+ }
2874
+
2875
+ const FAULT_CATEGORY_LABEL = { probe: "探针", target: "目标", build: "编译", flash: "烧录", toolchain: "工具链", network: "网络", debug: "调试", tool: "文件", other: "其它" };
2876
+
2877
+ /** 把当前筛选出的失败事件导成 CSV(S64):表头中文,UTF-8 带 BOM。 */
2878
+ function exportFaultsCsv(rows) {
2879
+ const header = ["序号", "时间", "工具", "分类", "规则", "摘要", "提示"];
2880
+ const body = rows.map((fault) =>
2881
+ [
2882
+ fault.seq,
2883
+ fault.time,
2884
+ fault.kind,
2885
+ FAULT_CATEGORY_LABEL[fault.category] ?? fault.category,
2886
+ fault.rule,
2887
+ fault.summary,
2888
+ fault.hint === "" ? "" : fault.hint,
2889
+ ].map(csvCell).join(","),
2890
+ );
2891
+ const text = "\ufeff" + [header.join(",")].concat(body).join("\r\n") + "\r\n";
2892
+ const blob = new Blob([text], { type: "text/csv;charset=utf-8" });
2893
+ const url = URL.createObjectURL(blob);
2894
+ const link = document.createElement("a");
2895
+ link.href = url;
2896
+ link.download = "stm32-faults-" + new Date().toISOString().replace(/[:.]/gu, "-") + ".csv";
2897
+ document.body.appendChild(link);
2898
+ link.click();
2899
+ document.body.removeChild(link);
2900
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
2901
+ }
2902
+
2903
+ function FaultPanel(props) {
2904
+ const state = useFaults(props.sessionId, 5000);
2905
+ const [category, setCategory] = useState("");
2906
+ const [rule, setRule] = useState("");
2907
+ const [groupNote, setGroupNote] = useState("");
2908
+ if (state.error !== "") {
2909
+ return e("div", { style: { padding: "12px", opacity: 0.75, fontSize: "12px" } }, "读取故障失败:" + state.error);
2910
+ }
2911
+ const faults = state.faults;
2912
+ if (faults === null) {
2913
+ return e("div", { style: { padding: "12px", opacity: 0.6, fontSize: "12px" } }, "读取故障列表…");
2914
+ }
2915
+ if (faults.length === 0) {
2916
+ return e("div", { style: { padding: "12px", opacity: 0.6, fontSize: "12px" } }, "本会话还没有失败事件。");
2917
+ }
2918
+ const counts = new Map();
2919
+ for (const fault of faults) counts.set(fault.category, (counts.get(fault.category) ?? 0) + 1);
2920
+ const byCategory = category === "" ? faults : faults.filter((fault) => fault.category === category);
2921
+ const shown = rule === "" ? byCategory : byCategory.filter((fault) => fault.rule === rule);
2922
+ const chip = (key, label, count) =>
2923
+ e(
2924
+ "button",
2925
+ {
2926
+ key: "fault-chip-" + key,
2927
+ type: "button",
2928
+ onClick: () => setCategory(key),
2929
+ style: Object.assign({}, debugStyles.button, category === key ? { background: "color-mix(in srgb, currentColor 14%, transparent)" } : {}),
2930
+ },
2931
+ label + " " + String(count),
2932
+ );
2933
+ const copyGroup = async (item) => {
2934
+ const text =
2935
+ "[故障组] " + String(item.rule) + " ×" + String(item.count) + "(" + String(item.category) + ")\n" +
2936
+ "提示:" + (item.hint === "" ? "(无匹配提示,按原文判断)" : String(item.hint)) + "\n" +
2937
+ "首见 #" + String(item.firstSeq) + " " + String(item.firstTime) + " · 末见 #" + String(item.lastSeq) + " " + String(item.lastTime);
2938
+ try {
2939
+ await navigator.clipboard.writeText(text);
2940
+ setGroupNote("已复制 " + String(item.rule));
2941
+ } catch {
2942
+ setGroupNote("浏览器没有给剪贴板权限");
2943
+ }
2944
+ };
2945
+ const groupRow = (item) =>
2946
+ e(
2947
+ "div",
2948
+ { key: "fault-group-" + item.rule, style: { display: "flex", gap: "4px", alignItems: "stretch" } },
2949
+ e(
2950
+ "button",
2951
+ {
2952
+ type: "button",
2953
+ title: item.hint === "" ? "命中规则 " + item.rule : item.hint,
2954
+ onClick: () => setRule(rule === item.rule ? "" : item.rule),
2955
+ style: Object.assign({}, debugStyles.button, {
2956
+ display: "flex",
2957
+ gap: "8px",
2958
+ alignItems: "baseline",
2959
+ width: "100%",
2960
+ justifyContent: "flex-start",
2961
+ textAlign: "left",
2962
+ padding: "4px 6px",
2963
+ fontSize: "12px",
2964
+ opacity: rule === "" || rule === item.rule ? 1 : 0.55,
2965
+ background: rule === item.rule ? "color-mix(in srgb, currentColor 14%, transparent)" : "transparent",
2966
+ }),
2967
+ },
2968
+ e("span", { style: { fontVariantNumeric: "tabular-nums", minWidth: "34px" } }, "×" + String(item.count)),
2969
+ e("span", { style: { opacity: 0.8 } }, String(item.rule)),
2970
+ e("span", { style: { marginLeft: "auto", opacity: 0.55 } }, clockText(item.lastTime)),
2971
+ ),
2972
+ e(
2973
+ "button",
2974
+ {
2975
+ type: "button",
2976
+ title: "复制这一组的规则、提示与首末时间,可贴进对话",
2977
+ style: Object.assign({}, debugStyles.button, { fontSize: "10px", padding: "0 5px" }),
2978
+ onClick: () => void copyGroup(item),
2979
+ },
2980
+ "复制",
2981
+ ),
2982
+ );
2983
+ const groupsBlock =
2984
+ state.groups.length === 0
2985
+ ? null
2986
+ : e(
2987
+ "div",
2988
+ { style: { paddingBottom: "4px" } },
2989
+ e(
2990
+ "div",
2991
+ { style: { display: "flex", gap: "8px", alignItems: "baseline", opacity: 0.6, fontSize: "12px", paddingBottom: "2px" } },
2992
+ e("span", {}, "按规则合并(" + String(state.groups.length) + " 组)"),
2993
+ groupNote === "" ? null : e("span", { style: { fontSize: "11px", opacity: 0.55 } }, groupNote),
2994
+ rule === ""
2995
+ ? null
2996
+ : e(
2997
+ "button",
2998
+ { type: "button", onClick: () => setRule(""), style: Object.assign({}, debugStyles.button, { fontSize: "11px", padding: "1px 6px" }) },
2999
+ "清除规则筛选",
3000
+ ),
3001
+ ),
3002
+ state.groups.slice(0, 6).map(groupRow),
3003
+ );
3004
+ return e(
3005
+ "div",
3006
+ { style: { display: "flex", flexDirection: "column", overflow: "auto", padding: "6px 10px 10px" } },
3007
+ groupsBlock,
3008
+ e(
3009
+ "div",
3010
+ { style: { display: "flex", flexWrap: "wrap", gap: "4px", paddingBottom: "6px" } },
3011
+ chip("", "全部", faults.length),
3012
+ Array.from(counts.keys())
3013
+ .sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0) || a.localeCompare(b))
3014
+ .map((key) => chip(key, FAULT_CATEGORY_LABEL[key] ?? key, counts.get(key) ?? 0)),
3015
+ e("span", { style: debugStyles.spacer }),
3016
+ e(
3017
+ "button",
3018
+ {
3019
+ type: "button",
3020
+ style: Object.assign({}, debugStyles.button, shown.length === 0 ? { opacity: 0.5 } : {}),
3021
+ disabled: shown.length === 0,
3022
+ title: "导出当前筛选结果(CSV,含分类、规则与提示)",
3023
+ onClick: () => exportFaultsCsv(shown),
3024
+ },
3025
+ "导出 CSV",
3026
+ ),
3027
+ ),
3028
+ category !== "" && rule !== ""
3029
+ ? e(
3030
+ "div",
3031
+ { style: { padding: "0 0 6px", fontSize: "11px", opacity: 0.7 } },
3032
+ "分类「" + (FAULT_CATEGORY_LABEL[category] ?? category) + "」与规则「" + rule + "」同时生效;",
3033
+ e("button", { type: "button", style: Object.assign({}, debugStyles.button, { fontSize: "11px", padding: "0 6px" }), onClick: () => setRule("") }, "只看分类"),
3034
+ e("button", { type: "button", style: Object.assign({}, debugStyles.button, { fontSize: "11px", padding: "0 6px" }), onClick: () => setCategory("") }, "只看规则"),
3035
+ )
3036
+ : null,
3037
+ shown.length === 0
3038
+ ? e("div", { style: { padding: "6px 0", opacity: 0.6, fontSize: "12px" } }, "这个分类下没有失败事件。")
3039
+ : null,
3040
+ shown
3041
+ .slice()
3042
+ .reverse()
3043
+ .map((fault) =>
3044
+ e(
3045
+ "div",
3046
+ { key: "fault-" + String(fault.seq), style: { padding: "6px 0", borderTop: "1px solid color-mix(in srgb, currentColor 8%, transparent)", fontSize: "12px" } },
3047
+ e(
3048
+ "div",
3049
+ { style: { display: "flex", gap: "8px", alignItems: "baseline" } },
3050
+ e("span", { style: { opacity: 0.55, fontVariantNumeric: "tabular-nums" } }, "#" + String(fault.seq)),
3051
+ e("span", { style: { opacity: 0.75 } }, String(fault.kind)),
3052
+ e(
3053
+ "span",
3054
+ { style: { marginLeft: "auto", padding: "0 6px", borderRadius: "999px", border: "1px solid color-mix(in srgb, currentColor 20%, transparent)", opacity: 0.8 } },
3055
+ FAULT_CATEGORY_LABEL[fault.category] ?? fault.category,
3056
+ ),
3057
+ ),
3058
+ e("div", { style: { opacity: 0.9, paddingTop: "2px" } }, String(fault.summary)),
3059
+ fault.hint === ""
3060
+ ? null
3061
+ : e("div", { style: { opacity: 0.7, paddingTop: "2px" } }, "先看:" + String(fault.hint)),
3062
+ ),
3063
+ ),
3064
+ );
3065
+ }
3066
+
3067
+ /** 产物页:构建目录里的 elf/hex/bin 与芯片容量;10 秒刷新。 */
3068
+ function useArtifacts(projectDir, intervalMs) {
3069
+ const [artifacts, setArtifacts] = useState(null);
3070
+ const [error, setError] = useState("");
3071
+ const [tick, setTick] = useState(0);
3072
+ useEffect(() => {
3073
+ let closed = false;
3074
+ if (typeof projectDir !== "string" || projectDir === "") {
3075
+ setArtifacts(null);
3076
+ setError("");
3077
+ return () => {
3078
+ closed = true;
3079
+ };
3080
+ }
3081
+ const load = async () => {
3082
+ const result = await callApi("GET", "artifacts?projectDir=" + encodeURIComponent(projectDir));
3083
+ if (closed) return;
3084
+ if (result.ok) {
3085
+ setArtifacts(result.value.artifacts);
3086
+ setError("");
3087
+ } else {
3088
+ setError(result.error);
3089
+ }
3090
+ };
3091
+ load();
3092
+ const timer = setInterval(load, intervalMs);
3093
+ return () => {
3094
+ closed = true;
3095
+ clearInterval(timer);
3096
+ };
3097
+ }, [projectDir, tick]);
3098
+ return { artifacts, error, reload: () => setTick((value) => value + 1) };
3099
+ }
3100
+
3101
+ /** 字节数 → 人类可读;产物大小与容量上限共用。 */
3102
+ function bytesText(bytes) {
3103
+ if (typeof bytes !== "number" || !Number.isFinite(bytes) || bytes < 0) return "—";
3104
+ if (bytes >= 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + " MB";
3105
+ if (bytes >= 1024) return (bytes / 1024).toFixed(1) + " KB";
3106
+ return String(bytes) + " B";
3107
+ }
3108
+
3109
+ /**
3110
+ * 最近一次构建的内存占用。
3111
+ * 数据来自 stm32_build 的 ok 事件(payload.result.memoryUsage),不另跑 size:
3112
+ * 构建时链接器已经打印过一次,复用同一份数字才不会出现两个口径。
3113
+ */
3114
+ function collectMemoryUsage(events) {
3115
+ let latest = null;
3116
+ for (const event of events) {
3117
+ if (event.kind !== "stm32_build" || event.status !== "ok") continue;
3118
+ const usage = event.payload?.result?.memoryUsage;
3119
+ if (Array.isArray(usage) && usage.length > 0) latest = { seq: event.seq, time: event.time, usage };
3120
+ }
3121
+ return latest;
3122
+ }
3123
+
3124
+ function MemoryBar(props) {
3125
+ const region = props.region;
3126
+ const percent = typeof region.percent === "number" ? Math.max(0, Math.min(100, region.percent)) : 0;
3127
+ return e(
3128
+ "div",
3129
+ { style: { display: "flex", alignItems: "center", gap: "8px", padding: "2px 0", fontSize: "12px" } },
3130
+ e("span", { style: { flex: "0 0 26%" } }, region.region),
3131
+ e(
3132
+ "span",
3133
+ { style: { flex: "1 1 auto", height: "8px", background: "color-mix(in srgb, currentColor 8%, transparent)", borderRadius: "2px" } },
3134
+ e("span", {
3135
+ style: {
3136
+ display: "block",
3137
+ height: "100%",
3138
+ width: percent + "%",
3139
+ background: "color-mix(in srgb, currentColor 45%, transparent)",
3140
+ borderRadius: "2px",
3141
+ },
3142
+ }),
3143
+ ),
3144
+ e("span", { style: { flex: "0 0 150px", textAlign: "right", fontVariantNumeric: "tabular-nums" } },
3145
+ bytesText(region.usedBytes) + " / " + bytesText(region.totalBytes) + "(" + percent.toFixed(1) + "%)"),
3146
+ );
3147
+ }
3148
+
3149
+ /** 产物页:文件清单 + 最近一次构建的 Flash/RAM 占用。 */
3150
+ /** 最近两次成功构建的 elf 校验和(S68):用来回答「这次和上次是不是同一个文件」。 */
3151
+ function collectBuildShas(events) {
3152
+ const out = [];
3153
+ for (const event of events) {
3154
+ if (event.kind !== "stm32_build" || event.status !== "ok") continue;
3155
+ const sha = event.payload?.result?.elfSha256;
3156
+ if (typeof sha === "string" && sha !== "") out.push({ seq: event.seq, time: event.time, sha: sha });
3157
+ }
3158
+ return out.slice(-2);
3159
+ }
3160
+
3161
+ function ArtifactPanel(props) {
3162
+ const projectDir = typeof props.projectDir === "string" ? props.projectDir : "";
3163
+ const state = useArtifacts(projectDir, 10000);
3164
+ if (projectDir === "") {
3165
+ return e("div", { style: { padding: "12px", opacity: 0.6, fontSize: "12px" } }, "当前没有可用的工程目录:在工具栏「工程」里选一个,或先打开调试会话。");
3166
+ }
3167
+ if (state.error !== "") {
3168
+ return e("div", { style: { padding: "12px", opacity: 0.75, fontSize: "12px" } }, state.error);
3169
+ }
3170
+ const artifacts = state.artifacts;
3171
+ if (artifacts === null) {
3172
+ return e("div", { style: { padding: "12px", opacity: 0.6, fontSize: "12px" } }, "读取产物…");
3173
+ }
3174
+ const memory = collectMemoryUsage(props.events ?? []);
3175
+ const fileRow = (label, file) =>
3176
+ e(
3177
+ "div",
3178
+ { key: label, style: { display: "flex", gap: "8px", fontSize: "12px", padding: "1px 0" } },
3179
+ e("span", { style: { flex: "0 0 52px", opacity: 0.7 } }, label),
3180
+ file === null
3181
+ ? e("span", { style: { opacity: 0.5 } }, "—")
3182
+ : e(
3183
+ "span",
3184
+ { style: { flex: "1 1 auto", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, title: file.path + (file.sha256 === "" ? "" : "\nsha256 " + file.sha256) },
3185
+ file.name + " " + bytesText(file.size) + " " + new Date(file.mtimeMs).toLocaleString() +
3186
+ (file.sha256 === "" ? "" : " · " + file.sha256.slice(0, 12) + "…"),
3187
+ ),
3188
+ );
3189
+ return e(
3190
+ "div",
3191
+ { style: { display: "flex", flexDirection: "column", padding: "6px 10px 10px" } },
3192
+ e(
3193
+ "div",
3194
+ { style: { fontSize: "12px", opacity: 0.8, paddingBottom: "4px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, title: artifacts.buildDir },
3195
+ "构建目录:" + (artifacts.buildDir === "" ? "(未识别)" : artifacts.buildDir),
3196
+ ),
3197
+ fileRow("ELF", artifacts.elf),
3198
+ fileRow("HEX", artifacts.hex),
3199
+ fileRow("BIN", artifacts.bin),
3200
+ e(
3201
+ "div",
3202
+ { style: { paddingTop: "6px", fontSize: "12px", opacity: 0.8 } },
3203
+ "芯片:" + (artifacts.chip === null
3204
+ ? "容量未知"
3205
+ : artifacts.chip.cpn + "(Flash " + bytesText(artifacts.chip.flashBytes) + " / RAM " + bytesText(artifacts.chip.ramBytes) + ")"),
3206
+ ),
3207
+ e(
3208
+ "div",
3209
+ { key: "sha", style: { display: "flex", alignItems: "center", gap: "6px", paddingTop: "4px", fontSize: "12px" } },
3210
+ e("span", { style: { opacity: 0.7 } }, "校验和"),
3211
+ e(
3212
+ "span",
3213
+ { style: { fontFamily: "ui-monospace, monospace", opacity: artifacts.sha256 === "" ? 0.45 : 0.85 }, title: artifacts.sha256 === "" ? "没有 elf,或文件过大未计算" : artifacts.sha256 },
3214
+ artifacts.sha256 === "" ? "—" : artifacts.sha256.slice(0, 16) + "…",
3215
+ ),
3216
+ artifacts.sha256 === ""
3217
+ ? null
3218
+ : e(
3219
+ "button",
3220
+ {
3221
+ style: debugStyles.button,
3222
+ onClick: () => {
3223
+ void navigator.clipboard.writeText(String(artifacts.sha256)).catch(() => undefined);
3224
+ },
3225
+ },
3226
+ "复制",
3227
+ ),
3228
+ ),
3229
+ (() => {
3230
+ const shas = collectBuildShas(props.events ?? []);
3231
+ if (shas.length < 2) {
3232
+ return e("div", { key: "build-diff", style: { paddingTop: "4px", fontSize: "12px", opacity: 0.6 } }, "构建对比:至少要有两次成功构建记录。");
3233
+ }
3234
+ const latest = shas[shas.length - 1];
3235
+ const previous = shas[shas.length - 2];
3236
+ const same = latest.sha === previous.sha;
3237
+ return e(
3238
+ "div",
3239
+ { key: "build-diff", style: { paddingTop: "4px", fontSize: "12px", opacity: 0.85, color: same ? "inherit" : D32_WARN } },
3240
+ (same ? "与上次构建相同(#" : "与上次构建不同(#") + String(previous.seq) + " " + clockText(previous.time) + ")",
3241
+ );
3242
+ })(),
3243
+ memory === null
3244
+ ? e("div", { key: "no-memory", style: { paddingTop: "4px", fontSize: "12px", opacity: 0.6 } }, "还没有构建记录:跑一次 stm32_build 后这里显示 Flash / RAM 占用。")
3245
+ : e(
3246
+ "div",
3247
+ { key: "memory", style: { paddingTop: "4px" } },
3248
+ memory.usage.map((region) => e(MemoryBar, { key: String(region.region), region: region })),
3249
+ ),
3250
+ (artifacts.notes ?? []).length === 0
3251
+ ? null
3252
+ : e(
3253
+ "div",
3254
+ { key: "notes", style: { paddingTop: "6px", fontSize: "11px", opacity: 0.6 } },
3255
+ artifacts.notes.map((note, index) => e("div", { key: "n" + String(index) }, note)),
3256
+ ),
3257
+ );
3258
+ }
3259
+
3260
+ const RTT_LEVEL_LABEL = { 1: "错误", 2: "警告", 3: "信息", 4: "调试" };
3261
+
3262
+ const CHANNEL_DEFS = [
3263
+ { key: "serial", label: "串口" },
3264
+ { key: "rtt", label: "RTT" },
3265
+ { key: "watch", label: "监视" },
3266
+ ];
3267
+
3268
+ /**
3269
+ * 把通道事件按通道名摊平成行尾。
3270
+ *
3271
+ * 通道没有独立序号的必要:面板只需要"最近 N 行",重连时按事件 seq 续播即可。
3272
+ */
3273
+ function collectChannelTails(events) {
3274
+ const tails = {};
3275
+ for (const def of CHANNEL_DEFS) tails[def.key] = [];
3276
+ for (const event of events) {
3277
+ if (typeof event.kind !== "string" || !event.kind.startsWith("channel:")) continue;
3278
+ const name = event.kind.slice("channel:".length);
3279
+ const bucket = tails[name];
3280
+ if (!Array.isArray(bucket)) continue;
3281
+ const lines = event.payload !== null && typeof event.payload === "object" && Array.isArray(event.payload.lines)
3282
+ ? event.payload.lines
3283
+ : [];
3284
+ for (const line of lines) bucket.push(String(line));
3285
+ if (bucket.length > 400) tails[name] = bucket.slice(bucket.length - 400);
3286
+ }
3287
+ return tails;
3288
+ }
3289
+
3290
+ function ChannelBlock(props) {
3291
+ const state = props.state;
3292
+ const lines = props.lines;
3293
+ const [draft, setDraft] = useState("");
3294
+ const [sendMsg, setSendMsg] = useState("");
3295
+ const [history, setHistory] = useState([]);
3296
+ /** 发送成功后把这一行留在历史里,点一下即可重发;只在内存里,刷新页面即清空。 */
3297
+ const remember = (text, message) => {
3298
+ if (text === "" || !message.startsWith("已发送")) return;
3299
+ setHistory((previous) => [{ text: text, at: Date.now() }, ...previous].slice(0, 20));
3300
+ };
3301
+ const send = async () => {
3302
+ if (props.onSend === undefined) return;
3303
+ const text = draft;
3304
+ setSendMsg("发送中…");
3305
+ const message = await props.onSend(text);
3306
+ setSendMsg(message);
3307
+ remember(text, message);
3308
+ if (message.startsWith("已发送")) setDraft("");
3309
+ };
3310
+ const resend = async (text) => {
3311
+ if (props.onSend === undefined) return;
3312
+ setSendMsg("发送中…");
3313
+ const message = await props.onSend(text);
3314
+ setSendMsg(message);
3315
+ remember(text, message);
3316
+ };
3317
+ const pauseAt = typeof state.pauseAt === "number" ? state.pauseAt : lines.length;
3318
+ const clearAt = typeof state.clearAt === "number" ? state.clearAt : 0;
3319
+ const window_ = lines.slice(clearAt, Math.max(clearAt, pauseAt));
3320
+ const paused = typeof state.pauseAt === "number";
3321
+ const [keyword, setKeyword] = useState("");
3322
+ const [level, setLevel] = useState(0);
3323
+ const needle = keyword.trim().toLowerCase();
3324
+ const shown = window_.filter((line) => {
3325
+ if (needle !== "" && !String(line).toLowerCase().includes(needle)) return false;
3326
+ if (level === 0) return true;
3327
+ const matched = /^\[(\d)\]/u.exec(String(line));
3328
+ return matched !== null && Number(matched[1]) === level;
3329
+ });
3330
+ return e(
3331
+ "div",
3332
+ { style: { display: "flex", flexDirection: "column", gap: "4px", padding: "6px 10px", borderBottom: "1px solid color-mix(in srgb, currentColor 8%, transparent)" } },
3333
+ e(
3334
+ "div",
3335
+ { style: { display: "flex", alignItems: "center", gap: "6px" } },
3336
+ e("strong", null, props.label),
3337
+ e("span", { style: { opacity: 0.55 } }, shown.length === window_.length ? String(lines.length) + " 行" : String(shown.length) + " / " + String(window_.length) + " 行"),
3338
+ props.tap === undefined
3339
+ ? null
3340
+ : e(
3341
+ "span",
3342
+ { style: { opacity: 0.7 }, title: props.tap.lastError === "" ? "服务端定时取增量并写入事件流" : props.tap.lastError },
3343
+ props.tap.active ? "常驻开 " + String(props.tap.lines) + " 行" : "常驻关",
3344
+ ),
3345
+ e("span", { style: debugStyles.spacer }),
3346
+ props.tap === undefined
3347
+ ? null
3348
+ : e(
3349
+ "button",
3350
+ { style: debugStyles.button, onClick: () => props.onToggleTap(!props.tap.active) },
3351
+ props.tap.active ? "停常驻" : "开常驻",
3352
+ ),
3353
+ e(
3354
+ "button",
3355
+ {
3356
+ style: Object.assign({}, debugStyles.button, shown.length === 0 ? { opacity: 0.5 } : {}),
3357
+ disabled: shown.length === 0,
3358
+ title: "导出当前显示的 " + String(shown.length) + " 行(含筛选结果)",
3359
+ onClick: () => exportChannelLines(props.channelKey, shown),
3360
+ },
3361
+ "导出",
3362
+ ),
3363
+ e(
3364
+ "button",
3365
+ {
3366
+ style: debugStyles.button,
3367
+ onClick: () => props.onTogglePause(),
3368
+ },
3369
+ paused ? "继续" : "暂停",
3370
+ ),
3371
+ e("button", { style: debugStyles.button, onClick: props.onClear }, "清空"),
3372
+ ),
3373
+ e(
3374
+ "div",
3375
+ { style: { display: "flex", alignItems: "center", gap: "6px", fontSize: "11px" } },
3376
+ e("input", {
3377
+ value: keyword,
3378
+ onChange: (event) => setKeyword(event.target.value),
3379
+ placeholder: "过滤关键字",
3380
+ style: { flex: "0 0 40%", fontSize: "11px", padding: "1px 6px" },
3381
+ }),
3382
+ props.channelKey === "rtt"
3383
+ ? [0, 1, 2, 3, 4].map((value) =>
3384
+ e(
3385
+ "button",
3386
+ {
3387
+ key: "lv" + String(value),
3388
+ style: Object.assign({}, debugStyles.button, level === value ? { fontWeight: 600, opacity: 1 } : { opacity: 0.55 }),
3389
+ onClick: () => setLevel(value),
3390
+ },
3391
+ value === 0 ? "全部" : RTT_LEVEL_LABEL[value],
3392
+ ),
3393
+ )
3394
+ : null,
3395
+ ),
3396
+ history.length === 0 || props.onSend === undefined
3397
+ ? null
3398
+ : e(
3399
+ "div",
3400
+ { style: { display: "flex", flexWrap: "wrap", gap: "4px", alignItems: "center" } },
3401
+ e("span", { style: { fontSize: "11px", opacity: 0.5 } }, "最近发送"),
3402
+ history.map((item, index) =>
3403
+ e(
3404
+ "button",
3405
+ {
3406
+ key: String(item.at) + ":" + String(index),
3407
+ type: "button",
3408
+ title: "重发:" + item.text + "(" + clockText(item.at) + ")",
3409
+ onClick: () => void resend(item.text),
3410
+ style: Object.assign({}, debugStyles.button, { fontSize: "11px", maxWidth: "46%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }),
3411
+ },
3412
+ item.text === "" ? "(空行)" : item.text,
3413
+ ),
3414
+ ),
3415
+ ),
3416
+ props.onSend === undefined
3417
+ ? null
3418
+ : e(
3419
+ "div",
3420
+ { style: { display: "flex", alignItems: "center", gap: "6px" } },
3421
+ e("input", {
3422
+ value: draft,
3423
+ onChange: (event) => setDraft(event.target.value),
3424
+ onKeyDown: (event) => {
3425
+ if (event.key === "Enter") void send();
3426
+ },
3427
+ placeholder: "输入一行,回车发送(空串表示只发换行)",
3428
+ style: { flex: "1 1 auto", fontSize: "12px", padding: "2px 6px" },
3429
+ }),
3430
+ e("button", { style: debugStyles.button, onClick: () => void send() }, "发送"),
3431
+ sendMsg === "" ? null : e("span", { style: { opacity: 0.6, fontSize: "11px" } }, sendMsg),
3432
+ ),
3433
+ shown.length === 0
3434
+ ? e("div", { style: { opacity: 0.5 } }, "暂无输出。")
3435
+ : e("pre", { style: Object.assign({}, debugStyles.pre, { padding: 0, maxHeight: "220px", overflow: "auto" }) }, shown.join("\n")),
3436
+ );
3437
+ }
3438
+
3439
+ /**
3440
+ * 常驻通道状态:串口与 RTT 的服务端 tap 是否在跑。
3441
+ * 开关本身不落 localStorage——它对应真实的轮询任务,重启 DSH 就该回到关闭。
3442
+ */
3443
+ function useChannelTaps(intervalMs) {
3444
+ const [channels, setChannels] = useState([]);
3445
+ const [error, setError] = useState("");
3446
+ const [tick, setTick] = useState(0);
3447
+ useEffect(() => {
3448
+ let closed = false;
3449
+ const load = async () => {
3450
+ const result = await callApi("GET", "channels");
3451
+ if (closed) return;
3452
+ if (result.ok) {
3453
+ setChannels(Array.isArray(result.value?.channels) ? result.value.channels : []);
3454
+ setError("");
3455
+ } else {
3456
+ setError(result.error);
3457
+ }
3458
+ };
3459
+ load();
3460
+ const timer = setInterval(load, intervalMs);
3461
+ return () => {
3462
+ closed = true;
3463
+ clearInterval(timer);
3464
+ };
3465
+ }, [intervalMs, tick]);
3466
+ const toggle = async (name, on) => {
3467
+ const result = await callApi("POST", on ? "channels/start" : "channels/stop", { [name]: true });
3468
+ if (!result.ok) setError(result.error);
3469
+ else if (Array.isArray(result.value?.channels)) setChannels(result.value.channels);
3470
+ setTick((value) => value + 1);
3471
+ };
3472
+ return { channels, error, toggle };
3473
+ }
3474
+
3475
+ /** 监视自动采样:状态与开关。采样结果由同一个事件流带回,面板不另拉数据。 */
3476
+ function useWatchRecording(intervalMs) {
3477
+ const [status, setStatus] = useState(null);
3478
+ const [error, setError] = useState("");
3479
+ const [tick, setTick] = useState(0);
3480
+ useEffect(() => {
3481
+ let closed = false;
3482
+ const load = async () => {
3483
+ const result = await callApi("GET", "watch-recording");
3484
+ if (closed) return;
3485
+ if (result.ok) {
3486
+ setStatus(result.value?.watchRecording ?? null);
3487
+ setError("");
3488
+ } else {
3489
+ setError(result.error);
3490
+ }
3491
+ };
3492
+ load();
3493
+ const timer = setInterval(load, intervalMs);
3494
+ return () => {
3495
+ closed = true;
3496
+ clearInterval(timer);
3497
+ };
3498
+ }, [intervalMs, tick]);
3499
+ const send = async (action) => {
3500
+ const result = await callApi("POST", "watch-recording/" + action, {});
3501
+ if (!result.ok) setError(result.error);
3502
+ else setStatus(result.value?.watchRecording ?? null);
3503
+ setTick((value) => value + 1);
3504
+ };
3505
+ return { status, error, start: () => send("start"), stop: () => send("stop") };
3506
+ }
3507
+
3508
+ /** 面板里发一行串口:走与 stm32_serial 相同的那条桥命令。 */
3509
+ async function sendSerialLine(text) {
3510
+ const result = await callApi("POST", "serial/send", { text });
3511
+ if (!result.ok) return result.error;
3512
+ const serial = result.value?.serial ?? {};
3513
+ return serial.ok === true ? "已发送 " + String(serial.bytes) + " B(" + String(serial.ackMs) + " ms)" : String(serial.message ?? "发送失败");
3514
+ }
3515
+
3516
+ /** 从事件流里算「谁还在跑」:start 未配对 ok/fail 即视为在途,progress 更新阶段。 */
3517
+ function collectRunning(events) {
3518
+ const order = [];
3519
+ const map = new Map();
3520
+ for (const event of events) {
3521
+ const payload = event.payload ?? {};
3522
+ const callId = typeof payload.callId === "string" ? payload.callId : "";
3523
+ if (callId === "") continue;
3524
+ if (event.kind === "progress") {
3525
+ const item = map.get(callId);
3526
+ if (item !== undefined) item.phase = String(payload.phase ?? "");
3527
+ continue;
3528
+ }
3529
+ if (event.status === "start") {
3530
+ if (!map.has(callId)) {
3531
+ map.set(callId, { callId, name: String(event.kind), startedAt: event.time, phase: "" });
3532
+ order.push(callId);
3533
+ }
3534
+ } else if (event.status === "ok" || event.status === "fail") {
3535
+ map.delete(callId);
3536
+ }
3537
+ }
3538
+ return order.filter((callId) => map.has(callId)).map((callId) => map.get(callId));
3539
+ }
3540
+
3541
+ /** 在途调用列表:显示已跑时长与阶段,可逐条请求中止。 */
3542
+ function RunningTools(props) {
3543
+ const [now, setNow] = useState(Date.now());
3544
+ const [message, setMessage] = useState("");
3545
+ const [busy, setBusy] = useState("");
3546
+ useEffect(() => {
3547
+ const timer = setInterval(() => setNow(Date.now()), 1000);
3548
+ return () => clearInterval(timer);
3549
+ }, []);
3550
+ const running = collectRunning(props.events ?? []);
3551
+ const abortOne = async (callId) => {
3552
+ setBusy(callId);
3553
+ const result = await callApi("POST", "abort", { callId });
3554
+ setBusy("");
3555
+ if (result.ok) {
3556
+ const count = result.value?.abort?.count ?? 0;
3557
+ setMessage("已请求中止 " + callId + "(" + String(count) + " 条)");
3558
+ } else {
3559
+ setMessage(result.error);
3560
+ }
3561
+ };
3562
+ const elapsed = (startedAt) => {
3563
+ const start = Date.parse(String(startedAt));
3564
+ if (!Number.isFinite(start)) return "";
3565
+ const ms = Math.max(0, now - start);
3566
+ return (ms / 1000).toFixed(1) + " s";
3567
+ };
3568
+ return e(
3569
+ "div",
3570
+ { style: { display: "flex", flexDirection: "column", gap: "4px" } },
3571
+ e("div", { style: { opacity: 0.7, fontWeight: 600 } }, "在途调用"),
3572
+ running.length === 0
3573
+ ? e("div", { style: { opacity: 0.5 } }, "当前没有在途的工具调用。")
3574
+ : running.map((item) =>
3575
+ e(
3576
+ "div",
3577
+ { key: item.callId, style: { display: "flex", alignItems: "center", gap: "6px", flexWrap: "wrap" } },
3578
+ e("span", { style: { fontFamily: "monospace" } }, item.callId),
3579
+ e("span", null, item.name),
3580
+ e("span", { style: { opacity: 0.7 } }, elapsed(item.startedAt)),
3581
+ item.phase === "" ? null : e("span", { style: { opacity: 0.7 } }, item.phase),
3582
+ e(
3583
+ "button",
3584
+ { style: debugStyles.button, disabled: busy === item.callId, onClick: () => abortOne(item.callId) },
3585
+ busy === item.callId ? "中止中…" : "中止",
3586
+ ),
3587
+ ),
3588
+ ),
3589
+ message === "" ? null : e("div", { style: { opacity: 0.7 } }, message),
3590
+ );
3591
+ }
3592
+
3593
+ /** .ioc 变更页的数据:当前配置与基线的差异,轮询 + 手动刷新。 */
3594
+ function useIocDiff(projectDir, intervalMs) {
3595
+ const [value, setValue] = useState({ diff: null, error: "" });
3596
+ const [tick, setTick] = useState(0);
3597
+ useEffect(() => {
3598
+ let closed = false;
3599
+ const load = async () => {
3600
+ const path = projectDir === "" ? "ioc-diff" : "ioc-diff?projectDir=" + encodeURIComponent(projectDir);
3601
+ const result = await callApi("GET", path);
3602
+ if (closed) return;
3603
+ if (result.ok) setValue({ diff: result.value.diff, error: "" });
3604
+ else setValue({ diff: null, error: result.error });
3605
+ };
3606
+ load();
3607
+ const timer = setInterval(load, intervalMs);
3608
+ return () => {
3609
+ closed = true;
3610
+ clearInterval(timer);
3611
+ };
3612
+ }, [projectDir, intervalMs, tick]);
3613
+ return { diff: value.diff, error: value.error, reload: () => setTick((previous) => previous + 1) };
3614
+ }
3615
+
3616
+ /** 变更页:把当前 .ioc 与基线逐键比较,并把当前配置记成新基线。 */
3617
+ function IocDiffPanel(props) {
3618
+ const projectDir = typeof props.projectDir === "string" ? props.projectDir : "";
3619
+ const state = useIocDiff(projectDir, 10000);
3620
+ const [message, setMessage] = useState("");
3621
+ const [saving, setSaving] = useState(false);
3622
+ const [restoring, setRestoring] = useState("");
3623
+ const [restoringAll, setRestoringAll] = useState(false);
3624
+ const restore = async (key) => {
3625
+ setRestoring(key);
3626
+ const result = await callApi("POST", "ioc-diff/restore", { projectDir: projectDir, key: key });
3627
+ setRestoring("");
3628
+ if (result.ok) {
3629
+ const report = result.value.restored;
3630
+ setMessage("已恢复 " + String(report.key) + ":" + String(report.before) + " → " + String(report.after) + "(已备份 " + String(report.backupPath) + ")");
3631
+ state.reload();
3632
+ } else {
3633
+ setMessage("恢复失败:" + result.error);
3634
+ }
3635
+ };
3636
+ const restoreAll = async () => {
3637
+ setRestoringAll(true);
3638
+ const result = await callApi("POST", "ioc-diff/restore-all", { projectDir: projectDir });
3639
+ setRestoringAll(false);
3640
+ if (result.ok) {
3641
+ const report = result.value.restoredAll;
3642
+ const count = Array.isArray(report.restored) ? report.restored.length : 0;
3643
+ setMessage(count === 0 ? "没有需要恢复的键。" : "已恢复 " + String(count) + " 个键(已备份 " + String(report.backupPath) + ")");
3644
+ state.reload();
3645
+ } else {
3646
+ setMessage("批量恢复失败:" + result.error);
3647
+ }
3648
+ };
3649
+ const save = async () => {
3650
+ setSaving(true);
3651
+ const result = await callApi("POST", "ioc-diff/save", { projectDir: projectDir });
3652
+ setSaving(false);
3653
+ if (result.ok) {
3654
+ setMessage("已记下基线:" + String(result.value.snapshot.savedAt) + "(" + String(result.value.snapshot.entries) + " 个键)");
3655
+ state.reload();
3656
+ } else {
3657
+ setMessage("记录基线失败:" + result.error);
3658
+ }
3659
+ };
3660
+ if (state.error !== "") return e("div", { style: debugStyles.empty }, state.error);
3661
+ const diff = state.diff;
3662
+ if (diff === null) return e("div", { style: debugStyles.empty }, "读取 .ioc 中…");
3663
+ const line = (key, text, canRestore) =>
3664
+ e(
3665
+ "div",
3666
+ { key: key, style: { display: "flex", gap: "6px", alignItems: "center" } },
3667
+ e(
3668
+ "span",
3669
+ { style: { flex: "1 1 auto", fontFamily: "ui-monospace, monospace", fontSize: "11px", opacity: 0.85, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, title: text },
3670
+ text,
3671
+ ),
3672
+ canRestore === true
3673
+ ? e(
3674
+ "button",
3675
+ { style: { fontSize: "10px", padding: "1px 6px" }, disabled: restoring !== "", onClick: () => restore(key) },
3676
+ restoring === key ? "恢复中…" : "恢复",
3677
+ )
3678
+ : null,
3679
+ );
3680
+ const section = (title, rows) =>
3681
+ e(
3682
+ "div",
3683
+ { key: title, style: { display: "flex", flexDirection: "column", gap: "1px", padding: "4px 0" } },
3684
+ e("div", { style: { fontSize: "12px", opacity: 0.7 } }, title + "(" + String(rows.length) + ")"),
3685
+ rows.length === 0 ? e("div", { style: { fontSize: "11px", opacity: 0.5 } }, "无") : rows,
3686
+ );
3687
+ return e(
3688
+ "div",
3689
+ { style: { display: "flex", flexDirection: "column", gap: "2px", padding: "8px 10px" } },
3690
+ e(
3691
+ "div",
3692
+ { style: { display: "flex", gap: "8px", alignItems: "center", fontSize: "12px" } },
3693
+ e("span", { style: { opacity: 0.7 } }, diff.iocName),
3694
+ e("span", { style: debugStyles.spacer }),
3695
+ e(
3696
+ "button",
3697
+ {
3698
+ style: Object.assign({}, debugStyles.button, diff.counts.removed + diff.counts.changed === 0 ? { opacity: 0.5 } : {}),
3699
+ disabled: saving === true || restoringAll === true || diff.counts.removed + diff.counts.changed === 0,
3700
+ title: "把「删除」「改动」的键都写回基线值;整批只备份一次。新增的键不动。",
3701
+ onClick: restoreAll,
3702
+ },
3703
+ restoringAll === true ? "恢复中…" : "全部恢复",
3704
+ ),
3705
+ e("button", { style: debugStyles.button, disabled: saving === true, onClick: save }, saving === true ? "记录中…" : "记下当前配置"),
3706
+ ),
3707
+ diff.hasSnapshot === false
3708
+ ? e("div", { style: { fontSize: "12px", opacity: 0.75 } }, diff.notes.join(";"))
3709
+ : e("div", { style: { fontSize: "11px", opacity: 0.6 } }, "基线 " + diff.savedAt + " · 新增 " + String(diff.counts.added) + " · 删除 " + String(diff.counts.removed) + " · 改动 " + String(diff.counts.changed)),
3710
+ message === "" ? null : e("div", { style: { fontSize: "11px", opacity: 0.8 } }, message),
3711
+ section("新增", diff.added.map((entry) => line(entry.key, "+ " + entry.key + "=" + entry.value, false))),
3712
+ section("删除", diff.removed.map((entry) => line(entry.key, "- " + entry.key + "=" + entry.value, true))),
3713
+ section("改动", diff.changed.map((entry) => line(entry.key, "~ " + entry.key + ":" + entry.before + " → " + entry.after, true))),
3714
+ );
3715
+ }
3716
+
3717
+ /** 最近一次某类工具的成功事件,用于概览里的「上次构建 / 上次烧录」。 */
3718
+ function lastEventOf(events, kind) {
3719
+ for (let index = events.length - 1; index >= 0; index -= 1) {
3720
+ const event = events[index];
3721
+ if (event.kind === kind && event.status === "ok") return event;
3722
+ }
3723
+ return null;
3724
+ }
3725
+
3726
+ /** 概览:把型号、时钟、容量与会话状态压成一屏,先看这里再看细节页。 */
3727
+ /** 工具链探测摘要:概览页只读用它,60 秒一次;探测本身会跑版本命令,不能太勤。 */
3728
+ function useProbeSummary(intervalMs) {
3729
+ const [summary, setSummary] = useState(null);
3730
+ useEffect(() => {
3731
+ let closed = false;
3732
+ const load = async () => {
3733
+ const result = await callApi("GET", "probe");
3734
+ if (!closed && result.ok) setSummary(result.value.summary);
3735
+ };
3736
+ load();
3737
+ const timer = setInterval(load, intervalMs);
3738
+ return () => {
3739
+ closed = true;
3740
+ clearInterval(timer);
3741
+ };
3742
+ }, [intervalMs]);
3743
+ return summary;
3744
+ }
3745
+
3746
+ /** 能力四项一行:编译 / 烧录 / 调试 / 生成,缺哪项一眼能看出。 */
3747
+ function capabilitiesText(capabilities) {
3748
+ if (capabilities === null || capabilities === undefined) return "—";
3749
+ const marks = [
3750
+ ["编译", capabilities.build === true],
3751
+ ["烧录", capabilities.flash === true],
3752
+ ["调试", capabilities.debug === true],
3753
+ ["生成", capabilities.generate === true],
3754
+ ];
3755
+ return marks.map((pair) => pair[0] + (pair[1] ? " ✓" : " ✗")).join(" ");
3756
+ }
3757
+
3758
+ function OverviewPanel(props) {
3759
+ const projectDir = typeof props.projectDir === "string" ? props.projectDir : "";
3760
+ const pinout = usePinout(projectDir, 10000);
3761
+ const clocks = useClockTree(projectDir, 10000);
3762
+ const artifacts = useArtifacts(projectDir, 10000);
3763
+ const probe = useProbeSummary(60000);
3764
+ const evidence = useEvidence(true);
3765
+ const memory = collectMemoryUsage(props.events ?? []);
3766
+ const runningNow = collectRunning(props.events ?? []);
3767
+ const build = lastEventOf(props.events ?? [], "stm32_build");
3768
+ const flash = lastEventOf(props.events ?? [], "stm32_flash");
3769
+ const failed = (props.events ?? []).filter((event) => event.status === "fail").length;
3770
+ const chips = [];
3771
+ chips.push([
3772
+ "操作记录",
3773
+ "导出 Markdown",
3774
+ () => exportSummary(props.events ?? [], { projectDir: projectDir, counts: kindCounts(props.events ?? [], 8) }),
3775
+ ]);
3776
+ if (projectDir === "") {
3777
+ chips.push(["工程", "未绑定:先打开调试会话"]);
3778
+ } else {
3779
+ chips.push(["工程", projectDir]);
3780
+ }
3781
+ const mcu = pinout.pinout?.mcu;
3782
+ chips.push(["型号", mcu === undefined || mcu === null ? "—" : (mcu.cpn ?? "—") + (mcu.package ? " / " + mcu.package : "")]);
3783
+ const sysclk = (clocks.clocks?.nodes ?? []).find((node) => node.label === "SYSCLK");
3784
+ chips.push(["SYSCLK", sysclk === undefined ? "—" : mhzText(sysclk.hz)]);
3785
+ const chip = artifacts.artifacts?.chip ?? null;
3786
+ chips.push(["容量", chip === null ? "—" : "Flash " + bytesText(chip.flashBytes) + " / RAM " + bytesText(chip.ramBytes)]);
3787
+ const debug = props.debug ?? null;
3788
+ chips.push([
3789
+ "会话",
3790
+ debug === null
3791
+ ? "—"
3792
+ : debug.active === true
3793
+ ? "进行中 · " + (debug.sessionId ?? "") + " · 剩 " + Math.max(0, Math.round((debug.remainingMs ?? 0) / 1000)) + " s"
3794
+ : "空闲",
3795
+ ]);
3796
+ chips.push([
3797
+ "工具链",
3798
+ probe === null
3799
+ ? "—"
3800
+ : (probe.ok === true ? "就绪" : "缺 " + (probe.missingRequired ?? []).join("、")) +
3801
+ " · " + String((probe.tools ?? []).filter((tool) => tool.found === true).length) + "/" + String((probe.tools ?? []).length) +
3802
+ " 项 · " + capabilitiesText(probe.capabilities),
3803
+ ]);
3804
+ const evidenceUsage = evidence.usage ?? null;
3805
+ chips.push([
3806
+ "证据",
3807
+ evidenceUsage === null
3808
+ ? "—"
3809
+ : String(evidenceUsage.count) + " 个 · " + bytesText(evidenceUsage.bytes),
3810
+ ]);
3811
+ const lastEvent = (props.events ?? [])[(props.events ?? []).length - 1] ?? null;
3812
+ chips.push(["最近事件", lastEvent === null ? "—" : clockText(lastEvent.time) + " · #" + String(lastEvent.seq)]);
3813
+ /* 告警摘要(S69):在途与失败合成一行,先说「现在有没有事要处理」。 */
3814
+ const warnParts = [];
3815
+ if (runningNow.length > 0) warnParts.push("在途 " + String(runningNow.length) + " 个 · " + runningNow.slice(0, 2).map((item) => item.name).join("、") + (runningNow.length > 2 ? " 等" : ""));
3816
+ if (failed > 0) warnParts.push("失败 " + String(failed) + " 条");
3817
+ const warnText = warnParts.length === 0 ? "无:没有在途调用,也没有失败事件" : warnParts.join(" · ");
3818
+ const warnClick =
3819
+ failed > 0 && typeof props.onShowFailures === "function"
3820
+ ? props.onShowFailures
3821
+ : runningNow.length > 0 && typeof props.onShowChannels === "function"
3822
+ ? props.onShowChannels
3823
+ : undefined;
3824
+ if (warnClick === undefined) chips.unshift(["告警", warnText]);
3825
+ else chips.unshift(["告警", warnText + (failed > 0 ? "(点这里只看失败)" : "(点这里看实时通道)"), warnClick]);
3826
+ chips.push(["上次构建", build === null ? "—" : clockText(build.time)]);
3827
+ chips.push(["上次烧录", flash === null ? "—" : clockText(flash.time)]);
3828
+ return e(
3829
+ "div",
3830
+ { style: { display: "flex", flexDirection: "column", gap: "2px", padding: "8px 10px" } },
3831
+ chips.map((pair) =>
3832
+ (typeof pair[2] === "function" || (pair[0] === "失败事件" && failed > 0 && typeof props.onShowFailures === "function"))
3833
+ ? e(
3834
+ "button",
3835
+ {
3836
+ key: pair[0],
3837
+ type: "button",
3838
+ title: pair[0] === "告警" ? "跳到实时通道处理告警" : pair[0] === "在途" ? "跳到实时通道看正在跑的调用" : "跳到实时通道,只看失败事件",
3839
+ onClick: () => (typeof pair[2] === "function" ? pair[2]() : props.onShowFailures()),
3840
+ style: {
3841
+ display: "flex",
3842
+ gap: "8px",
3843
+ fontSize: "12px",
3844
+ padding: "1px 0",
3845
+ background: "transparent",
3846
+ border: "none",
3847
+ color: "inherit",
3848
+ textAlign: "left",
3849
+ cursor: "pointer",
3850
+ },
3851
+ },
3852
+ e("span", { style: { flex: "0 0 68px", opacity: 0.65 } }, pair[0]),
3853
+ e(
3854
+ "span",
3855
+ { style: { flex: "1 1 auto", textDecoration: "underline" } },
3856
+ pair[0] === "告警" || pair[0] === "在途" ? pair[1] : pair[1] + "(点这里只看失败)",
3857
+ ),
3858
+ )
3859
+ : e(
3860
+ "div",
3861
+ { key: pair[0], style: { display: "flex", gap: "8px", fontSize: "12px", padding: "1px 0" } },
3862
+ e("span", { style: { flex: "0 0 68px", opacity: 0.65 } }, pair[0]),
3863
+ e("span", { style: { flex: "1 1 auto", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, title: pair[1] }, pair[1]),
3864
+ ),
3865
+ ),
3866
+ memory === null
3867
+ ? null
3868
+ : e("div", { key: "memory", style: { paddingTop: "4px" } }, memory.usage.map((region) => e(MemoryBar, { key: String(region.region), region: region }))),
3869
+ );
3870
+ }
3871
+
3872
+ function useSerialState(intervalMs) {
3873
+ const [state, setState] = useState({ serial: null, error: "" });
3874
+ const [tick, setTick] = useState(0);
3875
+ useEffect(() => {
3876
+ let alive = true;
3877
+ const load = async () => {
3878
+ const result = await callApi("GET", "serial");
3879
+ if (!alive) return;
3880
+ if (!result.ok) setState({ serial: null, error: result.error });
3881
+ else setState({ serial: result.value?.serial ?? null, error: "" });
3882
+ };
3883
+ load();
3884
+ const timer = setInterval(load, intervalMs);
3885
+ return () => {
3886
+ alive = false;
3887
+ clearInterval(timer);
3888
+ };
3889
+ }, [intervalMs, tick]);
3890
+ return { serial: state.serial, error: state.error, reload: () => setTick((n) => n + 1) };
3891
+ }
3892
+
3893
+ /** 探针信息:30 秒一次(USB 枚举走 pnputil,别跟会话状态同频)。 */
3894
+ function useProbeInfo(intervalMs) {
3895
+ const [info, setInfo] = useState(null);
3896
+ const [error, setError] = useState("");
3897
+ const [tick, setTick] = useState(0);
3898
+ useEffect(() => {
3899
+ let alive = true;
3900
+ const load = async () => {
3901
+ const result = await callApi("GET", "probe-info");
3902
+ if (!alive) return;
3903
+ if (!result.ok) {
3904
+ setInfo(null);
3905
+ setError(result.error);
3906
+ return;
3907
+ }
3908
+ setInfo(result.value?.probeInfo ?? null);
3909
+ setError("");
3910
+ };
3911
+ load();
3912
+ const timer = setInterval(load, intervalMs);
3913
+ return () => {
3914
+ alive = false;
3915
+ clearInterval(timer);
3916
+ };
3917
+ }, [intervalMs, tick]);
3918
+ return { info: info, error: error, reload: () => setTick((n) => n + 1) };
3919
+ }
3920
+
3921
+ /** 探针信息卡:类型 / VID:PID / 序列号 / 位置 / 走哪份 interface 配置。 */
3922
+ function ProbeCard(props) {
3923
+ const state = useProbeInfo(30_000);
3924
+ const info = state.info;
3925
+ const line = (label, value) =>
3926
+ e(
3927
+ "div",
3928
+ { key: "probe-" + label, style: { display: "flex", gap: "8px", fontSize: "12px", padding: "1px 0" } },
3929
+ e("span", { style: { flex: "0 0 64px", opacity: 0.65 } }, label),
3930
+ e("span", { style: { flex: "1 1 auto", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontFamily: "ui-monospace" }, title: String(value) }, String(value)),
3931
+ );
3932
+ const body =
3933
+ state.error !== ""
3934
+ ? e("div", { style: { fontSize: "12px", opacity: 0.75 } }, "读取探针信息失败:" + state.error)
3935
+ : info === null
3936
+ ? e("div", { style: { fontSize: "12px", opacity: 0.6 } }, "读取探针信息…")
3937
+ : info.present === false
3938
+ ? e(
3939
+ "div",
3940
+ { style: { fontSize: "12px", opacity: 0.75 } },
3941
+ "没看到 SWD 探针(ST-LINK / J-Link / CMSIS-DAP / DAPLink)。" + (info.others.length > 0 ? "其它 USB 设备:" + info.others.slice(0, 3).join("、") : ""),
3942
+ )
3943
+ : e(
3944
+ "div",
3945
+ { style: { display: "flex", flexDirection: "column" } },
3946
+ line("类型", info.probe.label),
3947
+ line("序列号", info.probe.serial === "" ? "—" : info.probe.serial),
3948
+ line("位置", info.probe.location === "" ? "—" : info.probe.location),
3949
+ line("接口", info.interfaceCfg),
3950
+ );
3951
+ return e(
3952
+ "div",
3953
+ { style: { padding: "6px 10px", border: "1px solid color-mix(in srgb, currentColor 14%, transparent)", borderRadius: "8px", display: "flex", flexDirection: "column", gap: "4px" } },
3954
+ e(
3955
+ "div",
3956
+ { style: { display: "flex", alignItems: "center", gap: "8px", fontSize: "12px", fontWeight: 600 } },
3957
+ e("span", null, "探针"),
3958
+ e("span", { style: { flex: "1 1 auto" } }),
3959
+ e("button", { type: "button", onClick: state.reload, style: debugStyles.button }, "刷新"),
3960
+ ),
3961
+ body,
3962
+ );
3963
+ }
3964
+
3965
+ function SerialCard(props) {
3966
+ const [port, setPort] = useState("");
3967
+ const [baudRate, setBaudRate] = useState("115200");
3968
+ const [ports, setPorts] = useState([]);
3969
+ const [note, setNote] = useState("");
3970
+ const serial = props.serial ?? null;
3971
+ const open = serial !== null && serial.open === true;
3972
+ // 串口开着时把当前参数回填到输入框,省得改完参数还得手抄一遍端口号。
3973
+ // 只在输入框为空时回填:不覆盖用户已经敲了一半的内容。
3974
+ useEffect(() => {
3975
+ if (serial === null || serial.open !== true) return;
3976
+ setPort((current) => (current.trim() === "" ? String(serial.port ?? "") : current));
3977
+ setBaudRate((current) => (current.trim() === "" || current === "115200" ? String(serial.baudRate ?? current) : current));
3978
+ }, [open === true ? serial.port + ":" + String(serial.baudRate) : ""]);
3979
+ const statusText = open
3980
+ ? serial.port + " · " + String(serial.baudRate) + " 8N1 · 桥 " + String(serial.bridgePid) + (serial.bridgeAlive ? "(活)" : "(已退)")
3981
+ : "未打开";
3982
+ const refreshPorts = async () => {
3983
+ const result = await callApi("GET", "serial/ports");
3984
+ if (!result.ok) {
3985
+ setNote(result.error);
3986
+ return;
3987
+ }
3988
+ setPorts(result.value?.serialPorts?.ports ?? []);
3989
+ setNote("可用端口 " + String((result.value?.serialPorts?.ports ?? []).length) + " 个");
3990
+ };
3991
+ const doOpen = async () => {
3992
+ const baud = Number(baudRate);
3993
+ const body = {};
3994
+ if (port.trim() !== "") body.port = port.trim();
3995
+ if (Number.isFinite(baud) && baud > 0) body.baudRate = baud;
3996
+ const result = await callApi("POST", "serial/open", body);
3997
+ setNote(result.ok ? String(result.value?.serial?.message ?? "") : result.error);
3998
+ if (result.ok) props.onChanged();
3999
+ };
4000
+ const doClose = async () => {
4001
+ const result = await callApi("POST", "serial/close", {});
4002
+ setNote(result.ok ? String(result.value?.serial?.message ?? "") : result.error);
4003
+ if (result.ok) props.onChanged();
4004
+ };
4005
+ return e(
4006
+ "div",
4007
+ {
4008
+ style: {
4009
+ display: "flex",
4010
+ flexDirection: "column",
4011
+ gap: "2px",
4012
+ padding: "6px 10px",
4013
+ border: "1px solid color-mix(in srgb, currentColor 14%, transparent)",
4014
+ borderRadius: "8px",
4015
+ },
4016
+ },
4017
+ e(
4018
+ "div",
4019
+ { style: { display: "flex", alignItems: "baseline", gap: "8px", flexWrap: "wrap" } },
4020
+ e("span", { style: { fontWeight: 600 } }, "串口"),
4021
+ e("span", { style: { opacity: 0.75 } }, statusText),
4022
+ e("span", { style: { flex: 1 } }),
4023
+ e("button", { type: "button", style: debugStyles.button, onClick: refreshPorts }, "刷新端口"),
4024
+ e("button", { type: "button", style: debugStyles.button, onClick: doOpen }, "打开"),
4025
+ e("button", { type: "button", style: debugStyles.button, onClick: doClose, disabled: !open }, "关闭"),
4026
+ ),
4027
+ e(
4028
+ "div",
4029
+ { style: { display: "flex", alignItems: "center", gap: "6px", flexWrap: "wrap", marginTop: "6px" } },
4030
+ e("input", {
4031
+ value: port,
4032
+ placeholder: ports.length > 0 ? ports.map((item) => item.port).join(" / ") : "COM3",
4033
+ onChange: (event) => setPort(event.target.value),
4034
+ style: debugStyles.input,
4035
+ }),
4036
+ e("input", {
4037
+ value: baudRate,
4038
+ placeholder: "115200",
4039
+ onChange: (event) => setBaudRate(event.target.value),
4040
+ style: Object.assign({}, debugStyles.input, { minWidth: "92px", width: "92px" }),
4041
+ }),
4042
+ open
4043
+ ? e(
4044
+ "button",
4045
+ {
4046
+ type: "button",
4047
+ style: Object.assign({}, debugStyles.button, { fontSize: "10px", padding: "1px 6px" }),
4048
+ title: "把当前会话的端口与波特率填回输入框",
4049
+ onClick: () => {
4050
+ setPort(String(serial.port ?? ""));
4051
+ setBaudRate(String(serial.baudRate ?? "115200"));
4052
+ setNote("已回填当前参数");
4053
+ },
4054
+ },
4055
+ "回填",
4056
+ )
4057
+ : null,
4058
+ ),
4059
+ props.error ? e("div", { style: { color: "#c0392b", marginTop: "4px" } }, String(props.error)) : null,
4060
+ note === "" ? null : e("div", { style: { opacity: 0.75, marginTop: "4px" } }, note),
4061
+ );
4062
+ }
4063
+
4064
+ function Channels(props) {
4065
+ const [view, setView] = useState({});
4066
+ const [tab, setTab] = useState("channels");
4067
+ useEffect(() => {
4068
+ if (typeof props.focusFailures === "number" && props.focusFailures > 0) setTab("channels");
4069
+ }, [props.focusFailures]);
4070
+ const debugInfo = useDebugStatus(5000);
4071
+ const [touchMessage, setTouchMessage] = useState("");
4072
+ const touchSession = async () => {
4073
+ const result = await callApi("POST", "debug/touch", {});
4074
+ if (!result.ok) setTouchMessage(result.error);
4075
+ else {
4076
+ setTouchMessage("已续期,剩余 " + String(Math.ceil(Number(result.value?.debug?.remainingMs ?? 0) / 1000)) + " s");
4077
+ debugInfo.reload();
4078
+ }
4079
+ };
4080
+ const closeSession = async () => {
4081
+ const result = await callApi("POST", "debug/stop", {});
4082
+ if (!result.ok) {
4083
+ setTouchMessage("关闭失败:" + result.error);
4084
+ return "关闭失败:" + result.error;
4085
+ }
4086
+ const debug = result.value?.debug ?? {};
4087
+ const note = debug.stopped === true ? "已关闭会话,探针已释放" : String(debug.message ?? "本来就没有会话");
4088
+ setTouchMessage(note);
4089
+ debugInfo.reload();
4090
+ return note;
4091
+ };
4092
+ const taps = useChannelTaps(3000);
4093
+ const serialState = useSerialState(4000);
4094
+ const recording = useWatchRecording(3000);
4095
+ const tapOf = (key) => taps.channels.find((item) => item.name === key);
4096
+ const tails = collectChannelTails(props.events);
4097
+ /* 工程目录:面板选过就用选的,否则跟当前调试会话,最后退到工作区里的第一个工程(S82/S84)。 */
4098
+ const projectDir = typeof props.projectDir === "string" && props.projectDir !== ""
4099
+ ? props.projectDir
4100
+ : (debugInfo.debug?.projectDir !== undefined && debugInfo.debug?.projectDir !== null && debugInfo.debug.projectDir !== ""
4101
+ ? debugInfo.debug.projectDir
4102
+ : (typeof props.fallbackProjectDir === "string" ? props.fallbackProjectDir : ""));
4103
+ const setStateFor = (key, patch) => {
4104
+ setView((previous) => {
4105
+ const next = Object.assign({}, previous);
4106
+ next[key] = Object.assign({}, previous[key] ?? {}, patch);
4107
+ return next;
4108
+ });
4109
+ };
4110
+ /* 未读失败角标(S65):停在别的标签时也能看见又有几条失败。 */
4111
+ const failCount = props.events.filter((item) => item.status === "fail").length;
4112
+ const [failSeen, setFailSeen] = useState(0);
4113
+ useEffect(() => {
4114
+ if (tab === "channels" || tab === "faults") setFailSeen(failCount);
4115
+ }, [tab, failCount]);
4116
+ const unseenFails = Math.max(0, failCount - failSeen);
4117
+ const tabButton = (key, label, badge) =>
4118
+ e(
4119
+ "button",
4120
+ {
4121
+ key: key,
4122
+ type: "button",
4123
+ className: "d32-tab",
4124
+ "data-active": tab === key ? "1" : "0",
4125
+ onClick: () => setTab(key),
4126
+ style: {
4127
+ padding: "8px 13px 7px",
4128
+ fontFamily: D32_FONT_CODE,
4129
+ fontSize: "11px",
4130
+ letterSpacing: "0.08em",
4131
+ border: 0,
4132
+ borderBottom: "2px solid transparent",
4133
+ background: "transparent",
4134
+ color: "inherit",
4135
+ cursor: "pointer",
4136
+ },
4137
+ },
4138
+ label,
4139
+ badge === undefined || badge === 0
4140
+ ? null
4141
+ : e(
4142
+ "span",
4143
+ { key: "badge", style: { marginLeft: "6px", padding: "0 5px", background: D32_ACCENT, color: "var(--dsw-alias-label-primary-foreground)", fontSize: "10px", letterSpacing: "0.04em" } },
4144
+ String(badge),
4145
+ ),
4146
+ );
4147
+ const header = e(
4148
+ "div",
4149
+ { key: "tabs", className: "d32-tabs", style: { display: "flex", gap: "0", padding: "0", background: "transparent", borderBottom: "1px solid var(--dsw-alias-border-l2)" } },
4150
+ tabButton("overview", DEBUG_LABELS.overview),
4151
+ tabButton("events", DEBUG_LABELS.events),
4152
+ tabButton("channels", DEBUG_LABELS.channels, unseenFails),
4153
+ tabButton("pinout", DEBUG_LABELS.pinout),
4154
+ tabButton("clocks", DEBUG_LABELS.clocks),
4155
+ tabButton("interrupts", DEBUG_LABELS.interrupts),
4156
+ tabButton("faults", DEBUG_LABELS.faults, unseenFails),
4157
+ tabButton("artifacts", DEBUG_LABELS.artifacts),
4158
+ tabButton("changes", DEBUG_LABELS.changes),
4159
+ );
4160
+ const body =
4161
+ tab === "overview"
4162
+ ? [e(OverviewPanel, { key: "overview", projectDir: projectDir, debug: debugInfo.debug, events: props.events, onShowFailures: props.onShowFailures, onShowChannels: () => setTab("channels") })]
4163
+ : tab === "events"
4164
+ ? [
4165
+ e(
4166
+ "div",
4167
+ {
4168
+ key: "events",
4169
+ className: "d32-events",
4170
+ style: { display: "flex", alignItems: "stretch", gap: "0", minHeight: "480px", height: "100%" },
4171
+ },
4172
+ e(Timeline, {
4173
+ key: "timeline",
4174
+ events: props.events,
4175
+ durations: props.durations,
4176
+ connection: props.connection,
4177
+ selectedSeq: props.selectedSeq,
4178
+ pickedSet: props.pickedSet,
4179
+ onPick: props.onPick,
4180
+ onSelect: props.onSelect,
4181
+ flex: "1 1 55%",
4182
+ }),
4183
+ e("div", { key: "events-split", style: { flex: "0 0 8px" } }),
4184
+ e(Detail, { key: "detail", event: props.selected, flex: "0 0 380px" }),
4185
+ ),
4186
+ ]
4187
+ : tab === "pinout"
4188
+ ? [e(PinoutPanel, { key: "pinout", projectDir: projectDir })]
4189
+ : tab === "clocks"
4190
+ ? [e(ClockPanel, { key: "clocks", projectDir: projectDir })]
4191
+ : tab === "interrupts"
4192
+ ? [e(InterruptPanel, { key: "interrupts", projectDir: projectDir })]
4193
+ : tab === "faults"
4194
+ ? [e(FaultPanel, { key: "faults", sessionId: props.sessionId })]
4195
+ : tab === "artifacts"
4196
+ ? [e(ArtifactPanel, { key: "artifacts", projectDir: projectDir, events: props.events })]
4197
+ : tab === "changes"
4198
+ ? [e(IocDiffPanel, { key: "changes", projectDir: projectDir })]
4199
+ : [
4200
+ e(SessionCard, { key: "session", debug: debugInfo.debug, error: debugInfo.error, onTouch: touchSession, touchMessage: touchMessage, onClose: closeSession }),
4201
+ e(ProbeCard, { key: "probe-card" }),
4202
+ e(SerialCard, { key: "serial-card", serial: serialState.serial, error: serialState.error, onChanged: serialState.reload }),
4203
+ e(BuildCard, { key: "build-card", projectDir: projectDir }),
4204
+ e(RunningTools, { key: "running", events: props.events }),
4205
+ e(BreakpointPanel, { key: "breakpoints", debug: debugInfo.debug, onChanged: debugInfo.reload }),
4206
+ e(WatchAdmin, { key: "watch-admin" }),
4207
+ e(WatchCurves, { key: "curves", events: props.events, recording: recording.status, onStart: recording.start, onStop: recording.stop }),
4208
+ ];
4209
+ const channelBlocks = CHANNEL_DEFS.map((def) =>
4210
+ e(ChannelBlock, {
4211
+ key: def.key,
4212
+ label: def.label,
4213
+ channelKey: def.key,
4214
+ lines: tails[def.key],
4215
+ state: view[def.key] ?? {},
4216
+ tap: tapOf(def.key),
4217
+ onSend: def.key === "serial" ? sendSerialLine : undefined,
4218
+ onToggleTap: (on) => taps.toggle(def.key, on),
4219
+ onTogglePause: () =>
4220
+ setStateFor(def.key, { pauseAt: typeof (view[def.key] ?? {}).pauseAt === "number" ? undefined : tails[def.key].length }),
4221
+ onClear: () => setStateFor(def.key, { clearAt: tails[def.key].length, pauseAt: undefined }),
4222
+ }),
4223
+ );
4224
+ return e(
4225
+ DebugPanel,
4226
+ { title: tab === "channels" ? DEBUG_LABELS.channels : DEBUG_LABELS.channels + " / " + (DEBUG_LABELS[tab] ?? tab), onCollapse: props.onCollapse },
4227
+ header,
4228
+ body,
4229
+ tab === "channels" ? channelBlocks : null,
4230
+ );
4231
+ }
4232
+
4233
+ /** 底部控制台:把当前可见事件按行铺开,便于一眼扫过整段联调。 */
4234
+ function ConsolePanel(props) {
4235
+ const lines = props.events.slice(-400).map((event) =>
4236
+ [
4237
+ clockText(event.time),
4238
+ DEBUG_STATUS_SIGN[event.status] ?? "·",
4239
+ String(event.kind),
4240
+ String(event.summary),
4241
+ ].join(" "),
4242
+ );
4243
+ return e(
4244
+ "div",
4245
+ { style: Object.assign({}, debugStyles.panel, { flex: "0 0 auto" }) },
4246
+ e(
4247
+ "div",
4248
+ { style: debugStyles.panelHead },
4249
+ "控制台",
4250
+ e("span", { style: debugStyles.spacer }),
4251
+ e("span", { style: { opacity: 0.6, fontWeight: 400 } }, String(props.events.length) + " 条"),
4252
+ e(
4253
+ "button",
4254
+ {
4255
+ style: debugStyles.button,
4256
+ onClick: props.onToggle,
4257
+ },
4258
+ props.collapsed === true ? "展开" : "收起",
4259
+ ),
4260
+ ),
4261
+ props.collapsed === true
4262
+ ? null
4263
+ : e(
4264
+ "div",
4265
+ { style: { maxHeight: "150px", overflow: "auto" } },
4266
+ lines.length === 0 ? e("div", { style: debugStyles.empty }, "控制台暂无输出。") : e("pre", { style: debugStyles.pre }, lines.join("\n")),
4267
+ ),
4268
+ );
4269
+ }
4270
+
4271
+ /** 证据目录里的回放候选:打开选择器时才拉一次。 */
4272
+ function useEvidence(open) {
4273
+ const [value, setValue] = useState({ root: "", files: [], groups: [], usage: null, policy: null });
4274
+ const [error, setError] = useState("");
4275
+ const [tick, setTick] = useState(0);
4276
+ useEffect(() => {
4277
+ if (!open) return undefined;
4278
+ let closed = false;
4279
+ const load = async () => {
4280
+ const result = await callApi("GET", "evidence");
4281
+ if (closed) return;
4282
+ if (result.ok) {
4283
+ setValue({
4284
+ root: String(result.value.evidence.root ?? ""),
4285
+ files: result.value.evidence.files ?? [],
4286
+ groups: result.value.evidence.groups ?? [],
4287
+ usage: result.value.evidence.usage ?? null,
4288
+ policy: result.value.evidence.policy ?? null,
4289
+ });
4290
+ setError("");
4291
+ } else {
4292
+ setError(result.error);
4293
+ }
4294
+ };
4295
+ load();
4296
+ return () => {
4297
+ closed = true;
4298
+ };
4299
+ }, [open, tick]);
4300
+ return { root: value.root, files: value.files, usage: value.usage, error: error, reload: () => setTick((previous) => previous + 1) };
4301
+ }
4302
+
4303
+ /** 载入一份证据文件。回放期间面板只读这份数据,不混入实时事件。 */
4304
+ function useReplay() {
4305
+ const [replay, setReplay] = useState(null);
4306
+ const [error, setError] = useState("");
4307
+ const [busy, setBusy] = useState(false);
4308
+ const load = async (path) => {
4309
+ setBusy(true);
4310
+ const result = await callApi("GET", "replay?path=" + encodeURIComponent(path));
4311
+ setBusy(false);
4312
+ if (result.ok) {
4313
+ const value = result.value.replay;
4314
+ setReplay({ file: String(value.file ?? path), events: value.events ?? [], skipped: Number(value.skipped ?? 0) });
4315
+ setError("");
4316
+ } else {
4317
+ setError(result.error);
4318
+ }
4319
+ };
4320
+ const clear = () => {
4321
+ setReplay(null);
4322
+ setError("");
4323
+ };
4324
+ return { replay: replay, error: error, busy: busy, load: load, clear: clear };
4325
+ }
4326
+
4327
+ /** 把当前视图导出成证据格式的 JSONL,便于随对话一起交付。 */
4328
+ function exportEvents(events) {
4329
+ const text = events.map((event) => JSON.stringify(event)).join("\n") + (events.length === 0 ? "" : "\n");
4330
+ const blob = new Blob([text], { type: "application/x-ndjson" });
4331
+ const url = URL.createObjectURL(blob);
4332
+ const link = document.createElement("a");
4333
+ link.href = url;
4334
+ link.download = "stm32-debug-" + new Date().toISOString().replace(/[:.]/gu, "-") + ".jsonl";
4335
+ document.body.appendChild(link);
4336
+ link.click();
4337
+ document.body.removeChild(link);
4338
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
4339
+ }
4340
+
4341
+ /**
4342
+ * 把一段事件整理成能贴给人的操作记录(S73)。
4343
+ *
4344
+ * 只做汇总与排序,不推断因果:失败原文照抄,好让人自己判断。
4345
+ */
4346
+ function summaryMarkdown(events, options) {
4347
+ const opts = options ?? {};
4348
+ const list = Array.isArray(events) ? events : [];
4349
+ const okCount = list.filter((item) => item.status === "ok").length;
4350
+ const failCount = list.filter((item) => item.status === "fail").length;
4351
+ const infoCount = list.length - okCount - failCount;
4352
+ const first = list.length === 0 ? null : list[0];
4353
+ const last = list.length === 0 ? null : list[list.length - 1];
4354
+ const durations = toolDurations(list);
4355
+ const lines = [];
4356
+ lines.push("# 调试台操作记录");
4357
+ lines.push("");
4358
+ if (typeof opts.projectDir === "string" && opts.projectDir !== "") lines.push("- 工程:" + opts.projectDir);
4359
+ if (first !== null && last !== null) lines.push("- 区间:" + String(first.time) + " → " + String(last.time));
4360
+ lines.push("- 事件:" + String(list.length) + " 条(成功 " + String(okCount) + " / 失败 " + String(failCount) + " / 其他 " + String(infoCount) + ")");
4361
+ lines.push("");
4362
+ lines.push("## 工具调用");
4363
+ lines.push("");
4364
+ const counts = Array.isArray(opts.counts) ? opts.counts : [];
4365
+ if (counts.length === 0) {
4366
+ lines.push("(这段时间没有工具调用)");
4367
+ } else {
4368
+ lines.push("| 工具 | 次数 | 最慢一次 |");
4369
+ lines.push("| --- | --- | --- |");
4370
+ for (const item of counts) {
4371
+ const slowest = Math.max(...list.filter((event) => event.kind === item.kind).map((event) => durations.get(callIdOf(event))?.ms ?? -1));
4372
+ lines.push("| " + String(item.kind).replace(/^stm32_/u, "") + " | " + String(item.count) + " | " + (slowest >= 0 ? durationText(slowest) : "—") + " |");
4373
+ }
4374
+ }
4375
+ lines.push("");
4376
+ lines.push("## 失败");
4377
+ lines.push("");
4378
+ const failures = list.filter((item) => item.status === "fail");
4379
+ if (failures.length === 0) {
4380
+ lines.push("(没有失败事件)");
4381
+ } else {
4382
+ for (const failure of failures) {
4383
+ lines.push("- #" + String(failure.seq) + " " + String(failure.time) + " " + String(failure.kind) + ":" + String(failure.summary));
4384
+ }
4385
+ }
4386
+ lines.push("");
4387
+ lines.push("## 构建与烧录");
4388
+ lines.push("");
4389
+ const builds = list.filter((item) => (item.kind === "stm32_build" || item.kind === "stm32_flash") && item.status === "ok");
4390
+ if (builds.length === 0) {
4391
+ lines.push("(这段时间没有成功构建或烧录)");
4392
+ } else {
4393
+ for (const build of builds) {
4394
+ const result = build.payload?.result ?? {};
4395
+ const parts = [String(build.kind), String(build.time)];
4396
+ if (typeof result.memoryUsage !== "undefined") {
4397
+ const usage = result.memoryUsage ?? {};
4398
+ parts.push("FLASH " + bytesText(usage.flash) + " / RAM " + bytesText(usage.ram));
4399
+ }
4400
+ if (typeof result.elfSha256 === "string" && result.elfSha256 !== "") parts.push("elf " + result.elfSha256.slice(0, 12) + "…");
4401
+ lines.push("- " + parts.join(" · "));
4402
+ }
4403
+ }
4404
+ return lines.join("\n") + "\n";
4405
+ }
4406
+
4407
+ /** 把操作记录下载成 Markdown(S73)。 */
4408
+ function exportSummary(events, options) {
4409
+ const text = summaryMarkdown(events, options);
4410
+ const blob = new Blob([text], { type: "text/markdown;charset=utf-8" });
4411
+ const url = URL.createObjectURL(blob);
4412
+ const link = document.createElement("a");
4413
+ link.href = url;
4414
+ link.download = "stm32-summary-" + new Date().toISOString().replace(/[:.]/gu, "-") + ".md";
4415
+ document.body.appendChild(link);
4416
+ link.click();
4417
+ document.body.removeChild(link);
4418
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
4419
+ }
4420
+
4421
+ /** CSV 单元格:含逗号、引号或换行时加引号并把引号翻倍(S59)。 */
4422
+ function csvCell(value) {
4423
+ const text = String(value ?? "");
4424
+ return /[",\n\r]/u.test(text) ? '"' + text.replace(/"/gu, '""') + '"' : text;
4425
+ }
4426
+
4427
+ /** 把引脚表导成 CSV(S59):Excel 里直接看得到列,UTF-8 带 BOM。 */
4428
+ function exportPinsCsv(pins) {
4429
+ const header = ["引脚", "信号", "标号", "模式"];
4430
+ const rows = pins.map((pin) => [pin.pin, pin.signal, pin.label ?? "", pin.mode ?? ""].map(csvCell).join(","));
4431
+ const text = "\ufeff" + [header.join(",")].concat(rows).join("\r\n") + "\r\n";
4432
+ const blob = new Blob([text], { type: "text/csv;charset=utf-8" });
4433
+ const url = URL.createObjectURL(blob);
4434
+ const link = document.createElement("a");
4435
+ link.href = url;
4436
+ link.download = "stm32-pins-" + new Date().toISOString().replace(/[:.]/gu, "-") + ".csv";
4437
+ document.body.appendChild(link);
4438
+ link.click();
4439
+ document.body.removeChild(link);
4440
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
4441
+ }
4442
+
4443
+ /** 把当前通道窗口导出成文本(S51):只导面板上看得见的那部分。 */
4444
+ function exportChannelLines(channelKey, lines) {
4445
+ const text = lines.map((line) => String(line)).join("\n") + (lines.length === 0 ? "" : "\n");
4446
+ const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
4447
+ const url = URL.createObjectURL(blob);
4448
+ const link = document.createElement("a");
4449
+ link.href = url;
4450
+ link.download = "stm32-" + channelKey + "-" + new Date().toISOString().replace(/[:.]/gu, "-") + ".txt";
4451
+ document.body.appendChild(link);
4452
+ link.click();
4453
+ document.body.removeChild(link);
4454
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
4455
+ }
4456
+
4457
+ /** 回放选择器:列出证据目录里的 jsonl,点一个即载入。 */
4458
+ function ReplayPicker(props) {
4459
+ const evidence = useEvidence(true);
4460
+ const fileButton = (file) =>
4461
+ e(
4462
+ "button",
4463
+ {
4464
+ key: file.path,
4465
+ type: "button",
4466
+ style: Object.assign({}, debugStyles.button, { textAlign: "left", marginBottom: "2px", maxWidth: "100%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }),
4467
+ title: file.path,
4468
+ disabled: props.busy === true,
4469
+ onClick: () => props.onLoad(file.path),
4470
+ },
4471
+ file.path + " " + bytesText(file.size),
4472
+ );
4473
+ const groups = Array.isArray(evidence.groups) ? evidence.groups : [];
4474
+ const rows = evidence.files.length === 0
4475
+ ? [e("div", { key: "empty", style: debugStyles.empty }, evidence.error === "" ? "证据目录里还没有文件:本会话的事件通常会在半分钟内写出第一份。" : evidence.error)]
4476
+ : groups.length > 0
4477
+ ? groups.map((group) =>
4478
+ e(
4479
+ "div",
4480
+ { key: "evidence-group-" + group.key, style: { paddingBottom: "4px" } },
4481
+ e(
4482
+ "div",
4483
+ { style: { display: "flex", gap: "8px", fontSize: "12px", opacity: 0.75, padding: "2px 0" } },
4484
+ e("span", { style: { fontFamily: "ui-monospace, monospace", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, group.key === "" ? "(未分目录)" : group.key),
4485
+ e("span", { style: { marginLeft: "auto", whiteSpace: "nowrap" } }, String(group.files.length) + " 个 · " + bytesText(group.bytes)),
4486
+ ),
4487
+ group.files.map(fileButton),
4488
+ ),
4489
+ )
4490
+ : evidence.files.map(fileButton);
4491
+ const usage = evidence.usage;
4492
+ const usageText = usage === null ? "" : String(usage.count) + " 个文件 · " + bytesText(usage.bytes);
4493
+ const prune = async () => {
4494
+ const result = await callApi("POST", "evidence/prune", {});
4495
+ if (result.ok) {
4496
+ const pruned = result.value.pruned;
4497
+ props.onMessage(
4498
+ "清理 " + String((pruned.removedDirs ?? []).length) + " 个目录、删掉 " + String(pruned.removedFiles ?? 0) + " 个文件(" + bytesText(pruned.removedBytes ?? 0) + ")",
4499
+ );
4500
+ evidence.reload();
4501
+ } else {
4502
+ props.onMessage(result.error);
4503
+ }
4504
+ };
4505
+ return e(
4506
+ "div",
4507
+ { style: { display: "flex", flexDirection: "column", gap: "4px", padding: "6px 0" } },
4508
+ e("div", { style: { fontSize: "12px", opacity: 0.7, display: "flex", gap: "8px", flexWrap: "wrap" }, title: evidence.root },
4509
+ e("span", { style: { flex: "1 1 auto", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, "证据目录:" + (evidence.root === "" ? "—" : evidence.root)),
4510
+ e(
4511
+ "span",
4512
+ {
4513
+ style: { flex: "0 0 auto", opacity: 0.6, fontSize: "11px" },
4514
+ title: evidence.policy === null || evidence.policy === undefined
4515
+ ? ""
4516
+ : "落盘间隔来自 " + String(evidence.policy.sources?.flushSeconds ?? "default") + ",保留来自 " + String(evidence.policy.sources?.keepDays ?? "default") + " / " + String(evidence.policy.sources?.keepSessions ?? "default"),
4517
+ },
4518
+ evidence.policy === null || evidence.policy === undefined
4519
+ ? ""
4520
+ : "每 " + String(evidence.policy.flushSeconds) + " s 落盘 · 保留 " + String(evidence.policy.keepDays) + " 天 / " + String(evidence.policy.keepSessions) + " 会话",
4521
+ ),
4522
+ usageText === "" ? null : e("span", { style: { opacity: 0.75 } }, usageText),
4523
+ e("button", { type: "button", style: debugStyles.button, onClick: prune, title: "删掉 7 天前、或超出 20 个会话的旧证据" }, "清理旧证据"),
4524
+ ),
4525
+ rows,
4526
+ );
4527
+ }
4528
+
4529
+ /** 深链:地址栏 #stm32-debug:event=<seq> 指向某条事件;刷新或粘链接能回到同一条。 */
4530
+ function readDebugEventSeq() {
4531
+ if (typeof window !== "object" || window === null || typeof window.location !== "object") return null;
4532
+ const hash = String(window.location.hash ?? "");
4533
+ const matched = /#stm32-debug:event=(\d+)/u.exec(hash);
4534
+ if (matched === null) return null;
4535
+ const seq = Number.parseInt(matched[1], 10);
4536
+ return Number.isFinite(seq) ? seq : null;
4537
+ }
4538
+
4539
+ function writeDebugEventSeq(seq) {
4540
+ if (typeof window !== "object" || window === null || typeof window.history !== "object") return;
4541
+ const next = seq === null ? "" : "#stm32-debug:event=" + String(seq);
4542
+ if (String(window.location.hash ?? "") === next) return;
4543
+ window.history.replaceState(null, "", window.location.pathname + window.location.search + next);
4544
+ }
4545
+
4546
+ /** 工程选择器数据(S82):工作区索引 + 现场扫描。 */
4547
+ function useProjects(projectDir, intervalMs) {
4548
+ const [value, setValue] = useState(null);
4549
+ const [error, setError] = useState("");
4550
+ const [tick, setTick] = useState(0);
4551
+ useEffect(() => {
4552
+ let closed = false;
4553
+ const load = async () => {
4554
+ const query = "projects?projectDir=" + encodeURIComponent(projectDir ?? "");
4555
+ const result = await callApi("GET", query);
4556
+ if (closed) return;
4557
+ if (result.ok) {
4558
+ setValue(result.value.projects ?? null);
4559
+ setError("");
4560
+ } else {
4561
+ setError(result.error);
4562
+ }
4563
+ };
4564
+ load();
4565
+ const timer = intervalMs === undefined || intervalMs <= 0 ? null : setInterval(load, intervalMs);
4566
+ return () => {
4567
+ closed = true;
4568
+ if (timer !== null) clearInterval(timer);
4569
+ };
4570
+ }, [projectDir, tick, intervalMs]);
4571
+ return { value, error, reload: () => setTick((value_) => value_ + 1) };
4572
+ }
4573
+
4574
+ function DebugConsole(props) {
4575
+ const sessionId = props !== null && typeof props === "object" && typeof props.sessionId === "string" ? props.sessionId : "";
4576
+ // 样式表在首次渲染后注入:服务端渲染或测试环境里没有 document 时直接跳过。
4577
+ useEffect(() => {
4578
+ ensureDebugStyleTag();
4579
+ }, []);
4580
+ const { events, connection } = useDebugEvents(sessionId);
4581
+ const [status, setStatus] = useState(null);
4582
+ useEffect(() => {
4583
+ let closed = false;
4584
+ const load = async () => {
4585
+ const result = await callApi("GET", sessionId === "" ? "status" : "status?session=" + encodeURIComponent(sessionId));
4586
+ if (!closed && result.ok) setStatus(result.value.status);
4587
+ };
4588
+ load();
4589
+ const timer = setInterval(load, 60_000);
4590
+ return () => {
4591
+ closed = true;
4592
+ clearInterval(timer);
4593
+ };
4594
+ }, [sessionId]);
4595
+ const [selectedSeq, setSelectedSeq] = useState(null);
4596
+ const [picked, setPicked] = useState([]);
4597
+ const [pickNote, setPickNote] = useState("");
4598
+ const [pickerOpen, setPickerOpen] = useState(false);
4599
+ const [pickerMessage, setPickerMessage] = useState("");
4600
+ const [onlyFail, setOnlyFail] = useState(false);
4601
+ const [sortBy, setSortBy] = useState("time");
4602
+ /* 新失败主动提示(S70):不用切标签也能知道刚才那次调用失败了。 */
4603
+ const [failToast, setFailToast] = useState(null);
4604
+ const failSeenRef = React.useRef(0);
4605
+ const [focusFailures, setFocusFailures] = useState(0);
4606
+ const replayState = useReplay();
4607
+ const replayRef = React.useRef(null);
4608
+ replayRef.current = replayState;
4609
+ useEffect(() => {
4610
+ if (sessionId === "" || autoLoadedRef.current === true) return;
4611
+ if (events.length > 0) return;
4612
+ const state = replayRef.current;
4613
+ if (state === null || state.replay !== null || state.busy === true) return;
4614
+ autoLoadedRef.current = true;
4615
+ (async () => {
4616
+ const listed = await callApi("GET", "evidence");
4617
+ if (!listed.ok) return;
4618
+ const files = listed.value.evidence?.files ?? [];
4619
+ if (files.length === 0) return;
4620
+ const mine = files.filter((item) => String(item.path).includes(sessionId));
4621
+ const pick = (mine.length > 0 ? mine : files)[0];
4622
+ if (pick === undefined) return;
4623
+ await state.load(pick.path);
4624
+ setPickerMessage("已载入最近一份历史记录(" + String(pick.path) + ");点「退出回放」回到实时。");
4625
+ })();
4626
+ }, [sessionId, events.length]);
4627
+ const [filter, setFilter] = useState("");
4628
+ const [layout, setLayout] = useState(readDebugLayout);
4629
+ /* 工程选择(S82):留空表示跟当前调试会话。 */
4630
+ const [projectOverride, setProjectOverride] = useState(() => {
4631
+ try {
4632
+ return window.localStorage.getItem(DEBUG_PROJECT_KEY(sessionId)) ?? "";
4633
+ } catch {
4634
+ return "";
4635
+ }
4636
+ });
4637
+ const projects = useProjects(projectOverride);
4638
+ const autoLoadedRef = React.useRef(false);
4639
+ useEffect(() => {
4640
+ const initial = readDebugEventSeq();
4641
+ if (initial !== null) setSelectedSeq(initial);
4642
+ }, []);
4643
+ useEffect(() => {
4644
+ const onKey = (event) => {
4645
+ if (event.key === "Escape" && filter !== "") {
4646
+ setFilter("");
4647
+ }
4648
+ };
4649
+ window.addEventListener("keydown", onKey);
4650
+ return () => window.removeEventListener("keydown", onKey);
4651
+ }, [filter]);
4652
+ useEffect(() => {
4653
+ const fails = events.filter((event) => event.status === "fail");
4654
+ if (fails.length === 0) return;
4655
+ const latest = fails[fails.length - 1];
4656
+ if (failSeenRef.current === 0) {
4657
+ // 首次加载把已有失败当成「已读」,只对之后新出现的提示。
4658
+ failSeenRef.current = latest.seq;
4659
+ return;
4660
+ }
4661
+ if (latest.seq <= failSeenRef.current) return;
4662
+ const fresh = fails.filter((event) => event.seq > failSeenRef.current).length;
4663
+ failSeenRef.current = latest.seq;
4664
+ setFailToast({ seq: latest.seq, kind: String(latest.kind), summary: String(latest.summary), count: fresh });
4665
+ }, [events]);
4666
+ const dragRef = React.useRef(null);
4667
+ const selected = (replayState.replay === null ? events : replayState.replay.events).find((event) => event.seq === selectedSeq) ?? null;
4668
+
4669
+ const matchedBase = onlyFail === true ? events.filter((event) => event.status === "fail") : events;
4670
+ const matched = filter.trim() === ""
4671
+ ? matchedBase
4672
+ : matchedBase.filter((event) => (String(event.kind) + " " + String(event.summary)).toLowerCase().includes(filter.trim().toLowerCase()));
4673
+ const visible = replayState.replay === null ? matched : replayState.replay.events;
4674
+ const durations = toolDurations(visible);
4675
+ const ordered =
4676
+ sortBy === "duration"
4677
+ ? visible
4678
+ .slice()
4679
+ .sort((left, right) => {
4680
+ const leftMs = durations.get(left.payload !== null && typeof left.payload === "object" ? String(left.payload.callId ?? "") : "")?.ms ?? -1;
4681
+ const rightMs = durations.get(right.payload !== null && typeof right.payload === "object" ? String(right.payload.callId ?? "") : "")?.ms ?? -1;
4682
+ return rightMs - leftMs;
4683
+ })
4684
+ : visible;
4685
+ const pickedSet = new Set(picked);
4686
+ const pickedEvents = picked
4687
+ .map((seq) => visible.find((event) => event.seq === seq))
4688
+ .filter((event) => event !== undefined);
4689
+
4690
+ const selectEvent = (event) => {
4691
+ setSelectedSeq(event.seq);
4692
+ writeDebugEventSeq(replayState.replay === null ? event.seq : null);
4693
+ };
4694
+
4695
+ const togglePick = (event) => {
4696
+ setPickNote("");
4697
+ setPicked((previous) => (previous.includes(event.seq) ? previous.filter((seq) => seq !== event.seq) : previous.concat([event.seq])));
4698
+ };
4699
+
4700
+ const copyPicked = () => {
4701
+ const text = eventRefBlock(pickedEvents);
4702
+ if (text === "") {
4703
+ setPickNote("先勾选几条事件。");
4704
+ return;
4705
+ }
4706
+ const clipboard = typeof navigator === "object" && navigator !== null ? navigator.clipboard : null;
4707
+ if (clipboard !== null && clipboard !== undefined && typeof clipboard.writeText === "function") {
4708
+ clipboard
4709
+ .writeText(text)
4710
+ .then(() => setPickNote("已复制 " + String(pickedEvents.length) + " 条引用"))
4711
+ .catch(() => setPickNote("复制失败:浏览器没有给剪贴板权限"));
4712
+ return;
4713
+ }
4714
+ setPickNote("复制失败:当前环境没有剪贴板接口");
4715
+ };
4716
+
4717
+ const updateLayout = (patch) => {
4718
+ setLayout((previous) => {
4719
+ const next = Object.assign({}, previous, patch);
4720
+ writeDebugLayout(next);
4721
+ return next;
4722
+ });
4723
+ };
4724
+
4725
+ const startDrag = (side) => (event) => {
4726
+ event.preventDefault();
4727
+ dragRef.current = { side, startX: event.clientX, left: layout.left, right: layout.right };
4728
+ };
4729
+
4730
+ useEffect(() => {
4731
+ const onMove = (event) => {
4732
+ const drag = dragRef.current;
4733
+ if (drag === null) return;
4734
+ const delta = event.clientX - drag.startX;
4735
+ if (drag.side === "left") {
4736
+ updateLayout({ left: Math.max(180, Math.min(720, drag.left + delta)) });
4737
+ } else {
4738
+ updateLayout({ right: Math.max(180, Math.min(720, drag.right - delta)) });
4739
+ }
4740
+ };
4741
+ const onUp = () => {
4742
+ dragRef.current = null;
4743
+ };
4744
+ window.addEventListener("pointermove", onMove);
4745
+ window.addEventListener("pointerup", onUp);
4746
+ return () => {
4747
+ window.removeEventListener("pointermove", onMove);
4748
+ window.removeEventListener("pointerup", onUp);
4749
+ };
4750
+ });
4751
+
4752
+ const collapsed = layout.collapsed ?? {};
4753
+ const panels = [];
4754
+ if (collapsed.channels !== true) {
4755
+ panels.push(
4756
+ e("div", {
4757
+ key: "divider-right",
4758
+ style: debugStyles.divider,
4759
+ onPointerDown: startDrag("right"),
4760
+ title: "拖动改宽;双击恢复默认",
4761
+ onDoubleClick: () => updateLayout({ right: 300 }),
4762
+ }),
4763
+ e(Channels, {
4764
+ key: "channels",
4765
+ events: visible,
4766
+ sessionId: sessionId,
4767
+ projectDir: projectOverride,
4768
+ fallbackProjectDir: (projects.value?.entries ?? []).length > 0 ? projects.value.entries[0].dir : "",
4769
+ focusFailures: focusFailures,
4770
+ selected: selected,
4771
+ selectedSeq: selectedSeq,
4772
+ pickedSet: pickedSet,
4773
+ picked: picked,
4774
+ onPick: togglePick,
4775
+ onSelect: selectEvent,
4776
+ durations: durations,
4777
+ connection: connection,
4778
+ onShowFailures: () => {
4779
+ setOnlyFail(true);
4780
+ setFocusFailures((previous) => previous + 1);
4781
+ },
4782
+ onCollapse: () => updateLayout({ collapsed: Object.assign({}, collapsed, { channels: true }) }),
4783
+ flex: "0 0 " + String(layout.right) + "px",
4784
+ }),
4785
+ );
4786
+ }
4787
+
4788
+ const drawerItems = [];
4789
+ if (collapsed.channels === true) drawerItems.push({ key: "channels", label: DEBUG_LABELS.channels });
4790
+
4791
+ return e(
4792
+ "div",
4793
+ { style: debugStyles.page, className: "d32-page" },
4794
+ e(StatusBar, { events, connection, status }),
4795
+ failToast === null
4796
+ ? null
4797
+ : e(
4798
+ "div",
4799
+ {
4800
+ key: "fail-toast",
4801
+ style: {
4802
+ display: "flex",
4803
+ alignItems: "center",
4804
+ gap: "8px",
4805
+ padding: "4px 8px",
4806
+ fontSize: "12px",
4807
+ borderRadius: "6px",
4808
+ background: "color-mix(in srgb, var(--dsw-alias-state-warn-primary) 14%, transparent)",
4809
+ border: "1px solid color-mix(in srgb, var(--dsw-alias-state-warn-primary) 45%, transparent)",
4810
+ },
4811
+ },
4812
+ e(
4813
+ "span",
4814
+ {
4815
+ style: { flex: "1 1 auto", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
4816
+ title: failToast.summary,
4817
+ },
4818
+ "新失败 " + (failToast.count > 1 ? "×" + String(failToast.count) + " " : "") + "#" + String(failToast.seq) + " " +
4819
+ failToast.kind.replace(/^stm32_/u, "") + ":" + failToast.summary,
4820
+ ),
4821
+ e(
4822
+ "button",
4823
+ {
4824
+ type: "button",
4825
+ style: debugStyles.button,
4826
+ onClick: () => {
4827
+ setOnlyFail(true);
4828
+ setFocusFailures((previous) => previous + 1);
4829
+ setFailToast(null);
4830
+ },
4831
+ },
4832
+ "看",
4833
+ ),
4834
+ e("button", { type: "button", style: debugStyles.button, title: "关掉提示", onClick: () => setFailToast(null) }, "×"),
4835
+ ),
4836
+ e(
4837
+ "div",
4838
+ { style: { display: "flex", alignItems: "center", gap: "8px" } },
4839
+ e("input", {
4840
+ style: debugStyles.input,
4841
+ placeholder: "筛选工具名或摘要",
4842
+ value: filter,
4843
+ onChange: (event) => setFilter(event.target.value),
4844
+ }),
4845
+ e(
4846
+ "button",
4847
+ {
4848
+ style: Object.assign({}, debugStyles.button, onlyFail === true ? { borderColor: "color-mix(in srgb, currentColor 45%, transparent)" } : {}),
4849
+ onClick: () => setOnlyFail((value) => !value),
4850
+ },
4851
+ onlyFail === true ? "只看失败" : "全部事件",
4852
+ ),
4853
+ e(
4854
+ "button",
4855
+ {
4856
+ style: Object.assign({}, debugStyles.button, sortBy === "duration" ? { borderColor: "color-mix(in srgb, currentColor 45%, transparent)" } : {}),
4857
+ title: "按耗时从长到短排列;没有 start/ok 配对的事件排在最后",
4858
+ onClick: () => setSortBy((value) => (value === "duration" ? "time" : "duration")),
4859
+ },
4860
+ sortBy === "duration" ? "按耗时" : "按时间",
4861
+ ),
4862
+ e("span", { style: { opacity: 0.6 } }, "显示 " + String(visible.length) + " / " + String(events.length)),
4863
+ kindCounts(matchedBase, 5).map((item) =>
4864
+ e(
4865
+ "button",
4866
+ {
4867
+ key: "kind-" + item.kind,
4868
+ style: Object.assign({}, debugStyles.button, filter.trim() === item.kind ? { borderColor: "color-mix(in srgb, currentColor 45%, transparent)" } : {}),
4869
+ title: "只看 " + item.kind + "(" + String(item.count) + " 条);再点一次取消",
4870
+ onClick: () => setFilter((value) => (value.trim() === item.kind ? "" : item.kind)),
4871
+ },
4872
+ item.kind.replace(/^stm32_/u, "") + " " + String(item.count),
4873
+ ),
4874
+ ),
4875
+ e("span", { style: debugStyles.spacer }),
4876
+ e(
4877
+ "button",
4878
+ {
4879
+ style: Object.assign({}, debugStyles.button, picked.length === 0 ? { opacity: 0.5 } : {}),
4880
+ disabled: picked.length === 0,
4881
+ title: "把勾选的事件按时间线顺序拼成一段引用,贴进对话即可",
4882
+ onClick: copyPicked,
4883
+ },
4884
+ "复制已选(" + String(pickedEvents.length) + ")",
4885
+ ),
4886
+ picked.length === 0
4887
+ ? null
4888
+ : e("button", { style: debugStyles.button, onClick: () => { setPicked([]); setPickNote(""); } }, "清空勾选"),
4889
+ pickNote === ""
4890
+ ? null
4891
+ : e("span", { style: { opacity: 0.75, fontSize: "12px" } }, pickNote),
4892
+ e("button", { style: debugStyles.button, onClick: () => setSelectedSeq(null) }, "清除选择"),
4893
+ e(
4894
+ "button",
4895
+ {
4896
+ style: debugStyles.button,
4897
+ title: "导出当前显示的事件(含文字筛选与「只看失败」;勾选不影响导出范围)",
4898
+ onClick: () => exportEvents(visible),
4899
+ },
4900
+ "导出 JSONL",
4901
+ ),
4902
+ e(
4903
+ "button",
4904
+ {
4905
+ style: debugStyles.button,
4906
+ onClick: () => (replayState.replay === null ? setPickerOpen((open) => !open) : replayState.clear()),
4907
+ },
4908
+ replayState.replay === null ? "回放…" : "退出回放",
4909
+ ),
4910
+ e(
4911
+ "select",
4912
+ {
4913
+ value: projectOverride,
4914
+ title: "选一个工程:概览、引脚、时钟、中断、产物、变更都跟着切;留空跟当前调试会话",
4915
+ style: { fontSize: "11px", padding: "1px 4px", maxWidth: "220px" },
4916
+ onChange: (event) => {
4917
+ const next = event.target.value;
4918
+ setProjectOverride(next);
4919
+ try {
4920
+ window.localStorage.setItem(DEBUG_PROJECT_KEY(sessionId), next);
4921
+ } catch {
4922
+ /* 存不了就只用本次会话的选择 */
4923
+ }
4924
+ },
4925
+ },
4926
+ [e("option", { key: "auto", value: "" }, "工程:跟随调试会话 / 自动选第一个")].concat(
4927
+ ((projects.value?.entries ?? [])).map((item) =>
4928
+ e("option", { key: item.dir, value: item.dir }, (item.exists === false ? "(缺失)" : "") + item.name),
4929
+ ),
4930
+ ),
4931
+ ),
4932
+ ),
4933
+ pickerMessage === "" ? null : e("div", { style: { padding: "2px 10px", opacity: 0.75, fontSize: "12px" } }, pickerMessage),
4934
+ pickerOpen === true && replayState.replay === null ? e(ReplayPicker, { busy: replayState.busy, onLoad: (path) => replayState.load(path), onMessage: (text) => setPickerMessage(text) }) : null,
4935
+ replayState.error !== "" ? e("div", { style: { fontSize: "12px", opacity: 0.8, padding: "4px 0" } }, "回放失败:" + replayState.error) : null,
4936
+ replayState.replay === null
4937
+ ? null
4938
+ : e(
4939
+ "div",
4940
+ { style: { display: "flex", gap: "8px", alignItems: "center", fontSize: "12px", padding: "4px 0", opacity: 0.85 } },
4941
+ e("span", { style: { flex: "1 1 auto", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, title: replayState.replay.file }, "回放:" + replayState.replay.file + "(" + String(replayState.replay.events.length) + " 条" + (replayState.replay.skipped > 0 ? ",跳过 " + String(replayState.replay.skipped) : "") + ")"),
4942
+ e("span", { style: { opacity: 0.7 } }, "实时事件已暂停显示"),
4943
+ ),
4944
+ e("div", { style: debugStyles.grid }, panels),
4945
+ e(ConsolePanel, {
4946
+ events: visible,
4947
+ collapsed: collapsed.console === true,
4948
+ onToggle: () => updateLayout({ collapsed: Object.assign({}, collapsed, { console: collapsed.console !== true }) }),
4949
+ }),
4950
+ drawerItems.length === 0
4951
+ ? null
4952
+ : e(
4953
+ "div",
4954
+ { style: debugStyles.drawer },
4955
+ e("span", { style: { opacity: 0.7 } }, "已收起"),
4956
+ drawerItems.map((item) =>
4957
+ e(
4958
+ "button",
4959
+ {
4960
+ key: item.key,
4961
+ style: debugStyles.button,
4962
+ onClick: () => {
4963
+ const next = Object.assign({}, collapsed);
4964
+ delete next[item.key];
4965
+ updateLayout({ collapsed: next });
4966
+ },
4967
+ },
4968
+ item.label + " ↗",
4969
+ ),
4970
+ ),
4971
+ ),
4972
+ );
4973
+ }
4974
+
653
4975
  /* ------------------------------ 插件入口 ------------------------------ */
654
4976
 
655
- /** 客户端插件只声明 slots(注册 settings.section 需要该声明)。 */
4977
+ /** 客户端插件只声明 slots(注册 settings.section 与 conversation.view 需要该声明)。 */
656
4978
  const inject = ["slots"];
657
4979
 
658
4980
  function apply(ctx) {
@@ -673,6 +4995,23 @@ window.__ModuleLoader__.load({
673
4995
  ),
674
4996
  "dsh-stm32: settings section",
675
4997
  );
4998
+ // 调试台:与「对话」「上下文」「编队」并列的主窗口标签,按会话渲染。
4999
+ ctx.effect(
5000
+ () =>
5001
+ ctx.slots.inject("conversation.view", () =>
5002
+ ctx.slots.register(
5003
+ {
5004
+ name: "conversation.view",
5005
+ id: "stm32-debug",
5006
+ order: 40,
5007
+ label: () => "调试台",
5008
+ inject: (sessionId) => ({ sessionId }),
5009
+ },
5010
+ DebugConsole,
5011
+ ),
5012
+ ),
5013
+ "dsh-stm32: debug console",
5014
+ );
676
5015
  }
677
5016
 
678
5017
  exports.apply = apply;