dsh-volcano-git-plugin 0.0.0-stage → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,4331 @@
1
+ /**
2
+ * dsh-volcano-git-plugin — Client half (web bundle).
3
+ *
4
+ * 由 DSH web shell 通过 `window.__ModuleLoader__.load` 加载。本 bundle:
5
+ * 1. 自挂载 `gitManager` Remote 命名空间(dsh-api-remotes 只硬编码挂载官方命名空间)
6
+ * 2. 注册 `conversation.input.left` 槽 → composer 工具行(模式/access-mode 选择器旁)
7
+ * 的 Git 入口按钮(session 作用域;hero 空白会话的 composer 同样渲染这一行,
8
+ * 一个槽位同时覆盖 hero 与会话内;仅当目标目录是 git 仓库时显示)
9
+ * 3. 注册 `shell.overlay` 槽 → 面板打开时渲染 GitPanel 弹窗
10
+ * (用 ReactDOM.createPortal 落 body,绕开 stacking context;
11
+ * 尺寸/遮罩/Esc 关闭行为与「设置」面板一致)
12
+ *
13
+ * 面板本体 GitPanel 是统一的组件,包含六个 Tab
14
+ * (变更 / 分支 / 历史 / 冲突 / Worktree / 设置)。
15
+ *
16
+ * 弹层规范(契约 docs/plans/2026-09-29-full-git-manager-v2.md §0,P0 修复):
17
+ * - 所有弹层(确认框、表单弹窗、diff 独立窗口、冲突编辑器)一律
18
+ * ReactDOM.createPortal(..., document.body),绝不手动 appendChild 挪 React DOM;
19
+ * - z-index 阶梯:面板 1000 < diff 窗口 1050 < 确认/表单弹窗 1100(弹窗叠弹窗每层 +10);
20
+ * - 模块级 modalStack({close,kind,z} 栈):document 级 Esc 与 mask 点击只关栈顶弹层,
21
+ * 面板 Esc 仅在栈空时关面板。
22
+ *
23
+ * IMPORTANT: 所有 React 组件在 bundle 作用域定义一次,函数身份稳定;
24
+ * 绝不在 render 里 inline 创建组件类型(每次新身份会让 React 卸载/重挂子树,丢输入态)。
25
+ */
26
+
27
+ window.__ModuleLoader__.load({
28
+ id: "dsh-volcano-git-plugin",
29
+ factory: (require) => {
30
+ var module = { exports: {} };
31
+ var exports = module.exports;
32
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
33
+ const React = require("react");
34
+ const ReactDOM = require("react-dom");
35
+ const ui = require("@deepseek-ai/dsh-client-ui-primitives");
36
+
37
+ // ---- CSS(gm- 前缀,颜色全部走 dsw 主题令牌以适配明暗;弹窗尺寸/结构与设置面板一致) ----
38
+ const CSS = `
39
+ .gm-overlay{position:fixed;inset:0;z-index:1000;display:flex;align-items:center;justify-content:center}
40
+ .gm-mask{position:absolute;inset:0;background:var(--dsw-alias-bg-mask-1);backdrop-filter:var(--dsw-mask-blur)}
41
+ .gm-panel{position:relative;z-index:1;width:800px;max-width:calc(100vw - 48px);height:min(800px,100vh - 48px);display:flex;flex-direction:column;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);border-radius:24px;box-shadow:var(--dsw-shadow-lv3);overflow:hidden}
42
+ .gm-head{display:flex;align-items:center;gap:10px;padding:12px 16px;border-bottom:1px solid var(--dsw-alias-border-l1)}
43
+ .gm-head-title{font-size:14px;font-weight:600;flex:none}
44
+ .gm-head-spacer{flex:1}
45
+ .gm-head-actions{display:flex;gap:6px;flex:none;align-items:center}
46
+ .gm-banner{padding:10px 14px;background:var(--dsw-alias-state-warn-tertiary);color:var(--dsw-alias-state-warn-label);font-size:12px;display:flex;align-items:center;gap:10px;border-bottom:1px solid var(--dsw-alias-border-l1)}
47
+ .gm-banner-danger{padding:10px 14px;background:var(--dsw-alias-interactive-bg-hover-danger);color:var(--dsw-alias-state-error-primary);font-size:12px;display:flex;align-items:center;gap:10px;border-bottom:1px solid var(--dsw-alias-border-l1)}
48
+ .gm-main{flex:1;display:flex;min-height:0}
49
+ .gm-tabs{display:flex;flex-direction:column;width:140px;flex:none;border-right:1px solid var(--dsw-alias-border-l1);padding:8px 6px;gap:2px}
50
+ .gm-tab{appearance:none;background:transparent;border:none;cursor:pointer;text-align:left;padding:8px 12px;border-radius:10px;font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);display:flex;align-items:center;gap:8px}
51
+ .gm-tab:hover{background:var(--dsw-specific-sidebar-nav-item-hover)}
52
+ .gm-tab-active{background:var(--dsw-specific-sidebar-nav-item-active);font-weight:500}
53
+ .gm-tab-badge{margin-left:auto;font-size:10px;line-height:14px;padding:0 6px;border-radius:999px;background:var(--dsw-alias-state-error-primary);color:var(--dsw-alias-label-primary-inverted);min-width:14px;text-align:center}
54
+ .gm-content{flex:1;min-width:0;overflow:auto;padding:14px 16px}
55
+ .gm-error{padding:8px 14px;border-radius:8px;background:var(--dsw-alias-interactive-bg-hover-danger);color:var(--dsw-alias-state-error-primary);font-size:12px;margin-bottom:10px;white-space:pre-wrap}
56
+ .gm-notice{padding:8px 14px;border-radius:8px;background:color-mix(in srgb,var(--dsw-alias-state-success-primary) 12%,transparent);color:var(--dsw-alias-state-success-primary);font-size:12px;margin-bottom:10px}
57
+ .gm-spinner{width:14px;height:14px;border-radius:50%;border:2px solid var(--dsw-alias-border-l1);border-top-color:var(--dsw-alias-brand-primary);animation:gm-spin .8s linear infinite;flex:none;display:inline-block;vertical-align:middle}
58
+ @keyframes gm-spin{to{transform:rotate(360deg)}}
59
+ .gm-spinner-sm{width:12px;height:12px}
60
+ /* 主按钮(蓝底)内的 spinner 用白色系,保证对比度 */
61
+ .gm-btn-primary .gm-spinner{border-color:color-mix(in srgb,#fff 35%,transparent);border-top-color:#fff}
62
+ /* 头部进行中状态条(spinner + 文案) */
63
+ .gm-busy{display:inline-flex;align-items:center;gap:6px;flex:none;font-size:12px;color:var(--dsw-alias-label-secondary);max-width:240px;white-space:nowrap;overflow:hidden}
64
+ .gm-busy-text{overflow:hidden;text-overflow:ellipsis}
65
+ /* 面板顶部不定进度条:任何操作进行中(busy)时出现,覆盖在面板顶缘不占布局 */
66
+ .gm-progress{position:absolute;top:0;left:0;right:0;height:2px;z-index:6;overflow:hidden;pointer-events:none}
67
+ .gm-progress::after{content:"";position:absolute;top:0;bottom:0;left:-35%;width:35%;border-radius:2px;background:var(--dsw-alias-brand-primary);animation:gm-progress 1.1s ease-in-out infinite}
68
+ @keyframes gm-progress{0%{left:-35%}100%{left:100%}}
69
+ .gm-empty{padding:36px 16px;text-align:center;color:var(--dsw-alias-label-tertiary);font-size:13px}
70
+
71
+ /* Composer 工具行入口按钮(模式/access-mode 选择器旁,conversation.input.left) */
72
+ .gm-toolbtn{display:inline-flex;align-items:center;gap:5px;height:28px;margin-left:-4px;padding:0 7px;border:none;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;cursor:pointer;white-space:nowrap;line-height:1}
73
+ .gm-toolbtn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
74
+ .gm-toolbtn svg{flex:none}
75
+ .gm-toolbtn-label{max-width:240px;overflow:hidden;text-overflow:ellipsis}
76
+
77
+ /* 面板头部 ahead/behind 只读徽章 */
78
+ .gm-badge{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:6px;background:var(--dsw-alias-bg-layer-1);border:1px solid var(--dsw-alias-border-l1);font-size:12px;color:var(--dsw-alias-label-primary);line-height:18px}
79
+ .gm-badge-ahead{color:var(--dsw-alias-state-success-primary);font-weight:500}
80
+ .gm-badge-behind{color:var(--dsw-alias-state-error-primary);font-weight:500}
81
+
82
+ /* Repo select + header controls */
83
+ .gm-head-path{font-size:12px;color:var(--dsw-alias-label-secondary);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
84
+ .gm-input{box-sizing:border-box;height:30px;font:inherit;font-size:12px;color:var(--dsw-alias-label-primary);background:var(--dsw-specific-input-major,var(--dsw-alias-bg-layer-1));border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:0 10px;outline:none}
85
+ .gm-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:30px;padding:0 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;cursor:pointer;white-space:nowrap}
86
+ .gm-btn:hover{background:var(--dsw-alias-interactive-bg-hover)}
87
+ .gm-btn-icon{width:30px;padding:0}
88
+ .gm-btn-primary{background:var(--dsw-alias-button-info-fill);color:#fff;border-color:transparent;background-clip:padding-box}
89
+ .gm-btn-primary:hover{background:var(--dsw-alias-button-info-hover)}
90
+ .gm-btn-danger{color:var(--dsw-alias-state-error-primary);border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary) 40%,transparent)}
91
+ .gm-btn-danger:hover{background:var(--dsw-alias-interactive-bg-hover-danger)}
92
+ .gm-btn:disabled{opacity:.5;cursor:not-allowed}
93
+ .gm-mini{display:inline-flex;align-items:center;justify-content:center;height:24px;padding:0 8px;border-radius:6px;border:1px solid var(--dsw-alias-border-l2);background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11px;cursor:pointer;white-space:nowrap;flex:none}
94
+ .gm-mini:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
95
+ .gm-mini-danger{color:var(--dsw-alias-state-error-primary);border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary) 40%,transparent)}
96
+ .gm-mini-danger:hover{background:var(--dsw-alias-interactive-bg-hover-danger);color:var(--dsw-alias-state-error-primary)}
97
+ .gm-mini:disabled{opacity:.5;cursor:not-allowed}
98
+
99
+ /* File list (Changes tab) */
100
+ .gm-filegroup{padding:8px 0}
101
+ .gm-filegroup-head{display:flex;align-items:center;gap:8px;font-weight:500;font-size:12px;color:var(--dsw-alias-label-secondary);padding:4px 2px;border-bottom:1px solid var(--dsw-alias-border-l1);margin-bottom:6px}
102
+ .gm-file{display:flex;align-items:center;gap:8px;padding:6px 8px;border-radius:8px;cursor:pointer;font-size:13px;color:var(--dsw-alias-label-primary);position:relative}
103
+ .gm-file:hover{background:var(--dsw-alias-interactive-bg-hover)}
104
+ .gm-file-active{background:var(--dsw-alias-interactive-bg-active)}
105
+ /* 分支行展开态 + 操作行(另起一行):行与操作行同底色、上下圆角互补,视觉上连成一张卡 */
106
+ .gm-file.gm-branch-open{background:var(--dsw-alias-interactive-bg-hover);border-radius:8px 8px 0 0}
107
+ .gm-branch-actions{display:flex;flex-wrap:wrap;gap:6px;align-items:center;padding:2px 10px 8px;background:var(--dsw-alias-interactive-bg-hover);border-radius:0 0 8px 8px}
108
+ /* 行尾展开指示(▸/▾):无边的微型按钮,键盘可聚焦 */
109
+ .gm-branch-caret{appearance:none;background:transparent;border:none;cursor:pointer;color:var(--dsw-alias-label-tertiary);font-size:10px;line-height:1;padding:4px;flex:none;border-radius:4px}
110
+ .gm-branch-caret:hover{color:var(--dsw-alias-label-primary)}
111
+ .gm-file-kind{font-size:10px;padding:0 6px;border-radius:999px;background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary);text-transform:uppercase;line-height:16px;flex:none}
112
+ .gm-file-kind-modified{background:color-mix(in srgb,var(--dsw-alias-brand-primary) 15%,transparent);color:var(--dsw-alias-brand-primary)}
113
+ .gm-file-kind-added{background:color-mix(in srgb,var(--dsw-alias-state-success-primary) 15%,transparent);color:var(--dsw-alias-state-success-primary)}
114
+ .gm-file-kind-deleted{background:color-mix(in srgb,var(--dsw-alias-state-error-primary) 15%,transparent);color:var(--dsw-alias-state-error-primary)}
115
+ .gm-file-kind-renamed{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 15%,transparent);color:var(--dsw-alias-state-business-primary)}
116
+ .gm-file-path{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
117
+ .gm-file-old{color:var(--dsw-alias-label-tertiary);font-size:11px;margin-left:4px}
118
+
119
+ /* 仓库切换器(分支 / 历史 / 冲突 / Worktree / 设置 Tab 顶部一行 chips) */
120
+ .gm-repo-bar{display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin-bottom:10px}
121
+ .gm-repo-chip{display:inline-flex;align-items:center;gap:5px;height:26px;padding:0 9px;max-width:240px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11px;cursor:pointer;white-space:nowrap;flex:none}
122
+ .gm-repo-chip:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
123
+ .gm-repo-chip-active{background:var(--dsw-specific-sidebar-nav-item-active);border-color:transparent;color:var(--dsw-alias-label-primary);font-weight:500}
124
+ .gm-repo-chip svg{flex:none}
125
+ .gm-repo-chip-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
126
+ .gm-repo-chip-count{font-size:10px;line-height:14px;padding:0 5px;border-radius:999px;background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary);flex:none}
127
+ .gm-repo-dot{width:6px;height:6px;border-radius:50%;background:var(--dsw-alias-state-error-primary);flex:none}
128
+
129
+ /* Worktree 行内状态(review 方案 B)与作用域条(方案 A,2026-10-20) */
130
+ .gm-wt-counts{font-size:11px;color:var(--dsw-alias-label-secondary);font-family:ui-monospace,monospace;flex:none;white-space:nowrap}
131
+ .gm-wt-counts-conflict{color:var(--dsw-alias-state-error-primary);font-weight:500}
132
+ .gm-wt-ab{font-size:10px;line-height:16px;padding:0 6px;border-radius:999px;background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary);flex:none;white-space:nowrap}
133
+ .gm-wt-row-active{background:var(--dsw-specific-sidebar-nav-item-active)}
134
+ .gm-wt-scope{display:flex;align-items:center;gap:8px;padding:7px 12px;font-size:12px;color:var(--dsw-alias-label-secondary);border-bottom:1px solid var(--dsw-alias-border-l1);background:color-mix(in srgb,var(--dsw-alias-brand-primary) 8%,transparent)}
135
+ .gm-wt-scope-path{color:var(--dsw-alias-label-primary);font-family:ui-monospace,monospace;font-size:11px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
136
+
137
+ /* 变更 Tab:按仓库分组的文件列表(子仓库支持 P0) */
138
+ .gm-repogroup{margin-top:12px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;overflow:hidden}
139
+ .gm-repogroup-head{display:flex;align-items:center;gap:8px;padding:7px 10px;background:var(--dsw-alias-bg-layer-1);font-size:12px}
140
+ .gm-repogroup-head>svg{flex:none;color:var(--dsw-alias-label-secondary)}
141
+ .gm-repogroup-name{font-weight:500;color:var(--dsw-alias-label-primary);max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
142
+ .gm-repogroup-rel{font-size:11px;color:var(--dsw-alias-label-tertiary);font-family:ui-monospace,monospace;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
143
+ .gm-repogroup-branch{font-size:10px;line-height:16px;padding:0 6px;border-radius:999px;background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary);max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:none}
144
+ .gm-repogroup-counts{font-size:11px;color:var(--dsw-alias-label-secondary);font-family:ui-monospace,monospace;flex:none}
145
+ .gm-repogroup-body{padding:4px 4px 8px}
146
+ .gm-sub-badge{font-size:10px;line-height:16px;padding:0 6px;border-radius:999px;white-space:nowrap;flex:none}
147
+ .gm-sub-badge-warn{background:var(--dsw-alias-state-warn-tertiary);color:var(--dsw-alias-state-warn-label)}
148
+ .gm-sub-badge-error{background:color-mix(in srgb,var(--dsw-alias-state-error-primary) 15%,transparent);color:var(--dsw-alias-state-error-primary)}
149
+ .gm-sub-badge-mute{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-tertiary)}
150
+ .gm-sub-badge-ok{background:color-mix(in srgb,var(--dsw-alias-state-success-primary) 15%,transparent);color:var(--dsw-alias-state-success-primary)}
151
+ .gm-mini-weak{opacity:.6}
152
+ .gm-mini-weak:hover{opacity:1}
153
+ .gm-notice-warn{padding:8px 14px;border-radius:8px;background:var(--dsw-alias-state-warn-tertiary);color:var(--dsw-alias-state-warn-label);font-size:12px;margin-bottom:10px;white-space:pre-wrap}
154
+
155
+ /* 设置 Tab「子仓库」管理区(submodule 管理,P2) */
156
+ .gm-sub-row{display:flex;align-items:center;gap:8px;padding:6px 8px;border-radius:8px;font-size:12px}
157
+ .gm-sub-row:hover{background:var(--dsw-alias-interactive-bg-hover)}
158
+ .gm-sub-row-name{flex:none;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-primary)}
159
+ .gm-sub-row-rel{flex:none;max-width:170px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;font-family:ui-monospace,monospace;color:var(--dsw-alias-label-tertiary)}
160
+ .gm-sub-row-meta{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;color:var(--dsw-alias-label-tertiary)}
161
+ .gm-sub-row-actions{flex:none;display:flex;align-items:center;gap:6px}
162
+ .gm-sub-group-hint{font-size:11px;color:var(--dsw-alias-label-tertiary);padding:2px 2px 4px}
163
+
164
+ /* Diff view */
165
+ .gm-diff{background:var(--dsw-alias-bg-layer-1);border-radius:10px;padding:10px 14px;margin-top:10px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;line-height:18px;overflow-x:auto;max-height:60vh}
166
+ .gm-diff-file{padding:6px 0;border-bottom:1px solid var(--dsw-alias-border-l1)}
167
+ .gm-diff-file:last-child{border-bottom:none}
168
+ .gm-diff-fileh{font-family:var(--dsw-font-sans,inherit);font-size:12px;font-weight:500;color:var(--dsw-alias-label-primary);padding:4px 0;cursor:pointer;display:flex;align-items:center;gap:8px}
169
+ .gm-diff-fileh:hover{color:var(--dsw-alias-brand-primary)}
170
+ .gm-diff-hunk{color:var(--dsw-alias-label-tertiary);font-size:11px;padding:2px 0;display:flex;align-items:center;gap:8px}
171
+ .gm-diff-hunk>span{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
172
+ .gm-diff-line{white-space:pre-wrap;word-break:break-all;overflow-wrap:anywhere;padding:0 6px}
173
+ .gm-diff-add{background:color-mix(in srgb,var(--dsw-alias-state-success-primary) 15%,transparent);color:var(--dsw-alias-state-success-primary)}
174
+ .gm-diff-del{background:color-mix(in srgb,var(--dsw-alias-state-error-primary) 15%,transparent);color:var(--dsw-alias-state-error-primary)}
175
+ .gm-diff-ctx{color:var(--dsw-alias-label-secondary)}
176
+ .gm-diff-meta{color:var(--dsw-alias-label-tertiary)}
177
+ .gm-diff-trunc{padding:8px 0;font-family:var(--dsw-font-sans,inherit);font-size:12px;color:var(--dsw-alias-label-tertiary);font-style:italic}
178
+
179
+ /* Diff 独立窗口(盖在面板 z-index:1000 之上、确认框 z-index:1100 之下) */
180
+ .gm-diffwin{position:fixed;inset:0;z-index:1050;display:flex;align-items:center;justify-content:center}
181
+ .gm-diffwin-panel{position:relative;z-index:1;width:min(1080px,calc(100vw - 64px));height:min(780px,100vh - 96px);display:flex;flex-direction:column;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);border-radius:16px;box-shadow:var(--dsw-shadow-lv3);overflow:hidden}
182
+ .gm-diffwin-body{flex:1;min-height:0;overflow:auto;padding:12px 16px}
183
+ .gm-diffwin-body .gm-diff{margin-top:0;max-height:none}
184
+
185
+ /* hunk 级操作按钮(IDEA 式逐块撤销/暂存/取消暂存) */
186
+ .gm-hunk-btn{flex:none;display:inline-flex;align-items:center;gap:4px;height:22px;padding:0 8px;border:1px solid var(--dsw-alias-border-l2);border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11px;cursor:pointer;white-space:nowrap}
187
+ .gm-hunk-btn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
188
+ .gm-hunk-btn-danger{color:var(--dsw-alias-state-error-primary);border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary) 40%,transparent)}
189
+ .gm-hunk-btn-danger:hover{background:var(--dsw-alias-interactive-bg-hover-danger);color:var(--dsw-alias-state-error-primary)}
190
+
191
+ /* Commit box */
192
+ .gm-commit{margin-top:14px;display:flex;flex-direction:column;gap:8px;padding:12px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}
193
+ .gm-textarea{box-sizing:border-box;width:100%;min-height:60px;font:inherit;font-size:12px;color:var(--dsw-alias-label-primary);background:var(--dsw-specific-input-major,var(--dsw-alias-bg-layer-1));border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:8px;outline:none;resize:vertical;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
194
+ .gm-checkbox{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--dsw-alias-label-secondary);cursor:pointer}
195
+ .gm-checkbox input{accent-color:var(--dsw-alias-brand-primary)}
196
+ .gm-radio{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--dsw-alias-label-primary);cursor:pointer;margin-right:14px}
197
+ .gm-radio input{accent-color:var(--dsw-alias-brand-primary)}
198
+
199
+ /* 折叠区(Stash / Tag / 设置) */
200
+ .gm-section{margin-top:14px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);padding:10px 12px}
201
+ .gm-section-head{display:flex;align-items:center;gap:8px;font-size:12px;font-weight:500;color:var(--dsw-alias-label-secondary)}
202
+ .gm-section-title{cursor:pointer;display:inline-flex;align-items:center;gap:6px;color:var(--dsw-alias-label-primary);font-weight:500}
203
+ .gm-section-title:hover{color:var(--dsw-alias-brand-primary)}
204
+ .gm-tag-badge{font-size:10px;padding:0 6px;border-radius:999px;line-height:16px;box-sizing:border-box;background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 10%,var(--dsw-alias-bg-layer-2));border:1px solid color-mix(in srgb,var(--dsw-alias-state-business-primary) 35%,transparent);color:var(--dsw-alias-state-business-primary);flex:none}
205
+
206
+ /* Confirm / form dialog(Portal 落 body,z-index 由 modalStack 阶梯给出) */
207
+ .gm-confirm{position:fixed;inset:0;z-index:1100;background:var(--dsw-alias-bg-mask-1);backdrop-filter:var(--dsw-mask-blur);display:flex;align-items:center;justify-content:center}
208
+ .gm-confirm-modal{width:min(420px,90vw);max-height:calc(100vh - 64px);overflow:auto;padding:18px;background:var(--dsw-alias-bg-layer-2);border-radius:16px;box-shadow:var(--dsw-shadow-lv3)}
209
+ .gm-confirm-title{font-size:14px;font-weight:600;margin-bottom:8px}
210
+ .gm-confirm-msg{font-size:13px;color:var(--dsw-alias-label-secondary);margin-bottom:14px;white-space:pre-wrap}
211
+ .gm-confirm-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:14px}
212
+ .gm-form-row{display:flex;flex-direction:column;gap:4px;margin-bottom:10px}
213
+ .gm-form-label{font-size:12px;color:var(--dsw-alias-label-secondary)}
214
+
215
+ /* 历史:过滤条 + 提交详情侧栏 */
216
+ .gm-filterbar{display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin-bottom:10px}
217
+ .gm-hist-wrap{display:flex;gap:12px;align-items:flex-start}
218
+ .gm-hist-main{flex:1;min-width:0}
219
+ .gm-hist-detail{width:270px;flex:none;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);padding:10px 12px;font-size:12px;overflow:auto;max-height:100%}
220
+ .gm-detail-msg{white-space:pre-wrap;word-break:break-word;color:var(--dsw-alias-label-primary);margin:6px 0 10px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;line-height:17px;max-height:220px;overflow:auto}
221
+ .gm-detail-file{display:flex;align-items:center;gap:6px;padding:4px 2px;cursor:pointer;border-radius:6px;font-size:12px;color:var(--dsw-alias-label-primary)}
222
+ .gm-detail-file:hover{background:var(--dsw-alias-interactive-bg-hover)}
223
+ .gm-detail-count{margin-left:auto;font-family:ui-monospace,monospace;font-size:10px;flex:none}
224
+ .gm-meta{font-size:11px;color:var(--dsw-alias-label-tertiary)}
225
+
226
+ /* 设置:config 表 */
227
+ .gm-cfg-row{display:flex;gap:6px;align-items:center;padding:4px 0}
228
+ .gm-cfg-row .gm-input{flex:1;min-width:0}
229
+
230
+ /* 模式切换按钮选中态(历史 Tab 提交 | Reflog) */
231
+ .gm-mini-on{background:var(--dsw-specific-sidebar-nav-item-active);color:var(--dsw-alias-label-primary);border-color:transparent}
232
+
233
+ /* Blame 只读窗口(gutter 分组 + 行号 + 行内容) */
234
+ .gm-blame{background:var(--dsw-alias-bg-layer-1);border-radius:10px;padding:10px 14px;margin-top:10px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;line-height:18px;overflow-x:auto}
235
+ .gm-blame-grp{margin-bottom:2px;border-left:3px solid color-mix(in srgb,var(--dsw-alias-brand-primary) 45%,transparent)}
236
+ .gm-blame-head{display:flex;align-items:center;gap:8px;font-family:var(--dsw-font-sans,inherit);font-size:11px;color:var(--dsw-alias-label-secondary);padding:2px 8px}
237
+ .gm-blame-sha{color:var(--dsw-alias-brand-primary);font-family:ui-monospace,monospace}
238
+ .gm-blame-row{display:flex;gap:10px;align-items:baseline;padding:0 8px}
239
+ .gm-blame-no{flex:none;width:42px;text-align:right;color:var(--dsw-alias-label-tertiary);font-size:11px;user-select:none}
240
+ .gm-blame-text{white-space:pre-wrap;word-break:break-all;overflow-wrap:anywhere;color:var(--dsw-alias-label-primary)}
241
+
242
+ /* 行级选择(diff 窗口内点选 / shift 点选多行,契约 §8.3) */
243
+ .gm-diff-sel-on{cursor:pointer}
244
+ .gm-diff-sel-on:hover{background:color-mix(in srgb,var(--dsw-alias-brand-primary) 10%,transparent)}
245
+ .gm-diff-line-sel{background:color-mix(in srgb,var(--dsw-alias-brand-primary) 22%,transparent)}
246
+ .gm-linebar{position:absolute;left:50%;bottom:18px;transform:translateX(-50%);display:flex;gap:8px;align-items:center;padding:8px 12px;border-radius:10px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);box-shadow:var(--dsw-shadow-lv3);z-index:2}
247
+
248
+ /* rebase todo 弹窗行 */
249
+ .gm-todo-row{display:flex;align-items:center;gap:6px;padding:3px 0}
250
+ .gm-todo-sha{flex:none;font-family:ui-monospace,monospace;font-size:11px;color:var(--dsw-alias-label-tertiary);width:64px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
251
+ .gm-todo-subject{flex:1;min-width:0;font-size:12px;color:var(--dsw-alias-label-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
252
+
253
+ /* toast(右下角轻提示,undo 的重做提示走这里) */
254
+ .gm-toast{position:fixed;right:24px;bottom:24px;z-index:1150;max-width:min(440px,calc(100vw - 48px));padding:10px 14px;border-radius:10px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);box-shadow:var(--dsw-shadow-lv3);font-size:12px;color:var(--dsw-alias-label-primary);display:flex;gap:10px;align-items:flex-start}
255
+ .gm-toast-text{flex:1;white-space:pre-wrap;word-break:break-word}
256
+ `;
257
+
258
+ // ---- Client Remote 自挂载 ----
259
+ // strict codec 双形态(与 typert.host.js 同因):0.1.5 客户端 registry 校验
260
+ // `schema.parse`,0.1.7 校验 `create()` 工厂——只写一边会在另一端
261
+ // ctx.remote.$mount 注册时抛错,插件整个 apply 失败、入口不出现。
262
+ const passthrough = () => ({ parse: (v) => v });
263
+ const method = (m) => ({
264
+ id: "dsh-volcano-git-plugin#gitManager/" + m,
265
+ service: "gitManager", namespace: "gitManager", method: m,
266
+ invocation: { kind: "direct" },
267
+ parameters: [{ name: "request", wire: "request", source: "json",
268
+ codec: { mode: "strict", typeSymbol: "dsh-volcano-git-plugin#GitManager" + m + "Request", schema: passthrough(), create: passthrough } }],
269
+ result: { mode: "strict", typeSymbol: "dsh-volcano-git-plugin#GitManager" + m + "Result", schema: passthrough(), create: passthrough },
270
+ });
271
+ // Remote 方法(与 index.js + typert.host.js 一致;self-test 静态守卫校验)。
272
+ // 前 30 个是 v1 方法,其后按契约顺序:stageHunk(P0) → P1 全家 → P2 全家 → P3-A 五个。
273
+ const CLIENT_METHODS = [
274
+ "probe","overview","status","diff","log","branches","remotes","worktrees",
275
+ "conflictContent","stage","unstage","discard","hunkApply","commit","branchCreate",
276
+ "checkout","branchDelete","branchRename","merge","mergeAbort","mergeContinue",
277
+ "cherryPick","resolveConflict","fetch","pull","push","worktreeAdd","worktreeRemove",
278
+ "worktreePrune","init",
279
+ "stageHunk",
280
+ "stashList","stashPush","stashPop","stashApply","stashDrop","stashClear",
281
+ "tags","tagCreate","tagDelete",
282
+ "reset","revert","blame","diffRange","reflog",
283
+ "remoteAdd","remoteRemove","remoteRename","configList","configSet","configUnset",
284
+ "rebasePlan","rebaseRun","fixupCommit","rebaseBranch","lineApply",
285
+ // 子仓库支持(契约 docs/plans/2026-10-13-subrepo-support.md §2.2,P0)
286
+ "repoTree",
287
+ // 子仓库支持 P1(§3.6):子模块指针提交是否在子仓库当前对象库中
288
+ "revExists",
289
+ // 子仓库支持 P2(§7 P2 / 方案 §2.2):submodule 管理五件套
290
+ // (init / update / sync / deinit / add——设置 Tab「子仓库」管理区、
291
+ // 变更 Tab 未初始化组头「初始化」、nested → submodule 注册共用)
292
+ "submoduleInit","submoduleUpdate","submoduleSync","submoduleDeinit","submoduleAdd",
293
+ ];
294
+ const CLIENT_REMOTE = {
295
+ package: "dsh-volcano-git-plugin",
296
+ descriptors: CLIENT_METHODS.map(method),
297
+ };
298
+
299
+ // 解包网关响应包络(archive-manager 同款;DSH 插件间曾出现过两种形态,赌形态必翻车)
300
+ function unwrap(res) {
301
+ if (!res || res.ok !== true) {
302
+ return { ok: false, error: (res && res.error) || { code: "transport", message: "调用失败" } };
303
+ }
304
+ const v = res.value;
305
+ if (v && typeof v === "object" && typeof v.ok === "boolean") return v;
306
+ return { ok: true, value: v };
307
+ }
308
+
309
+ // ---- 模块级状态(面板开关、目标路径) ----
310
+ let openState = { open: false, targetPath: undefined };
311
+ const listeners = new Set();
312
+ function setOpen(open, targetPath) {
313
+ openState = { open: !!open, targetPath: targetPath === undefined ? (openState.targetPath || null) : targetPath };
314
+ listeners.forEach((f) => f());
315
+ }
316
+ function useOpen() {
317
+ return React.useSyncExternalStore(
318
+ (cb) => { listeners.add(cb); return () => listeners.delete(cb); },
319
+ () => openState.open,
320
+ );
321
+ }
322
+ function useTargetPath() {
323
+ return React.useSyncExternalStore(
324
+ (cb) => { listeners.add(cb); return () => listeners.delete(cb); },
325
+ () => openState.targetPath,
326
+ );
327
+ }
328
+
329
+ // ---- Git 变更广播(composer 入口按钮徽标联动,v3) ----
330
+ // 面板内任何成功 mutation 都 notifyGitMutation();ComposerGitButton 订阅该
331
+ // 信号立即重跑 probe——否则切换分支后入口处的分支徽标要等 60s 轮询才更新。
332
+ let gitMutTick = 0;
333
+ const gitMutListeners = new Set();
334
+ function notifyGitMutation() {
335
+ gitMutTick += 1;
336
+ gitMutListeners.forEach((f) => f());
337
+ }
338
+ function useGitMutationTick() {
339
+ return React.useSyncExternalStore(
340
+ (cb) => { gitMutListeners.add(cb); return () => gitMutListeners.delete(cb); },
341
+ () => gitMutTick,
342
+ );
343
+ }
344
+
345
+ // ---- 弹层栈(契约 §0 P0 修复) ----
346
+ // modalStack:顶层弹层(diff 窗口 / 确认框 / 表单弹窗 / 冲突编辑器)注册 { close, kind, z }。
347
+ // document 级 Esc 只关栈顶;面板 Esc 仅在栈空时关面板;mask 点击只关自身。
348
+ // z-index 阶梯:面板 1000 < diffwin 1050 < dialog 1100(dialog 叠 dialog 每层 +10)。
349
+ const modalStack = [];
350
+ function useModalLayer(open, close, kind) {
351
+ const closeRef = React.useRef(close);
352
+ closeRef.current = close;
353
+ const baseZ = kind === "diffwin" ? 1050 : 1100;
354
+ const [z, setZ] = React.useState(baseZ);
355
+ React.useEffect(() => {
356
+ if (!open) return undefined;
357
+ // dialog 叠 dialog 时每层 +10;diffwin 恒 1050
358
+ const below = kind === "diffwin" ? 0 : modalStack.filter((m) => m.kind !== "diffwin").length;
359
+ const entry = {
360
+ kind,
361
+ z: baseZ + 10 * below,
362
+ close: () => { const f = closeRef.current; if (typeof f === "function") f(); },
363
+ };
364
+ modalStack.push(entry);
365
+ setZ(entry.z);
366
+ return () => {
367
+ const i = modalStack.indexOf(entry);
368
+ if (i >= 0) modalStack.splice(i, 1);
369
+ };
370
+ }, [open]);
371
+ return z;
372
+ }
373
+
374
+ // ---- 冲突来源跟踪(冲突 Tab 底部按钮分流,契约 §3.5) ----
375
+ // stash pop/apply 冲突不写 MERGE_HEAD,与 merge/cherry-pick/revert 冲突在 status 上
376
+ // 不可区分(status 只有 merging=MERGE_HEAD / rebasing=rebase-*)——由发起操作的
377
+ // UI 记录来源:"stash" | "cherry" | "revert" | "merge" | null(会话外产生的未知态)。
378
+ let conflictSource = null;
379
+ let stashConflictIndex = 0;
380
+
381
+ // ---- toast(右下角轻提示;undo/redo 提示走这里,契约 §8.5) ----
382
+ let toastState = { text: "", id: 0 };
383
+ const toastListeners = new Set();
384
+ function showToast(text) {
385
+ toastState = { text: String(text || ""), id: toastState.id + 1 };
386
+ toastListeners.forEach((f) => f());
387
+ }
388
+ function useToast() {
389
+ return React.useSyncExternalStore(
390
+ (cb) => { toastListeners.add(cb); return () => toastListeners.delete(cb); },
391
+ () => toastState,
392
+ );
393
+ }
394
+ function Toast(props) {
395
+ const t = useToast();
396
+ React.useEffect(() => {
397
+ if (!t.text) return undefined;
398
+ const timer = setTimeout(() => showToast(""), 10000);
399
+ return () => clearTimeout(timer);
400
+ }, [t.id]);
401
+ if (!t.text) return null;
402
+ return ReactDOM.createPortal(
403
+ React.createElement("div", { className: "gm-toast", role: "status" },
404
+ React.createElement("span", { className: "gm-toast-text" }, t.text),
405
+ React.createElement("button", { className: "gm-mini", title: "关闭", onClick: () => showToast("") }, "×"),
406
+ ),
407
+ document.body,
408
+ );
409
+ }
410
+
411
+ // git 空树 sha(40 位纯 hex,checkRev 放行):根提交(无父)逐版本 diff 的 from 兜底
412
+ const EMPTY_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
413
+
414
+ // ---- helpers ----
415
+ function fmtTime(unix) {
416
+ if (!unix) return "";
417
+ const d = Date.now() - Number(unix) * 1000;
418
+ const m = 60, h = 3600, D = 86400;
419
+ if (d < m) return "刚刚";
420
+ if (d < h) return Math.floor(d / m) + " 分钟前";
421
+ if (d < D) return Math.floor(d / h) + " 小时前";
422
+ if (d < 30 * D) return Math.floor(d / D) + " 天前";
423
+ const dt = new Date(Number(unix) * 1000);
424
+ return dt.getFullYear() + "-" + String(dt.getMonth() + 1).padStart(2, "0") + "-" + String(dt.getDate()).padStart(2, "0");
425
+ }
426
+
427
+ // 从 `git show --format=fuller` 文本里取出完整提交信息(subject + body)
428
+ function parseShowMessage(text) {
429
+ const idx = typeof text === "string" ? text.indexOf("\ndiff --git ") : -1;
430
+ const head = idx >= 0 ? text.slice(0, idx) : (text || "");
431
+ const out = [];
432
+ let started = false;
433
+ for (const line of head.split("\n")) {
434
+ if (/^(commit|Author|AuthorDate|Commit|CommitDate|Merge|Date):/.test(line)) { started = true; continue; }
435
+ if (!started) continue;
436
+ out.push(line.replace(/^ /, ""));
437
+ }
438
+ return out.join("\n").trim();
439
+ }
440
+
441
+ // ---- Composer 工具行入口按钮(conversation.input.left,模式/access-mode 选择器旁) ----
442
+ // 该槽是 session 作用域 list 槽,framework 注入完整标准 kit(sessionId / useSessions /
443
+ // useWorkspaces / useInput / inputActions,见 InputZone owner props);hero 空白会话的
444
+ // composer 同样渲染这一行,一个槽位同时覆盖 hero 与会话内。
445
+ // 仅当目标目录是 git 仓库时显示(probe 结果 60s 轮询刷新;非仓库返回 null 不占位)。
446
+ function ComposerGitButton(props) {
447
+ const remote = props && props.remote;
448
+ const sessionId = props && props.sessionId;
449
+ const useSessions = props && props.useSessions;
450
+ // sessionId 优先级:framework kit 显式传的 props.sessionId > list.current(兜底)
451
+ // session header.cwd 不可变(DSH 保留原始项目目录),实时目录在 workingDirectory 投影里
452
+ const summaryCwd = useSessions
453
+ ? useSessions((s) => {
454
+ const id = sessionId || (s && s.current);
455
+ const sum = id && s && s.byId ? s.byId[id] : undefined;
456
+ return (sum && sum.cwd) || null;
457
+ })
458
+ : null;
459
+ const liveCwd = props && props.useProjection ? props.useProjection("workingDirectory") : null;
460
+ const cwd = liveCwd || summaryCwd;
461
+ const [probe, setProbe] = React.useState(null);
462
+ const mutTick = useGitMutationTick();
463
+
464
+ React.useEffect(() => {
465
+ let alive = true;
466
+ async function run() {
467
+ if (!remote || !cwd) { setProbe(null); return; }
468
+ try {
469
+ const r = unwrap(await remote.probe({ path: cwd }));
470
+ if (!alive) return;
471
+ setProbe(r.ok && r.value ? r.value : { isRepo: false });
472
+ } catch (_) {
473
+ if (alive) setProbe({ isRepo: false });
474
+ }
475
+ }
476
+ run();
477
+ const t = setInterval(run, 60000);
478
+ return () => { alive = false; clearInterval(t); };
479
+ }, [cwd, remote, mutTick]);
480
+
481
+ if (!cwd || !probe || !probe.isRepo) return null;
482
+
483
+ const label = probe.detached
484
+ ? (probe.headShort || "detached")
485
+ : (probe.branch || "");
486
+ return React.createElement("button", {
487
+ type: "button",
488
+ className: "gm-toolbtn",
489
+ // 长分支名会被 CSS 折叠成省略号:title 必须带分支名,否则悬停看不到全名
490
+ title: label ? "Git 管理面板\n分支:" + label + "\n" + cwd : "Git 管理面板\n" + cwd,
491
+ "aria-label": label ? "打开 Git 管理面板(分支:" + label + ")" : "打开 Git 管理面板",
492
+ onClick: () => setOpen(true, cwd),
493
+ },
494
+ // git-branch 图标(Lucide 24×24)
495
+ React.createElement("svg", { width: 14, height: 14, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true },
496
+ React.createElement("path", { d: "M6 3v12" }),
497
+ React.createElement("circle", { cx: 18, cy: 6, r: 3 }),
498
+ React.createElement("circle", { cx: 6, cy: 18, r: 3 }),
499
+ React.createElement("path", { d: "M18 9a9 9 0 0 1-9 9" }),
500
+ ),
501
+ label ? React.createElement("span", { className: "gm-toolbtn-label", title: label }, label) : null,
502
+ );
503
+ }
504
+
505
+ // ============================================================================
506
+ // 通用弹层组件(全部 Portal 落 body + modalStack 注册,契约 §0)
507
+ // ============================================================================
508
+
509
+ // 通用二次确认弹窗(discard / 撤销 hunk / 删分支 / 中止 merge / 删 worktree /
510
+ // 删 stash / 清空 stash / 删 tag / 删 remote / 删 config 等危险操作)
511
+ function ConfirmDialog(props) {
512
+ const z = useModalLayer(!!props.open, props.onCancel, "dialog");
513
+ if (!props.open) return null;
514
+ return ReactDOM.createPortal(
515
+ React.createElement("div", {
516
+ className: "gm-confirm",
517
+ style: { zIndex: z },
518
+ role: "dialog",
519
+ "aria-modal": "true",
520
+ onMouseDown: (e) => { if (e.target === e.currentTarget && props.onCancel) props.onCancel(); },
521
+ },
522
+ React.createElement("div", { className: "gm-confirm-modal" },
523
+ React.createElement("div", { className: "gm-confirm-title" }, props.title),
524
+ React.createElement("div", { className: "gm-confirm-msg" }, props.message),
525
+ React.createElement("div", { className: "gm-confirm-actions" },
526
+ React.createElement("button", { className: "gm-btn", onClick: props.onCancel }, "取消"),
527
+ React.createElement("button", { className: "gm-btn " + (props.danger ? "gm-btn-danger" : "gm-btn-primary"), onClick: props.onConfirm }, props.confirmLabel || "确认"),
528
+ ),
529
+ ),
530
+ ),
531
+ document.body,
532
+ );
533
+ }
534
+
535
+ // 通用表单弹窗(stash 新建 / tag 新建 / worktree 添加 / reset / remote / config 等)
536
+ // children 是表单区(由各 Tab 用稳定的输入元素拼),actions 行固定「取消 + 提交」。
537
+ function FormDialog(props) {
538
+ const z = useModalLayer(!!props.open, props.onClose, "dialog");
539
+ if (!props.open) return null;
540
+ return ReactDOM.createPortal(
541
+ React.createElement("div", {
542
+ className: "gm-confirm",
543
+ style: { zIndex: z },
544
+ role: "dialog",
545
+ "aria-modal": "true",
546
+ onMouseDown: (e) => { if (e.target === e.currentTarget && props.onClose) props.onClose(); },
547
+ },
548
+ React.createElement("div", { className: "gm-confirm-modal", style: props.width ? { width: props.width } : null },
549
+ React.createElement("div", { className: "gm-confirm-title" }, props.title),
550
+ props.message ? React.createElement("div", { className: "gm-confirm-msg" }, props.message) : null,
551
+ props.children || null,
552
+ React.createElement("div", { className: "gm-confirm-actions" },
553
+ React.createElement("button", { className: "gm-btn", onClick: props.onClose }, "取消"),
554
+ React.createElement("button", {
555
+ className: "gm-btn " + (props.danger ? "gm-btn-danger" : "gm-btn-primary"),
556
+ onClick: props.onSubmit,
557
+ disabled: !!props.submitDisabled,
558
+ }, props.submitLabel || "确认"),
559
+ ),
560
+ ),
561
+ ),
562
+ document.body,
563
+ );
564
+ }
565
+
566
+ // ============================================================================
567
+ // DiffView:自绘统一 diff 渲染器
568
+ // parseUnifiedDiff(text) → [{ file, header, hunks, addCount, delCount, status, truncated }]
569
+ // ============================================================================
570
+ function parseUnifiedDiff(text) {
571
+ if (!text) return [];
572
+ const files = [];
573
+ const lines = text.split("\n");
574
+ let cur = null;
575
+ let curHunk = null;
576
+ let lineNoOld = 0, lineNoNew = 0;
577
+ for (const raw of lines) {
578
+ const line = raw;
579
+ if (line.startsWith("diff --git ")) {
580
+ if (cur) files.push(cur);
581
+ cur = { file: line.slice("diff --git ".length), header: line, hunks: [], addCount: 0, delCount: 0, status: "modified" };
582
+ curHunk = null;
583
+ } else if (line.startsWith("--- ")) {
584
+ if (cur) cur.oldPath = line.slice(4);
585
+ } else if (line.startsWith("+++ ")) {
586
+ if (cur) cur.newPath = line.slice(4);
587
+ } else if (line.startsWith("new file mode")) {
588
+ if (cur) cur.status = "added";
589
+ } else if (line.startsWith("deleted file mode")) {
590
+ if (cur) cur.status = "deleted";
591
+ } else if (line.startsWith("rename from") || line.startsWith("copy from")) {
592
+ if (cur) cur.status = line.startsWith("rename") ? "renamed" : "copied";
593
+ } else if (line.startsWith("@@")) {
594
+ const m = line.match(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
595
+ lineNoOld = m ? Number(m[1]) : 0;
596
+ lineNoNew = m ? Number(m[2]) : 0;
597
+ curHunk = { header: line, lines: [] };
598
+ if (cur) cur.hunks.push(curHunk);
599
+ } else if (curHunk && (line.startsWith("+") || line.startsWith("-") || line.startsWith(" ") || line.startsWith("\\"))) {
600
+ const kind = line.startsWith("+") ? "add" : line.startsWith("-") ? "del" : line.startsWith("\\") ? "meta" : "ctx";
601
+ curHunk.lines.push({ kind, text: line });
602
+ if (kind === "add") { cur.addCount++; lineNoNew++; }
603
+ else if (kind === "del") { cur.delCount++; lineNoOld++; }
604
+ else if (kind === "ctx") { lineNoOld++; lineNoNew++; }
605
+ }
606
+ }
607
+ if (cur) files.push(cur);
608
+ return files;
609
+ }
610
+
611
+ // 单次渲染行数上限(契约 §3.7:禁止一次渲染 >5000 行,超出截断 + 提示)
612
+ const RENDER_LINE_CAP = 5000;
613
+
614
+ function DiffView(props) {
615
+ const files = parseUnifiedDiff(props.text);
616
+ if (files.length === 0) {
617
+ return React.createElement("div", { className: "gm-diff" },
618
+ React.createElement("div", { className: "gm-diff-meta" }, "(空差异)"),
619
+ );
620
+ }
621
+ // hunkActions:每个代码块一排操作按钮(IDEA 式逐块操作);
622
+ // hunk 索引 = 该文件段内的序号(diff 窗口始终是单文件 diff)。
623
+ const hunkActions = Array.isArray(props.hunkActions) ? props.hunkActions : [];
624
+ let budget = RENDER_LINE_CAP;
625
+ let overflow = false;
626
+ return React.createElement("div", { className: "gm-diff" },
627
+ props.truncated ? React.createElement("div", { className: "gm-diff-trunc" }, "差异过大,已截断。请指定单文件以查看完整内容。") : null,
628
+ files.map((f, i) => {
629
+ const filePath = (f.newPath || f.oldPath || f.file || "").replace(/^[ab]\//, "").replace(/^"/, "").replace(/"$/, "");
630
+ return React.createElement("div", { key: i, className: "gm-diff-file" },
631
+ React.createElement("div", { className: "gm-diff-fileh" }, filePath + " ",
632
+ React.createElement("span", { className: "gm-file-kind gm-file-kind-added" }, "+" + f.addCount),
633
+ " ",
634
+ React.createElement("span", { className: "gm-file-kind gm-file-kind-deleted" }, "-" + f.delCount),
635
+ ),
636
+ f.hunks.map((h, j) => React.createElement("div", { key: j },
637
+ React.createElement("div", { className: "gm-diff-hunk" },
638
+ React.createElement("span", null, h.header),
639
+ hunkActions.map((a, ai) => React.createElement("button", {
640
+ key: ai,
641
+ className: "gm-hunk-btn" + (a.danger ? " gm-hunk-btn-danger" : ""),
642
+ title: a.title || undefined,
643
+ onClick: () => a.onClick(j),
644
+ }, a.label)),
645
+ ),
646
+ h.lines.map((ln, k) => {
647
+ if (budget <= 0) { overflow = true; return null; }
648
+ budget--;
649
+ // 行级选择(契约 §8.3):sel = { h: hunkIndex, a, b }(该 hunk 内 diff 行下标)
650
+ const selected = !!(props.sel && props.sel.h === j
651
+ && k >= Math.min(props.sel.a, props.sel.b)
652
+ && k <= Math.max(props.sel.a, props.sel.b));
653
+ return React.createElement("div", {
654
+ key: k,
655
+ className: "gm-diff-line gm-diff-" + ln.kind
656
+ + (props.onLineClick ? " gm-diff-sel-on" : "")
657
+ + (selected ? " gm-diff-line-sel" : ""),
658
+ onClick: props.onLineClick ? (e) => props.onLineClick(j, k, e.shiftKey) : undefined,
659
+ }, ln.text);
660
+ }),
661
+ )),
662
+ );
663
+ }),
664
+ overflow ? React.createElement("div", { className: "gm-diff-trunc" }, "内容超过 " + RENDER_LINE_CAP + " 行,仅显示前 " + RENDER_LINE_CAP + " 行。请指定单文件查看完整差异。") : null,
665
+ );
666
+ }
667
+
668
+ // 纯文本输出(diffRange kind=stat 等非 unified diff 内容)
669
+ function PlainText(props) {
670
+ const all = (props.text || "").split("\n");
671
+ const shown = all.slice(0, RENDER_LINE_CAP);
672
+ return React.createElement("div", { className: "gm-diff" },
673
+ props.truncated ? React.createElement("div", { className: "gm-diff-trunc" }, "输出过大,已截断。") : null,
674
+ shown.map((l, i) => React.createElement("div", { key: i, className: "gm-diff-line gm-diff-ctx" }, l === "" ? " " : l)),
675
+ all.length > RENDER_LINE_CAP ? React.createElement("div", { className: "gm-diff-trunc" }, "超过 " + RENDER_LINE_CAP + " 行,仅显示前 " + RENDER_LINE_CAP + " 行。") : null,
676
+ );
677
+ }
678
+
679
+ // ============================================================================
680
+ // DiffWindow:diff 独立窗口(Portal 落 body,z-index 1050 盖在面板之上;
681
+ // Esc/mask 只关窗口本身——modalStack 栈顶规则,确认框等弹窗会叠在它上面)
682
+ // ============================================================================
683
+ function DiffWindow(props) {
684
+ // { title, sub, loading, text, truncated, plain, onClose, onRefresh, actions,
685
+ // hunkActions: [{ label, danger, title, onClick(hunkIndex) }],
686
+ // sel, onLineClick, lineBar }
687
+ useModalLayer(true, props.onClose, "diffwin");
688
+ return ReactDOM.createPortal(
689
+ React.createElement("div", { className: "gm-diffwin", role: "dialog", "aria-modal": "true" },
690
+ React.createElement("div", { className: "gm-mask", onClick: props.onClose }),
691
+ React.createElement("div", { className: "gm-diffwin-panel" },
692
+ React.createElement("div", { className: "gm-head" },
693
+ React.createElement("span", { className: "gm-head-title" }, props.title || "差异"),
694
+ props.sub ? React.createElement("span", { className: "gm-head-path", title: props.sub }, props.sub) : null,
695
+ React.createElement("span", { className: "gm-head-spacer" }),
696
+ props.actions || null,
697
+ props.onRefresh ? React.createElement("button", { className: "gm-btn", onClick: props.onRefresh, disabled: !!props.loading }, "刷新") : null,
698
+ React.createElement("button", { className: "gm-btn gm-btn-icon", onClick: props.onClose, title: "关闭(Esc)", "aria-label": "关闭 diff 窗口" },
699
+ React.createElement("svg", { width: 14, height: 14, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", "aria-hidden": true },
700
+ React.createElement("path", { d: "M18 6 6 18" }),
701
+ React.createElement("path", { d: "m6 6 12 12" }),
702
+ ),
703
+ ),
704
+ ),
705
+ React.createElement("div", { className: "gm-diffwin-body" },
706
+ props.loading
707
+ ? React.createElement("div", { className: "gm-empty" },
708
+ React.createElement("span", { className: "gm-spinner" }),
709
+ " 加载差异…",
710
+ )
711
+ : props.plain
712
+ ? React.createElement(PlainText, { text: props.text || "", truncated: !!props.truncated })
713
+ : React.createElement(DiffView, {
714
+ text: props.text || "",
715
+ truncated: !!props.truncated,
716
+ hunkActions: props.hunkActions,
717
+ sel: props.sel,
718
+ onLineClick: props.onLineClick,
719
+ }),
720
+ ),
721
+ // 行级选择浮出操作条(由调用方构造;契约 §8.3)
722
+ props.lineBar || null,
723
+ ),
724
+ ),
725
+ document.body,
726
+ );
727
+ }
728
+
729
+ // ============================================================================
730
+ // BlameView / BlameWindow:只读 blame 窗口(契约 §3.4b)
731
+ // blameLine[] 按 sha 连续分组:gutter(short sha + author + 日期)+ 行号 + 行内容
732
+ // ============================================================================
733
+ function BlameView(props) {
734
+ const lines = Array.isArray(props.lines) ? props.lines : [];
735
+ // 按 sha 连续分组
736
+ const groups = [];
737
+ for (const ln of lines) {
738
+ const last = groups.length > 0 ? groups[groups.length - 1] : null;
739
+ if (last && last.sha === ln.sha) last.lines.push(ln);
740
+ else groups.push({ sha: ln.sha, short: ln.short, author: ln.author, at: ln.at, lines: [ln] });
741
+ }
742
+ let budget = RENDER_LINE_CAP;
743
+ let overflow = false;
744
+ return React.createElement("div", { className: "gm-blame" },
745
+ props.truncated ? React.createElement("div", { className: "gm-diff-trunc" }, "blame 数据过大,已截断。") : null,
746
+ groups.map((g, i) => React.createElement("div", { key: i, className: "gm-blame-grp" },
747
+ React.createElement("div", { className: "gm-blame-head" },
748
+ React.createElement("span", { className: "gm-blame-sha" }, g.short || (g.sha || "").slice(0, 8)),
749
+ React.createElement("span", null, g.author || ""),
750
+ React.createElement("span", { className: "gm-meta" }, fmtTime(g.at)),
751
+ ),
752
+ g.lines.map((ln, k) => {
753
+ if (budget <= 0) { overflow = true; return null; }
754
+ budget--;
755
+ return React.createElement("div", { key: k, className: "gm-blame-row" },
756
+ React.createElement("span", { className: "gm-blame-no" }, String(ln.line)),
757
+ React.createElement("span", { className: "gm-blame-text" }, ln.text === "" ? " " : ln.text),
758
+ );
759
+ }),
760
+ )),
761
+ overflow ? React.createElement("div", { className: "gm-diff-trunc" }, "超过 " + RENDER_LINE_CAP + " 行,仅显示前 " + RENDER_LINE_CAP + " 行。") : null,
762
+ );
763
+ }
764
+
765
+ function BlameWindow(props) {
766
+ // { title, sub, loading, lines, truncated, onClose, onRefresh }
767
+ useModalLayer(true, props.onClose, "diffwin");
768
+ return ReactDOM.createPortal(
769
+ React.createElement("div", { className: "gm-diffwin", role: "dialog", "aria-modal": "true" },
770
+ React.createElement("div", { className: "gm-mask", onClick: props.onClose }),
771
+ React.createElement("div", { className: "gm-diffwin-panel" },
772
+ React.createElement("div", { className: "gm-head" },
773
+ React.createElement("span", { className: "gm-head-title" }, props.title || "Blame"),
774
+ props.sub ? React.createElement("span", { className: "gm-head-path", title: props.sub }, props.sub) : null,
775
+ React.createElement("span", { className: "gm-head-spacer" }),
776
+ props.onRefresh ? React.createElement("button", { className: "gm-btn", onClick: props.onRefresh, disabled: !!props.loading }, "刷新") : null,
777
+ React.createElement("button", { className: "gm-btn gm-btn-icon", onClick: props.onClose, title: "关闭(Esc)", "aria-label": "关闭 blame 窗口" },
778
+ React.createElement("svg", { width: 14, height: 14, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", "aria-hidden": true },
779
+ React.createElement("path", { d: "M18 6 6 18" }),
780
+ React.createElement("path", { d: "m6 6 12 12" }),
781
+ ),
782
+ ),
783
+ ),
784
+ React.createElement("div", { className: "gm-diffwin-body" },
785
+ props.loading
786
+ ? React.createElement("div", { className: "gm-empty" },
787
+ React.createElement("span", { className: "gm-spinner" }),
788
+ " 加载 blame…",
789
+ )
790
+ : React.createElement(BlameView, { lines: props.lines || [], truncated: !!props.truncated }),
791
+ ),
792
+ ),
793
+ ),
794
+ document.body,
795
+ );
796
+ }
797
+
798
+ // ============================================================================
799
+ // RebaseTodoDialog:rebase todo 弹窗(契约 §8.6)
800
+ // 行 = ↑↓ + short sha + subject + action 下拉(pick/squash/fixup/drop/edit);
801
+ // squash/fixup 可填 message;提交后由调用方接危险级二次确认再调 rebaseRun。
802
+ // ============================================================================
803
+ function RebaseTodoDialog(props) {
804
+ // { entries, onClose, onSubmit(entries) }
805
+ const [items, setItems] = React.useState(() => (props.entries || []).map((e) => ({
806
+ sha: e.sha,
807
+ short: e.short || (e.sha || "").slice(0, 8),
808
+ subject: e.subject || "",
809
+ action: e.action && ["pick", "squash", "fixup", "drop", "edit"].indexOf(e.action) >= 0 ? e.action : "pick",
810
+ message: e.message || "",
811
+ })));
812
+ const move = (i, delta) => setItems((arr) => {
813
+ const j = i + delta;
814
+ if (j < 0 || j >= arr.length) return arr;
815
+ const n = arr.slice();
816
+ const t = n[i]; n[i] = n[j]; n[j] = t;
817
+ return n;
818
+ });
819
+ const setField = (i, field, value) => setItems((arr) => arr.map((it, k) => (k === i ? Object.assign({}, it, { [field]: value }) : it)));
820
+ const needMessage = items.some((it) => it.action === "squash" || it.action === "fixup");
821
+ return React.createElement(FormDialog, {
822
+ open: true,
823
+ width: "min(560px,92vw)",
824
+ title: "整理历史(rebase todo)",
825
+ message: "调整提交顺序与合并方式;「开始 Rebase」会改写当前分支历史(提交 sha 会变化)。",
826
+ submitLabel: "开始 Rebase",
827
+ onClose: props.onClose,
828
+ onSubmit: () => props.onSubmit(items),
829
+ children: React.createElement(React.Fragment, null,
830
+ items.length === 0
831
+ ? React.createElement("div", { className: "gm-meta", style: { padding: "8px 0" } }, "没有可整理的提交。")
832
+ : items.map((it, i) => React.createElement("div", { key: it.sha + "@" + i, className: "gm-todo-row" },
833
+ React.createElement("button", { className: "gm-mini", disabled: i === 0, title: "上移", onClick: () => move(i, -1) }, "↑"),
834
+ React.createElement("button", { className: "gm-mini", disabled: i === items.length - 1, title: "下移", onClick: () => move(i, 1) }, "↓"),
835
+ React.createElement("span", { className: "gm-todo-sha", title: it.sha }, it.short),
836
+ React.createElement("span", { className: "gm-todo-subject", title: it.subject }, it.subject),
837
+ React.createElement("select", {
838
+ className: "gm-input",
839
+ style: { width: 86, height: 24, flex: "none" },
840
+ value: it.action,
841
+ onChange: (e) => setField(i, "action", e.target.value),
842
+ },
843
+ ["pick", "squash", "fixup", "drop", "edit"].map((a) => React.createElement("option", { key: a, value: a }, a)),
844
+ ),
845
+ )),
846
+ needMessage
847
+ ? React.createElement("div", { style: { marginTop: 10 } },
848
+ items.map((it, i) => (it.action === "squash" || it.action === "fixup")
849
+ ? React.createElement("div", { key: "msg" + it.sha + "@" + i, className: "gm-form-row" },
850
+ React.createElement("span", { className: "gm-form-label" }, it.short + " 的合并信息(可选," + it.action + ")"),
851
+ React.createElement("input", {
852
+ className: "gm-input",
853
+ value: it.message,
854
+ placeholder: "留空则沿用 git 默认合并信息",
855
+ onChange: (e) => setField(i, "message", e.target.value),
856
+ }),
857
+ )
858
+ : null),
859
+ )
860
+ : null,
861
+ ),
862
+ });
863
+ }
864
+
865
+ // ============================================================================
866
+ // FileHistoryWindow:只读文件历史视图(契约 §8.4,纯 Client)
867
+ // log({file}) 提交列表;点行开该版本 diff(diffRange from=父提交 to=该提交)。
868
+ // ============================================================================
869
+ function FileHistoryWindow(props) {
870
+ // { file, loading, entries, onClose, onRefresh, onOpenCommit(entry) }
871
+ useModalLayer(true, props.onClose, "diffwin");
872
+ return ReactDOM.createPortal(
873
+ React.createElement("div", { className: "gm-diffwin", role: "dialog", "aria-modal": "true" },
874
+ React.createElement("div", { className: "gm-mask", onClick: props.onClose }),
875
+ React.createElement("div", { className: "gm-diffwin-panel" },
876
+ React.createElement("div", { className: "gm-head" },
877
+ React.createElement("span", { className: "gm-head-title" }, "历史 — " + props.file),
878
+ React.createElement("span", { className: "gm-head-spacer" }),
879
+ props.onRefresh ? React.createElement("button", { className: "gm-btn", onClick: props.onRefresh, disabled: !!props.loading }, "刷新") : null,
880
+ React.createElement("button", { className: "gm-btn gm-btn-icon", onClick: props.onClose, title: "关闭(Esc)", "aria-label": "关闭文件历史" },
881
+ React.createElement("svg", { width: 14, height: 14, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", "aria-hidden": true },
882
+ React.createElement("path", { d: "M18 6 6 18" }),
883
+ React.createElement("path", { d: "m6 6 12 12" }),
884
+ ),
885
+ ),
886
+ ),
887
+ React.createElement("div", { className: "gm-diffwin-body" },
888
+ props.loading
889
+ ? React.createElement("div", { className: "gm-empty" },
890
+ React.createElement("span", { className: "gm-spinner" }),
891
+ " 加载文件历史…",
892
+ )
893
+ : (props.entries || []).length === 0
894
+ ? React.createElement("div", { className: "gm-empty" }, "该文件没有历史(新文件或未跟踪)。")
895
+ : React.createElement("div", { style: { border: "1px solid var(--dsw-alias-border-l1)", borderRadius: 10, background: "var(--dsw-alias-bg-layer-1)", overflow: "hidden" } },
896
+ (props.entries || []).map((c) => React.createElement("div", {
897
+ key: c.sha,
898
+ className: "gm-file",
899
+ title: "点击查看该版本的差异",
900
+ onClick: () => props.onOpenCommit(c),
901
+ },
902
+ React.createElement("span", { style: { flex: "none", fontFamily: "ui-monospace,monospace", fontSize: 11, color: "var(--dsw-alias-label-tertiary)", marginRight: 8 } }, c.short),
903
+ React.createElement("span", { className: "gm-file-path" }, c.subject),
904
+ React.createElement("span", { className: "gm-meta" }, c.author),
905
+ React.createElement("span", { className: "gm-meta" }, fmtTime(c.at)),
906
+ )),
907
+ ),
908
+ ),
909
+ ),
910
+ ),
911
+ document.body,
912
+ );
913
+ }
914
+
915
+ // ============================================================================
916
+ // 子仓库支持(契约 docs/plans/2026-10-13-subrepo-support.md §3,P0)
917
+ // RepoSwitcher:分支 / 历史 / 冲突 / Worktree / 设置 Tab 顶部的仓库切换 chips。
918
+ // repos 为空或只有 1 个节点时不渲染(单仓库时无意义)。
919
+ // ============================================================================
920
+ const REPO_KIND_LABEL = { root: "主仓库", submodule: "子模块(submodule)", nested: "嵌套独立仓库" };
921
+
922
+ // 仓库类型图标(内联 SVG,stroke=currentColor;submodule=链接、nested/root=文件夹)
923
+ function repoKindIcon(kind) {
924
+ const common = {
925
+ width: 13, height: 13, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor",
926
+ strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true,
927
+ };
928
+ if (kind === "submodule") {
929
+ return React.createElement("svg", common,
930
+ React.createElement("path", { d: "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.71 1.71" }),
931
+ React.createElement("path", { d: "M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" }),
932
+ );
933
+ }
934
+ if (kind === "nested") {
935
+ return React.createElement("svg", common,
936
+ React.createElement("path", { d: "M4 20a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2Z" }),
937
+ );
938
+ }
939
+ return React.createElement("svg", common,
940
+ React.createElement("path", { d: "M4 20a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2Z" }),
941
+ React.createElement("circle", { cx: 9, cy: 13, r: 1.5 }),
942
+ React.createElement("circle", { cx: 15, cy: 15, r: 1.5 }),
943
+ React.createElement("path", { d: "m10.3 13.6 3.4 1.1" }),
944
+ );
945
+ }
946
+
947
+ // RepoNode.dirty 的合计(缺失字段按 0 计,Host 契约里四个计数恒为数字)
948
+ function repoDirtyTotal(d) {
949
+ const x = d || {};
950
+ return (x.staged || 0) + (x.unstaged || 0) + (x.untracked || 0);
951
+ }
952
+
953
+ // 分组顺序:root 在最上,其余按 relPath 字典序
954
+ function orderRepoNodes(list) {
955
+ const all = Array.isArray(list) ? list.slice() : [];
956
+ if (all.length === 0) return all;
957
+ const root = all.find((n) => n && ((n.kind === "root") || !n.relPath)) || all[0];
958
+ const rest = all.filter((n) => n && n !== root)
959
+ .sort((a, b) => String(a.relPath || "").localeCompare(String(b.relPath || "")));
960
+ return [root].concat(rest);
961
+ }
962
+
963
+ // RepoNode 的 submodule 状态徽标(变更 Tab 组头与设置 Tab「子仓库」管理区共用,
964
+ // 复用 .gm-sub-badge 系列色板)。node.error 优先——查询失败时不做状态推断。
965
+ function repoNodeBadge(node) {
966
+ if (!node) return null;
967
+ if (node.error) return { t: "查询失败", c: "gm-sub-badge-error" };
968
+ if (node.initialized === false) return { t: "未初始化", c: "gm-sub-badge-mute" };
969
+ if (node.submodule && node.submodule.state === "pointer-mismatch") return { t: "指针不符", c: "gm-sub-badge-warn" };
970
+ if (node.submodule && node.submodule.state === "conflict") return { t: "冲突", c: "gm-sub-badge-error" };
971
+ return null;
972
+ }
973
+
974
+ function RepoSwitcher(props) {
975
+ const repos = Array.isArray(props.repos) ? props.repos : [];
976
+ if (repos.length <= 1) return null;
977
+ return React.createElement("div", { className: "gm-repo-bar", role: "group", "aria-label": "仓库切换" },
978
+ repos.map((n) => {
979
+ const total = repoDirtyTotal(n.dirty);
980
+ const conflicted = (n.dirty && n.dirty.conflicted) || 0;
981
+ const active = props.activeRepoId === n.id;
982
+ return React.createElement("button", {
983
+ key: n.id,
984
+ type: "button",
985
+ className: "gm-repo-chip" + (active ? " gm-repo-chip-active" : ""),
986
+ title: (n.relPath ? n.relPath : n.path)
987
+ + "\n" + (REPO_KIND_LABEL[n.kind] || String(n.kind || "仓库"))
988
+ + (n.branch ? "\n分支:" + n.branch : "")
989
+ + (n.initialized === false ? "\n未初始化" : "")
990
+ + (n.error ? "\n状态查询失败:" + n.error : "")
991
+ + "\n点击切换该仓库(其余 Tab 全部作用于它)",
992
+ onClick: () => props.setActiveRepoId(n.id),
993
+ },
994
+ repoKindIcon(n.kind),
995
+ React.createElement("span", { className: "gm-repo-chip-name" },
996
+ n.kind === "root" ? ("主仓库" + (n.name ? " · " + n.name : "")) : (n.name || n.relPath || "仓库")),
997
+ n.initialized === false ? React.createElement("span", { className: "gm-sub-badge gm-sub-badge-mute" }, "未初始化") : null,
998
+ total > 0 ? React.createElement("span", { className: "gm-repo-chip-count" }, String(total)) : null,
999
+ conflicted > 0 ? React.createElement("span", { className: "gm-repo-dot" }) : null,
1000
+ );
1001
+ }),
1002
+ );
1003
+ }
1004
+
1005
+ // ============================================================================
1006
+ // GitPanel(六个 Tab 的内容;此处是壳)
1007
+ // ============================================================================
1008
+ function GitPanel(props) {
1009
+ const remote = props.remote;
1010
+ const onClose = props.onClose;
1011
+ const targetPath = useTargetPath();
1012
+ const slotProps = props.slotProps || {};
1013
+ const useSessions = slotProps.useSessions;
1014
+
1015
+ // 面板绑定打开它的那个会话目录(targetPath 在点击入口时捕获),不提供切换——
1016
+ // 从哪个会话的入口点开就管哪个仓库(用户反馈:可切换不符合直觉)。
1017
+ const summarySessionCwd = useSessions ? useSessions((s) => (s.current && s.byId[s.current] ? s.byId[s.current].cwd : null)) : null;
1018
+ const liveSessionCwd = slotProps.useProjection ? slotProps.useProjection("workingDirectory") : null;
1019
+ const currentSessionCwd = liveSessionCwd || summarySessionCwd;
1020
+ const repoPath = targetPath || currentSessionCwd || "";
1021
+ const [probe, setProbe] = React.useState(null);
1022
+ const [status, setStatus] = React.useState(null);
1023
+ const [remotes, setRemotes] = React.useState([]);
1024
+ const [tab, setTab] = React.useState("changes");
1025
+ const [error, setError] = React.useState(null);
1026
+ const [notice, setNotice] = React.useState(null); // 头部批量操作的成功/部分失败汇总(P2)
1027
+ const [busy, setBusy] = React.useState(null); // 正在执行的操作标签
1028
+ // 仓库树(子仓库支持 P0):repos = repoTree 返回的 RepoNode[],null = 未取到/失败
1029
+ const [repos, setRepos] = React.useState(null);
1030
+
1031
+ // 当前选中的子仓库。选择以 {root,id} 保存:repoPath 变化时 root 不匹配即派生为
1032
+ // ""(= 重置回主仓库),这样 scopedRepoPath 会立刻回到 repoPath,不会多打一轮
1033
+ // 旧仓库的请求,也不需要额外的 reset effect。
1034
+ const [repoSel, setRepoSel] = React.useState({ root: "", id: "" });
1035
+ const activeRepoId = repoSel.root === repoPath ? repoSel.id : "";
1036
+ const setActiveRepoId = React.useCallback(
1037
+ (id) => setRepoSel({ root: repoPath, id: (id === undefined || id === null) ? "" : String(id) }),
1038
+ [repoPath],
1039
+ );
1040
+
1041
+ // worktree 作用域(2026-10-20 review 方案 A):{ root, path, branch }。
1042
+ // root 与面板仓库不匹配即整体失效(面板重开/换会话目录自动回主仓库),
1043
+ // 优先级高于子仓库选择——进入 worktree 时清空 repoSel,两种作用域互斥。
1044
+ const [wtScope, setWtScope] = React.useState(null);
1045
+ const wtScopeActive = !!(wtScope && wtScope.root === repoPath && typeof wtScope.path === "string" && wtScope.path);
1046
+ const enterWorktree = React.useCallback((w) => {
1047
+ setRepoSel({ root: repoPath, id: "" });
1048
+ setWtScope({ root: repoPath, path: String(w.path || ""), branch: String(w.branch || "") });
1049
+ setTab("changes"); // 「查看」= 切到变更页 review 该 worktree 的改动
1050
+ }, [repoPath]);
1051
+ const exitWorktree = React.useCallback(() => setWtScope(null), []);
1052
+
1053
+ // 跨 Tab 范围对比请求(P1 §3.6):变更 Tab 的指针跳转按钮用它把
1054
+ // 「在子仓库中查看 a..b」转成历史 Tab 的一次范围对比。
1055
+ // nonce 递增保证同一对 sha 再点一次也能重新触发(effect 只认 nonce 变化);
1056
+ // requestRange(null) 是消费方回执——清空后手动切回历史 Tab 不会重复弹出旧对比。
1057
+ const [rangeReq, setRangeReq] = React.useState(null); // { fromSha, toSha, nonce } | null
1058
+ const rangeNonceRef = React.useRef(0);
1059
+ const requestRange = React.useCallback((fromSha, toSha) => {
1060
+ rangeNonceRef.current += 1;
1061
+ if (!fromSha || !toSha) { setRangeReq(null); return; }
1062
+ setRangeReq({ fromSha: String(fromSha), toSha: String(toSha), nonce: rangeNonceRef.current });
1063
+ }, []);
1064
+
1065
+ // 仓库树拉取(非致命:失败只置 null,不打断面板)。供 effect 与 mutation 后刷新复用。
1066
+ const refreshTree = React.useCallback(async () => {
1067
+ if (!repoPath) { setRepos(null); return; }
1068
+ try {
1069
+ const r = await unwrap(await remote.repoTree({ path: repoPath }));
1070
+ setRepos((r.ok && r.value && Array.isArray(r.value.repos)) ? r.value.repos : null);
1071
+ } catch (_) {
1072
+ setRepos(null);
1073
+ }
1074
+ }, [remote, repoPath]);
1075
+
1076
+ // activeRepo = 当前选中节点(找不到即 null → 所有操作回落到主仓库)
1077
+ const activeRepo = (repos || []).find((n) => n && n.id === activeRepoId) || null;
1078
+ // 作用域优先级:worktree > 子仓库 > 主仓库(wtScopeActive 时六 Tab 全部
1079
+ // 作用于该 worktree——变更/提交/hunk 操作/历史/分支都是它自己的)
1080
+ const scopedRepoPath = wtScopeActive ? wtScope.path : ((activeRepo && activeRepo.path) ? activeRepo.path : repoPath);
1081
+
1082
+ // 重新选 repo 时探活 + 并行拉仓库树(两者互不阻塞)
1083
+ React.useEffect(() => {
1084
+ refreshTree();
1085
+ }, [refreshTree]);
1086
+
1087
+ // 重新选 repo / 进入退出 worktree 作用域时探活(作用于当前作用域仓库
1088
+ // scopedRepoPath——deps 必须是它本身:repoPath 打开面板后恒定不变)
1089
+ React.useEffect(() => {
1090
+ let alive = true;
1091
+ async function probe1() {
1092
+ if (!scopedRepoPath) { setProbe({ isRepo: false }); setStatus(null); setRemotes([]); return; }
1093
+ setError(null);
1094
+ // 换仓库先清空上一个仓库的 status——头部徽标 / 横幅 / 冲突页都读它,
1095
+ // 否则切换瞬间会短暂显示上一个仓库的 ahead/behind 与冲突。
1096
+ // 批量 fetch/pull 的汇总 notice 同样属于那个仓库(面板级 P2)。
1097
+ setStatus(null);
1098
+ setNotice(null);
1099
+ const r = await unwrap(await remote.overview({ path: scopedRepoPath }));
1100
+ if (!alive) return;
1101
+ // worktree 作用域目标已不可用(目录被删/被外部 remove)→ 自动退回
1102
+ // 主仓库重探,避免面板停在「不是 git 仓库」的死态
1103
+ if (wtScopeActive && (!r.ok || !r.value.probe || r.value.probe.isRepo === false)) {
1104
+ setWtScope(null);
1105
+ return;
1106
+ }
1107
+ if (r.ok) {
1108
+ setProbe(r.value.probe);
1109
+ setStatus(r.value.status);
1110
+ setRemotes(r.value.remotes);
1111
+ } else {
1112
+ setProbe({ isRepo: false });
1113
+ setStatus(null);
1114
+ setError(r.error.message || r.error.code);
1115
+ }
1116
+ }
1117
+ probe1();
1118
+ return () => { alive = false; };
1119
+ }, [scopedRepoPath]);
1120
+
1121
+ // 15s 静默轮询(作用域仓库)
1122
+ // P1 §3.3:仓库树一起刷——六 Tab 徽标与切换器红点是对**所有仓库** dirty 的求和,
1123
+ // 只刷作用域仓库的 status 时其他仓库的徽标会一直停在上次快照(Host 侧 repoTree
1124
+ // 有 60s 缓存,这里的额外调用基本命中缓存)。
1125
+ React.useEffect(() => {
1126
+ if (!probe || !probe.isRepo) return;
1127
+ const t = setInterval(async () => {
1128
+ const r = await unwrap(await remote.status({ path: scopedRepoPath }));
1129
+ if (r.ok) setStatus(r.value);
1130
+ refreshTree();
1131
+ }, 15000);
1132
+ return () => clearInterval(t);
1133
+ }, [probe && probe.isRepo, scopedRepoPath, refreshTree, remote]);
1134
+
1135
+ // 通用 mutation 包装
1136
+ const act = async (label, fn) => {
1137
+ setBusy(label); setError(null);
1138
+ try {
1139
+ // 网关响应是外层包络 {ok, value:{ok, value}}:必须先 unwrap 再读方法字段。
1140
+ // 此前漏了这层解包——r.value.status 恒 undefined(变更列表不刷新)、
1141
+ // git 失败被当成功(错误条不出字)、merge/rebase 冲突不跳冲突页。
1142
+ const r = unwrap(await fn());
1143
+ if (!r.ok) { setError(r.error.message || r.error.code); return undefined; }
1144
+ // 变更方法都返回 { status } / { worktrees } / commit 等,按约定刷新
1145
+ if (r.value && r.value.status) setStatus(r.value.status);
1146
+ notifyGitMutation(); // 让 composer 入口按钮立即重 probe(分支徽标跟随切换)
1147
+ return r.value;
1148
+ } catch (e) {
1149
+ setError(String(e && e.message || e));
1150
+ } finally { setBusy(null); }
1151
+ };
1152
+
1153
+ // P2:全部仓库批量 fetch / pull(契约 §3.5)——等价于 `git submodule foreach`
1154
+ // 的语义,逐仓库串行调用现有 fetch/pull:单个仓库失败不中断其余(收集失败仓库名),
1155
+ // 结束后一次性汇总。全失败走现有错误条(没有成功的部分可展示)。
1156
+ // 作用域:repos 里 initialized 的全部节点(含 root);pull 跳过 detached /
1157
+ // 尚无提交的仓库(那类仓库没有可 pull 的分支,git 也会直接报错)。
1158
+ const bulkRemote = async (kind) => {
1159
+ const label = kind === "fetch" ? "Fetch 全部" : "Pull 全部";
1160
+ const nodes = (Array.isArray(repos) ? repos : [])
1161
+ .filter((n) => n && n.path && n.initialized !== false && !(kind === "pull" && (n.detached || n.unborn)));
1162
+ if (nodes.length === 0) { setNotice(label + ":没有已初始化的仓库可操作。"); return; }
1163
+ setBusy(label); setError(null); setNotice(null);
1164
+ const okNames = [], failNames = [];
1165
+ try {
1166
+ for (const n of nodes) {
1167
+ let r;
1168
+ try {
1169
+ r = await unwrap(kind === "fetch" ? await remote.fetch({ path: n.path }) : await remote.pull({ path: n.path }));
1170
+ } catch (_) { r = { ok: false }; }
1171
+ const name = n.relPath || (n.kind === "root" ? ("主仓库" + (n.name ? " · " + n.name : "")) : (n.name || n.relPath));
1172
+ if (r.ok) okNames.push(name); else failNames.push(name);
1173
+ }
1174
+ // 汇总:全失败走错误条;否则 notice(失败仓库名附在括号里)
1175
+ const verb = kind === "fetch" ? "Fetch" : "Pull";
1176
+ if (okNames.length === 0) {
1177
+ setError(verb + " 全部失败:" + failNames.join("、"));
1178
+ } else if (failNames.length > 0) {
1179
+ setNotice(verb + " 完成:成功 " + okNames.length + ",失败 " + failNames.length + "(" + failNames.join("、") + ")");
1180
+ } else {
1181
+ setNotice(verb + " 完成:成功 " + okNames.length + " 个");
1182
+ }
1183
+ } finally {
1184
+ setBusy(null);
1185
+ }
1186
+ // 收尾:仓库树徽标 + 作用域仓库 status(批量操作可能让 ahead/behind 变化)
1187
+ try { refreshTree(); } catch (_) { /* 忽略 */ }
1188
+ try {
1189
+ const s = await unwrap(await remote.status({ path: scopedRepoPath }));
1190
+ if (s.ok && s.value) setStatus(s.value);
1191
+ } catch (_) { /* 忽略:15s 轮询会自愈 */ }
1192
+ };
1193
+
1194
+ // busy 标签 → 头部状态条文案(未映射的 label 原样展示)
1195
+ const BUSY_LABEL = {
1196
+ "Fetch": "Fetch", "Pull": "Pull", "Push": "Push", "Fetch 全部": "Fetch 全部", "Pull 全部": "Pull 全部",
1197
+ commit: "提交", stage: "暂存", unstage: "取消暂存", "stage-all": "暂存全部", "unstage-all": "取消暂存全部",
1198
+ discard: "丢弃改动", "discard-all": "丢弃全部改动", checkout: "切换分支", merge: "合并", createBranch: "新建分支",
1199
+ deleteBranch: "删除分支", rebaseBranch: "Rebase", tagCreate: "新建 tag", tagDelete: "删除 tag", pushTag: "推送 tag",
1200
+ stashPush: "创建 stash", stashApply: "应用 stash", stashPop: "弹出 stash", stashDrop: "删除 stash",
1201
+ init: "初始化仓库", reset: "Reset", revert: "Revert", cherryPick: "Cherry-pick", undoCommit: "撤销提交",
1202
+ worktreeAdd: "新建 worktree", worktreeRemove: "删除 worktree", worktreePrune: "清理 worktree",
1203
+ submoduleUpdate: "更新子仓库", submoduleAdd: "添加子仓库", mergeContinue: "完成合并", mergeAbort: "中止合并",
1204
+ stageHunk: "暂存代码块", hunkApply: "应用代码块操作", lineApply: "应用行操作",
1205
+ remoteAdd: "添加 remote", remoteRename: "重命名 remote", remoteRemove: "删除 remote",
1206
+ configSet: "保存配置", configUnset: "删除配置",
1207
+ resolveOurs: "采用本方版本", resolveTheirs: "采用对方版本", resolveCustom: "保存手动编辑",
1208
+ };
1209
+ const busyText = (b) => (BUSY_LABEL[b] || b) + "…";
1210
+
1211
+ // 头部网络操作(Fetch/Pull/Push)的完成反馈:成功后 toast 展示 git 输出尾
1212
+ //(fetch/pull/push 的 value 都带 output 字段,git-core 的 NET_OUTPUT_TAIL 截尾);
1213
+ // 失败走 act 的错误条,无需 toast。
1214
+ const netDone = (verb, r) => {
1215
+ if (!r) return;
1216
+ const out = String(r.output || "").trim();
1217
+ showToast(verb + " 完成" + (out ? ":\n" + out.slice(-400) : "。"));
1218
+ };
1219
+ // 头部网络按钮:统一走 act(busy 互斥 + 错误处理 + status 刷新),
1220
+ // 进行中时按钮内嵌 spinner 并追加 "…"(此前 Fetch 不走 act,点了毫无反馈)。
1221
+ const headNetBtn = (label, primary) => React.createElement("button", {
1222
+ className: "gm-btn" + (primary ? " gm-btn-primary" : ""),
1223
+ disabled: !!busy,
1224
+ title: label === "Fetch" ? "从远端拉取最新引用(git fetch --prune)"
1225
+ : label === "Pull" ? "拉取并合并到当前分支(git pull)" : "推送当前分支到远端(git push)",
1226
+ onClick: async () => {
1227
+ const fn = label === "Fetch" ? () => remote.fetch({ path: scopedRepoPath })
1228
+ : label === "Pull" ? () => remote.pull({ path: scopedRepoPath })
1229
+ : () => remote.push({ path: scopedRepoPath });
1230
+ const r = await act(label, fn);
1231
+ if (r) netDone(label, r);
1232
+ refreshTree();
1233
+ },
1234
+ },
1235
+ busy === label ? React.createElement("span", { className: "gm-spinner gm-spinner-sm", key: "sp" }) : null,
1236
+ busy === label ? label + "…" : label,
1237
+ );
1238
+
1239
+ const head = React.createElement("div", { className: "gm-head" },
1240
+ React.createElement("span", { className: "gm-head-title" }, "Git 管理"),
1241
+ React.createElement("span", {
1242
+ className: "gm-head-path",
1243
+ title: scopedRepoPath === repoPath ? repoPath : (repoPath + "\n→ 当前仓库:" + scopedRepoPath),
1244
+ }, scopedRepoPath),
1245
+ React.createElement("span", { className: "gm-head-spacer" }),
1246
+ // 进行中状态条:任何 act/bulk 操作都在头部有可见反馈(spinner + 文案)
1247
+ busy ? React.createElement("span", { className: "gm-busy", role: "status", title: "正在执行操作:" + busyText(busy) },
1248
+ React.createElement("span", { className: "gm-spinner gm-spinner-sm" }),
1249
+ React.createElement("span", { className: "gm-busy-text" }, busyText(busy)),
1250
+ ) : null,
1251
+ React.createElement("div", { className: "gm-head-actions" },
1252
+ status && probe && !probe.detached && (status.ahead > 0 || status.behind > 0) ? React.createElement("span", { className: "gm-badge", style: { fontSize: 12 }, title: "与远端的差距:↑ 本地领先提交数,↓ 本地落后提交数" },
1253
+ status.ahead > 0 ? React.createElement("span", { className: "gm-badge-ahead" }, "↑" + status.ahead) : null,
1254
+ status.ahead > 0 && status.behind > 0 ? " " : null,
1255
+ status.behind > 0 ? React.createElement("span", { className: "gm-badge-behind" }, "↓" + status.behind) : null,
1256
+ ) : null,
1257
+ headNetBtn("Fetch"),
1258
+ headNetBtn("Pull"),
1259
+ headNetBtn("Push", true),
1260
+ // P2:多仓库时的批量 fetch / pull(单仓库时无意义,不渲染;
1261
+ // worktree 作用域期间隐藏——批量作用于主仓库树,与作用域无关)
1262
+ Array.isArray(repos) && repos.length > 1 && !wtScopeActive
1263
+ ? React.createElement("button", {
1264
+ className: "gm-mini",
1265
+ disabled: !!busy,
1266
+ title: "对所有已初始化的仓库(含主仓库)串行执行 git fetch;单个仓库失败不中断其余",
1267
+ onClick: () => bulkRemote("fetch"),
1268
+ }, busy === "Fetch 全部" ? React.createElement("span", { className: "gm-spinner gm-spinner-sm", key: "sp" }) : null, busy === "Fetch 全部" ? "Fetch 全部…" : "Fetch 全部")
1269
+ : null,
1270
+ Array.isArray(repos) && repos.length > 1 && !wtScopeActive
1271
+ ? React.createElement("button", {
1272
+ className: "gm-mini",
1273
+ disabled: !!busy,
1274
+ title: "对所有已初始化的仓库串行执行 git pull(detached / 尚无提交的仓库自动跳过);单个仓库失败不中断其余",
1275
+ onClick: () => bulkRemote("pull"),
1276
+ }, busy === "Pull 全部" ? React.createElement("span", { className: "gm-spinner gm-spinner-sm", key: "sp" }) : null, busy === "Pull 全部" ? "Pull 全部…" : "Pull 全部")
1277
+ : null,
1278
+ React.createElement("button", { className: "gm-btn gm-btn-icon", onClick: () => setOpen(false), title: "关闭(Esc)", "aria-label": "关闭 Git 管理面板" },
1279
+ React.createElement("svg", { width: 14, height: 14, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", "aria-hidden": true },
1280
+ React.createElement("path", { d: "M18 6 6 18" }),
1281
+ React.createElement("path", { d: "m6 6 12 12" }),
1282
+ ),
1283
+ ),
1284
+ ),
1285
+ );
1286
+
1287
+ const banner = (() => {
1288
+ if (!probe) return null;
1289
+ if (!probe.isRepo) {
1290
+ return React.createElement("div", { className: "gm-banner-danger" },
1291
+ React.createElement("span", null, "该目录不是 Git 仓库"),
1292
+ React.createElement("button", {
1293
+ className: "gm-btn gm-btn-primary",
1294
+ disabled: !!busy,
1295
+ onClick: async () => {
1296
+ const r = await unwrap(await remote.init({ path: scopedRepoPath }));
1297
+ if (r.ok) {
1298
+ setProbe(r.value.probe);
1299
+ setStatus(null);
1300
+ refreshTree();
1301
+ } else {
1302
+ setError(r.error.message || r.error.code);
1303
+ }
1304
+ },
1305
+ }, "初始化为 git 仓库 (main)"),
1306
+ );
1307
+ }
1308
+ if (status && status.merging) {
1309
+ return React.createElement("div", { className: "gm-banner" },
1310
+ React.createElement("span", null, "⚠ 合并进行中"),
1311
+ React.createElement("button", { className: "gm-btn", disabled: !!busy, onClick: async () => { const r = await act("mergeContinue", () => remote.mergeContinue({ path: scopedRepoPath })); if (r && r.value && r.value.status) setStatus(r.value.status); refreshTree(); } }, "继续"),
1312
+ React.createElement("button", { className: "gm-btn gm-btn-danger", disabled: !!busy, onClick: async () => { await act("mergeAbort", () => remote.mergeAbort({ path: scopedRepoPath })); setTab("conflicts"); refreshTree(); } }, "中止"),
1313
+ );
1314
+ }
1315
+ if (status && status.rebasing) {
1316
+ return React.createElement("div", { className: "gm-banner" },
1317
+ React.createElement("span", null, "⚠ 变基进行中"),
1318
+ );
1319
+ }
1320
+ return null;
1321
+ })();
1322
+
1323
+ // 六 Tab 徽标:仓库树可用时聚合所有节点的 dirty 计数,否则回落到当前 status。
1324
+ // worktree 作用域期间徽标跟随作用域仓库(树是主仓库的,与作用域无关)。
1325
+ const hasTree = Array.isArray(repos) && repos.length > 0;
1326
+ const badgeFromTree = hasTree && !wtScopeActive;
1327
+ const conflictedCount = badgeFromTree
1328
+ ? repos.reduce((n, x) => n + ((x && x.dirty && x.dirty.conflicted) || 0), 0)
1329
+ : ((status && status.conflicted) ? status.conflicted.length : 0);
1330
+ const changesCount = badgeFromTree
1331
+ ? repos.reduce((n, x) => n + repoDirtyTotal(x && x.dirty), 0)
1332
+ : (status ? (status.staged.length + status.unstaged.length + status.untracked.length) : 0);
1333
+
1334
+ const tabNav = React.createElement("nav", { className: "gm-tabs" },
1335
+ [
1336
+ ["changes", "变更"],
1337
+ ["branches", "分支"],
1338
+ ["history", "历史"],
1339
+ ["conflicts", "冲突"],
1340
+ ["worktree", "Worktree"],
1341
+ ["settings", "设置"],
1342
+ ].map(([k, label]) => React.createElement("button", {
1343
+ key: k,
1344
+ type: "button",
1345
+ className: "gm-tab" + (tab === k ? " gm-tab-active" : ""),
1346
+ onClick: () => setTab(k),
1347
+ },
1348
+ label,
1349
+ k === "changes" && changesCount > 0 ? React.createElement("span", { className: "gm-tab-badge" }, String(changesCount)) : null,
1350
+ k === "conflicts" && conflictedCount > 0 ? React.createElement("span", { className: "gm-tab-badge" }, String(conflictedCount)) : null,
1351
+ )),
1352
+ );
1353
+
1354
+ // Tab content:每个 Tab 的真实实现
1355
+ // worktreeAdd 成功后把新 worktree 注册为 DSH 工作区(host 侧按 canonical
1356
+ // 路径去重,重复注册安全)——这样它在 workspace-write 沙盒下天然可写
1357
+ // (writableRoots 只含 workspaceRoot + tmp,见 dsh-sandbox)。
1358
+ const workspacesService = props.workspaces;
1359
+ const registerWorkspace = async (wtPath) => {
1360
+ if (!workspacesService || typeof workspacesService.create !== "function") return null;
1361
+ try {
1362
+ const r = await workspacesService.create({ path: wtPath });
1363
+ if (r && r.ok === false) return null;
1364
+ return "已注册为 DSH 工作区(侧栏可直接打开,沙盒内可写)";
1365
+ } catch (_) {
1366
+ return null;
1367
+ }
1368
+ };
1369
+
1370
+ // 仓库切换器(分支 / 历史 / 冲突 / Worktree / 设置 Tab 顶部;变更 Tab 自带分组视图,不重复渲染)。
1371
+ // worktree 作用域期间不渲染——子仓库切换会顶掉 worktree 作用域,先退出再切。
1372
+ const repoBar = (tab === "changes" || !hasTree || wtScopeActive) ? null : React.createElement(RepoSwitcher, {
1373
+ repos,
1374
+ activeRepoId,
1375
+ setActiveRepoId,
1376
+ });
1377
+
1378
+ // worktree 作用域提示条:作用域从哪来、怎么退出(分支优先取实时 status,
1379
+ // worktree 内切分支后不至于显示旧名)
1380
+ const wtScopeBar = wtScopeActive ? React.createElement("div", { className: "gm-wt-scope" },
1381
+ React.createElement("span", { className: "gm-sub-badge gm-sub-badge-ok", style: { flex: "none" } }, "Worktree 作用域"),
1382
+ React.createElement("span", { className: "gm-wt-scope-path", title: wtScope.path }, wtScope.path),
1383
+ ((status && status.branch) || wtScope.branch) ? React.createElement("span", { className: "gm-repogroup-branch", title: "分支:" + ((status && status.branch) || wtScope.branch) }, (status && status.branch) || wtScope.branch) : null,
1384
+ React.createElement("span", { style: { flex: 1 } }),
1385
+ React.createElement("span", { style: { fontSize: 11, color: "var(--dsw-alias-label-tertiary)", whiteSpace: "nowrap" } }, "变更 / 提交 / 分支操作均作用于该 worktree"),
1386
+ React.createElement("button", { className: "gm-btn", onClick: exitWorktree, title: "退出 worktree 作用域,回到面板主仓库" }, "返回主仓库"),
1387
+ ) : null;
1388
+
1389
+ // 六 Tab 的 repoPath 换源:作用域仓库(选中子仓库时它的 toplevel)——现有全部
1390
+ // remote.*({path: repoPath}) 调用点无需改写逻辑,只换值来源(契约 §3.1)。
1391
+ const tabProps = { remote, repoPath: scopedRepoPath, rootRepoPath: repoPath, repos, activeRepo, setActiveRepoId, refreshTree, probe, status, busy, act, setError, onStatus: setStatus, onSwitchTab: setTab, registerWorkspace, rangeReq, requestRange, wtScopeActive, wtScopePath: wtScopeActive ? wtScope.path : null, enterWorktree, exitWorktree };
1392
+ const tabContent = (() => {
1393
+ if (!probe || !probe.isRepo) {
1394
+ return React.createElement("div", { className: "gm-empty" }, "该目录不是 Git 仓库。点击上方「初始化为 git 仓库」开始,或选择其他目录。");
1395
+ }
1396
+ switch (tab) {
1397
+ case "changes": return React.createElement(ChangesTab, tabProps);
1398
+ case "branches": return React.createElement(BranchesTab, tabProps);
1399
+ case "history": return React.createElement(HistoryTab, tabProps);
1400
+ case "conflicts": return React.createElement(ConflictsTab, tabProps);
1401
+ case "worktree": return React.createElement(WorktreesTab, tabProps);
1402
+ case "settings": return React.createElement(SettingsTab, tabProps);
1403
+ default: return React.createElement("div", { className: "gm-empty" }, "未知 Tab");
1404
+ }
1405
+ })();
1406
+
1407
+ const errBar = error ? React.createElement("div", { className: "gm-error" }, error) : null;
1408
+
1409
+ return React.createElement("div", { className: "gm-panel", onClick: (e) => e.stopPropagation() },
1410
+ // 顶部不定进度条:任何操作进行中(busy)时滑动动画,覆盖在面板顶缘、不占布局
1411
+ busy ? React.createElement("div", { className: "gm-progress", key: "gm-progress", "aria-hidden": "true" }) : null,
1412
+ head,
1413
+ banner,
1414
+ wtScopeBar,
1415
+ React.createElement("div", { className: "gm-main" },
1416
+ tabNav,
1417
+ React.createElement("div", { className: "gm-content" },
1418
+ errBar,
1419
+ notice ? React.createElement("div", { className: "gm-notice" }, notice) : null,
1420
+ repoBar,
1421
+ tabContent,
1422
+ ),
1423
+ ),
1424
+ );
1425
+ }
1426
+
1427
+ // ============================================================================
1428
+ // ChangesTab(提交框 / 暂存全部 / hunk 级操作 / Stash 区)
1429
+ // 子仓库支持 P0:按仓库分组的文件列表,组内一切操作作用于该组仓库自己的 toplevel。
1430
+ // ============================================================================
1431
+ const SCOPE_LABEL = {
1432
+ worktree: "未暂存(工作区 vs 暂存区)",
1433
+ staged: "已暂存(暂存区 vs HEAD)",
1434
+ untracked: "未跟踪(完整内容)",
1435
+ };
1436
+
1437
+ // ---- 子仓库聚合辅助(契约 §3.2,纯函数,bundle 作用域) ----
1438
+ // porcelain v2 <sub> 字段(Host 透传为 entry.subState)——4 字符位置型标志,
1439
+ // '.' 为空位:pos1 S=子模块有状态差异(恒 S)、pos2 C=子仓库 HEAD≠index 记录
1440
+ // 指针(未暂存指针不符)、pos3 M=已跟踪内容被修改、pos4 U=有未跟踪内容。
1441
+ // 实测样本:S..U / S.M. / SC.. / S...(AGENTS.md 实测纪律:不猜文档字面)。
1442
+ // 按标志位集合解码,未知串回落原始展示;普通文件恒为 "N...",Host 侧已过滤。
1443
+ function subStateLabels(sub) {
1444
+ const flags = [];
1445
+ if (typeof sub === "string" && sub.length > 0) {
1446
+ if (sub.indexOf("C") >= 0) flags.push("指针不符");
1447
+ if (sub.indexOf("M") >= 0) flags.push("内容已修改");
1448
+ if (sub.indexOf("U") >= 0) flags.push("有未跟踪内容");
1449
+ }
1450
+ return flags;
1451
+ }
1452
+ function shortSha(s) { return (s || "").slice(0, 7) || "—"; }
1453
+ // 统一成 posix、无尾斜杠(git 的未跟踪目录是 "dir/",relPath 是 "dir")
1454
+ function normalizeRel(p) {
1455
+ return String(p === undefined || p === null ? "" : p).replace(/\\/g, "/").replace(/\/+$/, "");
1456
+ }
1457
+ // 子模块条目徽标:优先 gitlink(指针 a→b),其次 subState 语义
1458
+ function subBadgeOf(entry) {
1459
+ if (entry && entry.gitlink && (entry.gitlink.fromSha || entry.gitlink.toSha)) {
1460
+ return { text: "指针 " + shortSha(entry.gitlink.fromSha) + " → " + shortSha(entry.gitlink.toSha), cls: "gm-sub-badge-warn" };
1461
+ }
1462
+ if (entry && entry.subState) {
1463
+ const flags = subStateLabels(entry.subState);
1464
+ return { text: flags.length > 0 ? flags.join("、") : ("子模块 " + entry.subState), cls: "gm-sub-badge-warn" };
1465
+ }
1466
+ return null;
1467
+ }
1468
+ // 子模块条目的指针信息(契约 §3.6):优先已暂存的指针变更 entry.gitlink
1469
+ // (hH 旧 → hI 新),其次未暂存漂移(子节点 submodule.sha vs recordedSha)。
1470
+ // recordedSha 为空(指针从未记录)→ 无可跳转指针,返回 null。
1471
+ // subId / subPath = 命中的子仓库节点(id 与绝对 path,revExists 与切作用域都用它)。
1472
+ function subPointerOf(entry, child) {
1473
+ const node = child || null;
1474
+ const wrap = (fromSha, toSha) => ({
1475
+ fromSha: fromSha,
1476
+ toSha: toSha,
1477
+ subId: node ? node.id : "",
1478
+ subPath: node ? (node.path || "") : "",
1479
+ });
1480
+ if (entry && entry.gitlink && entry.gitlink.fromSha && entry.gitlink.toSha) {
1481
+ return wrap(entry.gitlink.fromSha, entry.gitlink.toSha);
1482
+ }
1483
+ const sm = node && node.submodule;
1484
+ if (sm && sm.recordedSha && sm.sha && sm.recordedSha !== sm.sha) {
1485
+ return wrap(sm.recordedSha, sm.sha);
1486
+ }
1487
+ return null;
1488
+ }
1489
+
1490
+ function ChangesTab(props) {
1491
+ const remote = props.remote;
1492
+ const repoPath = props.repoPath; // 作用域仓库(其余 Tab / stash / diff 默认)
1493
+ const rootRepoPath = props.rootRepoPath || repoPath; // 打开面板时的根仓库
1494
+ // worktree 作用域:主仓库的仓库树与该 worktree 无关(repoTree 只含子仓库,
1495
+ // 不含 worktree)——退化为单组视图,组 = worktree 自身,组内操作照常走
1496
+ // 该组 toplevel(= worktree 目录)。
1497
+ const repos = props.wtScopeActive ? null : (Array.isArray(props.repos) ? props.repos : null);
1498
+ // worktree 作用域下单组的 status 复用面板级 props.status(probe effect 已
1499
+ // 按 scopedRepoPath 拉的就是 worktree 的 status)
1500
+ const rootIsScoped = props.wtScopeActive || !repoPath || repoPath === rootRepoPath;
1501
+ const status = props.status;
1502
+ const act = props.act;
1503
+ const setError = props.setError;
1504
+ const refreshTree = props.refreshTree;
1505
+
1506
+ const [diffWin, setDiffWin] = React.useState(null); // { file, scope, repoPath, groupName, gitlink, ptr, loading, text, truncated }
1507
+ const [blameWin, setBlameWin] = React.useState(null); // { file, ref, repoPath, groupName, loading, lines, truncated }
1508
+ const [lineSel, setLineSel] = React.useState(null); // { h, a, b }:diff 窗口内行级选择(hunk 内行下标)
1509
+ const [fileHist, setFileHist] = React.useState(null); // { file, repoPath, loading, entries }
1510
+ const [histDiff, setHistDiff] = React.useState(null); // { title, sub, loading, text, truncated }
1511
+ const [confirming, setConfirming] = React.useState(null);
1512
+ const [hunkConfirm, setHunkConfirm] = React.useState(null); // { hunkIndex }(撤销此块,危险)
1513
+ const [commitMsg, setCommitMsg] = React.useState("");
1514
+ const [amend, setAmend] = React.useState(false);
1515
+ const [stashes, setStashes] = React.useState(null); // null=未加载
1516
+ const [stashOpen, setStashOpen] = React.useState(false);
1517
+ const [stashDlg, setStashDlg] = React.useState(false);
1518
+ const [stashMsg, setStashMsg] = React.useState("");
1519
+ const [stashUntracked, setStashUntracked] = React.useState(false);
1520
+ // ---- 子仓库聚合 ----
1521
+ const [groupStatus, setGroupStatus] = React.useState({}); // repoPath → status 结构(取不到为 null)
1522
+ const [collapsed, setCollapsed] = React.useState(() => new Set()); // 默认全展开
1523
+ const [commitRepoId, setCommitRepoId] = React.useState(""); // 提交框目标仓库("" = root)
1524
+ const [notice, setNotice] = React.useState(null);
1525
+
1526
+ // 分组列表:root 在最上,其余按 relPath 字典序;repos 不可用时退化为单组(= 作用域仓库)
1527
+ const groupNodes = (repos && repos.length > 0)
1528
+ ? orderRepoNodes(repos)
1529
+ : [{ id: "", relPath: "", name: props.wtScopeActive ? "Worktree" : "主仓库", kind: "root", path: repoPath, dirty: null }];
1530
+ const childNodes = groupNodes.filter((n) => n && n.relPath);
1531
+ const nestedRels = childNodes.filter((n) => n.kind === "nested").map((n) => n.relPath);
1532
+ const childNodeByRel = {};
1533
+ childNodes.forEach((n) => { childNodeByRel[n.relPath] = n; });
1534
+ // 路径落在某个子仓库目录内(含正好相等)——用于 root 组的过滤与子模块行判定
1535
+ const isChildPath = (p) => {
1536
+ const s = normalizeRel(p);
1537
+ if (!s) return false;
1538
+ return childNodes.some((n) => s === n.relPath || s.indexOf(n.relPath + "/") === 0);
1539
+ };
1540
+ // 子模块行判定:subState / gitlink 命中,或路径命中某个子仓库(submodule / 已误暂存的 nested)
1541
+ const isSubEntry = (entry) => {
1542
+ if (!entry) return false;
1543
+ if (entry.subState || entry.gitlink) return true;
1544
+ return !!childNodeByRel[normalizeRel(entry.path)];
1545
+ };
1546
+
1547
+ // ---- 组内 status 数据获取 ----
1548
+ // root 组直接复用面板级 props.status(作用域为 root 时)——不双拉 root。
1549
+ const statusFor = (node) => {
1550
+ if (!node) return null;
1551
+ if (!node.relPath && rootIsScoped) return status || null;
1552
+ return groupStatus[node.path] || null;
1553
+ };
1554
+
1555
+ const reloadRepo = React.useCallback(async (path) => {
1556
+ if (!path) return;
1557
+ try {
1558
+ const r = await unwrap(await remote.status({ path }));
1559
+ const v = (r.ok && r.value) ? r.value : null;
1560
+ setGroupStatus((s) => Object.assign({}, s, { [path]: v }));
1561
+ } catch (_) {
1562
+ setGroupStatus((s) => Object.assign({}, s, { [path]: null }));
1563
+ }
1564
+ }, [remote]);
1565
+
1566
+ // 已拉过的路径不重复拉(fetchedRef 随根仓库切换重置)
1567
+ const fetchedRef = React.useRef({});
1568
+ React.useEffect(() => { fetchedRef.current = {}; }, [rootRepoPath]);
1569
+
1570
+ React.useEffect(() => {
1571
+ if (!repos || repos.length <= 1) return undefined;
1572
+ let alive = true;
1573
+ const jobs = [];
1574
+ orderRepoNodes(repos).forEach((n) => {
1575
+ if (!n || !n.path) return;
1576
+ // root 组:作用域为 root 时直接用面板级 props.status,不双拉;否则自己拉
1577
+ if (!n.relPath && rootIsScoped) return;
1578
+ if (n.relPath && n.initialized === false) return; // 未初始化的子模块没有文件变更
1579
+ if (fetchedRef.current[n.path]) return;
1580
+ fetchedRef.current[n.path] = true;
1581
+ jobs.push((async () => {
1582
+ try {
1583
+ const r = await unwrap(await remote.status({ path: n.path }));
1584
+ if (!alive) return;
1585
+ const v = (r.ok && r.value) ? r.value : null;
1586
+ setGroupStatus((s) => (s[n.path] === v ? s : Object.assign({}, s, { [n.path]: v })));
1587
+ } catch (_) {
1588
+ if (alive) setGroupStatus((s) => Object.assign({}, s, { [n.path]: null }));
1589
+ }
1590
+ })());
1591
+ });
1592
+ return () => { alive = false; };
1593
+ }, [repos, remote, rootIsScoped]);
1594
+
1595
+ // 非「面板级 status 覆盖范围」的仓库组静默轮询(面板 15s 轮询只覆盖作用域仓库)
1596
+ React.useEffect(() => {
1597
+ if (!repos || repos.length <= 1) return undefined;
1598
+ const nodes = orderRepoNodes(repos).filter((n) => n && n.path
1599
+ && (n.relPath ? n.initialized !== false : !rootIsScoped));
1600
+ if (nodes.length === 0) return undefined;
1601
+ const t = setInterval(() => { nodes.forEach((n) => { reloadRepo(n.path); }); }, 30000);
1602
+ return () => clearInterval(t);
1603
+ }, [repos, reloadRepo, rootIsScoped]);
1604
+
1605
+ // 本地 act:复用面板 act(busy / 错误条),成功后刷新该仓库 status + 仓库树。
1606
+ // 面板 act 会把返回值里的 status 写进面板级 status——当操作仓库 ≠ 作用域仓库时,
1607
+ // 那是「别的仓库的 status」,需立即重取作用域仓库 status 纠正。
1608
+ const actRepo = async (label, path, fn) => {
1609
+ const r = await act(label, fn);
1610
+ if (r === undefined) return undefined;
1611
+ if (path && path !== repoPath) {
1612
+ try {
1613
+ const s = await unwrap(await remote.status({ path: repoPath }));
1614
+ if (s.ok && s.value && props.onStatus) props.onStatus(s.value);
1615
+ } catch (_) { /* 忽略:面板 15s 轮询会自愈 */ }
1616
+ }
1617
+ await reloadRepo(path);
1618
+ if (typeof refreshTree === "function") refreshTree();
1619
+ return r;
1620
+ };
1621
+
1622
+ // ---- 未初始化子模块:一键初始化并拉取(P2,契约 §3.2 / §5.2) ----
1623
+ // `git submodule update --init --recursive <subPath>`:同时注册 url(init)
1624
+ // 与首次克隆内容(update);首次克隆走网络可能较慢(Host 180s 超时)。
1625
+ // 成功后该组从「未初始化」变为正常分组、文件区出现。
1626
+ const initSubmodule = async (node) => {
1627
+ if (!node || !node.relPath || !rootRepoPath) return;
1628
+ const r = await actRepo("submoduleUpdate", node.path,
1629
+ () => remote.submoduleUpdate({ path: rootRepoPath, subPath: node.relPath, init: true, recursive: true }));
1630
+ if (r === undefined) return; // 失败:错误已在面板错误条原样展示
1631
+ setNotice("已初始化子模块 " + (node.name || node.relPath));
1632
+ };
1633
+
1634
+ // ---- 提交目标仓库(提交框 select) ----
1635
+ const commitTargets = (repos || []).filter((n) => n && n.initialized !== false);
1636
+ const commitNode = commitTargets.find((n) => n.id === commitRepoId) || null;
1637
+ const commitPath = commitNode
1638
+ ? commitNode.path
1639
+ : ((repos && repos.length > 0) ? rootRepoPath : repoPath);
1640
+ const commitLabel = commitNode ? commitNode.name : "主仓库";
1641
+
1642
+ // ---- diff / blame / 文件历史(全部带 scopePath 参数:按组仓库发请求) ----
1643
+ // ptr:子模块行的指针信息 {fromSha,toSha,subId,subPath}(契约 §3.6),
1644
+ // 非子模块行传 null——窗口头部据此显示「指针 a → b」与下钻按钮。
1645
+ const openDiff = async (file, scope, dpath, groupName, isGitlink, ptr) => {
1646
+ const dp = dpath || repoPath;
1647
+ const gname = groupName || "";
1648
+ const p = ptr || null;
1649
+ setLineSel(null);
1650
+ setDiffWin({ file, scope, repoPath: dp, groupName: gname, gitlink: !!isGitlink, ptr: p, loading: true, text: "", truncated: false });
1651
+ const r = await unwrap(await remote.diff({ path: dp, scope, file }));
1652
+ if (!r.ok) { setDiffWin(null); setError(r.error.message || r.error.code); return; }
1653
+ setDiffWin({ file, scope, repoPath: dp, groupName: gname, gitlink: !!isGitlink, ptr: p, loading: false, text: r.value.text, truncated: r.value.truncated });
1654
+ };
1655
+
1656
+ const reloadDiff = async () => {
1657
+ if (!diffWin) return;
1658
+ const d = await unwrap(await remote.diff({ path: diffWin.repoPath, scope: diffWin.scope, file: diffWin.file }));
1659
+ if (!d.ok) return;
1660
+ const empty = !d.value.text;
1661
+ setLineSel(null);
1662
+ setDiffWin((cur) => (cur ? (empty ? null : { ...cur, loading: false, text: d.value.text, truncated: d.value.truncated }) : cur));
1663
+ };
1664
+
1665
+ // ---- 子仓库指针下钻(契约 §3.6) ----
1666
+ // 打开的 diff 窗口带 ptr 时先问 Host「这两个指针提交在不在子仓库当前对象库里」
1667
+ // (revExists):任一不在(浅克隆 / 指针已前移)或请求失败 → 按钮禁用并解释原因。
1668
+ const [ptrCheck, setPtrCheck] = React.useState(null); // { key, state: "checking"|"ok"|"missing", reason }
1669
+ const ptr = diffWin ? (diffWin.ptr || null) : null;
1670
+ const ptrKey = ptr ? (ptr.subPath + "|" + ptr.fromSha + "|" + ptr.toSha) : "";
1671
+ React.useEffect(() => {
1672
+ const p = diffWin && diffWin.ptr;
1673
+ if (!p || !p.subPath || !p.fromSha || !p.toSha) { setPtrCheck(null); return undefined; }
1674
+ const key = p.subPath + "|" + p.fromSha + "|" + p.toSha;
1675
+ let alive = true;
1676
+ setPtrCheck({ key, state: "checking", reason: "" });
1677
+ (async () => {
1678
+ let next = { key, state: "missing", reason: "指针提交不在该子仓库当前对象库(浅克隆或指针已前移)" };
1679
+ try {
1680
+ const r = await unwrap(await remote.revExists({ path: p.subPath, revs: [p.fromSha, p.toSha] }));
1681
+ if (alive && r.ok) {
1682
+ const checks = (r.value && Array.isArray(r.value.checks)) ? r.value.checks : [];
1683
+ if (checks.length > 0 && checks.every((c) => c && c.ok === true)) next = { key, state: "ok", reason: "" };
1684
+ }
1685
+ } catch (_) { /* 保持 missing:核验失败不允许跳转 */ }
1686
+ if (alive) setPtrCheck(next);
1687
+ })();
1688
+ return () => { alive = false; };
1689
+ }, [ptrKey, remote, diffWin && diffWin.file, diffWin && diffWin.scope]);
1690
+ const ptrState = ptr
1691
+ ? (ptr.subPath
1692
+ ? ((ptrCheck && ptrCheck.key === ptrKey) ? ptrCheck.state : "checking")
1693
+ : "no-sub") // gitlink 命中子节点以外的路径(嵌入仓库 / 未识别)→ 无法下钻
1694
+ : null;
1695
+ const ptrReason = (ptrCheck && ptrCheck.key === ptrKey) ? (ptrCheck.reason || "") : "";
1696
+ // 跳转:切作用域仓库 → 切历史 Tab → 请求该范围对比(tabProps 穿参,无全局变量)。
1697
+ const jumpToSubRange = () => {
1698
+ const p = diffWin && diffWin.ptr;
1699
+ if (!p || !p.subId || ptrState !== "ok") return;
1700
+ if (props.setActiveRepoId) props.setActiveRepoId(p.subId);
1701
+ if (props.onSwitchTab) props.onSwitchTab("history");
1702
+ if (props.requestRange) props.requestRange(p.fromSha, p.toSha);
1703
+ };
1704
+
1705
+ // ---- 行级选择(契约 §8.3):点选 / shift 点选 → lineApply ----
1706
+ const onLineClick = (h, k, shift) => {
1707
+ setLineSel((cur) => {
1708
+ if (!shift || !cur || cur.h !== h) return { h, a: k, b: k };
1709
+ return { h, a: cur.a, b: k };
1710
+ });
1711
+ };
1712
+ const applySelectedLines = async (mode) => {
1713
+ if (!lineSel || !diffWin) return;
1714
+ const r = await actRepo("lineApply", diffWin.repoPath, () => remote.lineApply({
1715
+ path: diffWin.repoPath,
1716
+ file: diffWin.file,
1717
+ scope: diffWin.scope === "staged" ? "staged" : "unstaged",
1718
+ hunkIndex: lineSel.h,
1719
+ rowStart: Math.min(lineSel.a, lineSel.b),
1720
+ rowEnd: Math.max(lineSel.a, lineSel.b),
1721
+ mode,
1722
+ }));
1723
+ if (r === undefined) return;
1724
+ await reloadDiff();
1725
+ };
1726
+ const lineBar = (diffWin && !diffWin.gitlink && lineSel && (diffWin.scope === "worktree" || diffWin.scope === "staged"))
1727
+ ? React.createElement("div", { className: "gm-linebar" },
1728
+ React.createElement("span", { className: "gm-meta" }, "已选 " + (Math.abs(lineSel.b - lineSel.a) + 1) + " 行"),
1729
+ diffWin.scope === "worktree" ? React.createElement("button", {
1730
+ className: "gm-btn gm-btn-primary",
1731
+ disabled: !!props.busy,
1732
+ title: "只暂存选中的行(lineApply stage)",
1733
+ onClick: () => applySelectedLines("stage"),
1734
+ }, "暂存选中行") : null,
1735
+ diffWin.scope === "worktree" ? React.createElement("button", {
1736
+ className: "gm-btn gm-btn-danger",
1737
+ disabled: !!props.busy,
1738
+ title: "丢弃选中行在工作区的改动(危险)",
1739
+ onClick: () => setConfirming({ kind: "lineDiscard" }),
1740
+ }, "撤销选中行") : null,
1741
+ diffWin.scope === "staged" ? React.createElement("button", {
1742
+ className: "gm-btn",
1743
+ disabled: !!props.busy,
1744
+ title: "把选中行移出暂存区(改动保留在工作区)",
1745
+ onClick: () => applySelectedLines("unstage"),
1746
+ }, "取消暂存选中行") : null,
1747
+ React.createElement("button", { className: "gm-mini", onClick: () => setLineSel(null) }, "取消选择"),
1748
+ )
1749
+ : null;
1750
+
1751
+ // ---- 文件级历史(契约 §8.4):log({file}) + 逐版本 diffRange ----
1752
+ const openFileHist = async (file, hpath) => {
1753
+ const hp = hpath || repoPath;
1754
+ setFileHist({ file, repoPath: hp, loading: true, entries: [] });
1755
+ const r = await unwrap(await remote.log({ path: hp, file, maxCount: 100 }));
1756
+ if (!r.ok) { setFileHist(null); setError(r.error.message || r.error.code); return; }
1757
+ setFileHist({ file, repoPath: hp, loading: false, entries: (r.value && r.value.commits) || [] });
1758
+ };
1759
+ const openHistDiff = async (file, c, hpath) => {
1760
+ const hp = hpath || (fileHist ? fileHist.repoPath : repoPath);
1761
+ // 根提交(无父)用空树 sha 当 from(纯 hex,checkRev 放行)
1762
+ const from = (c.parents && c.parents.length > 0) ? (c.sha + "^") : EMPTY_TREE_SHA;
1763
+ setHistDiff({ file, c, title: file, sub: (c.short || "") + " " + (c.subject || ""), loading: true, text: "", truncated: false });
1764
+ const r = await unwrap(await remote.diffRange({ path: hp, from, to: c.sha, file, kind: "patch" }));
1765
+ if (!r.ok) { setHistDiff(null); setError(r.error.message || r.error.code); return; }
1766
+ setHistDiff({ file, c, title: file, sub: (c.short || "") + " " + (c.subject || ""), loading: false, text: r.value.text, truncated: r.value.truncated });
1767
+ };
1768
+
1769
+ // 只读 blame 窗口(契约 §3.4b):变更 Tab 未暂存/已暂存文件行入口
1770
+ const openBlame = async (file, ref, bpath) => {
1771
+ const bp = bpath || repoPath;
1772
+ setBlameWin({ file, ref, repoPath: bp, loading: true, lines: [], truncated: false });
1773
+ const req = { path: bp, file };
1774
+ if (ref) req.ref = ref;
1775
+ const r = await unwrap(await remote.blame(req));
1776
+ if (!r.ok) { setBlameWin(null); setError(r.error.message || r.error.code); return; }
1777
+ setBlameWin({ file, ref, repoPath: bp, loading: false, lines: (r.value && r.value.lines) || [], truncated: !!(r.value && r.value.truncated) });
1778
+ };
1779
+
1780
+ // hunk 级操作:worktree=「暂存此块」(stageHunk,无确认)+「撤销此块」(危险,确认);
1781
+ // staged=「取消暂存此块」(hunkApply,无确认,改动保留在工作区)。
1782
+ // 子模块指针行(gitlink)没有 hunk 概念,diff 窗口不给这些操作。
1783
+ const stageHunk = async (hunkIndex) => {
1784
+ if (!diffWin) return;
1785
+ const r = await actRepo("stageHunk", diffWin.repoPath, () => remote.stageHunk({ path: diffWin.repoPath, file: diffWin.file, hunkIndex }));
1786
+ if (r === undefined) return;
1787
+ await reloadDiff();
1788
+ };
1789
+ const unstageHunk = async (hunkIndex) => {
1790
+ if (!diffWin) return;
1791
+ const r = await actRepo("hunkApply", diffWin.repoPath, () => remote.hunkApply({ path: diffWin.repoPath, scope: "staged", file: diffWin.file, hunkIndex }));
1792
+ if (r === undefined) return;
1793
+ await reloadDiff();
1794
+ };
1795
+ const onConfirmHunk = async () => {
1796
+ const c = hunkConfirm;
1797
+ setHunkConfirm(null);
1798
+ if (!c || !diffWin) return;
1799
+ const r = await actRepo("hunkApply", diffWin.repoPath, () => remote.hunkApply({ path: diffWin.repoPath, scope: diffWin.scope, file: diffWin.file, hunkIndex: c.hunkIndex }));
1800
+ if (r === undefined) return; // act 已把错误放进错误条
1801
+ await reloadDiff();
1802
+ };
1803
+
1804
+ const hunkActions = [];
1805
+ if (diffWin && !diffWin.gitlink && diffWin.scope === "worktree") {
1806
+ hunkActions.push({ label: "暂存此块", title: "把该代码块加入暂存区", danger: false, onClick: stageHunk });
1807
+ hunkActions.push({ label: "撤销此块", title: "丢弃该代码块在工作区的改动(恢复为暂存区版本)", danger: true, onClick: (j) => setHunkConfirm({ hunkIndex: j }) });
1808
+ } else if (diffWin && !diffWin.gitlink && diffWin.scope === "staged") {
1809
+ hunkActions.push({ label: "取消暂存此块", title: "把该代码块移出暂存区(改动保留在工作区,内容不丢)", danger: false, onClick: unstageHunk });
1810
+ }
1811
+
1812
+ // ---- stash(跟随作用域仓库 repoPath,契约 §4) ----
1813
+ const loadStashes = async () => {
1814
+ try {
1815
+ const u = await unwrap(await remote.stashList({ path: repoPath }));
1816
+ setStashes(u.ok ? ((u.value && u.value.stashes) || []) : []);
1817
+ } catch (_) {
1818
+ setStashes([]);
1819
+ }
1820
+ };
1821
+ const refreshStatus = async () => {
1822
+ const s = await unwrap(await remote.status({ path: repoPath }));
1823
+ if (s.ok && props.onStatus) props.onStatus(s.value);
1824
+ };
1825
+ React.useEffect(() => { loadStashes(); }, [repoPath]);
1826
+
1827
+ const doStashPush = async () => {
1828
+ const req = { path: repoPath };
1829
+ if (stashMsg.trim()) req.message = stashMsg.trim();
1830
+ if (stashUntracked) req.includeUntracked = true;
1831
+ const r = await act("stashPush", () => remote.stashPush(req));
1832
+ if (r === undefined) return;
1833
+ setStashDlg(false); setStashMsg(""); setStashUntracked(false);
1834
+ setStashOpen(true);
1835
+ if (r && r.stashes) setStashes(r.stashes); else await loadStashes();
1836
+ await refreshStatus();
1837
+ if (typeof refreshTree === "function") refreshTree();
1838
+ };
1839
+ const doStashOp = async (label, fn, index) => {
1840
+ const r = await act(label, fn);
1841
+ if (r === undefined) return;
1842
+ if (r && r.stashes) setStashes(r.stashes); else await loadStashes();
1843
+ await refreshStatus();
1844
+ if (typeof refreshTree === "function") refreshTree();
1845
+ // stash pop/apply 冲突(无 MERGE_HEAD)→ 记录来源并跳冲突页(契约 §3.5 分流)
1846
+ if ((label === "stashPop" || label === "stashApply")
1847
+ && r && r.status && r.status.conflicted && r.status.conflicted.length > 0
1848
+ && !r.status.merging && !r.status.rebasing) {
1849
+ conflictSource = "stash";
1850
+ stashConflictIndex = typeof index === "number" ? index : 0;
1851
+ if (props.onSwitchTab) props.onSwitchTab("conflicts");
1852
+ }
1853
+ };
1854
+
1855
+ // ---- 文件行(组内复用;scopePath = 该组仓库自己的 toplevel) ----
1856
+ // opt: { sub:子模块行, weaked:弱化 diff/blame/历史, ptr:指针跳转信息, discardable, badge, badgeCls, onEnter }
1857
+ const renderFileRow = (entry, scope, scopePath, groupName, opt) => {
1858
+ const o = opt || {};
1859
+ const kindClass = (entry.kind && ("gm-file-kind-" + entry.kind)) || "";
1860
+ const isActive = !!(diffWin && diffWin.file === entry.path && diffWin.scope === scope && diffWin.repoPath === scopePath);
1861
+ const weakCls = o.weaked ? " gm-mini-weak" : "";
1862
+ const isStaged = scope === "staged";
1863
+ const isWorktree = scope === "unstaged";
1864
+ const isUntracked = scope === "untracked";
1865
+ const where = groupName && groupName !== "主仓库" ? ("(仓库:" + groupName + ")") : "";
1866
+ return React.createElement("div", {
1867
+ key: entry.path,
1868
+ className: "gm-file" + (isActive ? " gm-file-active" : ""),
1869
+ title: "点击查看差异" + where,
1870
+ onClick: () => openDiff(entry.path, scope, scopePath, groupName, !!o.sub, o.ptr || null),
1871
+ },
1872
+ React.createElement("span", { className: "gm-file-kind " + kindClass }, o.sub ? "sub" : (entry.kind || "new")),
1873
+ React.createElement("span", { className: "gm-file-path" }, entry.path),
1874
+ o.badge ? React.createElement("span", { className: "gm-sub-badge " + (o.badgeCls || "") }, o.badge) : null,
1875
+ entry.oldPath ? React.createElement("span", { className: "gm-file-old" }, "← " + entry.oldPath) : null,
1876
+ isStaged ? React.createElement("button", { className: "gm-mini", disabled: !!props.busy, onClick: (ev) => { ev.stopPropagation(); actRepo("unstage", scopePath, () => remote.unstage({ path: scopePath, files: [entry.path] })); } }, "取消暂存") : null,
1877
+ isWorktree || isUntracked ? React.createElement("button", { className: "gm-mini", disabled: !!props.busy, onClick: (ev) => { ev.stopPropagation(); actRepo("stage", scopePath, () => remote.stage({ path: scopePath, files: [entry.path] })); } }, "暂存") : null,
1878
+ o.onEnter ? React.createElement("button", { className: "gm-mini", title: "把面板作用域切到该子仓库(其余 Tab 一并跟随)", onClick: (ev) => { ev.stopPropagation(); o.onEnter(); } }, "进入") : null,
1879
+ isStaged || isWorktree ? React.createElement("button", {
1880
+ className: "gm-mini" + weakCls,
1881
+ title: o.weaked ? "子模块指针条目:这里显示的是指针差异,不是文本内容" : "逐行追溯(blame)该文件",
1882
+ onClick: (ev) => { ev.stopPropagation(); openBlame(entry.path, null, scopePath); },
1883
+ }, "Blame") : null,
1884
+ isStaged || isWorktree ? React.createElement("button", {
1885
+ className: "gm-mini" + weakCls,
1886
+ title: "该文件的提交历史",
1887
+ onClick: (ev) => { ev.stopPropagation(); openFileHist(entry.path, scopePath); },
1888
+ }, "历史") : null,
1889
+ (isStaged || isWorktree || isUntracked) && o.discardable !== false ? React.createElement("button", {
1890
+ className: "gm-mini gm-mini-danger",
1891
+ disabled: !!props.busy,
1892
+ onClick: (ev) => { ev.stopPropagation(); setConfirming({ kind: "discard", entry, scope, repoPath: scopePath, repoName: groupName }); },
1893
+ }, isUntracked ? "删除" : "丢弃") : null,
1894
+ );
1895
+ };
1896
+
1897
+ // ---- scope 子组(Staged / Unstaged / Untracked) ----
1898
+ const renderScopeGroup = (label, entries, kind, scope, node) => {
1899
+ if (!entries || entries.length === 0) return null;
1900
+ const scopePath = node.path;
1901
+ const groupName = node.relPath ? node.relPath : "主仓库";
1902
+ // 未跟踪目录里属于子仓库目录的条目不进「删除全部」清单(它们由各自的组管理)
1903
+ const discardFiles = entries
1904
+ .map((e) => (typeof e === "string" ? e : e.path))
1905
+ .filter((p) => (kind === "untracked" ? !isChildPath(p) : true));
1906
+ return React.createElement("div", { key: kind, className: "gm-filegroup" },
1907
+ React.createElement("div", { className: "gm-filegroup-head" },
1908
+ React.createElement("span", null, label + " (" + entries.length + ")"),
1909
+ kind === "untracked" ? React.createElement("button", {
1910
+ className: "gm-mini gm-mini-danger",
1911
+ disabled: !!props.busy || discardFiles.length === 0,
1912
+ title: "删除该仓库下全部未跟踪文件/目录(嵌套仓库目录由 Host 保护跳过)",
1913
+ onClick: () => setConfirming({ kind: "discard-all", files: discardFiles, scope: "untracked", repoPath: scopePath, repoName: groupName }),
1914
+ }, "删除全部") : null,
1915
+ ),
1916
+ entries.map((e) => {
1917
+ const entry = typeof e === "string" ? { path: e } : e;
1918
+ // 子仓库目录(嵌套仓库 / 未初始化子模块)有自己的组,root 组不重复渲染
1919
+ if (kind === "untracked" && isChildPath(entry.path)) return null;
1920
+ const sub = kind !== "untracked" && isSubEntry(entry);
1921
+ const badge = sub ? subBadgeOf(entry) : null;
1922
+ const child = childNodeByRel[normalizeRel(entry.path)];
1923
+ // 子模块行的指针 a→b(契约 §3.6):已暂存指针变更优先,其次未暂存漂移
1924
+ const ptr = sub ? subPointerOf(entry, child) : null;
1925
+ return renderFileRow(entry, scope, scopePath, groupName, {
1926
+ sub: !!sub,
1927
+ weaked: !!sub,
1928
+ ptr: ptr,
1929
+ discardable: !sub, // 子模块指针行不给「丢弃」(撤销走「取消暂存」)
1930
+ badge: badge ? badge.text : null,
1931
+ badgeCls: badge ? badge.cls : "",
1932
+ onEnter: (sub && child) ? () => props.setActiveRepoId(child.id) : null,
1933
+ });
1934
+ }),
1935
+ );
1936
+ };
1937
+
1938
+ // ---- 仓库组(组头 + 组内三个 scope 子组) ----
1939
+ const toggleCollapse = (id) => setCollapsed((cur) => {
1940
+ const n = new Set(cur);
1941
+ if (n.has(id)) n.delete(id); else n.add(id);
1942
+ return n;
1943
+ });
1944
+
1945
+ const renderRepoGroup = (node) => {
1946
+ const st = statusFor(node);
1947
+ const isRoot = !node.relPath;
1948
+ const counts = st
1949
+ ? { staged: st.staged.length, unstaged: st.unstaged.length, untracked: st.untracked.length }
1950
+ : { staged: 0, unstaged: 0, untracked: 0 };
1951
+ const dirty = (!st && node.dirty) ? node.dirty : counts;
1952
+ const isCollapsed = collapsed.has(node.id);
1953
+ const displayName = isRoot ? ("主仓库" + (node.name ? " · " + node.name : "")) : (node.name || node.relPath);
1954
+ const branchText = node.branch
1955
+ ? node.branch
1956
+ : (node.detached ? ("detached " + shortSha(node.headShort)) : (node.unborn ? "(尚无提交)" : ""));
1957
+ const subBadge = repoNodeBadge(node);
1958
+ return React.createElement("div", { key: node.id || "root", className: "gm-repogroup" },
1959
+ React.createElement("div", { className: "gm-repogroup-head" },
1960
+ React.createElement("button", {
1961
+ className: "gm-mini",
1962
+ title: isCollapsed ? "展开该仓库的变更" : "折叠该仓库的变更",
1963
+ onClick: () => toggleCollapse(node.id || ""),
1964
+ }, isCollapsed ? "▸" : "▾"),
1965
+ repoKindIcon(node.kind),
1966
+ React.createElement("span", { className: "gm-repogroup-name", title: node.path }, displayName),
1967
+ node.relPath ? React.createElement("span", { className: "gm-repogroup-rel", title: "相对路径:" + node.relPath }, node.relPath) : null,
1968
+ branchText ? React.createElement("span", { className: "gm-repogroup-branch", title: "分支:" + branchText }, branchText) : null,
1969
+ React.createElement("span", { className: "gm-repogroup-counts", title: "已暂存 / 未暂存 / 未跟踪" },
1970
+ "+" + ((dirty && dirty.staged) || 0) + " −" + ((dirty && dirty.unstaged) || 0) + " ?" + ((dirty && dirty.untracked) || 0)),
1971
+ subBadge ? React.createElement("span", { className: "gm-sub-badge " + subBadge.c }, subBadge.t) : null,
1972
+ React.createElement("span", { style: { flex: 1 } }),
1973
+ // 未初始化子模块:组头一键初始化(P2),放在「进入」左侧
1974
+ node.initialized === false && !node.error
1975
+ ? React.createElement("button", {
1976
+ className: "gm-mini",
1977
+ disabled: !!props.busy,
1978
+ title: "初始化并拉取该子模块(git submodule update --init --recursive " + node.relPath + ";首次克隆需联网,可能较慢)",
1979
+ onClick: () => initSubmodule(node),
1980
+ }, "初始化")
1981
+ : null,
1982
+ React.createElement("button", {
1983
+ className: "gm-mini",
1984
+ disabled: isRoot ? !props.activeRepo : (node.initialized === false),
1985
+ title: isRoot
1986
+ ? "把面板作用域切回主仓库(分支 / 历史 / 冲突 / Worktree / 设置 一并跟随)"
1987
+ : "把面板作用域切到该仓库(分支 / 历史 / 冲突 / Worktree / 设置 一并跟随)",
1988
+ onClick: () => props.setActiveRepoId(isRoot ? "" : node.id),
1989
+ }, "进入"),
1990
+ ),
1991
+ isCollapsed ? null : React.createElement("div", { className: "gm-repogroup-body" },
1992
+ node.error ? React.createElement("div", { className: "gm-notice-warn" }, "状态查询失败:" + node.error) : null,
1993
+ node.initialized === false
1994
+ ? React.createElement("div", { className: "gm-meta", style: { padding: "4px 6px" } }, "未初始化的子模块:目录内没有内容,也没有文件变更。")
1995
+ : null,
1996
+ !st && !node.error && node.initialized !== false
1997
+ ? React.createElement("div", { className: "gm-meta", style: { padding: "4px 6px" } }, "加载该仓库状态…")
1998
+ : null,
1999
+ renderScopeGroup("Staged", st && st.staged, "staged", "staged", node),
2000
+ renderScopeGroup("Unstaged", st && st.unstaged, "unstaged", "worktree", node),
2001
+ renderScopeGroup("Untracked", st && st.untracked, "untracked", "untracked", node),
2002
+ st && st.conflicted && st.conflicted.length > 0
2003
+ ? React.createElement("div", { className: "gm-notice-warn" }, "该仓库有 " + st.conflicted.length + " 个冲突文件,请到「冲突」页处理。")
2004
+ : null,
2005
+ ),
2006
+ );
2007
+ };
2008
+
2009
+ const onConfirmDiscard = async () => {
2010
+ const c = confirming;
2011
+ setConfirming(null);
2012
+ if (!c) return;
2013
+ if (c.kind === "discard") {
2014
+ const p = c.repoPath || repoPath;
2015
+ const file = c.entry.path || c.entry;
2016
+ if (c.scope === "staged") {
2017
+ // 已暂存的「丢弃」= 取消暂存 + 丢弃工作区改动(回到 HEAD 版本)
2018
+ await actRepo("unstage", p, () => remote.unstage({ path: p, files: [file] }));
2019
+ }
2020
+ await actRepo("discard", p, () => remote.discard({ path: p, files: [file], includeUntracked: c.scope === "untracked" }));
2021
+ } else if (c.kind === "discard-all") {
2022
+ const p = c.repoPath || repoPath;
2023
+ const r = await actRepo("discard-all", p, () => remote.discard({ path: p, files: c.files, includeUntracked: true }));
2024
+ if (r && Array.isArray(r.skipped) && r.skipped.length > 0) {
2025
+ setNotice("已保护跳过 " + r.skipped.length + " 个嵌套仓库目录:" + r.skipped.join("、"));
2026
+ }
2027
+ } else if (c.kind === "stashDrop") {
2028
+ await doStashOp("stashDrop", () => remote.stashDrop({ path: repoPath, index: c.index }));
2029
+ } else if (c.kind === "stashClear") {
2030
+ await doStashOp("stashClear", () => remote.stashClear({ path: repoPath }));
2031
+ } else if (c.kind === "lineDiscard") {
2032
+ await applySelectedLines("discard");
2033
+ } else if (c.kind === "undoCommit") {
2034
+ // undo(契约 §8.5):soft reset HEAD~1,改动回暂存区;toast 带重做提示
2035
+ const r = await actRepo("undoCommit", commitPath, () => remote.reset({ path: commitPath, mode: "soft", target: "HEAD~1" }));
2036
+ if (r !== undefined) {
2037
+ showToast("已撤销最后一次提交,改动保留在暂存区(" + commitLabel + ")。\n重做:git reset --soft HEAD@{1}(或 git reflog 查看历史)。");
2038
+ }
2039
+ }
2040
+ };
2041
+
2042
+ const submitCommit = async () => {
2043
+ if (!commitMsg.trim()) { setError("提交信息不能为空"); return; }
2044
+ const r = await actRepo("commit", commitPath, () => remote.commit({ path: commitPath, message: commitMsg, amend }));
2045
+ if (r) { setCommitMsg(""); setAmend(false); setDiffWin(null); setNotice(null); }
2046
+ };
2047
+
2048
+ // amend 勾选时拉 HEAD 提交信息预填(空框才填,避免覆盖用户已输入内容)
2049
+ React.useEffect(() => {
2050
+ if (!amend) return undefined;
2051
+ let alive = true;
2052
+ (async () => {
2053
+ try {
2054
+ const r = await unwrap(await remote.log({ path: commitPath, maxCount: 1 }));
2055
+ if (!alive || !r.ok || !r.value || !r.value.commits || r.value.commits.length === 0) return;
2056
+ setCommitMsg((m) => (m.trim() ? m : r.value.commits[0].subject || ""));
2057
+ } catch (_) { /* 预填失败不阻塞,用户手输即可 */ }
2058
+ })();
2059
+ return () => { alive = false; };
2060
+ }, [amend, commitPath]);
2061
+
2062
+ const anyDirty = groupNodes.some((n) => {
2063
+ const st = statusFor(n);
2064
+ if (!st) return repoDirtyTotal(n.dirty) > 0;
2065
+ return (st.staged.length + st.unstaged.length + st.untracked.length) > 0;
2066
+ });
2067
+
2068
+ return React.createElement(React.Fragment, null,
2069
+ notice ? React.createElement("div", { className: "gm-notice-warn" }, notice) : null,
2070
+ // 提交框(置顶;目标仓库可切换,默认主仓库)
2071
+ React.createElement("div", { className: "gm-commit" },
2072
+ commitTargets.length > 1 ? React.createElement("div", { style: { display: "flex", gap: 8, alignItems: "center" } },
2073
+ React.createElement("span", { className: "gm-form-label" }, "提交到"),
2074
+ React.createElement("select", {
2075
+ className: "gm-input",
2076
+ style: { maxWidth: 260 },
2077
+ value: commitNode ? commitNode.id : "",
2078
+ title: "选择这次提交写入哪个仓库(各自独立的暂存区与提交历史)",
2079
+ onChange: (e) => setCommitRepoId(e.target.value),
2080
+ },
2081
+ commitTargets.map((n) => React.createElement("option", {
2082
+ key: n.id,
2083
+ value: n.id,
2084
+ }, (n.kind === "root" ? "主仓库" : n.name) + " (" + (n.branch || shortSha(n.headShort) || "?") + ")"))),
2085
+ ) : null,
2086
+ React.createElement("textarea", {
2087
+ className: "gm-textarea",
2088
+ placeholder: "提交信息(支持多行)",
2089
+ value: commitMsg,
2090
+ onChange: (e) => setCommitMsg(e.target.value),
2091
+ }),
2092
+ React.createElement("div", { style: { display: "flex", gap: 12, alignItems: "center" } },
2093
+ React.createElement("label", { className: "gm-checkbox", title: "修改上一次提交(勾选后自动预填 HEAD 提交信息)" },
2094
+ React.createElement("input", { type: "checkbox", checked: amend, onChange: (e) => setAmend(e.target.checked) }),
2095
+ "Amend(修改上一次提交)",
2096
+ ),
2097
+ React.createElement("span", { style: { flex: 1 } }),
2098
+ React.createElement("button", { className: "gm-btn gm-btn-primary", disabled: !!props.busy || !commitMsg.trim(), onClick: submitCommit }, "提交"),
2099
+ ),
2100
+ ),
2101
+ // 工具行:暂存全部(主仓库)/ 取消暂存全部(作用域仓库)/ 撤销上次提交(提交目标仓库)
2102
+ React.createElement("div", { className: "gm-filterbar", style: { marginTop: 12, marginBottom: 0 } },
2103
+ React.createElement("button", {
2104
+ className: "gm-btn",
2105
+ disabled: !!props.busy,
2106
+ title: nestedRels.length > 0
2107
+ ? "git add -A(排除嵌套独立仓库目录:避免误产生 gitlink)"
2108
+ : "git add -A:暂存全部改动(含未跟踪文件)",
2109
+ onClick: () => {
2110
+ const req = { path: rootRepoPath, files: [], all: true };
2111
+ if (nestedRels.length > 0) req.exclude = nestedRels.slice();
2112
+ return actRepo("stage-all", rootRepoPath, () => remote.stage(req));
2113
+ },
2114
+ }, "暂存全部"),
2115
+ React.createElement("button", {
2116
+ className: "gm-btn",
2117
+ disabled: !!props.busy || !status || status.staged.length === 0,
2118
+ title: "取消暂存当前作用域仓库的全部暂存改动",
2119
+ onClick: () => actRepo("unstage-all", repoPath, () => remote.unstage({ path: repoPath, files: status.staged.map((e) => e.path) })),
2120
+ }, "取消暂存全部"),
2121
+ React.createElement("button", {
2122
+ className: "gm-btn",
2123
+ disabled: !!props.busy,
2124
+ title: "git reset --soft HEAD~1:撤销最后一次提交,改动保留在暂存区(作用于提交目标仓库)",
2125
+ onClick: () => setConfirming({ kind: "undoCommit", repoName: commitLabel }),
2126
+ }, "撤销上次提交"),
2127
+ React.createElement("span", { style: { flex: 1 } }),
2128
+ !anyDirty ? React.createElement("span", { className: "gm-meta" },
2129
+ groupNodes.length > 1 ? "所有仓库的工作区干净。" : "工作区干净。") : null,
2130
+ ),
2131
+ // 按仓库分组的文件列表(root 在最上,其余按 relPath 字典序)
2132
+ groupNodes.map(renderRepoGroup),
2133
+ // Stash 折叠区
2134
+ React.createElement("div", { className: "gm-section" },
2135
+ React.createElement("div", { className: "gm-section-head" },
2136
+ React.createElement("span", {
2137
+ className: "gm-section-title",
2138
+ onClick: () => setStashOpen((v) => !v),
2139
+ title: stashOpen ? "收起" : "展开",
2140
+ }, stashOpen ? "▾" : "▸", " Stash (" + (stashes ? stashes.length : 0) + ")"),
2141
+ React.createElement("span", { style: { flex: 1 } }),
2142
+ React.createElement("button", { className: "gm-mini", disabled: !!props.busy, onClick: () => setStashDlg(true) }, "暂存更改到 stash…"),
2143
+ React.createElement("button", {
2144
+ className: "gm-mini gm-mini-danger",
2145
+ disabled: !!props.busy || !stashes || stashes.length === 0,
2146
+ onClick: () => setConfirming({ kind: "stashClear" }),
2147
+ }, "清空 stash"),
2148
+ ),
2149
+ stashOpen
2150
+ ? (stashes && stashes.length > 0
2151
+ ? stashes.map((s) => React.createElement("div", { key: s.index, className: "gm-file", style: { cursor: "default" } },
2152
+ React.createElement("span", { className: "gm-file-kind" }, "W" + s.index),
2153
+ React.createElement("span", { className: "gm-file-path", title: s.ref }, s.subject),
2154
+ React.createElement("span", { className: "gm-meta" }, fmtTime(s.at)),
2155
+ React.createElement("button", { className: "gm-mini", disabled: !!props.busy, title: "应用该 stash(保留 stash 条目)", onClick: () => doStashOp("stashApply", () => remote.stashApply({ path: repoPath, index: s.index }), s.index) }, "应用"),
2156
+ React.createElement("button", { className: "gm-mini", disabled: !!props.busy, title: "应用并删除该 stash 条目", onClick: () => doStashOp("stashPop", () => remote.stashPop({ path: repoPath, index: s.index }), s.index) }, "弹出"),
2157
+ React.createElement("button", { className: "gm-mini gm-mini-danger", disabled: !!props.busy, onClick: () => setConfirming({ kind: "stashDrop", index: s.index, subject: s.subject }) }, "删除"),
2158
+ ))
2159
+ : React.createElement("div", { className: "gm-meta", style: { padding: "6px 2px" } }, stashes === null ? "加载 stash…" : "暂无 stash。点右上「暂存更改到 stash…」保存当前改动。"))
2160
+ : null,
2161
+ ),
2162
+ // diff 独立窗口(含行级选择;契约 §8.3)
2163
+ diffWin ? React.createElement(DiffWindow, {
2164
+ title: (diffWin.groupName && diffWin.groupName !== "主仓库" ? (diffWin.groupName + " · ") : "") + diffWin.file,
2165
+ // 子模块指针条目:副标题升级为「指针 a → b」(契约 §3.6),下钻按钮在头部右侧
2166
+ sub: (SCOPE_LABEL[diffWin.scope] || diffWin.scope)
2167
+ + (ptr ? (" · 指针 " + shortSha(ptr.fromSha) + " → " + shortSha(ptr.toSha)) : (diffWin.gitlink ? "(子模块指针条目)" : "")),
2168
+ loading: diffWin.loading,
2169
+ text: diffWin.text,
2170
+ truncated: diffWin.truncated,
2171
+ onClose: () => { setDiffWin(null); setLineSel(null); },
2172
+ onRefresh: () => openDiff(diffWin.file, diffWin.scope, diffWin.repoPath, diffWin.groupName, diffWin.gitlink, diffWin.ptr),
2173
+ actions: ptr ? React.createElement("button", {
2174
+ className: "gm-btn",
2175
+ disabled: ptrState !== "ok" || !!props.busy,
2176
+ title: ptrState === "ok"
2177
+ ? ("切到该子仓库的历史页并对比 " + shortSha(ptr.fromSha) + ".." + shortSha(ptr.toSha))
2178
+ : (ptrState === "checking"
2179
+ ? "正在核验指针提交是否在子仓库当前对象库中…"
2180
+ : (ptrState === "no-sub"
2181
+ ? "该路径不在仓库树里(未初始化的子模块或嵌入仓库),无法下钻查看子仓库历史"
2182
+ : (ptrReason || "指针提交不在该子仓库当前对象库(浅克隆或指针已前移)"))),
2183
+ onClick: jumpToSubRange,
2184
+ }, ptrState === "checking"
2185
+ ? "核验指针…"
2186
+ : ("在子仓库中查看 " + shortSha(ptr.fromSha) + ".." + shortSha(ptr.toSha))) : null,
2187
+ hunkActions: hunkActions,
2188
+ sel: lineSel,
2189
+ onLineClick: onLineClick,
2190
+ lineBar: lineBar,
2191
+ }) : null,
2192
+ // 文件级历史(契约 §8.4)
2193
+ fileHist ? React.createElement(FileHistoryWindow, {
2194
+ file: fileHist.file,
2195
+ loading: fileHist.loading,
2196
+ entries: fileHist.entries,
2197
+ onClose: () => setFileHist(null),
2198
+ onRefresh: () => openFileHist(fileHist.file, fileHist.repoPath),
2199
+ onOpenCommit: (c) => openHistDiff(fileHist.file, c, fileHist.repoPath),
2200
+ }) : null,
2201
+ histDiff ? React.createElement(DiffWindow, {
2202
+ title: histDiff.title,
2203
+ sub: histDiff.sub,
2204
+ loading: histDiff.loading,
2205
+ text: histDiff.text,
2206
+ truncated: histDiff.truncated,
2207
+ onClose: () => setHistDiff(null),
2208
+ onRefresh: () => openHistDiff(histDiff.file, histDiff.c, fileHist ? fileHist.repoPath : repoPath),
2209
+ }) : null,
2210
+ // 只读 blame 窗口(契约 §3.4b)
2211
+ blameWin ? React.createElement(BlameWindow, {
2212
+ title: "Blame — " + blameWin.file,
2213
+ sub: blameWin.ref || "HEAD",
2214
+ loading: blameWin.loading,
2215
+ lines: blameWin.lines,
2216
+ truncated: blameWin.truncated,
2217
+ onClose: () => setBlameWin(null),
2218
+ onRefresh: () => openBlame(blameWin.file, blameWin.ref, blameWin.repoPath),
2219
+ }) : null,
2220
+ // 危险操作二次确认(Portal 落 body,浮于 diff 窗口 1050 之上,契约 §0)
2221
+ React.createElement(ConfirmDialog, {
2222
+ open: !!confirming && (confirming.kind === "discard" || confirming.kind === "discard-all"),
2223
+ title: "放弃变更?",
2224
+ message: "此操作会丢弃对以下文件的所有本地改动,无法撤销:"
2225
+ + (confirming && confirming.repoName ? "\n\n仓库:" + confirming.repoName : "")
2226
+ + "\n\n" + (confirming && confirming.kind === "discard" ? (confirming.entry.path || confirming.entry) : (confirming && confirming.files ? confirming.files.join("\n") : "")),
2227
+ danger: true,
2228
+ confirmLabel: "确认丢弃",
2229
+ onCancel: () => setConfirming(null),
2230
+ onConfirm: onConfirmDiscard,
2231
+ }),
2232
+ React.createElement(ConfirmDialog, {
2233
+ open: !!confirming && confirming.kind === "lineDiscard",
2234
+ title: "撤销选中行?",
2235
+ message: "将丢弃选中的 " + (lineSel ? (Math.abs(lineSel.b - lineSel.a) + 1) : 0) + " 行在工作区中的改动(恢复为暂存区版本),此操作无法撤销。\n\n" + (diffWin ? diffWin.file : ""),
2236
+ danger: true,
2237
+ confirmLabel: "撤销选中行",
2238
+ onCancel: () => setConfirming(null),
2239
+ onConfirm: onConfirmDiscard,
2240
+ }),
2241
+ React.createElement(ConfirmDialog, {
2242
+ open: !!confirming && confirming.kind === "undoCommit",
2243
+ title: "撤销上次提交?",
2244
+ message: "将执行 git reset --soft HEAD~1:撤销 " + (confirming && confirming.repoName ? confirming.repoName : "目标仓库")
2245
+ + " 的最后一次提交,其改动保留在暂存区(不丢失内容)。\n\n重做提示:git reset --soft HEAD@{1}(或 git reflog 查看历史)。",
2246
+ danger: false,
2247
+ confirmLabel: "撤销上次提交",
2248
+ onCancel: () => setConfirming(null),
2249
+ onConfirm: onConfirmDiscard,
2250
+ }),
2251
+ React.createElement(ConfirmDialog, {
2252
+ open: !!hunkConfirm,
2253
+ title: "撤销此代码块?",
2254
+ message: "将丢弃该代码块在工作区中的改动(恢复为暂存区版本),此操作无法撤销。\n\n" + (diffWin ? diffWin.file : ""),
2255
+ danger: true,
2256
+ confirmLabel: "撤销此块",
2257
+ onCancel: () => setHunkConfirm(null),
2258
+ onConfirm: onConfirmHunk,
2259
+ }),
2260
+ React.createElement(ConfirmDialog, {
2261
+ open: !!confirming && confirming.kind === "stashDrop",
2262
+ title: "删除 stash 条目?",
2263
+ message: "该 stash 条目将被永久删除,无法撤销:\n\n" + (confirming && confirming.kind === "stashDrop" ? "#" + confirming.index + " " + confirming.subject : ""),
2264
+ danger: true,
2265
+ confirmLabel: "删除",
2266
+ onCancel: () => setConfirming(null),
2267
+ onConfirm: onConfirmDiscard,
2268
+ }),
2269
+ React.createElement(ConfirmDialog, {
2270
+ open: !!confirming && confirming.kind === "stashClear",
2271
+ title: "清空全部 stash?",
2272
+ message: "所有 stash 条目将被永久删除,无法撤销。",
2273
+ danger: true,
2274
+ confirmLabel: "清空",
2275
+ onCancel: () => setConfirming(null),
2276
+ onConfirm: onConfirmDiscard,
2277
+ }),
2278
+ // stash 新建弹窗
2279
+ stashDlg ? React.createElement(FormDialog, {
2280
+ open: true,
2281
+ title: "暂存更改到 stash",
2282
+ message: "把当前工作区与暂存区的改动收进 stash(可稍后应用/弹出)。",
2283
+ submitLabel: "创建 stash",
2284
+ onClose: () => setStashDlg(false),
2285
+ onSubmit: doStashPush,
2286
+ children: React.createElement(React.Fragment, null,
2287
+ React.createElement("div", { className: "gm-form-row" },
2288
+ React.createElement("span", { className: "gm-form-label" }, "说明(可选,作为 stash message)"),
2289
+ React.createElement("textarea", { className: "gm-textarea", style: { minHeight: 48 }, placeholder: "stash 说明…", value: stashMsg, onChange: (e) => setStashMsg(e.target.value) }),
2290
+ ),
2291
+ React.createElement("label", { className: "gm-checkbox" },
2292
+ React.createElement("input", { type: "checkbox", checked: stashUntracked, onChange: (e) => setStashUntracked(e.target.checked) }),
2293
+ "包含未跟踪文件(git stash -u)",
2294
+ ),
2295
+ ),
2296
+ }) : null,
2297
+ );
2298
+ }
2299
+
2300
+ // ============================================================================
2301
+ // BranchesTab(分支 + Tag 区)
2302
+ // ============================================================================
2303
+
2304
+ // 按 "/" 把分支名切成前缀树(纯函数,供分支树渲染用)
2305
+ // 目录节点 { dir:true, name:"段名", path:"a/b", children:[] }
2306
+ // 叶子节点 { dir:false, name:"完整分支名", branch:原分支对象 }
2307
+ // 排序:目录在前、叶子在后,同类按 name 做数字感知 + 大小写不敏感比较
2308
+ // 注:git 不允许 "a" 与 "a/b" 同时存在,故无需处理「同一路径既是叶子又是目录」
2309
+ function buildBranchTree(list) {
2310
+ const root = [];
2311
+ (list || []).forEach((b) => {
2312
+ const segs = String(b.name).split("/").filter(Boolean);
2313
+ if (!segs.length) return;
2314
+ let cur = root, path = "";
2315
+ segs.forEach((seg, i) => {
2316
+ path = path ? path + "/" + seg : seg;
2317
+ if (i === segs.length - 1) {
2318
+ cur.push({ dir: false, name: b.name, branch: b });
2319
+ return;
2320
+ }
2321
+ let dir = null;
2322
+ for (const n of cur) if (n.dir && n.name === seg) { dir = n; break; }
2323
+ if (!dir) {
2324
+ dir = { dir: true, name: seg, path: path, children: [] };
2325
+ cur.push(dir);
2326
+ }
2327
+ cur = dir.children;
2328
+ });
2329
+ });
2330
+ const cmp = (a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" });
2331
+ const sortRec = (nodes) => {
2332
+ nodes.sort((a, b) => (a.dir === b.dir ? cmp(a, b) : (a.dir ? -1 : 1)));
2333
+ nodes.forEach((n) => { if (n.dir) sortRec(n.children); });
2334
+ };
2335
+ sortRec(root);
2336
+ return root;
2337
+ }
2338
+
2339
+ function BranchesTab(props) {
2340
+ const remote = props.remote;
2341
+ const repoPath = props.repoPath;
2342
+ const status = props.status;
2343
+ const act = props.act;
2344
+ const [branches, setBranches] = React.useState(null);
2345
+ const [remotes, setRemotes] = React.useState([]);
2346
+ const [tags, setTags] = React.useState([]);
2347
+ const [creating, setCreating] = React.useState({ name: "", start: "", checkout: true });
2348
+ const [createDlg, setCreateDlg] = React.useState(null);
2349
+ const [foldClosed, setFoldClosed] = React.useState(() => new Set());
2350
+ const [openRow, setOpenRow] = React.useState(null); // 展开操作行的分支("l:refs/..." | "r:refs/...";同一时间只展开一行)
2351
+ const [confirming, setConfirming] = React.useState(null);
2352
+ const [tagDlg, setTagDlg] = React.useState(false);
2353
+ const [tagForm, setTagForm] = React.useState({ name: "", target: "HEAD", message: "", force: false });
2354
+
2355
+ const loadTags = async () => {
2356
+ try {
2357
+ const u = await unwrap(await remote.tags({ path: repoPath }));
2358
+ setTags(u.ok ? ((u.value && u.value.tags) || []) : []);
2359
+ } catch (_) { setTags([]); }
2360
+ };
2361
+ const refresh = async () => {
2362
+ const [b, r] = await Promise.all([
2363
+ unwrap(await remote.branches({ path: repoPath })),
2364
+ unwrap(await remote.remotes({ path: repoPath })),
2365
+ ]);
2366
+ if (b.ok) setBranches(b.value);
2367
+ if (r.ok) setRemotes(r.value);
2368
+ };
2369
+
2370
+ React.useEffect(() => { refresh(); loadTags(); }, [repoPath]);
2371
+
2372
+ // 切换作用域仓库 → 清空上一个仓库的分支/远端数据(避免短暂串仓库)
2373
+ // 顺带清空分支树折叠态:折叠路径是仓库内分支名,跨仓库无意义
2374
+ React.useEffect(() => { setBranches(null); setRemotes([]); setTags([]); setFoldClosed(new Set()); setOpenRow(null); }, [repoPath]);
2375
+
2376
+ // 分支树分组折叠(Set 不可变更新,仿 ChangesTab 的 toggleCollapse)
2377
+ const toggleFold = (p) => setFoldClosed((cur) => {
2378
+ const n = new Set(cur);
2379
+ if (n.has(p)) n.delete(p); else n.add(p);
2380
+ return n;
2381
+ });
2382
+
2383
+ const createNew = async (form) => {
2384
+ const f = form && form.name !== undefined ? form : creating;
2385
+ if (!f.name.trim()) return;
2386
+ const payload = { path: repoPath, name: f.name.trim() };
2387
+ if (f.start) payload.startPoint = f.start;
2388
+ // Host branchCreate 支持 checkout:创建后立即切到新分支(默认开)
2389
+ if (f.checkout !== false) payload.checkout = true;
2390
+ await act("createBranch", () => remote.branchCreate(payload));
2391
+ setCreating({ name: "", start: "", checkout: true });
2392
+ refresh();
2393
+ };
2394
+
2395
+ const doCheckout = async (name) => {
2396
+ await act("checkout", () => remote.checkout({ path: repoPath, name }));
2397
+ refresh();
2398
+ };
2399
+ const doMerge = async (name) => {
2400
+ const r = await act("merge", () => remote.merge({ path: repoPath, branch: name }));
2401
+ if (r && r.merged === false && status && status.conflicted.length > 0) {
2402
+ // 切到冲突 tab
2403
+ conflictSource = "merge";
2404
+ if (props.onSwitchTab) props.onSwitchTab("conflicts");
2405
+ }
2406
+ };
2407
+ const doDelete = async (name, force) => {
2408
+ setConfirming(null);
2409
+ await act("deleteBranch", () => remote.branchDelete({ path: repoPath, name, force: !!force }));
2410
+ refresh();
2411
+ };
2412
+ // rebaseBranch(契约 §8.1):当前分支 rebase 到 branch 之上;冲突不抛错(done:false)
2413
+ const doRebase = async (name) => {
2414
+ setConfirming(null);
2415
+ const r = await act("rebaseBranch", () => remote.rebaseBranch({ path: repoPath, branch: name }));
2416
+ if (r === undefined) return;
2417
+ refresh();
2418
+ if (r.done === false) {
2419
+ conflictSource = "rebase";
2420
+ if (props.onSwitchTab) props.onSwitchTab("conflicts");
2421
+ setError("Rebase 遇到冲突:请在「冲突」页解决后点「继续 Rebase」(或「中止 Rebase」回退)。\n提示:git rebase --abort 可回到 rebase 前的状态(reflog 可查)。");
2422
+ } else {
2423
+ showToast("Rebase 完成:当前分支已重放到 \"" + name + "\" 之上(历史已改写)。\n回退提示:git reset --hard HEAD@{1}(或 git reflog 查看历史)。");
2424
+ }
2425
+ };
2426
+
2427
+ // ---- tag 操作 ----
2428
+ const doTagCreate = async () => {
2429
+ const name = tagForm.name.trim();
2430
+ if (!name) return;
2431
+ const req = { path: repoPath, name };
2432
+ if (tagForm.target.trim()) req.sha = tagForm.target.trim(); // 契约:target 映射 wire 字段 sha
2433
+ if (tagForm.message.trim()) req.message = tagForm.message.trim(); // message 非空 → annotated
2434
+ if (tagForm.force) req.force = true;
2435
+ const r = await act("tagCreate", () => remote.tagCreate(req));
2436
+ if (r === undefined) return;
2437
+ if (r && r.tags) setTags(r.tags); else await loadTags();
2438
+ setTagDlg(false);
2439
+ setTagForm({ name: "", target: "HEAD", message: "", force: false });
2440
+ };
2441
+ const doTagDelete = async (name) => {
2442
+ setConfirming(null);
2443
+ const r = await act("tagDelete", () => remote.tagDelete({ path: repoPath, name }));
2444
+ if (r && r.tags) setTags(r.tags); else await loadTags();
2445
+ };
2446
+ const doTagPush = async (name) => {
2447
+ // push tag:走 push 的 refSpec(--force-with-lease 语义由 Host 保证)
2448
+ await act("pushTag", () => remote.push({ path: repoPath, remote: "origin", refSpec: "refs/tags/" + name }));
2449
+ };
2450
+
2451
+ // 叶子行(分支树 depth 层缩进)+ 展开后的操作行(用户反馈 #2 第二版:
2452
+ // 所有操作按钮**另起一行**)。点击行或行尾 ▸/▾ 展开/收起,同一时间只展开一行;
2453
+ // 相比悬停展开不会因鼠标划过导致列表高度跳动,相比右侧浮层不遮挡提交说明。
2454
+ // 行本身保持只有 名字/短sha/ahead-behind/说明,分支多/层级深时名字完整可读。
2455
+ const renderRow = (b, isRemote, depth) => {
2456
+ const openKey = (isRemote ? "r:" : "l:") + b.refname;
2457
+ const isOpen = openRow === openKey;
2458
+ const indent = 10 + (depth || 0) * 16;
2459
+ return React.createElement(React.Fragment, { key: b.refname },
2460
+ React.createElement("div", {
2461
+ className: "gm-file" + (b.current ? " gm-file-active" : "") + (isOpen ? " gm-branch-open" : ""),
2462
+ style: { paddingLeft: indent },
2463
+ onClick: () => setOpenRow(isOpen ? null : openKey),
2464
+ },
2465
+ React.createElement("span", { className: "gm-file-kind " + (b.current ? "gm-file-kind-added" : "") }, b.current ? "★" : (isRemote ? "R" : "L")),
2466
+ React.createElement("span", { className: "gm-file-path", title: b.name }, b.name),
2467
+ React.createElement("span", { style: { fontSize: 11, color: "var(--dsw-alias-label-tertiary)", fontFamily: "ui-monospace,monospace" } }, b.shortSha),
2468
+ b.upstream ? React.createElement("span", { style: { fontSize: 11, color: "var(--dsw-alias-label-secondary)" } }, " ↑" + (b.ahead || 0) + " ↓" + (b.behind || 0) + (b.upstreamGone ? " gone" : "")) : null,
2469
+ React.createElement("span", { style: { fontSize: 11, color: "var(--dsw-alias-label-tertiary)", marginLeft: 8, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, title: b.subject }, b.subject),
2470
+ // 行尾展开指示(键盘可达:stopPropagation 防止与行 onClick 叠成双次切换)
2471
+ React.createElement("button", {
2472
+ className: "gm-branch-caret",
2473
+ title: isOpen ? "收起该分支的操作" : "展开该分支的操作",
2474
+ "aria-expanded": isOpen ? "true" : "false",
2475
+ onClick: (e) => { e.stopPropagation(); setOpenRow(isOpen ? null : openKey); },
2476
+ }, isOpen ? "▾" : "▸"),
2477
+ ),
2478
+ isOpen ? React.createElement("div", { className: "gm-branch-actions", style: { paddingLeft: indent + 30 } },
2479
+ isRemote
2480
+ ? React.createElement("button", {
2481
+ className: "gm-mini",
2482
+ title: "检出该远程分支为新的本地分支(可改分支名与起点)",
2483
+ onClick: () => setCreateDlg({ name: b.name.replace(/^[^/]+\//, ""), start: b.name, checkout: true }),
2484
+ }, "检出为本地分支…")
2485
+ : React.createElement(React.Fragment, null,
2486
+ // 基于此分支新建(起点预填,可改)
2487
+ React.createElement("button", {
2488
+ className: "gm-mini",
2489
+ title: "以 \"" + b.name + "\" 为起点新建一个分支(可改起点)",
2490
+ onClick: () => setCreateDlg({ name: "", start: b.name, checkout: true }),
2491
+ }, "以此为起点新建分支…"),
2492
+ b.current ? null : React.createElement("button", { className: "gm-mini", title: "切换到该分支(git checkout)", onClick: () => doCheckout(b.name) }, "切换到此分支"),
2493
+ b.current || b.name === "main" ? null : React.createElement("button", { className: "gm-mini", title: "把该分支合并进当前分支(git merge)", onClick: () => doMerge(b.name) }, "合并到当前分支"),
2494
+ b.current ? null : React.createElement("button", {
2495
+ className: "gm-mini",
2496
+ title: "把当前分支 rebase 到该分支之上(改写当前分支历史,需确认)",
2497
+ onClick: () => setConfirming({ kind: "rebase", name: b.name }),
2498
+ }, "Rebase 当前分支到此…"),
2499
+ b.current ? null : React.createElement("button", { className: "gm-mini gm-mini-danger", title: "删除该分支(需确认;未合并将失败)", onClick: () => setConfirming({ kind: "delete", name: b.name }) }, "删除分支"),
2500
+ ),
2501
+ ) : null,
2502
+ );
2503
+ };
2504
+
2505
+ // 目录分组下的叶子总数(递归求,用于目录行右侧灰色计数)
2506
+ const branchLeafCount = (nodes) => nodes.reduce((acc, n) => acc + (n.dir ? branchLeafCount(n.children) : 1), 0);
2507
+
2508
+ // 分支树递归渲染:目录行(▸/▾ 可折叠 + 计数)+ 叶子行
2509
+ const renderBranchNodes = (nodes, depth, isRemote) => nodes.map((n) => {
2510
+ if (!n.dir) return renderRow(n.branch, isRemote, depth);
2511
+ const closed = foldClosed.has(n.path);
2512
+ return React.createElement(React.Fragment, { key: n.path },
2513
+ React.createElement("div", {
2514
+ className: "gm-file",
2515
+ style: { cursor: "default", paddingLeft: 10 + depth * 16 },
2516
+ },
2517
+ React.createElement("button", {
2518
+ className: "gm-mini",
2519
+ title: closed ? "展开该分组" : "折叠该分组",
2520
+ onClick: () => toggleFold(n.path),
2521
+ }, closed ? "▸" : "▾"),
2522
+ React.createElement("span", { className: "gm-file-path" }, n.name),
2523
+ React.createElement("span", { style: { fontSize: 11, color: "var(--dsw-alias-label-tertiary)" } }, "(" + branchLeafCount(n.children) + ")"),
2524
+ ),
2525
+ closed ? null : renderBranchNodes(n.children, depth + 1, isRemote),
2526
+ );
2527
+ });
2528
+
2529
+ if (!branches) return React.createElement("div", { className: "gm-empty" }, "加载分支…");
2530
+
2531
+ const localTree = buildBranchTree(branches.locals);
2532
+ const remoteTree = buildBranchTree(branches.remotes);
2533
+
2534
+ return React.createElement(React.Fragment, null,
2535
+ // 新建分支置顶(用户反馈 #3):分支多时不用滚到底部找入口。
2536
+ // gm-commit 默认 margin-top:14,置顶后归零让它贴住内容区顶部。
2537
+ React.createElement("div", { className: "gm-commit", style: { marginTop: 0 } },
2538
+ React.createElement("div", { style: { fontSize: 12, fontWeight: 500 } }, "新建分支"),
2539
+ React.createElement("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" } },
2540
+ React.createElement("input", { className: "gm-input", placeholder: "分支名", value: creating.name, onChange: (e) => setCreating((s) => ({ ...s, name: e.target.value })) }),
2541
+ // 起点改为下拉:默认 HEAD 或挑一个已有本地 / 远程分支
2542
+ React.createElement("select", {
2543
+ className: "gm-input",
2544
+ style: { maxWidth: 220 },
2545
+ value: creating.start,
2546
+ onChange: (e) => setCreating((s) => ({ ...s, start: e.target.value })),
2547
+ },
2548
+ React.createElement("option", { value: "" }, "起点:默认 HEAD"),
2549
+ React.createElement("optgroup", { label: "本地分支" }, branches.locals.map((b) =>
2550
+ React.createElement("option", { key: b.refname, value: b.name }, b.name + (b.current ? "(当前)" : "")))),
2551
+ React.createElement("optgroup", { label: "远程分支" }, branches.remotes.map((b) =>
2552
+ React.createElement("option", { key: b.refname, value: b.name }, b.name))),
2553
+ ),
2554
+ React.createElement("label", { className: "gm-checkbox", title: "创建成功后立即切换到新分支(git switch 到新分支)" },
2555
+ React.createElement("input", { type: "checkbox", checked: creating.checkout, onChange: (e) => setCreating((s) => ({ ...s, checkout: e.target.checked })) }),
2556
+ "创建后切换到新分支",
2557
+ ),
2558
+ React.createElement("button", { className: "gm-btn gm-btn-primary", onClick: () => createNew() }, "新建"),
2559
+ ),
2560
+ ),
2561
+ React.createElement("div", { className: "gm-filegroup" },
2562
+ React.createElement("div", { className: "gm-filegroup-head" }, React.createElement("span", null, "本地 (" + branches.locals.length + ")"))),
2563
+ branches.locals.length === 0
2564
+ ? React.createElement("div", { className: "gm-meta", style: { padding: "6px 2px" } }, "(无)")
2565
+ : renderBranchNodes(localTree, 0, false),
2566
+ branches.remotes.length > 0 ? React.createElement("div", { className: "gm-filegroup" },
2567
+ React.createElement("div", { className: "gm-filegroup-head" }, React.createElement("span", null, "远程 (" + branches.remotes.length + ")"))) : null,
2568
+ renderBranchNodes(remoteTree, 0, true),
2569
+ // Tag 区
2570
+ React.createElement("div", { className: "gm-section" },
2571
+ React.createElement("div", { className: "gm-section-head" },
2572
+ React.createElement("span", null, "Tag (" + tags.length + ")"),
2573
+ React.createElement("span", { style: { flex: 1 } }),
2574
+ React.createElement("button", { className: "gm-mini", onClick: () => setTagDlg(true) }, "新建 tag…"),
2575
+ ),
2576
+ tags.length === 0
2577
+ ? React.createElement("div", { className: "gm-meta", style: { padding: "6px 2px" } }, "暂无 tag。")
2578
+ : tags.map((t) => {
2579
+ const tagKey = "t:" + t.name;
2580
+ const tagOpen = openRow === tagKey;
2581
+ return React.createElement(React.Fragment, { key: t.name },
2582
+ React.createElement("div", {
2583
+ className: "gm-file" + (tagOpen ? " gm-branch-open" : ""),
2584
+ style: { cursor: "pointer" },
2585
+ onClick: () => setOpenRow(tagOpen ? null : tagKey),
2586
+ },
2587
+ React.createElement("span", { className: "gm-file-kind" }, "T"),
2588
+ React.createElement("span", { className: "gm-file-path" }, t.name),
2589
+ t.annotated ? React.createElement("span", { className: "gm-tag-badge", title: t.message || "annotated tag" }, "annotated") : null,
2590
+ React.createElement("span", { className: "gm-meta", style: { fontFamily: "ui-monospace,monospace" } }, t.short),
2591
+ React.createElement("span", { className: "gm-meta", title: t.subject }, (t.subject || "").slice(0, 40)),
2592
+ React.createElement("span", { className: "gm-meta" }, fmtTime(t.at)),
2593
+ React.createElement("button", {
2594
+ className: "gm-branch-caret",
2595
+ title: tagOpen ? "收起该 tag 的操作" : "展开该 tag 的操作",
2596
+ "aria-expanded": tagOpen ? "true" : "false",
2597
+ onClick: (e) => { e.stopPropagation(); setOpenRow(tagOpen ? null : tagKey); },
2598
+ }, tagOpen ? "▾" : "▸"),
2599
+ ),
2600
+ tagOpen ? React.createElement("div", { className: "gm-branch-actions", style: { paddingLeft: 40 } },
2601
+ React.createElement("button", { className: "gm-mini", title: "推送该 tag 到 origin", onClick: () => doTagPush(t.name) }, "推送到 origin"),
2602
+ React.createElement("button", { className: "gm-mini gm-mini-danger", title: "删除该本地 tag(需确认;已推送的远端 tag 不受影响)", onClick: () => setConfirming({ kind: "tagDelete", name: t.name }) }, "删除 tag"),
2603
+ ) : null,
2604
+ );
2605
+ }),
2606
+ ),
2607
+ React.createElement(ConfirmDialog, {
2608
+ open: !!confirming && confirming.kind === "delete",
2609
+ title: "删除分支?",
2610
+ message: "确认删除分支 \"" + (confirming && confirming.name) + "\"?若未合并且无 -D,将失败。",
2611
+ danger: true,
2612
+ confirmLabel: "删除(未合并则失败)",
2613
+ onCancel: () => setConfirming(null),
2614
+ onConfirm: () => doDelete(confirming && confirming.name, false),
2615
+ }),
2616
+ React.createElement(ConfirmDialog, {
2617
+ open: !!confirming && confirming.kind === "rebase",
2618
+ title: "Rebase 当前分支?",
2619
+ message: "将把当前分支 rebase 到 \"" + (confirming && confirming.name) + "\" 之上:当前分支的提交会被重放(sha 变化,历史改写)。\n若已推送远端,之后需要 force push(--force-with-lease)。\n冲突可在「冲突」页「中止 Rebase」回退。",
2620
+ danger: true,
2621
+ confirmLabel: "开始 Rebase",
2622
+ onCancel: () => setConfirming(null),
2623
+ onConfirm: () => doRebase(confirming && confirming.name),
2624
+ }),
2625
+ React.createElement(ConfirmDialog, {
2626
+ open: !!confirming && confirming.kind === "tagDelete",
2627
+ title: "删除 tag?",
2628
+ message: "确认删除 tag \"" + (confirming && confirming.name) + "\"?本地 tag 将被删除,已推送的远端 tag 不受影响。",
2629
+ danger: true,
2630
+ confirmLabel: "删除",
2631
+ onCancel: () => setConfirming(null),
2632
+ onConfirm: () => doTagDelete(confirming && confirming.name),
2633
+ }),
2634
+ // 基于既有分支新建分支的弹窗(本地行 / 远程行都走这里)
2635
+ createDlg ? React.createElement(FormDialog, {
2636
+ open: true,
2637
+ title: "基于 \"" + createDlg.start + "\" 新建分支",
2638
+ submitLabel: "新建分支",
2639
+ onClose: () => setCreateDlg(null),
2640
+ // 先关弹窗再提交:失败时错误由面板错误条展示
2641
+ onSubmit: () => { const f = createDlg; setCreateDlg(null); return createNew(f); },
2642
+ submitDisabled: !createDlg.name.trim(),
2643
+ children: React.createElement(React.Fragment, null,
2644
+ React.createElement("div", { className: "gm-form-row" },
2645
+ React.createElement("span", { className: "gm-form-label" }, "新分支名"),
2646
+ React.createElement("input", { className: "gm-input", placeholder: "如 feature/login", value: createDlg.name, onChange: (e) => setCreateDlg((s) => ({ ...s, name: e.target.value })) }),
2647
+ ),
2648
+ React.createElement("div", { className: "gm-form-row" },
2649
+ React.createElement("span", { className: "gm-form-label" }, "起点(commit-ish:分支名 / tag / sha,默认 HEAD)"),
2650
+ React.createElement("input", { className: "gm-input", title: "可填 commit-ish:分支名、tag 或 sha;留空则用当前 HEAD", value: createDlg.start, onChange: (e) => setCreateDlg((s) => ({ ...s, start: e.target.value })) }),
2651
+ ),
2652
+ React.createElement("label", { className: "gm-checkbox", title: "创建成功后立即切换到新分支" },
2653
+ React.createElement("input", { type: "checkbox", checked: createDlg.checkout, onChange: (e) => setCreateDlg((s) => ({ ...s, checkout: e.target.checked })) }),
2654
+ "创建后切换到新分支",
2655
+ ),
2656
+ ),
2657
+ }) : null,
2658
+ // 新建 tag 弹窗
2659
+ tagDlg ? React.createElement(FormDialog, {
2660
+ open: true,
2661
+ title: "新建 tag",
2662
+ submitLabel: "创建",
2663
+ onClose: () => setTagDlg(false),
2664
+ onSubmit: doTagCreate,
2665
+ submitDisabled: !tagForm.name.trim(),
2666
+ children: React.createElement(React.Fragment, null,
2667
+ React.createElement("div", { className: "gm-form-row" },
2668
+ React.createElement("span", { className: "gm-form-label" }, "Tag 名称"),
2669
+ React.createElement("input", { className: "gm-input", placeholder: "如 v1.0.0", value: tagForm.name, onChange: (e) => setTagForm((s) => ({ ...s, name: e.target.value })) }),
2670
+ ),
2671
+ React.createElement("div", { className: "gm-form-row" },
2672
+ React.createElement("span", { className: "gm-form-label" }, "目标提交(commit-ish,默认 HEAD)"),
2673
+ React.createElement("input", { className: "gm-input", placeholder: "HEAD / sha / 分支名", value: tagForm.target, onChange: (e) => setTagForm((s) => ({ ...s, target: e.target.value })) }),
2674
+ ),
2675
+ React.createElement("div", { className: "gm-form-row" },
2676
+ React.createElement("span", { className: "gm-form-label" }, "说明(非空则创建 annotated tag)"),
2677
+ React.createElement("textarea", { className: "gm-textarea", style: { minHeight: 48 }, placeholder: "tag 说明…", value: tagForm.message, onChange: (e) => setTagForm((s) => ({ ...s, message: e.target.value })) }),
2678
+ ),
2679
+ React.createElement("label", { className: "gm-checkbox" },
2680
+ React.createElement("input", { type: "checkbox", checked: tagForm.force, onChange: (e) => setTagForm((s) => ({ ...s, force: e.target.checked })) }),
2681
+ "force(覆盖同名 tag)",
2682
+ ),
2683
+ ),
2684
+ }) : null,
2685
+ );
2686
+ }
2687
+
2688
+ // ============================================================================
2689
+ // HistoryTab(分支线 SVG + 过滤条 + 提交详情侧栏 + 范围对比 + revert/reset)
2690
+ // ============================================================================
2691
+ function HistoryTab(props) {
2692
+ const remote = props.remote;
2693
+ const repoPath = props.repoPath;
2694
+ const act = props.act;
2695
+ const setError = props.setError;
2696
+ const [log, setLog] = React.useState(null); // { commits, graph, hasMore }
2697
+ const [refMode, setRefMode] = React.useState("all"); // all | current | ref:<name>
2698
+ const [viewMode, setViewMode] = React.useState("log"); // "log" | "reflog"(契约 §3.4b)
2699
+ const [reflog, setReflog] = React.useState(null); // reflogEntry[] | null
2700
+ const [reflogLimit, setReflogLimit] = React.useState(200);
2701
+ const [blameWin, setBlameWin] = React.useState(null); // { file, ref, loading, lines, truncated }
2702
+ const [rebaseDlg, setRebaseDlg] = React.useState(null); // { base, entries }(rebase todo 弹窗)
2703
+ const [fixupDlg, setFixupDlg] = React.useState(null); // { sha, subject }
2704
+ const [fixupForm, setFixupForm] = React.useState({ mode: "fixup", message: "" });
2705
+ const [fileHist, setFileHist] = React.useState(null); // { file, loading, entries }
2706
+ const [histDiff, setHistDiff] = React.useState(null); // { file, c, title, sub, loading, text, truncated }
2707
+ const [confirming, setConfirming] = React.useState(null); // { kind: undoMove|rebaseRun|fixupRun, ... }
2708
+ const [busyLocal, setBusyLocal] = React.useState(null); // rebase/fixup 进行中标记
2709
+ const [filters, setFilters] = React.useState({ file: "", author: "", grep: "", since: "", until: "" });
2710
+ const [refOptions, setRefOptions] = React.useState([]); // 分支/tag 名(ref 过滤下拉)
2711
+ const [maxCount, setMaxCount] = React.useState(200);
2712
+ const [diffWin, setDiffWin] = React.useState(null); // { sha, subject, loading, text, truncated }
2713
+ const [hoverRow, setHoverRow] = React.useState(null); // 悬停行 → 分支线聚焦高亮
2714
+ const [picking, setPicking] = React.useState(false); // cherry-pick 进行中(禁用按钮防重复点击)
2715
+ const [detail, setDetail] = React.useState(null); // 提交详情侧栏 { sha, subject, author, at, loading, message, files }
2716
+ const [resetDlg, setResetDlg] = React.useState(null); // { sha, subject }
2717
+ const [resetMode, setResetMode] = React.useState("mixed");
2718
+ const [resetText, setResetText] = React.useState("");
2719
+ const [comparing, setComparing] = React.useState(false); // 范围对比选择态
2720
+ const [cmpSel, setCmpSel] = React.useState([]); // [base, head]
2721
+ const [cmpDiff, setCmpDiff] = React.useState(null); // { kind, from, to, text, truncated, loading }
2722
+
2723
+ const refresh = async () => {
2724
+ const req = { path: repoPath, maxCount, all: refMode === "all" };
2725
+ if (refMode.indexOf("ref:") === 0) req.ref = refMode.slice(4);
2726
+ if (filters.file.trim()) req.file = filters.file.trim();
2727
+ if (filters.author.trim()) req.author = filters.author.trim();
2728
+ if (filters.grep.trim()) req.grep = filters.grep.trim();
2729
+ if (filters.since) req.since = filters.since;
2730
+ if (filters.until) req.until = filters.until;
2731
+ const r = await unwrap(await remote.log(req));
2732
+ if (r.ok) setLog(r.value);
2733
+ else setError(r.error.message || r.error.code);
2734
+ };
2735
+
2736
+ // 切换作用域仓库 → 立刻清空上一个仓库的历史(避免短暂显示别的仓库的提交)
2737
+ React.useEffect(() => { setLog(null); setDetail(null); }, [repoPath]);
2738
+
2739
+ // 过滤条件变更 → 防抖重取
2740
+ React.useEffect(() => {
2741
+ const t = setTimeout(refresh, 250);
2742
+ return () => clearTimeout(t);
2743
+ }, [repoPath, maxCount, refMode, filters]);
2744
+
2745
+ // ref 过滤下拉的候选(分支 + tag)
2746
+ React.useEffect(() => {
2747
+ let alive = true;
2748
+ (async () => {
2749
+ const names = [];
2750
+ try {
2751
+ const b = await unwrap(await remote.branches({ path: repoPath }));
2752
+ if (b.ok && b.value) {
2753
+ for (const x of (b.value.locals || [])) names.push(x.name);
2754
+ }
2755
+ } catch (_) { /* 忽略 */ }
2756
+ try {
2757
+ const t = await unwrap(await remote.tags({ path: repoPath }));
2758
+ if (t.ok && t.value) {
2759
+ for (const x of (t.value.tags || [])) names.push(x.name);
2760
+ }
2761
+ } catch (_) { /* 忽略 */ }
2762
+ if (alive) setRefOptions(names);
2763
+ })();
2764
+ return () => { alive = false; };
2765
+ }, [repoPath]);
2766
+
2767
+ // Reflog 模式(契约 §3.4b):reflog 取数
2768
+ React.useEffect(() => {
2769
+ if (viewMode !== "reflog") return undefined;
2770
+ let alive = true;
2771
+ (async () => {
2772
+ try {
2773
+ const r = await unwrap(await remote.reflog({ path: repoPath, limit: reflogLimit }));
2774
+ if (!alive) return;
2775
+ if (r.ok) setReflog((r.value && r.value.entries) || []);
2776
+ else setError(r.error.message || r.error.code);
2777
+ } catch (e) {
2778
+ if (alive) setError(String(e && e.message || e));
2779
+ }
2780
+ })();
2781
+ return () => { alive = false; };
2782
+ }, [viewMode, repoPath, reflogLimit]);
2783
+
2784
+ // 只读 blame 窗口(契约 §3.4b):提交详情侧栏文件行入口(ref=该提交)
2785
+ const openBlame = async (file, ref) => {
2786
+ setBlameWin({ file, ref, loading: true, lines: [], truncated: false });
2787
+ const req = { path: repoPath, file };
2788
+ if (ref) req.ref = ref;
2789
+ const r = await unwrap(await remote.blame(req));
2790
+ if (!r.ok) { setBlameWin(null); setError(r.error.message || r.error.code); return; }
2791
+ setBlameWin({ file, ref, loading: false, lines: (r.value && r.value.lines) || [], truncated: !!(r.value && r.value.truncated) });
2792
+ };
2793
+
2794
+ // ---- rebase todo(契约 §8.6):todo = 该提交(含)到 HEAD,base 传该提交的父 ----
2795
+ const openRebaseDlg = async () => {
2796
+ if (!detail) return;
2797
+ const base = detail.sha + "^"; // Host 口径 base..HEAD(不含 base),见契约 §8.1
2798
+ setBusyLocal(detail.sha);
2799
+ try {
2800
+ const r = await unwrap(await remote.rebasePlan({ path: repoPath, base }));
2801
+ if (!r.ok) { setError(r.error.message || r.error.code); return; }
2802
+ setRebaseDlg({ base, entries: (r.value && r.value.entries) || [] });
2803
+ } finally {
2804
+ setBusyLocal(null);
2805
+ }
2806
+ };
2807
+ const doRebaseRun = async () => {
2808
+ const c = confirming;
2809
+ setConfirming(null);
2810
+ if (!c) return;
2811
+ setBusyLocal("rebaseRun");
2812
+ try {
2813
+ const r = await unwrap(await remote.rebaseRun({ path: repoPath, base: c.base, entries: c.entries }));
2814
+ if (!r.ok) { setError(r.error.message || r.error.code); return; }
2815
+ if (props.onStatus && r.value && r.value.status) props.onStatus(r.value.status);
2816
+ refresh();
2817
+ if (r.value && r.value.done === false) {
2818
+ conflictSource = "rebase";
2819
+ if (props.onSwitchTab) props.onSwitchTab("conflicts");
2820
+ setError("Rebase 遇到冲突:请在「冲突」页解决后点「继续 Rebase」(或「中止 Rebase」回退)。\n提示:git rebase --abort 可回到 rebase 前的状态(reflog 可查)。");
2821
+ } else {
2822
+ setDetail(null);
2823
+ showToast("Rebase 完成,历史已改写。\n回退提示:git reset --hard HEAD@{1}(或 git reflog 查看历史)。");
2824
+ }
2825
+ } finally {
2826
+ setBusyLocal(null);
2827
+ }
2828
+ };
2829
+
2830
+ // ---- fixup(契约 §8.6):用暂存改动修正历史提交,改写历史 ----
2831
+ const openFixupDlg = () => {
2832
+ if (!detail) return;
2833
+ setFixupForm({ mode: "fixup", message: "" });
2834
+ setFixupDlg({ sha: detail.sha, subject: detail.subject });
2835
+ };
2836
+ const doFixupRun = async () => {
2837
+ const c = confirming;
2838
+ setConfirming(null);
2839
+ if (!c) return;
2840
+ setBusyLocal("fixup");
2841
+ try {
2842
+ const req = { path: repoPath, sha: c.sha, mode: c.mode };
2843
+ if (c.message && c.message.trim()) req.message = c.message.trim();
2844
+ const r = await unwrap(await remote.fixupCommit(req));
2845
+ if (!r.ok) { setError(r.error.message || r.error.code); return; }
2846
+ if (props.onStatus && r.value && r.value.status) props.onStatus(r.value.status);
2847
+ refresh();
2848
+ if (r.value && r.value.done === false) {
2849
+ conflictSource = "rebase";
2850
+ if (props.onSwitchTab) props.onSwitchTab("conflicts");
2851
+ setError("fixup/squash rebase 遇到冲突:请在「冲突」页解决后点「继续 Rebase」(或「中止 Rebase」回退)。");
2852
+ } else {
2853
+ setDetail(null);
2854
+ showToast("已用暂存改动修正 " + c.sha.slice(0, 8) + "(历史已改写)。\n回退提示:git reset --hard HEAD@{1}(或 git reflog 查看历史)。");
2855
+ }
2856
+ } finally {
2857
+ setBusyLocal(null);
2858
+ }
2859
+ };
2860
+
2861
+ // ---- undo(契约 §8.5):撤销上次分支移动(mixed reset @{1}) ----
2862
+ const doUndoMove = async () => {
2863
+ setConfirming(null);
2864
+ const r = await act("undoMove", () => remote.reset({ path: repoPath, mode: "mixed", target: "@{1}" }));
2865
+ if (r === undefined) return;
2866
+ refresh();
2867
+ showToast("已撤销上次分支移动,工作区改动保留。\n重做:git reset --mixed HEAD@{1}(或 git reflog 查看历史)。");
2868
+ };
2869
+
2870
+ // ---- 文件级历史(契约 §8.4) ----
2871
+ const openFileHist = async (file) => {
2872
+ setFileHist({ file, loading: true, entries: [] });
2873
+ const r = await unwrap(await remote.log({ path: repoPath, file, maxCount: 100 }));
2874
+ if (!r.ok) { setFileHist(null); setError(r.error.message || r.error.code); return; }
2875
+ setFileHist({ file, loading: false, entries: (r.value && r.value.commits) || [] });
2876
+ };
2877
+ const openHistDiff = async (file, c) => {
2878
+ const from = (c.parents && c.parents.length > 0) ? (c.sha + "^") : EMPTY_TREE_SHA;
2879
+ setHistDiff({ file, c, title: file, sub: (c.short || "") + " " + (c.subject || ""), loading: true, text: "", truncated: false });
2880
+ const r = await unwrap(await remote.diffRange({ path: repoPath, from, to: c.sha, file, kind: "patch" }));
2881
+ if (!r.ok) { setHistDiff(null); setError(r.error.message || r.error.code); return; }
2882
+ setHistDiff({ file, c, title: file, sub: (c.short || "") + " " + (c.subject || ""), loading: false, text: r.value.text, truncated: r.value.truncated });
2883
+ };
2884
+
2885
+ // 点击提交 → 打开提交详情侧栏(行内「diff」按钮直接开 diff 窗口)
2886
+ const openDetail = async (c) => {
2887
+ setDetail({ sha: c.sha, subject: c.subject, author: c.author, at: c.at, parents: c.parents || [], loading: true, message: c.subject || "", files: [] });
2888
+ const r = await unwrap(await remote.diff({ path: repoPath, scope: "commit", sha: c.sha }));
2889
+ if (!r.ok) {
2890
+ setDetail((d) => (d && d.sha === c.sha ? { ...d, loading: false } : d));
2891
+ setError(r.error.message || r.error.code);
2892
+ return;
2893
+ }
2894
+ const files = parseUnifiedDiff(r.value.text).map((f) => ({
2895
+ path: (f.newPath || f.oldPath || f.file || "").replace(/^[ab]\//, "").replace(/^"/, "").replace(/"$/, ""),
2896
+ status: f.status,
2897
+ add: f.addCount,
2898
+ del: f.delCount,
2899
+ }));
2900
+ const msg = parseShowMessage(r.value.text) || c.subject || "";
2901
+ setDetail((d) => (d && d.sha === c.sha ? { ...d, loading: false, message: msg, files } : d));
2902
+ };
2903
+
2904
+ // 行内「diff」按钮 → 只读 diff 窗口(历史提交 diff 无 hunk 操作)
2905
+ const openCommitDiff = async (c) => {
2906
+ setDiffWin({ sha: c.sha, subject: c.subject, loading: true, text: "", truncated: false });
2907
+ const r = await unwrap(await remote.diff({ path: repoPath, scope: "commit", sha: c.sha }));
2908
+ if (!r.ok) { setDiffWin(null); setError(r.error.message || r.error.code); return; }
2909
+ setDiffWin({ sha: c.sha, subject: c.subject, loading: false, text: r.value.text, truncated: r.value.truncated });
2910
+ };
2911
+
2912
+ // 详情侧栏点文件 → 该提交该文件的只读 diff 窗口
2913
+ const openFileDiff = async (c, file) => {
2914
+ setDiffWin({ sha: c.sha, subject: file, loading: true, text: "", truncated: false });
2915
+ const r = await unwrap(await remote.diff({ path: repoPath, scope: "commit", sha: c.sha, file }));
2916
+ if (!r.ok) { setDiffWin(null); setError(r.error.message || r.error.code); return; }
2917
+ setDiffWin({ sha: c.sha, subject: file, loading: false, text: r.value.text, truncated: r.value.truncated });
2918
+ };
2919
+
2920
+ // cherry-pick:把提交拣选到当前分支。非破坏操作(新增提交),无需二次确认。
2921
+ // 冲突时后端返回 picked:false(不抛错)→ 关窗跳冲突页,「继续」即完成 pick。
2922
+ const doCherryPick = async (sha) => {
2923
+ setPicking(true);
2924
+ try {
2925
+ const r = await unwrap(await remote.cherryPick({ path: repoPath, sha }));
2926
+ if (!r.ok) { setError(r.error.message || r.error.code); return; }
2927
+ if (props.onStatus) props.onStatus(r.value.status);
2928
+ setDiffWin(null);
2929
+ refresh();
2930
+ if (r.value.picked === false) {
2931
+ conflictSource = "cherry";
2932
+ if (props.onSwitchTab) props.onSwitchTab("conflicts");
2933
+ setError("Cherry-pick 遇到冲突:请在「冲突」页解决后点「继续」完成(或「中止操作」回退)。");
2934
+ } else {
2935
+ conflictSource = null;
2936
+ }
2937
+ } finally {
2938
+ setPicking(false);
2939
+ }
2940
+ };
2941
+
2942
+ // revert 提交(非破坏,同 cherry-pick 契约:冲突不抛错、跳冲突页)
2943
+ const doRevert = async (sha) => {
2944
+ setPicking(true);
2945
+ try {
2946
+ const r = await unwrap(await remote.revert({ path: repoPath, sha }));
2947
+ if (!r.ok) { setError(r.error.message || r.error.code); return; }
2948
+ if (props.onStatus) props.onStatus(r.value.status);
2949
+ setDetail(null);
2950
+ refresh();
2951
+ if (r.value.reverted === false) {
2952
+ conflictSource = "revert";
2953
+ if (props.onSwitchTab) props.onSwitchTab("conflicts");
2954
+ setError("Revert 遇到冲突:请在「冲突」页解决后点「继续」完成(或「中止操作」回退)。");
2955
+ } else {
2956
+ conflictSource = null;
2957
+ }
2958
+ } finally {
2959
+ setPicking(false);
2960
+ }
2961
+ };
2962
+
2963
+ // reset 当前分支到指定提交(hard 需输入 RESET 打字确认)
2964
+ const doReset = async () => {
2965
+ const d = resetDlg;
2966
+ setResetDlg(null);
2967
+ setResetText("");
2968
+ if (!d) return;
2969
+ const r = await act("reset", () => remote.reset({ path: repoPath, mode: resetMode, target: d.sha }));
2970
+ if (r === undefined) return;
2971
+ setDetail(null);
2972
+ setDiffWin(null);
2973
+ refresh();
2974
+ };
2975
+
2976
+ // ---- 范围对比 ----
2977
+ const openCompareDiff = async (from, to, kind) => {
2978
+ setCmpDiff({ kind, from, to, loading: true, text: "", truncated: false });
2979
+ const r = await unwrap(await remote.diffRange({ path: repoPath, from, to, kind }));
2980
+ if (!r.ok) { setCmpDiff(null); setError(r.error.message || r.error.code); return; }
2981
+ setCmpDiff({ kind, from, to, loading: false, text: r.value.text, truncated: r.value.truncated });
2982
+ };
2983
+ const pickCompare = async (c) => {
2984
+ if (cmpSel.length === 0) { setCmpSel([{ sha: c.sha, short: c.short, subject: c.subject }]); return; }
2985
+ const base = cmpSel[0];
2986
+ setCmpSel([base, { sha: c.sha, short: c.short, subject: c.subject }]);
2987
+ await openCompareDiff(base.sha, c.sha, "patch");
2988
+ };
2989
+ const exitCompare = () => {
2990
+ setComparing(false);
2991
+ setCmpSel([]);
2992
+ setCmpDiff(null);
2993
+ };
2994
+
2995
+ // P1 §3.6:外部(子模块指针跳转按钮)请求的范围对比——复用现有对比流程,
2996
+ // 直接发起 diffRange 并弹对比窗口。rangeReq 为 null / nonce 未变 → 不触发;
2997
+ // 消费后立刻 requestRange(null) 回执清空(一次性),否则用户手动切回历史 Tab
2998
+ // (组件重新挂载)会重复弹出这次对比。切换作用域仓库时重置记账,允许重放。
2999
+ const rangeNonceRef = React.useRef(0);
3000
+ React.useEffect(() => { rangeNonceRef.current = 0; }, [repoPath]);
3001
+ React.useEffect(() => {
3002
+ const rr = props.rangeReq;
3003
+ if (!rr || !rr.fromSha || !rr.toSha || typeof rr.nonce !== "number") return;
3004
+ if (rangeNonceRef.current === rr.nonce) return;
3005
+ rangeNonceRef.current = rr.nonce;
3006
+ setComparing(true);
3007
+ setCmpSel([
3008
+ { sha: rr.fromSha, short: shortSha(rr.fromSha), subject: "指针 " + shortSha(rr.fromSha) },
3009
+ { sha: rr.toSha, short: shortSha(rr.toSha), subject: "指针 " + shortSha(rr.toSha) },
3010
+ ]);
3011
+ if (props.requestRange) props.requestRange(null);
3012
+ openCompareDiff(rr.fromSha, rr.toSha, "patch");
3013
+ }, [props.rangeReq && props.rangeReq.nonce, repoPath]);
3014
+
3015
+ if (!log && viewMode === "log") return React.createElement("div", { className: "gm-empty" }, "加载历史…");
3016
+
3017
+ const { commits, graph, hasMore } = log || { commits: [], graph: { nodes: [], links: [], laneCount: 1 }, hasMore: false };
3018
+ const ROW_H = 32, PAD = 16;
3019
+ const PALETTE = ["#5b8cff","#2fb37d","#d99a1f","#9b7ff0","#e5484d","#18a0fb","#f76b15","#12a594","#e93d82","#8e4ec6","#6d7c8f","#a18072"];
3020
+ // 分支(车道)多时自动压缩列宽:图形区宽度封顶 ~170px,
3021
+ // 避免车道全部铺开把提交内容挤变形。
3022
+ const lanes = Math.max(1, graph.laneCount || 1);
3023
+ const COL_W = lanes <= 8 ? 14 : Math.max(5, Math.round(150 / lanes));
3024
+ const NODE_R = COL_W >= 10 ? 4 : 3;
3025
+ const width = Math.max(56, lanes * COL_W + PAD);
3026
+ const totalH = commits.length * ROW_H;
3027
+
3028
+ const X = (col) => PAD / 2 + col * COL_W;
3029
+ const Y = (row) => row * ROW_H + ROW_H / 2;
3030
+ // 长边省略阈值(行):跨度超过它的边改为"两端实线 stub + 中段细虚线",
3031
+ // 压住长斜线/长竖线的视觉噪音,但保留走向线索。
3032
+ const SPAN_ELIDE = 24;
3033
+
3034
+ // 悬停聚焦:边与悬停提交直接相连,或同车道竖线从上方跨到下方,算"相关"
3035
+ const hoverCol = hoverRow !== null && graph.nodes[hoverRow] ? graph.nodes[hoverRow].col : null;
3036
+ const isHot = (l) => {
3037
+ if (hoverRow === null) return false;
3038
+ if (l.fromRow === hoverRow || l.toRow === hoverRow) return true;
3039
+ return hoverCol !== null && l.fromCol === hoverCol && l.fromRow < hoverRow && (l.toRow === null || l.toRow > hoverRow);
3040
+ };
3041
+ // 悬停时相关边排到最后画(压在最上层);sort 稳定,其余保持原始顺序
3042
+ const orderedLinks = hoverRow === null ? graph.links
3043
+ : graph.links.slice().sort((a, b) => (isHot(a) ? 1 : 0) - (isHot(b) ? 1 : 0));
3044
+
3045
+ const renderLink = (l, i) => {
3046
+ const x1 = X(l.fromCol), x2 = X(l.toCol);
3047
+ const y1 = Y(l.fromRow);
3048
+ const y2 = (l.toRow === null ? totalH : Y(l.toRow));
3049
+ const color = PALETTE[l.color % PALETTE.length];
3050
+ const span = l.toRow === null ? Infinity : l.toRow - l.fromRow;
3051
+ const elided = span > SPAN_ELIDE;
3052
+ const hot = isHot(l);
3053
+ // 视觉分层:parent 竖线当背景骨架(淡),merge 斜线是信息(细但实)
3054
+ const baseOp = l.kind === "parent" ? 0.45 : l.kind === "collapse" ? 0.55 : 0.7;
3055
+ const opacity = hoverRow === null ? baseOp : (hot ? 0.95 : baseOp * 0.25);
3056
+ const sw = (l.kind === "merge" ? 1.25 : 1.5) + (hot ? 0.5 : 0);
3057
+ const key = "l" + i;
3058
+
3059
+ if (elided) {
3060
+ const stub = ROW_H * 1.2;
3061
+ const midEnd = l.toRow === null ? totalH - 8 : y2 - stub;
3062
+ const parts = [
3063
+ React.createElement("path", { key: key + "-a", d: "M " + x1 + " " + y1 + " L " + x1 + " " + (y1 + stub), stroke: color, strokeWidth: sw, fill: "none", opacity }),
3064
+ React.createElement("path", { key: key + "-m", d: "M " + x1 + " " + (y1 + stub) + " L " + x2 + " " + midEnd, stroke: color, strokeWidth: 1, fill: "none", opacity: opacity * 0.35, strokeDasharray: "2 4" }),
3065
+ ];
3066
+ if (l.toRow === null) {
3067
+ // 父提交在窗口外:底边小倒三角,明示"延伸出去"
3068
+ parts.push(React.createElement("path", { key: key + "-z", d: "M " + (x2 - 3.5) + " " + (totalH - 8) + " L " + (x2 + 3.5) + " " + (totalH - 8) + " L " + x2 + " " + (totalH - 2.5) + " Z", fill: color, stroke: "none", opacity }));
3069
+ } else {
3070
+ parts.push(React.createElement("path", { key: key + "-b", d: "M " + x2 + " " + midEnd + " L " + x2 + " " + y2, stroke: color, strokeWidth: sw, fill: "none", opacity }));
3071
+ }
3072
+ return parts;
3073
+ }
3074
+ if (l.kind === "collapse" || l.fromCol === l.toCol) {
3075
+ // 同列竖线 / collapse 短横
3076
+ return React.createElement("path", { key, d: "M " + x1 + " " + y1 + " L " + x2 + " " + y2, stroke: color, strokeWidth: sw, fill: "none", opacity });
3077
+ }
3078
+ // 跨列用 cubic bezier
3079
+ return React.createElement("path", { key, d: "M " + x1 + " " + y1 + " C " + x1 + " " + (y1 + ROW_H) + ", " + x2 + " " + (y2 - ROW_H) + ", " + x2 + " " + y2, stroke: color, strokeWidth: sw, fill: "none", opacity });
3080
+ };
3081
+
3082
+ const onRowClick = (c) => {
3083
+ if (comparing) { pickCompare(c); return; }
3084
+ openDetail(c);
3085
+ };
3086
+
3087
+ // 过滤条:「提交 | Reflog」模式切换(契约 §3.4b);log 过滤器只在提交模式显示
3088
+ const filterChildren = [
3089
+ React.createElement("button", {
3090
+ key: "mode-log",
3091
+ className: "gm-mini" + (viewMode === "log" ? " gm-mini-on" : ""),
3092
+ onClick: () => setViewMode("log"),
3093
+ }, "提交"),
3094
+ React.createElement("button", {
3095
+ key: "mode-reflog",
3096
+ className: "gm-mini" + (viewMode === "reflog" ? " gm-mini-on" : ""),
3097
+ onClick: () => setViewMode("reflog"),
3098
+ }, "Reflog"),
3099
+ ];
3100
+ if (viewMode === "log") {
3101
+ filterChildren.push(
3102
+ React.createElement("select", {
3103
+ key: "ref",
3104
+ className: "gm-input",
3105
+ style: { maxWidth: 150 },
3106
+ value: refMode,
3107
+ title: "ref 过滤:全部 / 当前分支 / 指定分支或 tag",
3108
+ onChange: (e) => setRefMode(e.target.value),
3109
+ },
3110
+ React.createElement("option", { value: "all" }, "全部(所有分支)"),
3111
+ React.createElement("option", { value: "current" }, "当前分支"),
3112
+ refOptions.map((n) => React.createElement("option", { key: "ref:" + n, value: "ref:" + n }, n)),
3113
+ ),
3114
+ React.createElement("input", { key: "file", className: "gm-input", style: { width: 110 }, placeholder: "路径过滤", value: filters.file, onChange: (e) => setFilters((s) => ({ ...s, file: e.target.value })) }),
3115
+ React.createElement("input", { key: "author", className: "gm-input", style: { width: 90 }, placeholder: "作者", value: filters.author, onChange: (e) => setFilters((s) => ({ ...s, author: e.target.value })) }),
3116
+ React.createElement("input", { key: "grep", className: "gm-input", style: { width: 100 }, placeholder: "grep 信息", value: filters.grep, onChange: (e) => setFilters((s) => ({ ...s, grep: e.target.value })) }),
3117
+ React.createElement("input", { key: "since", className: "gm-input", style: { width: 130 }, type: "date", title: "起始日期", value: filters.since, onChange: (e) => setFilters((s) => ({ ...s, since: e.target.value })) }),
3118
+ React.createElement("input", { key: "until", className: "gm-input", style: { width: 130 }, type: "date", title: "截止日期", value: filters.until, onChange: (e) => setFilters((s) => ({ ...s, until: e.target.value })) }),
3119
+ React.createElement("button", {
3120
+ key: "clear",
3121
+ className: "gm-mini",
3122
+ onClick: () => { setFilters({ file: "", author: "", grep: "", since: "", until: "" }); setRefMode("all"); },
3123
+ }, "清除过滤"),
3124
+ React.createElement("span", { key: "spacer", style: { flex: 1 } }),
3125
+ React.createElement("button", {
3126
+ key: "compare",
3127
+ className: "gm-mini",
3128
+ title: "依次点两个提交(base → head)对比差异",
3129
+ onClick: () => (comparing ? exitCompare() : (setComparing(true), setCmpSel([]))),
3130
+ }, comparing ? "退出对比" : "对比…"),
3131
+ React.createElement("button", {
3132
+ key: "undo-move",
3133
+ className: "gm-mini",
3134
+ title: "git reset --mixed @{1}:撤销上次分支移动(checkout/reset 等),工作区改动保留",
3135
+ onClick: () => setConfirming({ kind: "undoMove" }),
3136
+ }, "撤销上次分支移动"),
3137
+ );
3138
+ }
3139
+ const filterBar = React.createElement("div", { className: "gm-filterbar" }, filterChildren);
3140
+
3141
+ const compareHint = comparing
3142
+ ? React.createElement("div", { className: "gm-notice" },
3143
+ cmpSel.length === 0
3144
+ ? "对比模式:点击选择 base 提交…"
3145
+ : (cmpSel.length === 1
3146
+ ? "对比模式:已选 base " + cmpSel[0].short + ",点击选择 head 提交…"
3147
+ : "对比模式:已选 " + cmpSel[0].short + " → " + cmpSel[1].short + ",差异已在弹窗中展示(点「退出对比」结束)"),
3148
+ )
3149
+ : null;
3150
+
3151
+ const list = React.createElement("div", { style: { position: "relative", border: "1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.12))", borderRadius: 10, background: "var(--dsw-alias-bg-layer-1)", overflow: "hidden" } },
3152
+ React.createElement("svg", {
3153
+ width, height: totalH,
3154
+ style: { position: "absolute", left: 0, top: 0, pointerEvents: "none" },
3155
+ "aria-hidden": true,
3156
+ },
3157
+ orderedLinks.map(renderLink),
3158
+ graph.nodes.map((n, i) => React.createElement("circle", {
3159
+ key: "n" + i,
3160
+ cx: X(n.col),
3161
+ cy: Y(i),
3162
+ r: NODE_R + (hoverRow === i ? 0.75 : 0),
3163
+ fill: PALETTE[n.color % PALETTE.length],
3164
+ opacity: hoverRow === null || hoverRow === i ? 1 : 0.35,
3165
+ })),
3166
+ ),
3167
+ commits.map((c, i) => React.createElement("div", {
3168
+ key: c.sha,
3169
+ className: "gm-file" + ((diffWin && diffWin.sha === c.sha) || (detail && detail.sha === c.sha) || (comparing && cmpSel.some((s) => s.sha === c.sha)) ? " gm-file-active" : ""),
3170
+ style: { paddingLeft: width + 8, height: ROW_H, lineHeight: ROW_H + "px", boxSizing: "border-box" },
3171
+ title: comparing ? "点击选择对比提交(base → head)" : "点击查看提交详情",
3172
+ onClick: () => onRowClick(c),
3173
+ onMouseEnter: () => setHoverRow(i),
3174
+ onMouseLeave: () => setHoverRow(null),
3175
+ },
3176
+ React.createElement("span", { style: { flex: "none", fontFamily: "ui-monospace,monospace", fontSize: 11, color: "var(--dsw-alias-label-tertiary)", marginRight: 8 } }, c.short),
3177
+ c.refs ? React.createElement("span", { style: { flex: "none", maxWidth: 140, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontSize: 10, lineHeight: "16px", boxSizing: "border-box", padding: "0 6px", borderRadius: 999, background: "color-mix(in srgb,var(--dsw-alias-brand-primary) 10%,var(--dsw-alias-bg-layer-2))", border: "1px solid color-mix(in srgb,var(--dsw-alias-brand-primary) 35%,transparent)", color: "var(--dsw-alias-brand-primary)", marginRight: 8 } }, c.refs) : null,
3178
+ React.createElement("span", { style: { flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, c.subject),
3179
+ React.createElement("span", { style: { flex: "none", whiteSpace: "nowrap", fontSize: 11, color: "var(--dsw-alias-label-tertiary)", marginLeft: 8 } }, c.author),
3180
+ React.createElement("span", { style: { flex: "none", whiteSpace: "nowrap", fontSize: 11, color: "var(--dsw-alias-label-tertiary)", marginLeft: 8 } }, fmtTime(c.at)),
3181
+ React.createElement("button", {
3182
+ className: "gm-mini",
3183
+ title: "查看该提交的差异",
3184
+ onClick: (ev) => { ev.stopPropagation(); openCommitDiff(c); },
3185
+ }, "diff"),
3186
+ )),
3187
+ );
3188
+
3189
+ // Reflog 模式列表(契约 §3.4b:复用提交行样式,无分支线,点行开提交详情)
3190
+ const reflogList = React.createElement("div", { style: { border: "1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.12))", borderRadius: 10, background: "var(--dsw-alias-bg-layer-1)", overflow: "hidden" } },
3191
+ reflog === null
3192
+ ? React.createElement("div", { className: "gm-empty" }, "加载 reflog…")
3193
+ : reflog.length === 0
3194
+ ? React.createElement("div", { className: "gm-empty" }, "reflog 为空。")
3195
+ : reflog.map((e, i) => React.createElement("div", {
3196
+ key: e.sha + "@" + i,
3197
+ className: "gm-file" + (detail && detail.sha === e.sha ? " gm-file-active" : ""),
3198
+ title: "点击查看该提交详情",
3199
+ onClick: () => openDetail({ sha: e.sha, subject: e.message, author: "", at: e.at }),
3200
+ },
3201
+ React.createElement("span", { style: { flex: "none", fontFamily: "ui-monospace,monospace", fontSize: 11, color: "var(--dsw-alias-label-tertiary)", marginRight: 8 } }, e.short),
3202
+ React.createElement("span", { className: "gm-meta", style: { flex: "none", fontFamily: "ui-monospace,monospace" } }, e.selector || ""),
3203
+ React.createElement("span", { className: "gm-file-path" }, e.message),
3204
+ React.createElement("span", { className: "gm-meta" }, fmtTime(e.at)),
3205
+ )),
3206
+ );
3207
+
3208
+ // 提交详情侧栏
3209
+ const detailPane = detail ? React.createElement("div", { className: "gm-hist-detail" },
3210
+ React.createElement("div", { className: "gm-section-head", style: { marginBottom: 6 } },
3211
+ React.createElement("span", null, "提交详情"),
3212
+ React.createElement("span", { style: { flex: 1 } }),
3213
+ React.createElement("button", { className: "gm-mini", onClick: () => setDetail(null), title: "关闭详情" }, "×"),
3214
+ ),
3215
+ React.createElement("div", { className: "gm-meta", style: { fontFamily: "ui-monospace,monospace" } }, detail.sha.slice(0, 12)),
3216
+ React.createElement("div", { className: "gm-meta" }, detail.author + " · " + fmtTime(detail.at)),
3217
+ React.createElement("div", { className: "gm-detail-msg" }, detail.loading ? "加载提交内容…" : detail.message),
3218
+ React.createElement("div", { style: { fontWeight: 500, fontSize: 12, marginBottom: 4 } }, "变更文件 (" + detail.files.length + ")"),
3219
+ detail.files.length === 0
3220
+ ? React.createElement("div", { className: "gm-meta" }, detail.loading ? "…" : "(无文件变更或为空提交)")
3221
+ : detail.files.map((f) => React.createElement("div", {
3222
+ key: f.path,
3223
+ className: "gm-detail-file",
3224
+ title: "点击查看该文件差异",
3225
+ onClick: () => openFileDiff(detail, f.path),
3226
+ },
3227
+ React.createElement("span", { className: "gm-file-kind " + (f.status === "added" ? "gm-file-kind-added" : f.status === "deleted" ? "gm-file-kind-deleted" : f.status === "renamed" || f.status === "copied" ? "gm-file-kind-renamed" : "gm-file-kind-modified") }, f.status),
3228
+ React.createElement("span", { className: "gm-file-path" }, f.path),
3229
+ React.createElement("button", {
3230
+ className: "gm-mini",
3231
+ title: "在该提交处逐行追溯(blame)此文件",
3232
+ onClick: (ev) => { ev.stopPropagation(); openBlame(f.path, detail.sha); },
3233
+ }, "Blame"),
3234
+ React.createElement("button", {
3235
+ className: "gm-mini",
3236
+ title: "该文件的提交历史",
3237
+ onClick: (ev) => { ev.stopPropagation(); openFileHist(f.path); },
3238
+ }, "历史"),
3239
+ React.createElement("span", { className: "gm-detail-count" }, "+" + f.add + " -" + f.del),
3240
+ )),
3241
+ React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 8, marginTop: 12 } },
3242
+ React.createElement("button", { className: "gm-btn", disabled: picking || detail.loading, onClick: () => openCommitDiff({ sha: detail.sha, subject: detail.subject }) }, "查看 diff"),
3243
+ React.createElement("button", {
3244
+ className: "gm-btn",
3245
+ disabled: picking,
3246
+ title: "生成一个反向提交(非破坏操作)",
3247
+ onClick: () => doRevert(detail.sha),
3248
+ }, picking ? "Revert…" : "Revert 此提交"),
3249
+ React.createElement("button", {
3250
+ className: "gm-btn",
3251
+ disabled: picking || detail.loading || !!busyLocal || (detail.parents && detail.parents.length === 0),
3252
+ title: (detail.parents && detail.parents.length === 0)
3253
+ ? "根提交没有父提交,无法从这里整理历史"
3254
+ : "rebase todo:整理该提交(含)到 HEAD 的提交顺序与合并方式(改写历史)",
3255
+ onClick: openRebaseDlg,
3256
+ }, busyLocal === detail.sha ? "读取 todo…" : "从这里整理历史…"),
3257
+ React.createElement("button", {
3258
+ className: "gm-btn",
3259
+ disabled: picking || !!busyLocal || (detail.parents && detail.parents.length === 0),
3260
+ title: "用当前暂存的改动为该提交创建 fixup/squash 提交并 rebase 合入(改写历史)",
3261
+ onClick: openFixupDlg,
3262
+ }, "用暂存改动修正此提交…"),
3263
+ React.createElement("button", {
3264
+ className: "gm-btn gm-btn-danger",
3265
+ disabled: picking,
3266
+ onClick: () => { setResetDlg({ sha: detail.sha, subject: detail.subject }); setResetText(""); setResetMode("mixed"); },
3267
+ }, "Reset 当前分支到此提交…"),
3268
+ ),
3269
+ ) : null;
3270
+
3271
+ return React.createElement(React.Fragment, null,
3272
+ filterBar,
3273
+ compareHint,
3274
+ React.createElement("div", { className: "gm-hist-wrap" },
3275
+ React.createElement("div", { className: "gm-hist-main" },
3276
+ viewMode === "reflog" ? reflogList : list,
3277
+ viewMode === "reflog"
3278
+ ? React.createElement("div", { style: { display: "flex", gap: 10, alignItems: "center", marginTop: 10 } },
3279
+ reflog && reflog.length >= reflogLimit
3280
+ ? React.createElement("button", { className: "gm-btn", onClick: () => setReflogLimit((c) => c + 200) }, "加载更多(已加载 " + reflog.length + ")")
3281
+ : React.createElement("span", { className: "gm-meta" }, "共 " + (reflog ? reflog.length : 0) + " 条 reflog"),
3282
+ )
3283
+ : React.createElement("div", { style: { display: "flex", gap: 10, alignItems: "center", marginTop: 10 } },
3284
+ hasMore
3285
+ ? React.createElement("button", { className: "gm-btn", onClick: () => setMaxCount((c) => c + 200) }, "加载更多(已加载 " + commits.length + ")")
3286
+ : React.createElement("span", { className: "gm-meta" }, "共 " + commits.length + " 个提交"),
3287
+ ),
3288
+ ),
3289
+ detailPane,
3290
+ ),
3291
+ // 只读 diff 窗口(含 Cherry-pick)
3292
+ diffWin ? React.createElement(DiffWindow, {
3293
+ title: "Commit " + diffWin.sha.slice(0, 12),
3294
+ sub: diffWin.subject || "",
3295
+ loading: diffWin.loading,
3296
+ text: diffWin.text,
3297
+ truncated: diffWin.truncated,
3298
+ onClose: () => setDiffWin(null),
3299
+ onRefresh: () => openCommitDiff({ sha: diffWin.sha, subject: diffWin.subject }),
3300
+ actions: React.createElement("button", {
3301
+ className: "gm-btn",
3302
+ disabled: picking || diffWin.loading,
3303
+ title: "把该提交拣选(cherry-pick)到当前分支",
3304
+ onClick: () => doCherryPick(diffWin.sha),
3305
+ }, picking ? "Cherry-pick…" : "Cherry-pick 到当前分支"),
3306
+ }) : null,
3307
+ // 范围对比 diff 窗口(stat / patch 切换)
3308
+ cmpDiff ? React.createElement(DiffWindow, {
3309
+ title: "对比 " + cmpDiff.from.slice(0, 8) + "…" + cmpDiff.to.slice(0, 8),
3310
+ sub: (cmpSel[0] ? cmpSel[0].subject : "") + " → " + (cmpSel[1] ? cmpSel[1].subject : ""),
3311
+ loading: cmpDiff.loading,
3312
+ text: cmpDiff.text,
3313
+ truncated: cmpDiff.truncated,
3314
+ plain: cmpDiff.kind === "stat",
3315
+ onClose: exitCompare,
3316
+ onRefresh: () => openCompareDiff(cmpDiff.from, cmpDiff.to, cmpDiff.kind),
3317
+ actions: React.createElement(React.Fragment, null,
3318
+ React.createElement("button", { className: "gm-btn", disabled: cmpDiff.kind === "stat" || cmpDiff.loading, onClick: () => openCompareDiff(cmpDiff.from, cmpDiff.to, "stat") }, "stat"),
3319
+ React.createElement("button", { className: "gm-btn", disabled: cmpDiff.kind === "patch" || cmpDiff.loading, onClick: () => openCompareDiff(cmpDiff.from, cmpDiff.to, "patch") }, "patch"),
3320
+ React.createElement("button", { className: "gm-btn", onClick: exitCompare }, "退出对比"),
3321
+ ),
3322
+ }) : null,
3323
+ // 只读 blame 窗口(契约 §3.4b)
3324
+ blameWin ? React.createElement(BlameWindow, {
3325
+ title: "Blame — " + blameWin.file,
3326
+ sub: blameWin.ref || "HEAD",
3327
+ loading: blameWin.loading,
3328
+ lines: blameWin.lines,
3329
+ truncated: blameWin.truncated,
3330
+ onClose: () => setBlameWin(null),
3331
+ onRefresh: () => openBlame(blameWin.file, blameWin.ref),
3332
+ }) : null,
3333
+ // 文件级历史(契约 §8.4)
3334
+ fileHist ? React.createElement(FileHistoryWindow, {
3335
+ file: fileHist.file,
3336
+ loading: fileHist.loading,
3337
+ entries: fileHist.entries,
3338
+ onClose: () => setFileHist(null),
3339
+ onRefresh: () => openFileHist(fileHist.file),
3340
+ onOpenCommit: (c) => openHistDiff(fileHist.file, c),
3341
+ }) : null,
3342
+ histDiff ? React.createElement(DiffWindow, {
3343
+ title: histDiff.title,
3344
+ sub: histDiff.sub,
3345
+ loading: histDiff.loading,
3346
+ text: histDiff.text,
3347
+ truncated: histDiff.truncated,
3348
+ onClose: () => setHistDiff(null),
3349
+ onRefresh: () => openHistDiff(histDiff.file, histDiff.c),
3350
+ }) : null,
3351
+ // rebase todo 弹窗(契约 §8.6)→ 提交后接危险级二次确认
3352
+ rebaseDlg ? React.createElement(RebaseTodoDialog, {
3353
+ entries: rebaseDlg.entries,
3354
+ onClose: () => setRebaseDlg(null),
3355
+ onSubmit: (items) => {
3356
+ const d = rebaseDlg;
3357
+ setRebaseDlg(null);
3358
+ setConfirming({ kind: "rebaseRun", base: d.base, entries: items });
3359
+ },
3360
+ }) : null,
3361
+ // fixup/squash 弹窗(契约 §8.6)→ 提交后接危险级二次确认
3362
+ fixupDlg ? React.createElement(FormDialog, {
3363
+ open: true,
3364
+ title: "用暂存改动修正 " + fixupDlg.sha.slice(0, 8),
3365
+ message: fixupDlg.subject || "",
3366
+ submitLabel: "下一步",
3367
+ onClose: () => setFixupDlg(null),
3368
+ onSubmit: () => {
3369
+ const d = fixupDlg;
3370
+ const f = fixupForm;
3371
+ setFixupDlg(null);
3372
+ setConfirming({ kind: "fixupRun", sha: d.sha, mode: f.mode, message: f.message });
3373
+ },
3374
+ children: React.createElement(React.Fragment, null,
3375
+ React.createElement("div", { style: { marginBottom: 10 } },
3376
+ React.createElement("label", { className: "gm-radio" },
3377
+ React.createElement("input", { type: "radio", name: "gm-fixup-mode", checked: fixupForm.mode === "fixup", onChange: () => setFixupForm((s) => ({ ...s, mode: "fixup" })) }),
3378
+ "fixup(并入该提交,沿用其提交信息)",
3379
+ ),
3380
+ React.createElement("label", { className: "gm-radio" },
3381
+ React.createElement("input", { type: "radio", name: "gm-fixup-mode", checked: fixupForm.mode === "squash", onChange: () => setFixupForm((s) => ({ ...s, mode: "squash" })) }),
3382
+ "squash(并入该提交,编辑合并信息)",
3383
+ ),
3384
+ ),
3385
+ fixupForm.mode === "squash"
3386
+ ? React.createElement("div", { className: "gm-form-row" },
3387
+ React.createElement("span", { className: "gm-form-label" }, "合并信息(可选,留空沿用 git 默认)"),
3388
+ React.createElement("input", { className: "gm-input", value: fixupForm.message, onChange: (e) => setFixupForm((s) => ({ ...s, message: e.target.value })) }),
3389
+ )
3390
+ : null,
3391
+ ),
3392
+ }) : null,
3393
+ // 危险级二次确认(undo / rebase / fixup)
3394
+ React.createElement(ConfirmDialog, {
3395
+ open: !!confirming && confirming.kind === "undoMove",
3396
+ title: "撤销上次分支移动?",
3397
+ message: "将执行 git reset --mixed @{1}:分支指针回退到上一次移动前的位置,工作区改动保留(暂存区会被清空)。\n\n重做提示:git reset --mixed HEAD@{1}(或 git reflog 查看历史)。",
3398
+ danger: true,
3399
+ confirmLabel: "撤销分支移动",
3400
+ onCancel: () => setConfirming(null),
3401
+ onConfirm: doUndoMove,
3402
+ }),
3403
+ React.createElement(ConfirmDialog, {
3404
+ open: !!confirming && confirming.kind === "rebaseRun",
3405
+ title: "开始 Rebase?",
3406
+ message: "将按整理后的 todo 重放提交,改写当前分支历史(提交 sha 会变化)。\n若已推送远端,之后需要 force push(--force-with-lease)。\n冲突可随时「中止 Rebase」回退(git rebase --abort)。",
3407
+ danger: true,
3408
+ confirmLabel: "开始 Rebase",
3409
+ onCancel: () => setConfirming(null),
3410
+ onConfirm: doRebaseRun,
3411
+ }),
3412
+ React.createElement(ConfirmDialog, {
3413
+ open: !!confirming && confirming.kind === "fixupRun",
3414
+ title: "用暂存改动修正该提交?",
3415
+ message: "将创建 " + (confirming && confirming.kind === "fixupRun" ? confirming.mode : "fixup") + " 提交并 rebase 合入目标提交——当前分支历史会被改写(提交 sha 会变化)。\n若已推送远端,之后需要 force push(--force-with-lease)。",
3416
+ danger: true,
3417
+ confirmLabel: "修正并改写历史",
3418
+ onCancel: () => setConfirming(null),
3419
+ onConfirm: doFixupRun,
3420
+ }),
3421
+ // reset 弹窗(hard 需输入 RESET 打字确认)
3422
+ resetDlg ? React.createElement(FormDialog, {
3423
+ open: true,
3424
+ title: "Reset 当前分支到 " + resetDlg.sha.slice(0, 8) + "?",
3425
+ message: resetDlg.subject || "",
3426
+ submitLabel: "Reset",
3427
+ danger: resetMode === "hard",
3428
+ submitDisabled: resetMode === "hard" && resetText.trim() !== "RESET",
3429
+ onClose: () => { setResetDlg(null); setResetText(""); },
3430
+ onSubmit: doReset,
3431
+ children: React.createElement(React.Fragment, null,
3432
+ React.createElement("div", { style: { marginBottom: 10 } },
3433
+ React.createElement("label", { className: "gm-radio" },
3434
+ React.createElement("input", { type: "radio", name: "gm-reset-mode", checked: resetMode === "soft", onChange: () => setResetMode("soft") }),
3435
+ "soft(保留暂存区与工作区)",
3436
+ ),
3437
+ React.createElement("label", { className: "gm-radio" },
3438
+ React.createElement("input", { type: "radio", name: "gm-reset-mode", checked: resetMode === "mixed", onChange: () => setResetMode("mixed") }),
3439
+ "mixed(保留工作区,清空暂存区)",
3440
+ ),
3441
+ React.createElement("label", { className: "gm-radio" },
3442
+ React.createElement("input", { type: "radio", name: "gm-reset-mode", checked: resetMode === "hard", onChange: () => setResetMode("hard") }),
3443
+ "hard(⚠ 清空暂存区与工作区,不可恢复)",
3444
+ ),
3445
+ ),
3446
+ resetMode === "hard"
3447
+ ? React.createElement("div", { className: "gm-form-row" },
3448
+ React.createElement("span", { className: "gm-form-label", style: { color: "var(--dsw-alias-state-error-primary)" } }, "hard 会丢弃所有未提交改动,无法撤销。请输入 RESET 确认:"),
3449
+ React.createElement("input", { className: "gm-input", placeholder: "RESET", value: resetText, onChange: (e) => setResetText(e.target.value) }),
3450
+ )
3451
+ : null,
3452
+ ),
3453
+ }) : null,
3454
+ );
3455
+ }
3456
+
3457
+ // ============================================================================
3458
+ // ConflictsTab
3459
+ // ============================================================================
3460
+ function ConflictsTab(props) {
3461
+ const remote = props.remote;
3462
+ const repoPath = props.repoPath;
3463
+ const status = props.status;
3464
+ const act = props.act;
3465
+ const setError = props.setError;
3466
+ const [editing, setEditing] = React.useState(null); // { file, content }
3467
+ const [confirming, setConfirming] = React.useState(null);
3468
+
3469
+ React.useEffect(() => {
3470
+ if (editing && status && !status.conflicted.find((c) => c.path === editing.file)) {
3471
+ setEditing(null);
3472
+ }
3473
+ }, [status]);
3474
+
3475
+ const startEdit = async (file) => {
3476
+ const r = await unwrap(await remote.conflictContent({ path: repoPath, file }));
3477
+ if (r.ok) setEditing({ file, content: (r.value.worktree !== undefined ? r.value.worktree : "") });
3478
+ else setError(r.error.message || r.error.code);
3479
+ };
3480
+
3481
+ // 指针冲突条目(契约 §3.6):冲突路径命中仓库树里的子节点(submodule / 嵌套均算)
3482
+ // → 渲染「指针冲突」行,只给 ours/theirs 两个指针按钮(Host 侧 custom 对 gitlink
3483
+ // 会抛错,手动编辑没有意义,不提供入口)。
3484
+ const repos = Array.isArray(props.repos) ? props.repos : [];
3485
+ const nodeByRel = {};
3486
+ repos.forEach((n) => { if (n && n.relPath) nodeByRel[normalizeRel(n.relPath)] = n; });
3487
+ const pointerNodeOf = (path) => nodeByRel[normalizeRel(path)] || null;
3488
+
3489
+ // 解决后除面板 act 的 status 刷新外,再刷一次仓库树——六 Tab 徽标与切换器红点
3490
+ // 是对所有仓库 dirty.conflicted 求和(§3.3),只刷作用域仓库的 status 不够。
3491
+ const refreshTree = typeof props.refreshTree === "function" ? props.refreshTree : null;
3492
+ const afterResolve = async (r) => {
3493
+ if (refreshTree) await refreshTree();
3494
+ return r;
3495
+ };
3496
+ const resolveOurs = (file) => act("resolveOurs", () => remote.resolveConflict({ path: repoPath, file, strategy: "ours" })).then(afterResolve);
3497
+ const resolveTheirs = (file) => act("resolveTheirs", () => remote.resolveConflict({ path: repoPath, file, strategy: "theirs" })).then(afterResolve);
3498
+ const resolveCustom = async (file, content) => act("resolveCustom", () => remote.resolveConflict({ path: repoPath, file, strategy: "custom", content }));
3499
+ const doAbort = async () => {
3500
+ setConfirming(null);
3501
+ conflictSource = null;
3502
+ await act("mergeAbort", () => remote.mergeAbort({ path: repoPath }));
3503
+ };
3504
+ // stash 冲突收尾:解决并暂存后删除对应 stash 条目(契约 §3.5)
3505
+ const doStashDrop = async () => {
3506
+ setConfirming(null);
3507
+ await act("stashDrop", () => remote.stashDrop({ path: repoPath, index: stashConflictIndex }));
3508
+ conflictSource = null;
3509
+ const s = await unwrap(await remote.status({ path: repoPath }));
3510
+ if (s.ok && props.onStatus) props.onStatus(s.value);
3511
+ if (props.onSwitchTab) props.onSwitchTab("changes");
3512
+ };
3513
+
3514
+ if (!status) return React.createElement("div", { className: "gm-empty" }, "加载冲突…");
3515
+ if (status.conflicted.length === 0) {
3516
+ return React.createElement("div", { className: "gm-empty" }, "当前没有冲突。");
3517
+ }
3518
+ // 底部按钮分流(契约 §3.5 + §8.6):来源判断顺序 rebase > merge/cherry/revert > stash。
3519
+ // rebase 态(rebase-merge/rebase-apply)→「继续 Rebase / 中止 Rebase」;
3520
+ // stash 冲突(仅 unmerged,无 MERGE_HEAD 等状态文件)→「删除 stash 条目 / 中止」;
3521
+ // merge / cherry-pick / revert 维持「继续 / 中止」。conflictSource==null 表示冲突
3522
+ // 产生于本会话之外(无法区分),两套按钮都给,避免用户卡死。
3523
+ const rebaseMode = !!status.rebasing;
3524
+ const stashMode = !rebaseMode && conflictSource === "stash";
3525
+ const unknownMode = !rebaseMode && conflictSource == null && !status.merging;
3526
+ return React.createElement(React.Fragment, null,
3527
+ status.conflicted.map((c) => {
3528
+ const ptrNode = pointerNodeOf(c.path);
3529
+ return React.createElement("div", { key: c.path, className: "gm-filegroup" },
3530
+ React.createElement("div", { className: "gm-filegroup-head" },
3531
+ React.createElement("span", null, c.path),
3532
+ React.createElement("span", { className: "gm-file-kind gm-file-kind-renamed" }, c.xy),
3533
+ ptrNode
3534
+ ? React.createElement("span", { className: "gm-sub-badge gm-sub-badge-warn", title: "子仓库指针(gitlink)冲突:解决方式是选用一侧记录的指针,不提供手动编辑" }, "子模块指针")
3535
+ : null,
3536
+ React.createElement("span", { style: { flex: 1 } }),
3537
+ ptrNode
3538
+ ? React.createElement(React.Fragment, null,
3539
+ React.createElement("button", {
3540
+ className: "gm-btn",
3541
+ title: "把该子仓库指针取为当前分支(ours)记录的提交",
3542
+ onClick: () => resolveOurs(c.path),
3543
+ }, "用我们的指针"),
3544
+ React.createElement("button", {
3545
+ className: "gm-btn",
3546
+ title: "把该子仓库指针取为待合并侧(theirs)记录的提交",
3547
+ onClick: () => resolveTheirs(c.path),
3548
+ }, "用他们的指针"),
3549
+ )
3550
+ : React.createElement(React.Fragment, null,
3551
+ React.createElement("button", { className: "gm-btn", onClick: () => resolveOurs(c.path) }, "用我们的"),
3552
+ React.createElement("button", { className: "gm-btn", onClick: () => resolveTheirs(c.path) }, "用他们的"),
3553
+ React.createElement("button", { className: "gm-btn gm-btn-primary", onClick: () => startEdit(c.path) }, "手动编辑"),
3554
+ ),
3555
+ ),
3556
+ );
3557
+ }),
3558
+ rebaseMode
3559
+ ? React.createElement("div", {
3560
+ className: "gm-banner",
3561
+ style: { marginTop: 14, borderRadius: 8, borderBottom: "none" },
3562
+ }, "Rebase 进行中:解决冲突并暂存后点「继续 Rebase」;「中止 Rebase」回到 rebase 前的状态。")
3563
+ : null,
3564
+ (stashMode || unknownMode) && !rebaseMode
3565
+ ? React.createElement("div", {
3566
+ className: "gm-banner",
3567
+ style: { marginTop: 14, borderRadius: 8, borderBottom: "none" },
3568
+ }, "stash 应用冲突:解决并暂存后删除 stash 条目,或中止(丢弃未解决的冲突文件改动,stash 保留)")
3569
+ : null,
3570
+ React.createElement("div", { style: { marginTop: 14, display: "flex", gap: 8 } },
3571
+ rebaseMode
3572
+ ? React.createElement("button", { className: "gm-btn", onClick: async () => { await act("mergeContinue", () => remote.mergeContinue({ path: repoPath })); } }, "继续 Rebase")
3573
+ : (stashMode ? null : React.createElement("button", { className: "gm-btn", onClick: async () => { await act("mergeContinue", () => remote.mergeContinue({ path: repoPath })); } }, "继续(提交解决方案,完成 merge/cherry-pick)")),
3574
+ stashMode || unknownMode ? React.createElement("button", { className: "gm-btn gm-btn-danger", onClick: () => setConfirming({ kind: "stashDrop" }) }, "删除 stash 条目") : null,
3575
+ React.createElement("button", {
3576
+ className: "gm-btn gm-btn-danger",
3577
+ onClick: () => setConfirming({ kind: "abortMerge" }),
3578
+ }, rebaseMode ? "中止 Rebase" : (stashMode || unknownMode ? "中止" : "中止操作")),
3579
+ ),
3580
+ // 手动编辑器(Portal 落 body + modalStack,与其余弹层同规范)
3581
+ editing ? React.createElement(FormDialog, {
3582
+ open: true,
3583
+ width: "min(900px,94vw)",
3584
+ title: "手动解决 — " + editing.file,
3585
+ submitLabel: "保存并标记已解决",
3586
+ onClose: () => setEditing(null),
3587
+ onSubmit: async () => { await resolveCustom(editing.file, editing.content); setEditing(null); },
3588
+ children: React.createElement("textarea", {
3589
+ className: "gm-textarea",
3590
+ style: { minHeight: 320, fontFamily: "ui-monospace,SFMono-Regular,Menlo,monospace" },
3591
+ value: editing.content,
3592
+ onChange: (e) => setEditing({ ...editing, content: e.target.value }),
3593
+ }),
3594
+ }) : null,
3595
+ React.createElement(ConfirmDialog, {
3596
+ open: !!confirming && confirming.kind === "abortMerge",
3597
+ title: "中止当前操作?",
3598
+ message: rebaseMode
3599
+ ? "进行中的 rebase 会被中止(git rebase --abort),回到 rebase 前的状态(reflog 可查)。"
3600
+ : (stashMode || unknownMode
3601
+ ? "将丢弃未解决的冲突文件改动,stash 条目保留(不会丢失)。"
3602
+ : "进行中的 merge / cherry-pick 会被中止,所有冲突解决作废。"),
3603
+ danger: true,
3604
+ confirmLabel: "中止",
3605
+ onCancel: () => setConfirming(null),
3606
+ onConfirm: doAbort,
3607
+ }),
3608
+ React.createElement(ConfirmDialog, {
3609
+ open: !!confirming && confirming.kind === "stashDrop",
3610
+ title: "删除 stash 条目?",
3611
+ message: "确认已解决并暂存冲突后,删除对应 stash 条目(# " + stashConflictIndex + ")?该条目将被永久删除,无法撤销。",
3612
+ danger: true,
3613
+ confirmLabel: "删除 stash 条目",
3614
+ onCancel: () => setConfirming(null),
3615
+ onConfirm: doStashDrop,
3616
+ }),
3617
+ );
3618
+ }
3619
+
3620
+ // ============================================================================
3621
+ // WorktreesTab
3622
+ // ============================================================================
3623
+ function WorktreesTab(props) {
3624
+ const remote = props.remote;
3625
+ const repoPath = props.repoPath;
3626
+ const act = props.act;
3627
+ const wtScopePath = props.wtScopePath || null; // 当前作用域中的 worktree 路径(null = 未进入)
3628
+ const [worktrees, setWorktrees] = React.useState(null);
3629
+ const [addDlg, setAddDlg] = React.useState(false);
3630
+ const [adding, setAdding] = React.useState({ path: "", newBranch: "", startPoint: "" });
3631
+ const [confirming, setConfirming] = React.useState(null);
3632
+ const [notice, setNotice] = React.useState(null);
3633
+
3634
+ const refresh = React.useCallback(async () => {
3635
+ try {
3636
+ const r = await unwrap(await remote.worktrees({ path: repoPath }));
3637
+ if (r.ok) setWorktrees(r.value.worktrees);
3638
+ } catch (_) { /* 查询失败保持原列表;错误统一走 act 的错误条 */ }
3639
+ }, [remote, repoPath]);
3640
+
3641
+ React.useEffect(() => { refresh(); }, [refresh]);
3642
+
3643
+ // 挂载期间 15s 轮询:行内脏计数(Host 每行跑一次 status)随外部操作漂移
3644
+ React.useEffect(() => {
3645
+ const t = setInterval(() => { refresh(); }, 15000);
3646
+ return () => clearInterval(t);
3647
+ }, [refresh]);
3648
+
3649
+ // 切换作用域仓库 → 清空上一个仓库的 worktree 列表(避免短暂串仓库)
3650
+ React.useEffect(() => { setWorktrees(null); setNotice(null); }, [repoPath]);
3651
+
3652
+ // mutation 的 value 就是最新 worktrees 列表(含行内状态),直接采用
3653
+ const applyResult = (v) => { if (v && Array.isArray(v.worktrees)) setWorktrees(v.worktrees); };
3654
+
3655
+ const doAdd = async () => {
3656
+ if (!adding.path) return;
3657
+ const wtPath = adding.path;
3658
+ setNotice(null);
3659
+ const payload = { path: repoPath, worktreePath: wtPath };
3660
+ if (adding.newBranch) payload.newBranch = adding.newBranch;
3661
+ if (adding.startPoint) payload.startPoint = adding.startPoint;
3662
+ const v = await act("worktreeAdd", () => remote.worktreeAdd(payload));
3663
+ if (v === undefined) return;
3664
+ setAddDlg(false);
3665
+ setAdding({ path: "", newBranch: "", startPoint: "" });
3666
+ applyResult(v);
3667
+ // act 失败时返回 undefined;只在添加成功时注册工作区
3668
+ if (props.registerWorkspace) {
3669
+ const msg = await props.registerWorkspace(wtPath);
3670
+ if (msg) setNotice(msg);
3671
+ }
3672
+ };
3673
+ const doRemove = async (wtPath, force) => {
3674
+ setConfirming(null);
3675
+ const v = await act("worktreeRemove", () => remote.worktreeRemove({ path: repoPath, worktreePath: wtPath, force: !!force }));
3676
+ applyResult(v);
3677
+ };
3678
+ const doPrune = async () => {
3679
+ const v = await act("worktreePrune", () => remote.worktreePrune({ path: repoPath }));
3680
+ applyResult(v);
3681
+ };
3682
+
3683
+ if (!worktrees) return React.createElement("div", { className: "gm-empty" }, "加载 Worktree…");
3684
+
3685
+ // 行内状态串(review 方案 B):"2+ 1~ 3?" = 暂存/未暂存/未跟踪计数;全 0 显示「干净」
3686
+ const countsOf = (w) => {
3687
+ if (!w.dirty) return null;
3688
+ const parts = [];
3689
+ if (w.dirty.staged > 0) parts.push(w.dirty.staged + "+");
3690
+ if (w.dirty.unstaged > 0) parts.push(w.dirty.unstaged + "~");
3691
+ if (w.dirty.untracked > 0) parts.push(w.dirty.untracked + "?");
3692
+ if (parts.length === 0) parts.push("干净");
3693
+ const title = "未提交改动:暂存 " + w.dirty.staged + " / 未暂存 " + w.dirty.unstaged
3694
+ + " / 未跟踪 " + w.dirty.untracked
3695
+ + (w.dirty.conflicted > 0 ? " / 冲突 " + w.dirty.conflicted : "");
3696
+ return { text: parts.join(" "), title, conflicted: w.dirty.conflicted || 0 };
3697
+ };
3698
+
3699
+ return React.createElement(React.Fragment, null,
3700
+ notice ? React.createElement("div", { className: "gm-notice" }, notice) : null,
3701
+ React.createElement("div", { className: "gm-filegroup" },
3702
+ React.createElement("div", { className: "gm-filegroup-head" },
3703
+ React.createElement("span", null, "Worktree (" + worktrees.length + ")"),
3704
+ React.createElement("span", { style: { flex: 1 } }),
3705
+ React.createElement("button", { className: "gm-btn", onClick: doPrune }, "Prune"),
3706
+ React.createElement("button", { className: "gm-btn gm-btn-primary", onClick: () => setAddDlg(true) }, "添加"),
3707
+ ),
3708
+ worktrees.map((w) => {
3709
+ // 作用域命中比较对大小写不敏感(Windows 路径 + git 输出正斜杠混排)
3710
+ const scoped = !!(wtScopePath && w.path && (w.path === wtScopePath || w.path.toLowerCase() === wtScopePath.toLowerCase()));
3711
+ const counts = countsOf(w);
3712
+ const ahead = (w.ahead || 0), behind = (w.behind || 0);
3713
+ return React.createElement("div", { key: w.path, className: "gm-file" + (scoped ? " gm-wt-row-active" : "") },
3714
+ React.createElement("span", { className: "gm-file-kind " + (w.current ? "gm-file-kind-added" : (w.bare ? "gm-file-kind-renamed" : "")) }, w.current ? "★" : (w.bare ? "B" : "L")),
3715
+ React.createElement("span", { className: "gm-file-path", title: w.path }, w.path),
3716
+ React.createElement("span", { style: { fontSize: 11, color: "var(--dsw-alias-label-tertiary)" } }, w.bare ? "(bare)" : (w.detached ? ("(detached " + (w.headShort || (w.headSha || "").slice(0, 7)) + ")") : (w.branch || "(?)"))),
3717
+ w.error ? React.createElement("span", { className: "gm-sub-badge gm-sub-badge-error", title: "状态查询失败:" + w.error }, "状态查询失败") : null,
3718
+ counts ? React.createElement("span", { className: "gm-wt-counts" + (counts.conflicted > 0 ? " gm-wt-counts-conflict" : ""), title: counts.title }, counts.text) : null,
3719
+ counts && counts.conflicted > 0 ? React.createElement("span", { className: "gm-repo-dot", title: "该 worktree 有 " + counts.conflicted + " 个冲突文件" }) : null,
3720
+ ahead > 0 || behind > 0 ? React.createElement("span", { className: "gm-wt-ab", title: "与上游分支的差距:↑ 本地领先提交数,↓ 本地落后提交数" }, "↑" + ahead + " ↓" + behind) : null,
3721
+ scoped ? React.createElement("span", { className: "gm-sub-badge gm-sub-badge-ok" }, "作用域中") : null,
3722
+ React.createElement("span", { style: { flex: 1 } }),
3723
+ !w.bare && !w.current && !scoped ? React.createElement("button", {
3724
+ className: "gm-btn",
3725
+ title: "面板作用域切进该 worktree:变更 / 提交 / hunk 操作 / 历史全部作用于它",
3726
+ onClick: () => { if (props.enterWorktree) props.enterWorktree(w); },
3727
+ }, "查看") : null,
3728
+ !w.current && !scoped ? React.createElement("button", { className: "gm-btn gm-btn-danger", onClick: () => setConfirming({ kind: "remove", path: w.path }) }, "删除") : null,
3729
+ );
3730
+ }),
3731
+ ),
3732
+ React.createElement(ConfirmDialog, {
3733
+ open: !!confirming,
3734
+ title: "删除 Worktree?",
3735
+ message: "确认删除 Worktree " + (confirming && confirming.path) + "?如含未提交改动需 force。",
3736
+ danger: true,
3737
+ confirmLabel: "删除",
3738
+ onCancel: () => setConfirming(null),
3739
+ onConfirm: () => doRemove(confirming && confirming.path, false),
3740
+ }),
3741
+ // 添加 Worktree 弹窗(路径 + 新分支 + 起点)
3742
+ addDlg ? React.createElement(FormDialog, {
3743
+ open: true,
3744
+ title: "添加 Worktree",
3745
+ submitLabel: "添加",
3746
+ submitDisabled: !adding.path.trim(),
3747
+ onClose: () => setAddDlg(false),
3748
+ onSubmit: doAdd,
3749
+ children: React.createElement(React.Fragment, null,
3750
+ React.createElement("div", { className: "gm-form-row" },
3751
+ React.createElement("span", { className: "gm-form-label" }, "Worktree 绝对路径"),
3752
+ React.createElement("input", { className: "gm-input", placeholder: "如 D:/worktrees/feat-x", value: adding.path, onChange: (e) => setAdding((s) => ({ ...s, path: e.target.value })) }),
3753
+ ),
3754
+ React.createElement("div", { className: "gm-form-row" },
3755
+ React.createElement("span", { className: "gm-form-label" }, "新分支名(可选)"),
3756
+ React.createElement("input", { className: "gm-input", placeholder: "留空则使用起点的 detached/分支状态", value: adding.newBranch, onChange: (e) => setAdding((s) => ({ ...s, newBranch: e.target.value })) }),
3757
+ ),
3758
+ React.createElement("div", { className: "gm-form-row" },
3759
+ React.createElement("span", { className: "gm-form-label" }, "起点(可选,commit-ish / 分支名)"),
3760
+ React.createElement("input", { className: "gm-input", placeholder: "默认 HEAD", value: adding.startPoint, onChange: (e) => setAdding((s) => ({ ...s, startPoint: e.target.value })) }),
3761
+ ),
3762
+ ),
3763
+ }) : null,
3764
+ );
3765
+ }
3766
+
3767
+ // ============================================================================
3768
+ // SettingsTab(remote 增删改 + config 读写;Host P2 方法未就位时显示占位)
3769
+ // ============================================================================
3770
+ // ============================================================================
3771
+ // SubReposSection(设置 Tab「子仓库」管理区,子仓库支持 P2)
3772
+ // 数据源 = tabProps.repos(repoTree 结果;null = 仓库树不可用,整区占位)。
3773
+ // 行 = 子模块节点(初始化/更新/同步 url/卸载/进入);尾部 = 未注册的嵌套
3774
+ // 独立仓库(有 remote origin url 才可「注册为 submodule」)。
3775
+ // 所有操作走面板 act(busy 防重入 + 错误条原样展示 Host 报错)。
3776
+ // ============================================================================
3777
+ function SubReposSection(props) {
3778
+ const remote = props.remote;
3779
+ const repos = Array.isArray(props.repos) ? props.repos : null;
3780
+ const rootRepoPath = props.rootRepoPath || props.repoPath;
3781
+ const scopedPath = props.repoPath; // 当前作用域仓库(可能≠root)
3782
+ const act = props.act;
3783
+ const busy = !!props.busy;
3784
+ const [notice, setNotice] = React.useState(null);
3785
+ const [addDlg, setAddDlg] = React.useState(null); // { url, subPath, name }
3786
+ const [confirming, setConfirming] = React.useState(null); // { kind:"deinit", node }
3787
+
3788
+ // Host 未上线 submodule 方法时(灰度 / 旧 Host):整区只读提示,不发请求
3789
+ const hasApi = typeof remote.submoduleUpdate === "function" && typeof remote.submoduleAdd === "function";
3790
+ React.useEffect(() => { setNotice(null); setAddDlg(null); setConfirming(null); }, [rootRepoPath]);
3791
+
3792
+ const ordered = repos ? orderRepoNodes(repos) : [];
3793
+ const subNodes = ordered.filter((n) => n && n.kind === "submodule");
3794
+ const nestedNodes = ordered.filter((n) => n && n.kind === "nested");
3795
+
3796
+ // 成功后的收尾:刷新仓库树(徽标 / 初始化态 / 嵌套转子模块后的分组)+
3797
+ // 纠正作用域仓库 status(面板 act 会把「被操作仓库」的 status 写进面板级
3798
+ // status——当操作仓库 ≠ 作用域仓库时那是别的仓库的 status,需重取,
3799
+ // 同 ChangesTab 的 actRepo 约定)。
3800
+ const afterMutate = async () => {
3801
+ if (typeof props.refreshTree === "function") await props.refreshTree();
3802
+ if (scopedPath && scopedPath !== rootRepoPath && props.onStatus) {
3803
+ try {
3804
+ const s = await unwrap(await remote.status({ path: scopedPath }));
3805
+ if (s.ok && s.value) props.onStatus(s.value);
3806
+ } catch (_) { /* 忽略:面板 15s 轮询自愈 */ }
3807
+ }
3808
+ };
3809
+ // act 返回 undefined = 失败(错误已进面板错误条,原样展示,不覆盖)
3810
+ const run = async (label, fn, okText) => {
3811
+ const r = await act(label, fn);
3812
+ if (r === undefined) return false;
3813
+ setNotice(okText);
3814
+ await afterMutate();
3815
+ return true;
3816
+ };
3817
+
3818
+ const doInit = (node) => run("submoduleUpdate",
3819
+ () => remote.submoduleUpdate({ path: rootRepoPath, subPath: node.relPath, init: true, recursive: true }),
3820
+ "已初始化 " + (node.name || node.relPath));
3821
+ const doUpdate = (node) => run("submoduleUpdate",
3822
+ () => remote.submoduleUpdate({ path: rootRepoPath, subPath: node.relPath }),
3823
+ "已更新 " + (node.name || node.relPath));
3824
+ const doSync = (node) => run("submoduleSync",
3825
+ () => remote.submoduleSync({ path: rootRepoPath, subPath: node.relPath }),
3826
+ "已用 .gitmodules 的 url 同步 " + (node.name || node.relPath));
3827
+ const doDeinit = (node) => run("submoduleDeinit",
3828
+ // force:true 与确认弹窗文案对齐(「会清空工作区内容」= deinit -f 语义);
3829
+ // 不带 -f 时 git 对有本地改动/未跟踪文件的子模块会直接拒绝,弹窗警告就落空了。
3830
+ () => remote.submoduleDeinit({ path: rootRepoPath, subPath: node.relPath, force: true }),
3831
+ "已卸载 " + (node.name || node.relPath) + "(.gitmodules 注册保留,可用初始化恢复)");
3832
+ const doRegister = (node) => run("submoduleAdd",
3833
+ () => remote.submoduleAdd({ path: rootRepoPath, url: node.originUrl, subPath: node.relPath }),
3834
+ "已注册子模块 " + (node.name || node.relPath) + "(就地注册,目录内容未变)");
3835
+
3836
+ const doAdd = async () => {
3837
+ const d = addDlg;
3838
+ if (!d) return;
3839
+ const req = { path: rootRepoPath, url: d.url.trim(), subPath: normalizeRel(d.subPath.trim()) };
3840
+ if (d.name.trim()) req.name = d.name.trim();
3841
+ const r = await act("submoduleAdd", () => remote.submoduleAdd(req));
3842
+ if (r === undefined) return; // 失败:表单保留,用户可改 url / 相对路径重试
3843
+ setAddDlg(null);
3844
+ setNotice("已添加子模块 " + (req.name || req.subPath));
3845
+ await afterMutate();
3846
+ };
3847
+
3848
+ const enterRepo = (node) => {
3849
+ if (typeof props.setActiveRepoId === "function") props.setActiveRepoId(node.id);
3850
+ };
3851
+
3852
+ // 行:name + relPath + 状态徽标 + 分支/HEAD + url(次要色)+ 按钮组
3853
+ const renderSubRow = (node) => {
3854
+ const badge = repoNodeBadge(node);
3855
+ const name = node.name || node.relPath;
3856
+ const rev = node.branch
3857
+ ? ("分支 " + node.branch)
3858
+ : (node.detached ? ("detached " + shortSha(node.headShort)) : (node.unborn ? "(尚无提交)" : shortSha(node.headShort)));
3859
+ const url = (node.submodule && node.submodule.url) ? node.submodule.url : "";
3860
+ const meta = rev + (url ? " · " + url : "");
3861
+ return React.createElement("div", { key: node.id, className: "gm-sub-row" },
3862
+ repoKindIcon(node.kind),
3863
+ React.createElement("span", { className: "gm-sub-row-name", title: name }, name),
3864
+ React.createElement("span", { className: "gm-sub-row-rel", title: "相对主仓库路径:" + node.relPath }, node.relPath),
3865
+ badge ? React.createElement("span", { className: "gm-sub-badge " + badge.c }, badge.t) : null,
3866
+ React.createElement("span", { className: "gm-sub-row-meta", title: meta }, meta),
3867
+ React.createElement("span", { className: "gm-sub-row-actions" },
3868
+ node.initialized === false
3869
+ ? React.createElement("button", {
3870
+ className: "gm-mini",
3871
+ disabled: busy || !hasApi,
3872
+ title: "初始化并拉取(git submodule update --init --recursive " + node.relPath + ";首次克隆需联网,可能较慢)",
3873
+ onClick: () => doInit(node),
3874
+ }, "初始化并拉取")
3875
+ : React.createElement(React.Fragment, null,
3876
+ React.createElement("button", {
3877
+ className: "gm-mini",
3878
+ disabled: busy || !hasApi,
3879
+ title: "拉取主仓库记录的指针(git submodule update " + node.relPath + ";首次克隆需联网,可能较慢)",
3880
+ onClick: () => doUpdate(node),
3881
+ }, "更新"),
3882
+ React.createElement("button", {
3883
+ className: "gm-mini",
3884
+ disabled: busy || !hasApi,
3885
+ title: "把 .gitmodules 里登记的 url 同步到 .git/config(git submodule sync " + node.relPath + ")",
3886
+ onClick: () => doSync(node),
3887
+ }, "同步 url"),
3888
+ React.createElement("button", {
3889
+ className: "gm-mini gm-mini-danger",
3890
+ disabled: busy || !hasApi,
3891
+ title: "卸载该子模块(git submodule deinit " + node.relPath + ",会清空其工作区内容)",
3892
+ onClick: () => setConfirming({ kind: "deinit", node }),
3893
+ }, "卸载"),
3894
+ ),
3895
+ React.createElement("button", {
3896
+ className: "gm-mini",
3897
+ disabled: busy || node.initialized === false,
3898
+ title: "把面板作用域切到该子仓库(分支 / 历史 / 冲突 / Worktree / 设置 一并跟随)",
3899
+ onClick: () => enterRepo(node),
3900
+ }, "进入"),
3901
+ ),
3902
+ );
3903
+ };
3904
+
3905
+ // 未注册的嵌套独立仓库:有 remote origin url 才能就地注册为 submodule
3906
+ const renderNestedRow = (node) => {
3907
+ const name = node.name || node.relPath;
3908
+ const rev = node.branch
3909
+ ? ("分支 " + node.branch)
3910
+ : (node.detached ? ("detached " + shortSha(node.headShort)) : shortSha(node.headShort));
3911
+ return React.createElement("div", { key: node.id, className: "gm-sub-row" },
3912
+ repoKindIcon(node.kind),
3913
+ React.createElement("span", { className: "gm-sub-row-name", title: name }, name),
3914
+ React.createElement("span", { className: "gm-sub-row-rel", title: "相对主仓库路径:" + node.relPath }, node.relPath),
3915
+ React.createElement("span", { className: "gm-sub-badge gm-sub-badge-mute" }, "未注册"),
3916
+ React.createElement("span", { className: "gm-sub-row-meta", title: node.originUrl ? ("origin: " + node.originUrl) : "无 remote" },
3917
+ node.originUrl ? (rev + " · " + node.originUrl) : (rev + " · (无 remote.origin.url)")),
3918
+ React.createElement("span", { className: "gm-sub-row-actions" },
3919
+ React.createElement("button", {
3920
+ className: "gm-mini",
3921
+ disabled: busy || !hasApi || !node.originUrl,
3922
+ title: node.originUrl
3923
+ ? "就地注册为 submodule(git submodule add " + node.originUrl + " " + node.relPath + ";目录内容不动,仅写入 .gitmodules 与 gitlink)"
3924
+ : "该仓库没有配置 remote.origin.url,无法注册为 submodule",
3925
+ onClick: () => doRegister(node),
3926
+ }, "注册为 submodule"),
3927
+ React.createElement("button", {
3928
+ className: "gm-mini",
3929
+ disabled: busy,
3930
+ title: "把面板作用域切到该仓库(分支 / 历史 / 冲突 / Worktree / 设置 一并跟随)",
3931
+ onClick: () => enterRepo(node),
3932
+ }, "进入"),
3933
+ ),
3934
+ );
3935
+ };
3936
+
3937
+ const sectionHead = React.createElement("div", { className: "gm-section-head" },
3938
+ React.createElement("span", null, "子仓库" + (repos ? "(子模块 " + subNodes.length + " / 嵌套 " + nestedNodes.length + ")" : "")),
3939
+ React.createElement("span", { style: { flex: 1 } }),
3940
+ React.createElement("button", {
3941
+ className: "gm-mini",
3942
+ disabled: busy || !hasApi || !rootRepoPath,
3943
+ title: hasApi
3944
+ ? "把一个新仓库注册为子模块(会克隆到给定相对路径并在主仓库写入 gitlink 与 .gitmodules)"
3945
+ : "当前 Host 版本尚未提供 submodule 管理方法",
3946
+ onClick: () => setAddDlg({ url: "", subPath: "", name: "" }),
3947
+ }, "添加子模块"),
3948
+ );
3949
+
3950
+ let body;
3951
+ if (!repos) {
3952
+ body = React.createElement("div", { className: "gm-meta", style: { padding: "6px 2px" } },
3953
+ "子仓库信息不可用:当前 Host 未提供仓库树(repoTree)或查询失败。");
3954
+ } else if (subNodes.length === 0 && nestedNodes.length === 0) {
3955
+ body = React.createElement("div", { className: "gm-meta", style: { padding: "6px 2px" } },
3956
+ "当前仓库没有子模块,也没有嵌套独立仓库。");
3957
+ } else {
3958
+ body = React.createElement(React.Fragment, null,
3959
+ subNodes.map(renderSubRow),
3960
+ nestedNodes.length > 0
3961
+ ? React.createElement("div", { className: "gm-sub-group-hint" }, "未注册的嵌套仓库(普通目录里的独立 git 仓库)")
3962
+ : null,
3963
+ nestedNodes.map(renderNestedRow),
3964
+ );
3965
+ }
3966
+
3967
+ return React.createElement("div", { className: "gm-section", style: { marginTop: 0 } },
3968
+ sectionHead,
3969
+ notice ? React.createElement("div", { className: "gm-notice", style: { marginTop: 8, marginBottom: 4 } }, notice) : null,
3970
+ body,
3971
+ // 「添加子模块」表单弹窗(与 remote / worktree / tag 新建同款 FormDialog 体系)
3972
+ addDlg ? React.createElement(FormDialog, {
3973
+ open: true,
3974
+ title: "添加子模块",
3975
+ message: "会在主仓库下克隆该仓库到指定相对路径,并写入 .gitmodules 与 gitlink(git submodule add)。",
3976
+ submitLabel: "添加",
3977
+ submitDisabled: !addDlg.url.trim() || !addDlg.subPath.trim() || !!busy,
3978
+ onClose: () => setAddDlg(null),
3979
+ onSubmit: doAdd,
3980
+ children: React.createElement(React.Fragment, null,
3981
+ React.createElement("div", { className: "gm-form-row" },
3982
+ React.createElement("span", { className: "gm-form-label" }, "仓库地址"),
3983
+ React.createElement("input", {
3984
+ className: "gm-input",
3985
+ placeholder: "https://… 或 git@… 或本地绝对路径",
3986
+ value: addDlg.url,
3987
+ onChange: (e) => setAddDlg((s) => ({ ...s, url: e.target.value })),
3988
+ }),
3989
+ ),
3990
+ React.createElement("div", { className: "gm-form-row" },
3991
+ React.createElement("span", { className: "gm-form-label" }, "相对路径(相对主仓库根,如 libs/extra)"),
3992
+ React.createElement("input", {
3993
+ className: "gm-input",
3994
+ placeholder: "libs/extra",
3995
+ value: addDlg.subPath,
3996
+ onChange: (e) => setAddDlg((s) => ({ ...s, subPath: e.target.value })),
3997
+ }),
3998
+ ),
3999
+ React.createElement("div", { className: "gm-form-row" },
4000
+ React.createElement("span", { className: "gm-form-label" }, "名称(可选,缺省用路径末段)"),
4001
+ React.createElement("input", {
4002
+ className: "gm-input",
4003
+ placeholder: "extra",
4004
+ value: addDlg.name,
4005
+ onChange: (e) => setAddDlg((s) => ({ ...s, name: e.target.value })),
4006
+ }),
4007
+ ),
4008
+ ),
4009
+ }) : null,
4010
+ // 卸载是危险操作:清空子仓库工作区内容(.gitmodules 注册保留,可再初始化回来)
4011
+ React.createElement(ConfirmDialog, {
4012
+ open: !!confirming && confirming.kind === "deinit",
4013
+ title: "卸载子模块?",
4014
+ message: "卸载会清空该子仓库工作区内容(.gitmodules 注册保留),可用初始化恢复。\n目标:"
4015
+ + (confirming && confirming.node ? ((confirming.node.name || confirming.node.relPath) + "(" + confirming.node.relPath + ")") : ""),
4016
+ danger: true,
4017
+ confirmLabel: "卸载",
4018
+ onCancel: () => setConfirming(null),
4019
+ onConfirm: async () => {
4020
+ const node = confirming && confirming.node;
4021
+ setConfirming(null);
4022
+ if (!node) return;
4023
+ await doDeinit(node);
4024
+ },
4025
+ }),
4026
+ );
4027
+ }
4028
+
4029
+ function SettingsTab(props) {
4030
+ const remote = props.remote;
4031
+ const repoPath = props.repoPath;
4032
+ const act = props.act;
4033
+ const [ready, setReady] = React.useState(null); // null=探测中 / true / false(即将推出)
4034
+ const [remotes, setRemotes] = React.useState([]);
4035
+ const [entries, setEntries] = React.useState([]);
4036
+ const [globalScope, setGlobalScope] = React.useState(false);
4037
+ const [confirming, setConfirming] = React.useState(null);
4038
+ const [remoteDlg, setRemoteDlg] = React.useState(null); // { mode: "add" | "rename", name, url, pushUrl, oldName }
4039
+ const [cfgNew, setCfgNew] = React.useState({ key: "", value: "" });
4040
+ const [cfgEdit, setCfgEdit] = React.useState({}); // key → { key, value }(行内编辑暂存)
4041
+
4042
+ // 切换作用域仓库 → 清空上一个仓库的 config / remote 与行内编辑暂存(避免短暂串仓库)
4043
+ React.useEffect(() => { setReady(null); setEntries([]); setRemotes([]); setCfgEdit({}); }, [repoPath]);
4044
+
4045
+ // P2 就位探测:Host 未实现 configList/remoteAdd 时 RPC 会报错 → 显示「即将推出」,
4046
+ // 绝不在未就位时反复调用未定义方法。
4047
+ React.useEffect(() => {
4048
+ let alive = true;
4049
+ (async () => {
4050
+ if (typeof remote.configList !== "function" || typeof remote.remoteAdd !== "function") {
4051
+ setReady(false);
4052
+ return;
4053
+ }
4054
+ try {
4055
+ const u = await unwrap(await remote.configList({ path: repoPath, global: globalScope }));
4056
+ if (!alive) return;
4057
+ if (u.ok) {
4058
+ setReady(true);
4059
+ setEntries((u.value && u.value.entries) || []);
4060
+ const r = await unwrap(await remote.remotes({ path: repoPath }));
4061
+ if (alive && r.ok) setRemotes(r.value || []);
4062
+ } else {
4063
+ setReady(false);
4064
+ }
4065
+ } catch (_) {
4066
+ if (alive) setReady(false);
4067
+ }
4068
+ })();
4069
+ return () => { alive = false; };
4070
+ }, [repoPath]);
4071
+
4072
+ const loadConfig = async () => {
4073
+ const u = await unwrap(await remote.configList({ path: repoPath, global: globalScope }));
4074
+ if (u.ok) setEntries((u.value && u.value.entries) || []);
4075
+ };
4076
+ React.useEffect(() => { if (ready) loadConfig(); }, [globalScope, ready]);
4077
+
4078
+ const doRemoteSubmit = async () => {
4079
+ const d = remoteDlg;
4080
+ if (!d) return;
4081
+ if (d.mode === "add") {
4082
+ if (!d.name.trim() || !d.url.trim()) return;
4083
+ const req = { path: repoPath, name: d.name.trim(), url: d.url.trim() };
4084
+ if (d.pushUrl.trim()) req.pushUrl = d.pushUrl.trim();
4085
+ const r = await act("remoteAdd", () => remote.remoteAdd(req));
4086
+ if (r && r.remotes) setRemotes(r.remotes);
4087
+ } else {
4088
+ if (!d.oldName || !d.name.trim() || d.name.trim() === d.oldName) return;
4089
+ const r = await act("remoteRename", () => remote.remoteRename({ path: repoPath, oldName: d.oldName, newName: d.name.trim() }));
4090
+ if (r && r.remotes) setRemotes(r.remotes);
4091
+ }
4092
+ setRemoteDlg(null);
4093
+ };
4094
+
4095
+ const doCfgSave = async (key) => {
4096
+ const edit = cfgEdit[key];
4097
+ if (!edit || !edit.key.trim() || !edit.value.trim()) return;
4098
+ const req = { path: repoPath, key: edit.key.trim(), value: edit.value };
4099
+ if (globalScope) req.global = true;
4100
+ const r = await act("configSet", () => remote.configSet(req));
4101
+ if (r && r.entries) setEntries(r.entries); else await loadConfig();
4102
+ setCfgEdit((s) => { const n = { ...s }; delete n[key]; return n; });
4103
+ };
4104
+ const doCfgUnset = async (key) => {
4105
+ setConfirming(null);
4106
+ const req = { path: repoPath, key };
4107
+ if (globalScope) req.global = true;
4108
+ const r = await act("configUnset", () => remote.configUnset(req));
4109
+ if (r && r.entries) setEntries(r.entries); else await loadConfig();
4110
+ };
4111
+ const doCfgAdd = async () => {
4112
+ if (!cfgNew.key.trim() || !cfgNew.value.trim()) return;
4113
+ const req = { path: repoPath, key: cfgNew.key.trim(), value: cfgNew.value };
4114
+ if (globalScope) req.global = true;
4115
+ const r = await act("configSet", () => remote.configSet(req));
4116
+ if (r && r.entries) setEntries(r.entries); else await loadConfig();
4117
+ setCfgNew({ key: "", value: "" });
4118
+ };
4119
+
4120
+ // 「子仓库」管理区(子仓库支持 P2):置于设置页内容区顶部(Remote 区之前),
4121
+ // 不依赖 configList / remoteAdd 是否就绪——故在 ready 分支之前就构造好。
4122
+ const subReposSection = React.createElement(SubReposSection, {
4123
+ remote,
4124
+ repos: props.repos,
4125
+ repoPath,
4126
+ rootRepoPath: props.rootRepoPath || repoPath,
4127
+ act,
4128
+ busy: props.busy,
4129
+ onStatus: props.onStatus,
4130
+ refreshTree: props.refreshTree,
4131
+ setActiveRepoId: props.setActiveRepoId,
4132
+ });
4133
+
4134
+ if (ready === null) return React.createElement(React.Fragment, null,
4135
+ subReposSection,
4136
+ React.createElement("div", { className: "gm-empty" }, "加载设置…"),
4137
+ );
4138
+
4139
+ if (ready === false) {
4140
+ return React.createElement(React.Fragment, null,
4141
+ subReposSection,
4142
+ React.createElement("div", { className: "gm-empty" },
4143
+ React.createElement("div", { style: { fontWeight: 500, marginBottom: 8 } }, "设置(remote / config 管理)"),
4144
+ "即将推出:当前 Host 版本尚未提供 remoteAdd / remoteRemove / remoteRename / configList / configSet / configUnset 方法。",
4145
+ ),
4146
+ );
4147
+ }
4148
+
4149
+ return React.createElement(React.Fragment, null,
4150
+ subReposSection,
4151
+ // Remote 区
4152
+ React.createElement("div", { className: "gm-section", style: { marginTop: 0 } },
4153
+ React.createElement("div", { className: "gm-section-head" },
4154
+ React.createElement("span", null, "Remote (" + remotes.length + ")"),
4155
+ React.createElement("span", { style: { flex: 1 } }),
4156
+ React.createElement("button", { className: "gm-mini", onClick: () => setRemoteDlg({ mode: "add", name: "", url: "", pushUrl: "" }) }, "添加 remote…"),
4157
+ ),
4158
+ remotes.length === 0
4159
+ ? React.createElement("div", { className: "gm-meta", style: { padding: "6px 2px" } }, "暂无 remote。")
4160
+ : remotes.map((r) => React.createElement("div", { key: r.name, className: "gm-file", style: { cursor: "default" } },
4161
+ React.createElement("span", { className: "gm-file-kind" }, "R"),
4162
+ React.createElement("span", { className: "gm-file-path" }, r.name),
4163
+ React.createElement("span", { className: "gm-meta", style: { maxWidth: 200, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, r.fetchUrl || ""),
4164
+ React.createElement("span", { className: "gm-meta", style: { maxWidth: 160, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, r.pushUrl && r.pushUrl !== r.fetchUrl ? "push: " + r.pushUrl : ""),
4165
+ React.createElement("button", { className: "gm-mini", onClick: () => setRemoteDlg({ mode: "rename", oldName: r.name, name: r.name, url: "", pushUrl: "" }) }, "重命名"),
4166
+ React.createElement("button", { className: "gm-mini gm-mini-danger", onClick: () => setConfirming({ kind: "remoteRemove", name: r.name }) }, "删除"),
4167
+ )),
4168
+ ),
4169
+ // Config 区
4170
+ React.createElement("div", { className: "gm-section" },
4171
+ React.createElement("div", { className: "gm-section-head" },
4172
+ React.createElement("span", null, "Config (" + entries.length + ")"),
4173
+ React.createElement("span", { style: { flex: 1 } }),
4174
+ React.createElement("label", { className: "gm-checkbox" },
4175
+ React.createElement("input", { type: "checkbox", checked: globalScope, onChange: (e) => setGlobalScope(e.target.checked) }),
4176
+ "global(取消勾选为 local)",
4177
+ ),
4178
+ ),
4179
+ entries.map((e) => {
4180
+ const edit = cfgEdit[e.key] || { key: e.key, value: e.value };
4181
+ return React.createElement("div", { key: e.key, className: "gm-cfg-row" },
4182
+ React.createElement("input", {
4183
+ className: "gm-input",
4184
+ style: { maxWidth: 220 },
4185
+ value: edit.key,
4186
+ onChange: (ev) => setCfgEdit((s) => ({ ...s, [e.key]: { ...edit, key: ev.target.value } })),
4187
+ }),
4188
+ React.createElement("input", {
4189
+ className: "gm-input",
4190
+ value: edit.value,
4191
+ onChange: (ev) => setCfgEdit((s) => ({ ...s, [e.key]: { ...edit, value: ev.target.value } })),
4192
+ }),
4193
+ React.createElement("button", { className: "gm-mini", onClick: () => doCfgSave(e.key) }, "保存"),
4194
+ React.createElement("button", { className: "gm-mini gm-mini-danger", onClick: () => setConfirming({ kind: "configUnset", key: e.key }) }, "删除"),
4195
+ );
4196
+ }),
4197
+ React.createElement("div", { className: "gm-cfg-row", style: { marginTop: 8 } },
4198
+ React.createElement("input", { className: "gm-input", style: { maxWidth: 220 }, placeholder: "key(如 user.name)", value: cfgNew.key, onChange: (e) => setCfgNew((s) => ({ ...s, key: e.target.value })) }),
4199
+ React.createElement("input", { className: "gm-input", placeholder: "value", value: cfgNew.value, onChange: (e) => setCfgNew((s) => ({ ...s, value: e.target.value })) }),
4200
+ React.createElement("button", { className: "gm-mini", disabled: !cfgNew.key.trim() || !cfgNew.value.trim(), onClick: doCfgAdd }, "添加"),
4201
+ ),
4202
+ ),
4203
+ React.createElement(ConfirmDialog, {
4204
+ open: !!confirming && confirming.kind === "remoteRemove",
4205
+ title: "删除 remote?",
4206
+ message: "确认删除 remote \"" + (confirming && confirming.name) + "\"?",
4207
+ danger: true,
4208
+ confirmLabel: "删除",
4209
+ onCancel: () => setConfirming(null),
4210
+ onConfirm: async () => {
4211
+ const name = confirming && confirming.name;
4212
+ setConfirming(null);
4213
+ const r = await act("remoteRemove", () => remote.remoteRemove({ path: repoPath, name }));
4214
+ if (r && r.remotes) setRemotes(r.remotes);
4215
+ },
4216
+ }),
4217
+ React.createElement(ConfirmDialog, {
4218
+ open: !!confirming && confirming.kind === "configUnset",
4219
+ title: "删除配置项?",
4220
+ message: "确认从 " + (globalScope ? "global" : "local") + " config 删除 \"" + (confirming && confirming.key) + "\"?",
4221
+ danger: true,
4222
+ confirmLabel: "删除",
4223
+ onCancel: () => setConfirming(null),
4224
+ onConfirm: () => doCfgUnset(confirming && confirming.key),
4225
+ }),
4226
+ remoteDlg ? React.createElement(FormDialog, {
4227
+ open: true,
4228
+ title: remoteDlg.mode === "add" ? "添加 remote" : "重命名 remote",
4229
+ submitLabel: remoteDlg.mode === "add" ? "添加" : "重命名",
4230
+ submitDisabled: remoteDlg.mode === "add"
4231
+ ? (!remoteDlg.name.trim() || !remoteDlg.url.trim())
4232
+ : (!remoteDlg.name.trim() || remoteDlg.name.trim() === remoteDlg.oldName),
4233
+ onClose: () => setRemoteDlg(null),
4234
+ onSubmit: doRemoteSubmit,
4235
+ children: React.createElement(React.Fragment, null,
4236
+ React.createElement("div", { className: "gm-form-row" },
4237
+ React.createElement("span", { className: "gm-form-label" }, "名称"),
4238
+ React.createElement("input", { className: "gm-input", placeholder: "如 origin", value: remoteDlg.name, onChange: (e) => setRemoteDlg((s) => ({ ...s, name: e.target.value })) }),
4239
+ ),
4240
+ remoteDlg.mode === "add" ? React.createElement(React.Fragment, null,
4241
+ React.createElement("div", { className: "gm-form-row" },
4242
+ React.createElement("span", { className: "gm-form-label" }, "fetch URL"),
4243
+ React.createElement("input", { className: "gm-input", placeholder: "https://… 或 git@…", value: remoteDlg.url, onChange: (e) => setRemoteDlg((s) => ({ ...s, url: e.target.value })) }),
4244
+ ),
4245
+ React.createElement("div", { className: "gm-form-row" },
4246
+ React.createElement("span", { className: "gm-form-label" }, "push URL(可选,缺省与 fetch 相同)"),
4247
+ React.createElement("input", { className: "gm-input", value: remoteDlg.pushUrl, onChange: (e) => setRemoteDlg((s) => ({ ...s, pushUrl: e.target.value })) }),
4248
+ ),
4249
+ ) : null,
4250
+ ),
4251
+ }) : null,
4252
+ );
4253
+ }
4254
+
4255
+ // ---- apply ----
4256
+ async function apply(ctx) {
4257
+ await ctx.remote.$mount(CLIENT_REMOTE);
4258
+
4259
+ // 诊断冒烟:若浏览器控制台出现这行,说明 client bundle 已加载并进入 apply。
4260
+ // 找不到入口时先看这行在不在,区分"bundle 没加载" vs "槽位/组件 bug"。
4261
+ try { console.log("[dsh-volcano-git-plugin] client apply() ran, mounting UI"); } catch (_) { /* noop */ }
4262
+
4263
+ // 样式注入(动态 HMR 不可用,正式插件的样式走手动 style 标签)
4264
+ const styleTag = document.createElement("style");
4265
+ styleTag.textContent = CSS;
4266
+ document.head.appendChild(styleTag);
4267
+ ctx.effect(() => () => styleTag.remove());
4268
+
4269
+ // ctx.get 不受 inject 属性守卫限制(与 archive-manager 同款)
4270
+ const remote = ctx.get("remote.gitManager");
4271
+ // 客户端 workspaces 服务(核心服务,恒在;create({path}) host 侧按 canonical 路径去重)
4272
+ const workspaces = ctx.get("workspaces");
4273
+
4274
+ // ① Composer 工具行入口(conversation.input.left,模式/access-mode 选择器旁)
4275
+ // 该槽有完整标准 kit(含 useSessions),只需注入 remote。
4276
+ // hero 空白会话的 composer 同样渲染这一行,一个槽位同时覆盖 hero 与会话内。
4277
+ function ComposerGitButtonSlot(props) {
4278
+ return React.createElement(ComposerGitButton, Object.assign({}, props, { remote }));
4279
+ }
4280
+ ctx.slots.inject("conversation.input.left", () => ctx.slots.register(
4281
+ { name: "conversation.input.left", id: "dsh-volcano-git-plugin", order: 100, label: () => "Git" },
4282
+ ComposerGitButtonSlot,
4283
+ ));
4284
+
4285
+ // ② shell.overlay 注册:仅承担全屏面板(唯一入口在 composer 工具行)。
4286
+ // DOM 用 ReactDOM.createPortal 落到 body(z-index 1000),绕开
4287
+ // shell.overlay 槽位宿主 stacking context 的 z-index 锁死。
4288
+ // React 树仍属于 shell.overlay 槽(生命周期完整),只是 DOM 出口换了。
4289
+ // 结构与设置面板一致:mask 点击关闭 + document 级 Esc 关闭。
4290
+ // Esc 层级(契约 §0):modalStack 非空时 Esc 只关栈顶弹层(diff 窗口/
4291
+ // 确认框/表单弹窗),栈空才关面板。
4292
+ ctx.slots.inject("shell.overlay", () => ctx.slots.register(
4293
+ { name: "shell.overlay", id: "dsh-volcano-git-plugin", order: 150 },
4294
+ (props) => {
4295
+ const isOpen = useOpen();
4296
+ React.useEffect(() => {
4297
+ if (!isOpen) return;
4298
+ const onKey = (e) => {
4299
+ if (e.key === "Escape") {
4300
+ if (modalStack.length > 0) {
4301
+ const top = modalStack[modalStack.length - 1];
4302
+ if (top && typeof top.close === "function") top.close();
4303
+ return;
4304
+ }
4305
+ setOpen(false);
4306
+ }
4307
+ };
4308
+ document.addEventListener("keydown", onKey);
4309
+ return () => document.removeEventListener("keydown", onKey);
4310
+ }, [isOpen]);
4311
+ if (!isOpen) return React.createElement(Toast, null);
4312
+ const close = () => setOpen(false);
4313
+ return React.createElement(React.Fragment, null,
4314
+ React.createElement(Toast, null),
4315
+ ReactDOM.createPortal(
4316
+ React.createElement("div", { className: "gm-overlay", role: "presentation" },
4317
+ React.createElement("div", { className: "gm-mask", "aria-hidden": true, onClick: close }),
4318
+ React.createElement(GitPanel, { slotProps: props, remote, workspaces, onClose: close }),
4319
+ ),
4320
+ document.body,
4321
+ ),
4322
+ );
4323
+ },
4324
+ ));
4325
+ }
4326
+
4327
+ exports.apply = apply;
4328
+ exports.inject = ["slots", "remote"];
4329
+ return module.exports;
4330
+ },
4331
+ });