deepseek-harness-git 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,2991 @@
1
+ /**
2
+ * dsh-git — browser half.
3
+ *
4
+ * One source-control page in the main column, reached from the sidebar's global
5
+ * panel icon. The page is a plain Module Loader plugin: `window.__ModuleLoader__`
6
+ * hands it React, and every read or write travels over the authenticated
7
+ * `/api/dsh-git` exact Fetch route published by the host half.
8
+ *
9
+ * The panel is root-scoped on purpose. It lists the profile's Workspaces itself
10
+ * and remembers the last repository, so it stays usable while no Session is
11
+ * selected — the same posture as the Plugins and Schedules pages.
12
+ */
13
+
14
+ window.__ModuleLoader__.load({
15
+ id: 'deepseek-harness-git',
16
+ factory(require) {
17
+ const React = require('react')
18
+ const h = React.createElement
19
+ const {
20
+ useState, useEffect, useMemo, useRef, useCallback,
21
+ } = React
22
+
23
+ /** Locale namespace and main-panel id. Both halves must agree on the id. */
24
+ const NS = 'dsh-git'
25
+ const PANEL_ID = 'dsh-git'
26
+ /** Exact route the host half registers on Connection's `/api` channel. */
27
+ const ROUTE = '/api/dsh-git'
28
+ const REPO_KEY = 'dsh-git.repo'
29
+ const WORKSPACE_KEY = 'dsh-git.workspace'
30
+ const ACTIVE_PREFIX = 'dsh-git.active:'
31
+ const ENABLED_PREFIX = 'dsh-git.enabled:'
32
+ const DRAFT_PREFIX = 'dsh-git.draft:'
33
+ const MODEL_KEY = 'dsh-git.messageModel'
34
+ /** Separator for a provider/model pair inside one <option> value. */
35
+ const MODEL_SEPARATOR = '\t'
36
+ /** Client-side render cap for one patch. */
37
+ const RENDER_LINES = 1500
38
+
39
+ //#region copy
40
+
41
+ const EN = {
42
+ panelTitle: 'Git',
43
+ loading: 'Loading…',
44
+ panelUnavailable: 'The Git panel is not connected to the Host.',
45
+ routeUnreachable: 'The Git panel route is unreachable ({message}).',
46
+ httpError: 'The Git panel route answered HTTP {status}.',
47
+ refused: 'The Git panel refused this request.',
48
+ retry: 'Retry',
49
+ refresh: 'Refresh',
50
+ cancel: 'Cancel',
51
+ dismiss: 'Dismiss',
52
+ create: 'Create',
53
+ repository: 'Repository',
54
+ repositories: 'Repositories',
55
+ chooseRepository: 'Choose repository',
56
+ chooseWorkspace: 'Choose workspace',
57
+ workspace: 'Workspace',
58
+ manageRepos: 'Manage repositories',
59
+ repositoriesTitle: 'Repositories in {workspace}',
60
+ repositoriesHint: 'Choose which repositories this panel loads. The scan walks up to four levels below the workspace and skips build directories.',
61
+ detectedRepos: '{n} repositories detected',
62
+ loadedRepos: 'Loaded repositories',
63
+ noRepositoriesFound: 'No Git repositories found',
64
+ noRepositoriesHint: 'Scan again, or initialize a repository at the workspace root.',
65
+ noRepositoriesLoaded: 'No repositories loaded',
66
+ loadRepositoriesHint: 'Open Manage repositories and choose at least one.',
67
+ scanAgain: 'Scan again',
68
+ scanning: 'Scanning repositories…',
69
+ scanTruncated: 'The scan stopped at its directory limit; some repositories may be missing.',
70
+ selectAll: 'Select all',
71
+ clearSelection: 'Clear',
72
+ close: 'Close',
73
+ rootRepository: 'Workspace root',
74
+ repoCount: '{n} loaded',
75
+ noWorkspaces: 'No workspaces yet',
76
+ noWorkspacesHint: 'Add a workspace in the sidebar, then open this panel again.',
77
+ branch: 'Branch',
78
+ switchBranch: 'Switch branch',
79
+ newBranch: 'New branch',
80
+ newBranchPlaceholder: 'branch-name',
81
+ detachedHead: 'Detached HEAD',
82
+ noBranches: 'No local branches yet',
83
+ aheadCount: '{n} ahead',
84
+ behindCount: '{n} behind',
85
+ noUpstream: 'No upstream',
86
+ publishBranch: 'Publish branch',
87
+ publishBranchHint: 'Push this branch and set its upstream',
88
+ publishingBranch: 'Publishing branch…',
89
+ branchPublished: 'Published {branch} and set its upstream.',
90
+ setUpstream: 'Set upstream…',
91
+ manageRemotes: 'Manage remotes…',
92
+ remotesTitle: 'Remote repositories',
93
+ remotesText: 'Add a remote repository, fetch it, then set a branch upstream.',
94
+ remoteName: 'Name',
95
+ remoteUrl: 'URL',
96
+ remoteUrlPlaceholder: 'git@github.com:you/repo.git',
97
+ addRemote: 'Add remote',
98
+ addingRemote: 'Adding remote…',
99
+ remoteAdded: 'Added remote {name}.',
100
+ removeRemote: 'Remove remote',
101
+ removingRemote: 'Removing remote…',
102
+ remoteRemoved: 'Removed remote {name}.',
103
+ noRemotesConfigured: 'No remotes yet. Add one below.',
104
+ remoteInUseWarning: 'Removing a remote also clears the upstream of branches that tracked it.',
105
+ close: 'Close',
106
+ setUpstreamTitle: 'Set upstream',
107
+ setUpstreamText: 'Choose the remote branch that {branch} should track.',
108
+ upstreamPushHint: 'The branch {branch} has no remote counterpart yet; push it first to create one.',
109
+ remote: 'Remote',
110
+ remoteBranch: 'Remote branch',
111
+ noRemotes: 'No remotes are configured. Use Manage remotes to add one.',
112
+ noRemoteBranches: 'No remote branches; fetch the remote first.',
113
+ loadingBranches: 'Loading branches…',
114
+ savingUpstream: 'Setting upstream…',
115
+ upstreamSet: 'Upstream set to {upstream}.',
116
+ deleteBranch: 'Delete branch',
117
+ deleteBranchTitle: 'Delete branch?',
118
+ deleteBranchText: 'Delete the local branch {branch}. Git refuses when it has unmerged commits.',
119
+ branchDeleted: 'Deleted branch {branch}.',
120
+ deletingBranch: 'Deleting branch…',
121
+ delete: 'Delete',
122
+ save: 'Save',
123
+ branchSwitched: 'Switched to {branch}',
124
+ branchCreated: 'Created {branch}',
125
+ branchRequired: 'Enter a branch name.',
126
+ fetch: 'Fetch',
127
+ pull: 'Pull',
128
+ push: 'Push',
129
+ fetchDone: 'Fetched from every remote.',
130
+ pullDone: 'Pulled the latest changes.',
131
+ pushDone: 'Pushed the current branch.',
132
+ commit: 'Commit',
133
+ commitPlaceholder: 'Message (Ctrl+Enter to commit)',
134
+ commitMessageRequired: 'Enter a commit message.',
135
+ nothingStaged: 'Stage a change first.',
136
+ amend: 'Amend last commit',
137
+ amendHint: 'Replace the previous commit with this one',
138
+ generateMessage: 'Generate',
139
+ generateHint: 'Generate a commit message from the changes (replaces the current message)',
140
+ generatingMessage: 'Generating a commit message…',
141
+ noChangesHint: 'There are no changes to describe.',
142
+ messageEmpty: 'The model returned an empty commit message.',
143
+ aiModel: 'AI model',
144
+ modelDefault: 'Default (new session model)',
145
+ modelsLoading: 'Loading models…',
146
+ modelsUnavailable: 'No models available',
147
+ modelHint: 'Model used for AI commit message generation',
148
+ stageAll: 'Stage all',
149
+ unstageAll: 'Unstage all',
150
+ stagedCount: '{n} staged',
151
+ commitSuccess: 'Committed {hash}',
152
+ committing: 'Committing…',
153
+ stage: 'Stage',
154
+ unstage: 'Unstage',
155
+ stagedNotice: 'Staged changes.',
156
+ unstagedNotice: 'Unstaged changes.',
157
+ stagedAllNotice: 'Staged all changes.',
158
+ unstagedAllNotice: 'Unstaged all changes.',
159
+ discard: 'Discard changes',
160
+ discardTitle: 'Discard changes?',
161
+ discardText: 'This permanently reverts the selected working-tree changes.',
162
+ discardUntrackedText: 'This permanently deletes the selected untracked files.',
163
+ discardConfirm: 'Discard',
164
+ discarded: 'Discarded changes.',
165
+ discarding: 'Discarding…',
166
+ filesCount: '{n} files',
167
+ stagedChanges: 'Staged changes',
168
+ mergeChanges: 'Merge changes',
169
+ changes: 'Changes',
170
+ history: 'Recent commits',
171
+ noStaged: 'Nothing staged.',
172
+ noConflicts: 'No conflicts.',
173
+ noChanges: 'Working tree clean.',
174
+ noCommits: 'No commits yet.',
175
+ markResolved: 'Mark resolved',
176
+ expand: 'Expand',
177
+ collapse: 'Collapse',
178
+ showAll: 'Show all {n} lines',
179
+ showLess: 'Show less',
180
+ truncated: 'The patch was truncated.',
181
+ selectFile: 'Select a file',
182
+ selectFileHint: 'Choose a changed file to review its diff.',
183
+ noDiff: 'No textual changes.',
184
+ binaryDiff: 'Binary file — no textual diff.',
185
+ diffFailed: 'Could not load the diff.',
186
+ workingTree: 'Working tree',
187
+ stagedVersion: 'Staged',
188
+ commitDetails: 'Commit {hash}',
189
+ filesChanged: '{n} files changed',
190
+ backToChanges: 'Back to changes',
191
+ notARepository: 'Not a Git repository',
192
+ notARepositoryHint: 'This workspace has no Git repository. Initialize one to start tracking changes.',
193
+ initRepository: 'Initialize repository',
194
+ initializing: 'Initializing…',
195
+ initialized: 'Repository initialized.',
196
+ gitMissing: 'Git was not found',
197
+ gitMissingHint: 'Install Git and make sure it is on PATH, then refresh.',
198
+ modified: 'Modified',
199
+ added: 'Added',
200
+ deleted: 'Deleted',
201
+ renamed: 'Renamed',
202
+ copied: 'Copied',
203
+ untracked: 'Untracked',
204
+ conflicted: 'Conflicted',
205
+ typeChanged: 'Type changed',
206
+ justNow: 'just now',
207
+ minutesAgo: '{n} min ago',
208
+ hoursAgo: '{n} h ago',
209
+ daysAgo: '{n} d ago',
210
+ loadingFailed: 'Could not load the repository.',
211
+ renderFailed: 'Git panel failed to render',
212
+ syncDone: 'Up to date.',
213
+ }
214
+
215
+ const ZH = {
216
+ panelTitle: 'Git',
217
+ loading: '加载中…',
218
+ panelUnavailable: 'Git 面板未连接到 Host。',
219
+ routeUnreachable: 'Git 面板路由不可达({message})。',
220
+ httpError: 'Git 面板路由返回 HTTP {status}。',
221
+ refused: 'Git 面板拒绝了此请求。',
222
+ retry: '重试',
223
+ refresh: '刷新',
224
+ cancel: '取消',
225
+ dismiss: '关闭',
226
+ create: '创建',
227
+ repository: '仓库',
228
+ repositories: '仓库',
229
+ chooseRepository: '选择仓库',
230
+ chooseWorkspace: '选择工作区',
231
+ workspace: '工作区',
232
+ manageRepos: '管理仓库',
233
+ repositoriesTitle: '{workspace} 中的仓库',
234
+ repositoriesHint: '选择此面板要加载的仓库。扫描最多深入工作区以下四层,并跳过构建目录。',
235
+ detectedRepos: '检测到 {n} 个仓库',
236
+ loadedRepos: '已加载仓库',
237
+ noRepositoriesFound: '未找到 Git 仓库',
238
+ noRepositoriesHint: '请重新扫描,或在工作区根目录初始化仓库。',
239
+ noRepositoriesLoaded: '未加载仓库',
240
+ loadRepositoriesHint: '打开“管理仓库”并至少选择一个。',
241
+ scanAgain: '重新扫描',
242
+ scanning: '正在扫描仓库…',
243
+ scanTruncated: '扫描达到目录上限,部分仓库可能未显示。',
244
+ selectAll: '全选',
245
+ clearSelection: '清空',
246
+ close: '关闭',
247
+ rootRepository: '工作区根目录',
248
+ repoCount: '已加载 {n} 个',
249
+ noWorkspaces: '暂无工作区',
250
+ noWorkspacesHint: '请先在侧边栏添加工作区,然后重新打开此面板。',
251
+ branch: '分支',
252
+ switchBranch: '切换分支',
253
+ newBranch: '新建分支',
254
+ newBranchPlaceholder: '分支名称',
255
+ detachedHead: '游离 HEAD',
256
+ noBranches: '暂无本地分支',
257
+ aheadCount: '领先 {n} 个提交',
258
+ behindCount: '落后 {n} 个提交',
259
+ noUpstream: '无上游分支',
260
+ publishBranch: '发布分支',
261
+ publishBranchHint: '推送此分支并设置上游',
262
+ publishingBranch: '正在发布分支…',
263
+ branchPublished: '已发布 {branch} 并设置上游。',
264
+ setUpstream: '设置上游…',
265
+ manageRemotes: '管理远程仓库…',
266
+ remotesTitle: '远程仓库',
267
+ remotesText: '添加远程仓库,抓取后即可设置分支上游。',
268
+ remoteName: '名称',
269
+ remoteUrl: 'URL',
270
+ remoteUrlPlaceholder: 'git@github.com:you/repo.git',
271
+ addRemote: '添加远程仓库',
272
+ addingRemote: '正在添加远程仓库…',
273
+ remoteAdded: '已添加远程仓库 {name}。',
274
+ removeRemote: '移除远程仓库',
275
+ removingRemote: '正在移除远程仓库…',
276
+ remoteRemoved: '已移除远程仓库 {name}。',
277
+ noRemotesConfigured: '还没有远程仓库,在下面添加。',
278
+ remoteInUseWarning: '移除远程仓库会同时清除跟踪它的分支的上游。',
279
+ close: '关闭',
280
+ setUpstreamTitle: '设置上游',
281
+ setUpstreamText: '选择 {branch} 要跟踪的远程分支。',
282
+ upstreamPushHint: '分支 {branch} 还没有远程对应分支,先推送一次即可创建。',
283
+ remote: '远程仓库',
284
+ remoteBranch: '远程分支',
285
+ noRemotes: '没有配置远程仓库。请用“管理远程仓库”添加。',
286
+ noRemoteBranches: '没有远程分支,请先抓取远程。',
287
+ loadingBranches: '正在加载分支…',
288
+ savingUpstream: '正在设置上游…',
289
+ upstreamSet: '上游已设置为 {upstream}。',
290
+ deleteBranch: '删除分支',
291
+ deleteBranchTitle: '删除分支?',
292
+ deleteBranchText: '删除本地分支 {branch}。如果有未合并提交,Git 会拒绝。',
293
+ branchDeleted: '已删除分支 {branch}。',
294
+ deletingBranch: '正在删除分支…',
295
+ delete: '删除',
296
+ save: '保存',
297
+ branchSwitched: '已切换到 {branch}',
298
+ branchCreated: '已创建 {branch}',
299
+ branchRequired: '请输入分支名称。',
300
+ fetch: '获取',
301
+ pull: '拉取',
302
+ push: '推送',
303
+ fetchDone: '已从所有远程获取。',
304
+ pullDone: '已拉取最新更改。',
305
+ pushDone: '已推送当前分支。',
306
+ commit: '提交',
307
+ commitPlaceholder: '提交信息(Ctrl+Enter 提交)',
308
+ commitMessageRequired: '请输入提交信息。',
309
+ nothingStaged: '请先暂存更改。',
310
+ amend: '修补上次提交',
311
+ amendHint: '用本次提交替换上一次提交',
312
+ generateMessage: 'AI 生成',
313
+ generateHint: '根据更改生成提交信息(会替换当前内容)',
314
+ generatingMessage: '正在生成提交信息…',
315
+ noChangesHint: '没有可描述的更改。',
316
+ messageEmpty: '模型返回了空的提交信息。',
317
+ aiModel: 'AI 模型',
318
+ modelDefault: '默认(新会话模型)',
319
+ modelsLoading: '正在加载模型…',
320
+ modelsUnavailable: '没有可用模型',
321
+ modelHint: '用于 AI 生成提交信息的模型',
322
+ stageAll: '全部暂存',
323
+ unstageAll: '全部取消暂存',
324
+ stagedCount: '已暂存 {n} 个',
325
+ commitSuccess: '已提交 {hash}',
326
+ committing: '正在提交…',
327
+ stage: '暂存',
328
+ unstage: '取消暂存',
329
+ stagedNotice: '已暂存更改。',
330
+ unstagedNotice: '已取消暂存。',
331
+ stagedAllNotice: '已暂存全部更改。',
332
+ unstagedAllNotice: '已取消全部暂存。',
333
+ discard: '放弃更改',
334
+ discardTitle: '放弃更改?',
335
+ discardText: '此操作将永久还原所选的工作区更改。',
336
+ discardUntrackedText: '此操作将永久删除所选的未跟踪文件。',
337
+ discardConfirm: '放弃',
338
+ discarded: '已放弃更改。',
339
+ discarding: '正在放弃…',
340
+ filesCount: '{n} 个文件',
341
+ stagedChanges: '已暂存的更改',
342
+ mergeChanges: '合并更改',
343
+ changes: '更改',
344
+ history: '最近提交',
345
+ noStaged: '暂无已暂存的更改。',
346
+ noConflicts: '没有冲突。',
347
+ noChanges: '工作区干净。',
348
+ noCommits: '暂无提交。',
349
+ markResolved: '标记为已解决',
350
+ expand: '展开',
351
+ collapse: '收起',
352
+ showAll: '显示全部 {n} 行',
353
+ showLess: '收起',
354
+ truncated: '补丁已被截断。',
355
+ selectFile: '选择文件',
356
+ selectFileHint: '选择一个更改的文件以查看差异。',
357
+ noDiff: '没有文本差异。',
358
+ binaryDiff: '二进制文件,无文本差异。',
359
+ diffFailed: '无法加载差异。',
360
+ workingTree: '工作区',
361
+ stagedVersion: '已暂存',
362
+ commitDetails: '提交 {hash}',
363
+ filesChanged: '{n} 个文件更改',
364
+ backToChanges: '返回更改',
365
+ notARepository: '不是 Git 仓库',
366
+ notARepositoryHint: '此工作区没有 Git 仓库。初始化后即可开始跟踪更改。',
367
+ initRepository: '初始化仓库',
368
+ initializing: '正在初始化…',
369
+ initialized: '仓库已初始化。',
370
+ gitMissing: '未找到 Git',
371
+ gitMissingHint: '请安装 Git 并确保它在 PATH 中,然后刷新。',
372
+ modified: '已修改',
373
+ added: '已添加',
374
+ deleted: '已删除',
375
+ renamed: '已重命名',
376
+ copied: '已复制',
377
+ untracked: '未跟踪',
378
+ conflicted: '冲突',
379
+ typeChanged: '类型变更',
380
+ justNow: '刚刚',
381
+ minutesAgo: '{n} 分钟前',
382
+ hoursAgo: '{n} 小时前',
383
+ daysAgo: '{n} 天前',
384
+ loadingFailed: '无法加载仓库。',
385
+ renderFailed: 'Git 面板渲染失败',
386
+ syncDone: '已是最新。',
387
+ }
388
+
389
+ //#endregion
390
+
391
+ //#region styles
392
+
393
+ const CSS = `
394
+ .dg-root{position:relative;display:flex;flex-direction:column;height:100%;min-height:0;overflow:hidden;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-size:13px;line-height:1.45;container-type:inline-size}
395
+ .dg-root *{box-sizing:border-box}
396
+ .dg-header{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;flex:none;padding:16px 20px 12px;border-bottom:0.5px solid var(--dsw-alias-border-l1)}
397
+ .dg-heading{min-width:0;display:flex;flex-direction:column;gap:3px}
398
+ .dg-title-row{display:flex;align-items:center;gap:10px;min-width:0;flex-wrap:wrap}
399
+ .dg-glyph{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:8px;border:0.5px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-brand-primary);flex:none}
400
+ .dg-title{margin:0;font-size:18px;line-height:1.2;font-weight:600;letter-spacing:-0.01em}
401
+ .dg-subtitle{margin:0;min-width:0;max-width:min(720px,60vw);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11.5px}
402
+ .dg-toolbar{display:flex;align-items:center;gap:4px;flex:none;padding-top:2px}
403
+ .dg-chip{display:inline-flex;align-items:center;gap:6px;max-width:260px;border:0.5px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-secondary);border-radius:999px;padding:3px 10px;font:inherit;font-size:12px;line-height:1.5;cursor:pointer;min-width:0}
404
+ .dg-chip:hover{border-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-primary)}
405
+ .dg-chip:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
406
+ .dg-chip-text{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
407
+ .dg-chip-meta{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;flex:none}
408
+ .dg-chip[data-current="true"]{color:var(--dsw-alias-brand-primary);border-color:color-mix(in srgb, var(--dsw-alias-brand-primary) 45%, transparent)}
409
+ .dg-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;border:0.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);border-radius:6px;padding:5px 10px;font:inherit;font-size:12px;line-height:1.5;cursor:pointer;white-space:nowrap}
410
+ .dg-btn:hover:not(:disabled){border-color:var(--dsw-alias-brand-primary)}
411
+ .dg-btn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
412
+ .dg-btn:disabled{opacity:.45;cursor:default}
413
+ .dg-btn-primary{background:var(--dsw-alias-brand-primary);border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-bg-base);font-weight:600}
414
+ .dg-btn-danger{color:var(--dsw-alias-state-error-primary);border-color:color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, var(--dsw-alias-border-l2))}
415
+ .dg-btn-danger:hover:not(:disabled){background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 10%, transparent);border-color:var(--dsw-alias-state-error-primary)}
416
+ .dg-btn-ghost{border-color:transparent;background:transparent;color:var(--dsw-alias-label-secondary)}
417
+ .dg-btn-ghost:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}
418
+ .dg-icon-btn{display:inline-flex;align-items:center;justify-content:center;gap:2px;width:26px;height:26px;padding:0;border:0;border-radius:5px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;flex:none;font:inherit;font-size:11px}
419
+ .dg-icon-btn:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}
420
+ .dg-icon-btn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-1px}
421
+ .dg-icon-btn:disabled{opacity:.4;cursor:default}
422
+ .dg-badge{display:inline-flex;align-items:center;justify-content:center;min-width:14px;height:14px;padding:0 3px;border-radius:999px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary);font-size:10px;font-variant-numeric:tabular-nums;line-height:1}
423
+ .dg-busy{display:inline-flex;align-items:center;gap:6px;max-width:190px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary);font-size:11.5px;padding:0 4px}
424
+ .dg-banners{display:flex;flex-direction:column;gap:6px;flex:none;padding:8px 20px 0}
425
+ .dg-banner{display:flex;align-items:flex-start;gap:8px;border:0.5px solid var(--dsw-alias-border-l2);border-radius:7px;padding:6px 9px;font-size:12px;line-height:1.5}
426
+ .dg-banner-text{flex:1;min-width:0;white-space:pre-wrap;overflow-wrap:anywhere}
427
+ .dg-banner-ok{border-color:color-mix(in srgb, var(--dsw-alias-state-success-primary) 40%, transparent);background:color-mix(in srgb, var(--dsw-alias-state-success-primary) 10%, transparent);color:var(--dsw-alias-state-success-primary)}
428
+ .dg-banner-error{border-color:color-mix(in srgb, var(--dsw-alias-state-error-primary) 40%, transparent);background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 10%, transparent);color:var(--dsw-alias-state-error-primary)}
429
+ .dg-banner-warn{border-color:color-mix(in srgb, var(--dsw-alias-state-warn-primary) 40%, transparent);background:color-mix(in srgb, var(--dsw-alias-state-warn-primary) 10%, transparent);color:var(--dsw-alias-state-warn-primary)}
430
+ .dg-banner .dg-icon-btn{width:20px;height:20px;margin:-2px -2px 0 0}
431
+ .dg-body{display:grid;grid-template-columns:minmax(300px,360px) minmax(0,1fr);flex:1;min-height:0}
432
+ .dg-body-single{display:flex;align-items:stretch;justify-content:stretch}
433
+ .dg-side{display:flex;flex-direction:column;min-height:0;overflow:hidden;border-right:0.5px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-base)}
434
+ .dg-side-scroll{flex:1;min-height:0;overflow:auto}
435
+ .dg-commit{display:flex;flex-direction:column;gap:7px;flex:none;padding:12px 12px 10px;border-bottom:0.5px solid var(--dsw-alias-border-l1)}
436
+ .dg-textarea{width:100%;min-height:64px;max-height:180px;resize:vertical;border:0.5px solid var(--dsw-alias-border-l2);border-radius:7px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;font-size:12.5px;line-height:1.5;padding:7px 9px}
437
+ .dg-textarea::placeholder{color:var(--dsw-alias-label-secondary)}
438
+ .dg-textarea:focus{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-1px;border-color:transparent}
439
+ .dg-model-row{display:flex;align-items:center;gap:6px;min-width:0}
440
+ .dg-model-label{color:var(--dsw-alias-label-secondary);font-size:11px;white-space:nowrap;flex:none}
441
+ .dg-model-select{flex:1;min-width:0;height:24px;border:0.5px solid var(--dsw-alias-border-l2);border-radius:6px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;font-size:11.5px;padding:0 5px}
442
+ .dg-model-select:focus{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-1px}
443
+ .dg-model-select:disabled{opacity:.55;cursor:not-allowed}
444
+ .dg-commit-row{display:flex;align-items:center;justify-content:space-between;gap:8px;min-height:20px}
445
+ .dg-check{display:inline-flex;align-items:center;gap:5px;color:var(--dsw-alias-label-secondary);font-size:11.5px;cursor:pointer;user-select:none}
446
+ .dg-check input{margin:0;accent-color:var(--dsw-alias-brand-primary)}
447
+ .dg-commit-count{color:var(--dsw-alias-label-secondary);font-size:11.5px;font-variant-numeric:tabular-nums}
448
+ .dg-commit-actions{display:flex;align-items:center;gap:6px;justify-content:flex-end;flex-wrap:wrap}
449
+ .dg-section{border-bottom:0.5px solid var(--dsw-alias-border-l1)}
450
+ .dg-section-head{display:flex;align-items:center;gap:4px;padding:5px 8px 5px 12px;position:sticky;top:0;z-index:2;background:var(--dsw-alias-bg-base)}
451
+ .dg-section-toggle{display:flex;align-items:center;gap:6px;flex:1;min-width:0;border:0;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11px;font-weight:600;letter-spacing:.045em;text-transform:uppercase;text-align:left;padding:3px 0;cursor:pointer}
452
+ .dg-section-toggle:hover{color:var(--dsw-alias-label-primary)}
453
+ .dg-section-toggle:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px;border-radius:4px}
454
+ .dg-section-title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
455
+ .dg-count{display:inline-flex;align-items:center;justify-content:center;min-width:17px;height:16px;padding:0 5px;border-radius:999px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary);font-size:10.5px;font-weight:600;letter-spacing:0;font-variant-numeric:tabular-nums}
456
+ .dg-section-empty{padding:4px 12px 10px;color:var(--dsw-alias-label-secondary);font-size:11.5px}
457
+ .dg-file{display:flex;align-items:center;gap:1px;padding-right:6px}
458
+ .dg-file[data-active="true"]{background:var(--dsw-alias-bg-layer-2)}
459
+ .dg-file:hover{background:var(--dsw-alias-bg-layer-2)}
460
+ .dg-file-main{display:flex;align-items:center;gap:7px;flex:1;min-width:0;border:0;background:transparent;color:inherit;font:inherit;text-align:left;padding:3px 6px 3px 12px;cursor:pointer}
461
+ .dg-file-main:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-2px}
462
+ .dg-status{display:inline-flex;align-items:center;justify-content:center;width:13px;flex:none;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;font-weight:700}
463
+ .dg-status[data-s="M"]{color:var(--dsw-alias-state-warn-primary)}
464
+ .dg-status[data-s="A"],.dg-status[data-s="U"]{color:var(--dsw-alias-state-success-primary)}
465
+ .dg-status[data-s="D"],.dg-status[data-s="!"]{color:var(--dsw-alias-state-error-primary)}
466
+ .dg-status[data-s="R"],.dg-status[data-s="C"]{color:var(--dsw-alias-brand-primary)}
467
+ .dg-file-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12.5px}
468
+ .dg-dir{color:var(--dsw-alias-label-secondary)}
469
+ .dg-file-orig{margin-left:6px;color:var(--dsw-alias-label-secondary);font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:none;max-width:45%}
470
+ .dg-file-actions{display:flex;align-items:center;gap:1px;flex:none;opacity:0}
471
+ .dg-file:hover .dg-file-actions,.dg-file:focus-within .dg-file-actions{opacity:1}
472
+ .dg-file-actions .dg-icon-btn{width:22px;height:22px}
473
+ .dg-commit-row-button{display:flex;flex-direction:column;gap:1px;width:100%;border:0;background:transparent;color:inherit;font:inherit;text-align:left;padding:5px 12px;cursor:pointer}
474
+ .dg-commit-row-button:hover{background:var(--dsw-alias-bg-layer-2)}
475
+ .dg-commit-row-button:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-2px}
476
+ .dg-commit-line{display:flex;align-items:baseline;gap:7px;min-width:0;width:100%}
477
+ .dg-hash{flex:none;color:var(--dsw-alias-brand-primary);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px}
478
+ .dg-subject{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12.5px}
479
+ .dg-commit-meta{color:var(--dsw-alias-label-secondary);font-size:10.5px;padding-left:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
480
+ .dg-diff{display:flex;flex-direction:column;min-width:0;min-height:0;background:var(--dsw-alias-bg-base)}
481
+ .dg-diff-head{display:flex;align-items:center;justify-content:space-between;gap:12px;flex:none;min-height:45px;padding:8px 16px;border-bottom:0.5px solid var(--dsw-alias-border-l1)}
482
+ .dg-diff-title{display:flex;align-items:center;gap:8px;min-width:0;flex:1}
483
+ .dg-diff-path{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12.5px}
484
+ .dg-diff-actions{display:flex;align-items:center;gap:4px;flex:none}
485
+ .dg-diff-sub{color:var(--dsw-alias-label-secondary);font-size:11.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
486
+ .dg-seg{display:inline-flex;align-items:center;padding:2px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);border:0.5px solid var(--dsw-alias-border-l1);flex:none}
487
+ .dg-seg-btn{border:0;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11.5px;line-height:1.5;padding:2px 8px;border-radius:4px;cursor:pointer}
488
+ .dg-seg-btn:hover:not(:disabled){color:var(--dsw-alias-label-primary)}
489
+ .dg-seg-btn[data-on="true"]{background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);box-shadow:0 1px 2px rgba(0,0,0,.08)}
490
+ .dg-seg-btn:disabled{opacity:.4;cursor:default}
491
+ .dg-diff-body{flex:1;min-height:0;overflow:auto;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px;line-height:20px}
492
+ .dg-commit-detail{display:flex;flex-direction:column;gap:2px;padding:8px 16px;border-bottom:0.5px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);flex:none}
493
+ .dg-commit-detail-subject{font-size:13px;font-weight:600;overflow-wrap:anywhere}
494
+ .dg-commit-detail-meta{color:var(--dsw-alias-label-secondary);font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
495
+ .dg-file-block{border-bottom:0.5px solid var(--dsw-alias-border-l1)}
496
+ .dg-file-block-head{display:flex;align-items:center;gap:8px;padding:6px 12px;position:sticky;top:0;z-index:1;background:var(--dsw-alias-bg-layer-1);border-bottom:0.5px solid var(--dsw-alias-border-l1);font-family:inherit}
497
+ .dg-file-block-path{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px}
498
+ .dg-file-block-orig{flex:none;color:var(--dsw-alias-label-secondary);font-size:11px}
499
+ .dg-tag{display:inline-flex;align-items:center;border:0.5px solid var(--dsw-alias-border-l2);border-radius:999px;padding:0 7px;color:var(--dsw-alias-label-secondary);font-size:10.5px;line-height:1.6;white-space:nowrap}
500
+ .dg-line{display:flex;min-width:max-content}
501
+ .dg-ln{flex:none;width:46px;padding-right:8px;text-align:right;color:var(--dsw-alias-label-secondary);opacity:.7;user-select:none;font-size:11px}
502
+ .dg-sign{flex:none;width:18px;text-align:center;user-select:none;color:var(--dsw-alias-label-secondary)}
503
+ .dg-code{white-space:pre;padding-right:18px;min-width:0}
504
+ .dg-line-add{background:color-mix(in srgb, var(--dsw-alias-state-success-primary) 13%, transparent)}
505
+ .dg-line-add .dg-sign{color:var(--dsw-alias-state-success-primary)}
506
+ .dg-line-del{background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent)}
507
+ .dg-line-del .dg-sign{color:var(--dsw-alias-state-error-primary)}
508
+ .dg-line-ctx .dg-code{color:var(--dsw-alias-label-primary)}
509
+ .dg-hunk-row{padding:2px 12px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-brand-primary);font-size:11.5px;white-space:pre;min-width:max-content}
510
+ .dg-meta-row{padding:1px 12px;color:var(--dsw-alias-label-secondary);font-size:11px;white-space:pre;min-width:max-content}
511
+ .dg-diff-more{display:flex;justify-content:center;padding:8px 12px}
512
+ .dg-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;flex:1;min-height:0;height:100%;padding:40px 24px;text-align:center;color:var(--dsw-alias-label-secondary)}
513
+ .dg-empty-glyph{display:flex;align-items:center;justify-content:center;width:46px;height:46px;border-radius:13px;border:0.5px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-secondary)}
514
+ .dg-empty-title{font-size:14px;font-weight:600;color:var(--dsw-alias-label-primary)}
515
+ .dg-empty-text{font-size:12px;line-height:1.6;max-width:360px}
516
+ .dg-empty-path{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;max-width:520px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
517
+ .dg-menu-anchor{position:relative;display:inline-flex;min-width:0}
518
+ .dg-menu{position:absolute;top:calc(100% + 6px);left:0;z-index:50;min-width:250px;max-width:min(460px,70vw);max-height:340px;overflow:auto;padding:4px;border-radius:8px;border:0.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-overlay);box-shadow:0 10px 28px rgba(0,0,0,.2)}
519
+ .dg-menu-item{display:flex;align-items:flex-start;gap:7px;width:100%;border:0;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:12.5px;text-align:left;padding:6px 8px;border-radius:5px;cursor:pointer}
520
+ .dg-menu-item:hover{background:var(--dsw-alias-bg-layer-2)}
521
+ .dg-menu-item:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-2px}
522
+ .dg-menu-item[data-current="true"]{color:var(--dsw-alias-brand-primary)}
523
+ .dg-branch-row{display:flex;align-items:center;gap:2px}
524
+ .dg-branch-switch{flex:1;min-width:0}
525
+ .dg-branch-delete{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;border:0;border-radius:5px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;flex:none}
526
+ .dg-branch-delete:hover{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-state-error-primary)}
527
+ .dg-branch-delete:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-2px}
528
+ .dg-menu-check{display:inline-flex;align-items:center;justify-content:center;width:14px;height:18px;flex:none;color:var(--dsw-alias-brand-primary)}
529
+ .dg-menu-item-main{display:flex;flex-direction:column;gap:1px;min-width:0}
530
+ .dg-menu-item-title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
531
+ .dg-menu-item-path{color:var(--dsw-alias-label-secondary);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:10.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:340px}
532
+ .dg-menu-label{padding:6px 8px 2px;color:var(--dsw-alias-label-secondary);font-size:10.5px;font-weight:600;letter-spacing:.045em;text-transform:uppercase}
533
+ .dg-menu-empty{padding:4px 8px 8px;color:var(--dsw-alias-label-secondary);font-size:11.5px}
534
+ .dg-menu-sep{height:0.5px;background:var(--dsw-alias-border-l1);margin:4px 0}
535
+ .dg-menu-input-row{display:flex;align-items:center;gap:6px;padding:3px 6px 6px}
536
+ .dg-input{flex:1;min-width:0;border:0.5px solid var(--dsw-alias-border-l2);border-radius:6px;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;padding:4px 7px}
537
+ .dg-input:focus{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-1px;border-color:transparent}
538
+ .dg-modal-backdrop{position:absolute;inset:0;z-index:80;display:flex;align-items:center;justify-content:center;padding:24px;background:color-mix(in srgb, #000 38%, transparent)}
539
+ .dg-modal{width:min(430px,100%);display:flex;flex-direction:column;gap:10px;padding:16px;border-radius:10px;border:0.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-overlay);box-shadow:0 18px 44px rgba(0,0,0,.28)}
540
+ .dg-modal-title{font-size:14px;font-weight:600}
541
+ .dg-modal-text{color:var(--dsw-alias-label-secondary);font-size:12.5px;line-height:1.6}
542
+ .dg-modal-path{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11.5px;color:var(--dsw-alias-label-primary);overflow-wrap:anywhere}
543
+ .dg-modal-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:2px}
544
+ .dg-field{display:flex;flex-direction:column;gap:4px}
545
+ .dg-field-label{font-size:11px;color:var(--dsw-alias-label-secondary)}
546
+ .dg-select{flex:none;height:28px;padding:0 6px}
547
+ .dg-remote-list{display:flex;flex-direction:column;gap:4px;max-height:180px;overflow:auto}
548
+ .dg-remote-row{display:flex;align-items:center;gap:6px}
549
+ .dg-remote-info{display:flex;flex-direction:column;gap:1px;min-width:0;flex:1}
550
+ .dg-remote-name{font-size:12px;font-weight:600}
551
+ .dg-remote-url{font-size:10.5px;color:var(--dsw-alias-label-secondary);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
552
+ .dg-modal-error{font-size:11.5px;line-height:1.5;color:var(--dsw-alias-state-error-primary);word-break:break-word}
553
+ .dg-modal-wide{width:min(600px,100%)}
554
+ .dg-manager-meta{display:flex;align-items:center;gap:8px;color:var(--dsw-alias-label-secondary);font-size:11.5px;min-height:18px}
555
+ .dg-repo-list{display:flex;flex-direction:column;gap:1px;max-height:min(360px,50vh);overflow:auto;padding:4px;border:0.5px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-base)}
556
+ .dg-repo-row{display:flex;align-items:flex-start;gap:8px;padding:6px 8px;border-radius:6px;cursor:pointer}
557
+ .dg-repo-row:hover{background:var(--dsw-alias-bg-layer-2)}
558
+ .dg-repo-row input{margin:3px 0 0;accent-color:var(--dsw-alias-brand-primary);flex:none}
559
+ .dg-repo-main{display:flex;flex-direction:column;gap:1px;min-width:0;flex:1}
560
+ .dg-repo-name{font-size:12.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
561
+ .dg-repo-path{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:10.5px;color:var(--dsw-alias-label-secondary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
562
+ .dg-manager-actions{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-top:2px}
563
+ .dg-manager-spacer{flex:1}
564
+ .dg-spin{animation:dg-spin .9s linear infinite}
565
+ @keyframes dg-spin{to{transform:rotate(360deg)}}
566
+ @media (prefers-reduced-motion: reduce){.dg-spin{animation:none}}
567
+ @media (max-width:900px){
568
+ .dg-body{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(260px,42%) minmax(0,1fr)}
569
+ .dg-side{border-right:0;border-bottom:0.5px solid var(--dsw-alias-border-l1)}
570
+ .dg-subtitle{max-width:60vw}
571
+ }
572
+ @container (max-width:820px){
573
+ .dg-body{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(260px,42%) minmax(0,1fr)}
574
+ .dg-side{border-right:0;border-bottom:0.5px solid var(--dsw-alias-border-l1)}
575
+ }
576
+ @container (max-width:600px){
577
+ .dg-busy{display:none}
578
+ .dg-subtitle{display:none}
579
+ }
580
+ `
581
+
582
+ //#endregion
583
+
584
+ //#region helpers
585
+
586
+ function cx(...values) {
587
+ return values.filter(Boolean).join(' ')
588
+ }
589
+
590
+ function readLocal(key) {
591
+ try {
592
+ return window.localStorage.getItem(key)
593
+ } catch {
594
+ return null
595
+ }
596
+ }
597
+
598
+ function writeLocal(key, value) {
599
+ try {
600
+ if (value === null || value === undefined || value === '') window.localStorage.removeItem(key)
601
+ else window.localStorage.setItem(key, String(value))
602
+ } catch {
603
+ /* storage can be unavailable in a hardened page; drafts are optional */
604
+ }
605
+ }
606
+
607
+ /** Persisted model override for AI commit messages; null means "default". */
608
+ function readModelSelection() {
609
+ const raw = readLocal(MODEL_KEY)
610
+ if (raw === null || raw === '') return null
611
+ try {
612
+ const parsed = JSON.parse(raw)
613
+ if (parsed !== null && typeof parsed === 'object'
614
+ && typeof parsed.provider === 'string' && parsed.provider !== ''
615
+ && typeof parsed.model === 'string' && parsed.model !== '') {
616
+ return { provider: parsed.provider, model: parsed.model }
617
+ }
618
+ } catch {
619
+ /* fall through to the default */
620
+ }
621
+ return null
622
+ }
623
+
624
+ function writeModelSelection(selection) {
625
+ if (selection === null) {
626
+ writeLocal(MODEL_KEY, null)
627
+ return
628
+ }
629
+ writeLocal(MODEL_KEY, JSON.stringify({ provider: selection.provider, model: selection.model }))
630
+ }
631
+
632
+ function modelKey(provider, model) {
633
+ return `${provider}${MODEL_SEPARATOR}${model}`
634
+ }
635
+
636
+ function parseModelKey(value) {
637
+ if (typeof value !== 'string') return null
638
+ const index = value.indexOf(MODEL_SEPARATOR)
639
+ if (index <= 0 || index === value.length - 1) return null
640
+ return { provider: value.slice(0, index), model: value.slice(index + 1) }
641
+ }
642
+
643
+ /** Persisted repository selection for one Workspace: null when never saved. */
644
+ function readEnabledList(workspace) {
645
+ if (typeof workspace !== 'string' || workspace === '') return null
646
+ const raw = readLocal(ENABLED_PREFIX + workspace)
647
+ if (raw === null) return null
648
+ try {
649
+ const parsed = JSON.parse(raw)
650
+ return Array.isArray(parsed) ? parsed.filter((entry) => typeof entry === 'string') : null
651
+ } catch {
652
+ return null
653
+ }
654
+ }
655
+
656
+ function writeEnabledList(workspace, list) {
657
+ if (typeof workspace !== 'string' || workspace === '') return
658
+ writeLocal(ENABLED_PREFIX + workspace, JSON.stringify(list))
659
+ }
660
+
661
+ function readActiveRepo(workspace) {
662
+ if (typeof workspace !== 'string' || workspace === '') return null
663
+ return readLocal(ACTIVE_PREFIX + workspace)
664
+ }
665
+
666
+ function writeActiveRepo(workspace, repoPath) {
667
+ if (typeof workspace !== 'string' || workspace === '') return
668
+ writeLocal(ACTIVE_PREFIX + workspace, repoPath)
669
+ }
670
+
671
+ function samePath(left, right) {
672
+ if (typeof left !== 'string' || typeof right !== 'string') return false
673
+ const a = left.replace(/\\/g, '/').replace(/\/+$/, '')
674
+ const b = right.replace(/\\/g, '/').replace(/\/+$/, '')
675
+ const windows = left.includes('\\') || right.includes('\\')
676
+ || /^[A-Za-z]:\//.test(a) || /^[A-Za-z]:\//.test(b)
677
+ return windows ? a.toLowerCase() === b.toLowerCase() : a === b
678
+ }
679
+
680
+ function baseName(value) {
681
+ const text = String(value ?? '').replace(/[\\/]+$/, '')
682
+ const index = Math.max(text.lastIndexOf('/'), text.lastIndexOf('\\'))
683
+ return index === -1 ? text : text.slice(index + 1)
684
+ }
685
+
686
+ function splitPath(value) {
687
+ const text = String(value ?? '')
688
+ const index = text.lastIndexOf('/')
689
+ return index === -1
690
+ ? { dir: '', base: text }
691
+ : { dir: text.slice(0, index + 1), base: text.slice(index + 1) }
692
+ }
693
+
694
+ /** A rename touches two pathspecs; every mutation must carry both. */
695
+ function entryPaths(entry) {
696
+ if (entry === null || entry === undefined) return []
697
+ const paths = [entry.path]
698
+ if (typeof entry.originalPath === 'string' && entry.originalPath !== '' && entry.originalPath !== entry.path) {
699
+ paths.push(entry.originalPath)
700
+ }
701
+ return paths
702
+ }
703
+
704
+ function statusKey(status) {
705
+ switch (status) {
706
+ case 'M': return 'modified'
707
+ case 'A': return 'added'
708
+ case 'D': return 'deleted'
709
+ case 'R': return 'renamed'
710
+ case 'C': return 'copied'
711
+ case 'U': return 'untracked'
712
+ case '!': return 'conflicted'
713
+ case 'T': return 'typeChanged'
714
+ default: return 'modified'
715
+ }
716
+ }
717
+
718
+ function relativeTime(iso, t) {
719
+ if (!iso) return ''
720
+ const time = Date.parse(iso)
721
+ if (Number.isNaN(time)) return String(iso)
722
+ const seconds = Math.max(0, Math.round((Date.now() - time) / 1000))
723
+ if (seconds < 60) return t('justNow')
724
+ const minutes = Math.round(seconds / 60)
725
+ if (minutes < 60) return t('minutesAgo', { n: minutes })
726
+ const hours = Math.round(minutes / 60)
727
+ if (hours < 24) return t('hoursAgo', { n: hours })
728
+ const days = Math.round(hours / 24)
729
+ if (days < 30) return t('daysAgo', { n: days })
730
+ try {
731
+ return new Date(time).toLocaleDateString()
732
+ } catch {
733
+ return String(iso)
734
+ }
735
+ }
736
+
737
+ function summarizePatch(diff) {
738
+ if (diff === null || diff === undefined) return null
739
+ const files = Array.isArray(diff.files) ? diff.files : []
740
+ let added = 0
741
+ let removed = 0
742
+ for (const file of files) {
743
+ const lines = Array.isArray(file.lines) ? file.lines : []
744
+ for (const line of lines) {
745
+ if (line.kind === 'add') added += 1
746
+ if (line.kind === 'del') removed += 1
747
+ }
748
+ }
749
+ return { files: files.length, added, removed }
750
+ }
751
+
752
+ //#endregion
753
+
754
+ //#region icons
755
+
756
+ function makeIcon(children) {
757
+ return function Icon({ size = 14, className }) {
758
+ return h('svg', {
759
+ width: size,
760
+ height: size,
761
+ viewBox: '0 0 16 16',
762
+ fill: 'none',
763
+ stroke: 'currentColor',
764
+ strokeWidth: 1.5,
765
+ strokeLinecap: 'round',
766
+ strokeLinejoin: 'round',
767
+ 'aria-hidden': true,
768
+ className,
769
+ style: { display: 'block', flex: 'none' },
770
+ }, ...children)
771
+ }
772
+ }
773
+
774
+ const GitMark = makeIcon([
775
+ h('circle', { key: 'a', cx: 4, cy: 3.5, r: 1.7 }),
776
+ h('circle', { key: 'b', cx: 4, cy: 12.5, r: 1.7 }),
777
+ h('circle', { key: 'c', cx: 12, cy: 6, r: 1.7 }),
778
+ h('path', { key: 'd', d: 'M4 5.2v5.6' }),
779
+ h('path', { key: 'e', d: 'M12 7.7v1.1a3.2 3.2 0 0 1-3.2 3.2H5.7' }),
780
+ ])
781
+ const ChevronDown = makeIcon([h('path', { key: 'a', d: 'M4 6l4 4 4-4' })])
782
+ const ChevronRight = makeIcon([h('path', { key: 'a', d: 'M6 3.5l4.5 4.5L6 12.5' })])
783
+ const RefreshIcon = makeIcon([
784
+ h('path', { key: 'a', d: 'M13.2 8a5.2 5.2 0 1 1-1.6-3.8' }),
785
+ h('path', { key: 'b', d: 'M13.2 2.6v3.2H10' }),
786
+ ])
787
+ const PlusIcon = makeIcon([h('path', { key: 'a', d: 'M8 3v10M3 8h10' })])
788
+ const MinusIcon = makeIcon([h('path', { key: 'a', d: 'M3 8h10' })])
789
+ const TrashIcon = makeIcon([
790
+ h('path', { key: 'a', d: 'M3 4.8h10' }),
791
+ h('path', { key: 'b', d: 'M6.4 4.8V3.3h3.2v1.5' }),
792
+ h('path', { key: 'c', d: 'M4.6 4.8l.6 8.2h5.6l.6-8.2' }),
793
+ ])
794
+ const UndoIcon = makeIcon([
795
+ h('path', { key: 'a', d: 'M3.4 6.6h5.2a3.2 3.2 0 1 1 0 6.4H5.8' }),
796
+ h('path', { key: 'b', d: 'M3.4 6.6l2.7-2.7M3.4 6.6l2.7 2.7' }),
797
+ ])
798
+ const CloudIcon = makeIcon([
799
+ h('path', { key: 'a', d: 'M4.4 11.4a2.9 2.9 0 0 1 .2-5.8 3.6 3.6 0 0 1 6.9.9 2.5 2.5 0 0 1 .1 4.9' }),
800
+ h('path', { key: 'b', d: 'M8 7.2v4.6M6.1 9.9L8 11.8l1.9-1.9' }),
801
+ ])
802
+ const ArrowDownIcon = makeIcon([
803
+ h('path', { key: 'a', d: 'M8 2.8v10.4' }),
804
+ h('path', { key: 'b', d: 'M4.4 9.6L8 13.2l3.6-3.6' }),
805
+ ])
806
+ const ArrowUpIcon = makeIcon([
807
+ h('path', { key: 'a', d: 'M8 13.2V2.8' }),
808
+ h('path', { key: 'b', d: 'M4.4 6.4L8 2.8l3.6 3.6' }),
809
+ ])
810
+ const CheckIcon = makeIcon([h('path', { key: 'a', d: 'M3.2 8.4l3 3 6.6-6.8' })])
811
+ const FolderIcon = makeIcon([
812
+ h('path', { key: 'a', d: 'M2.4 4.4h4l1.3 1.6h5.9v6.6h-11.2z' }),
813
+ ])
814
+ const WarningIcon = makeIcon([
815
+ h('path', { key: 'a', d: 'M8 2.4l6 11.2H2z' }),
816
+ h('path', { key: 'b', d: 'M8 6.2v3.4M8 11.3v.1' }),
817
+ ])
818
+ const CommitIcon = makeIcon([
819
+ h('circle', { key: 'a', cx: 8, cy: 8, r: 2.7 }),
820
+ h('path', { key: 'b', d: 'M2.2 8h3.1M10.7 8h3.1' }),
821
+ ])
822
+ const FileIcon = makeIcon([
823
+ h('path', { key: 'a', d: 'M4 2.4h5l3 3v8.2H4z' }),
824
+ h('path', { key: 'b', d: 'M9 2.4v3h3' }),
825
+ ])
826
+ const ListIcon = makeIcon([
827
+ h('path', { key: 'a', d: 'M2.5 4h11M2.5 8h11M2.5 12h11' }),
828
+ ])
829
+ const SparklesIcon = makeIcon([
830
+ h('path', { key: 'a', d: 'M8 2.2l1.2 3.2 3.2 1.2-3.2 1.2L8 11l-1.2-3.2L3.6 6.6l3.2-1.2z' }),
831
+ h('path', { key: 'b', d: 'M12.6 10.4l.6 1.5 1.5.6-1.5.6-.6 1.5-.6-1.5-1.5-.6 1.5-.6z' }),
832
+ ])
833
+ const CloseIcon = makeIcon([h('path', { key: 'a', d: 'M4 4l8 8M12 4l-8 8' })])
834
+
835
+ //#endregion
836
+
837
+ //#region primitives
838
+
839
+ function Spinner({ size = 14 }) {
840
+ return h('span', { className: 'dg-spin', style: { display: 'inline-flex' } }, h(RefreshIcon, { size }))
841
+ }
842
+
843
+ function IconButton({
844
+ title, onClick, disabled, children, className, ariaLabel,
845
+ }) {
846
+ return h('button', {
847
+ type: 'button',
848
+ className: cx('dg-icon-btn', className),
849
+ title,
850
+ 'aria-label': ariaLabel ?? title,
851
+ onClick,
852
+ disabled,
853
+ }, children)
854
+ }
855
+
856
+ function Button({
857
+ variant = 'default', onClick, disabled, children, title, type = 'button',
858
+ }) {
859
+ return h('button', {
860
+ type,
861
+ className: cx('dg-btn', variant === 'primary' && 'dg-btn-primary', variant === 'ghost' && 'dg-btn-ghost', variant === 'danger' && 'dg-btn-danger'),
862
+ onClick,
863
+ disabled,
864
+ title,
865
+ }, children)
866
+ }
867
+
868
+ function StatusBadge({ status, title }) {
869
+ return h('span', { className: 'dg-status', 'data-s': status, title }, status)
870
+ }
871
+
872
+ function Menu({
873
+ open, onClose, children, align = 'left', role = 'menu', label,
874
+ }) {
875
+ const ref = useRef(null)
876
+ useEffect(() => {
877
+ if (!open) return undefined
878
+ const onPointerDown = (event) => {
879
+ if (ref.current !== null && !ref.current.contains(event.target)) onClose()
880
+ }
881
+ const onKeyDown = (event) => {
882
+ if (event.key === 'Escape') onClose()
883
+ }
884
+ document.addEventListener('mousedown', onPointerDown, true)
885
+ document.addEventListener('keydown', onKeyDown)
886
+ return () => {
887
+ document.removeEventListener('mousedown', onPointerDown, true)
888
+ document.removeEventListener('keydown', onKeyDown)
889
+ }
890
+ }, [open, onClose])
891
+ if (!open) return null
892
+ return h('div', {
893
+ ref,
894
+ className: 'dg-menu',
895
+ role,
896
+ 'aria-label': label,
897
+ style: align === 'right' ? { left: 'auto', right: 0 } : undefined,
898
+ }, children)
899
+ }
900
+
901
+ function EmptyState({ icon, title, text, children }) {
902
+ return h('div', { className: 'dg-empty' },
903
+ h('span', { className: 'dg-empty-glyph' }, icon ?? h(GitMark, { size: 22 })),
904
+ h('span', { className: 'dg-empty-title' }, title),
905
+ text !== undefined && text !== null ? h('span', { className: 'dg-empty-text' }, text) : null,
906
+ children)
907
+ }
908
+
909
+ //#endregion
910
+
911
+ //#region diff
912
+
913
+ const HIDDEN_META = /^(diff --git |diff --cc |diff --combined |index |--- |\+\+\+ |similarity index )/
914
+
915
+ function DiffLine({ line }) {
916
+ if (line.kind === 'hunk') {
917
+ return h('div', { className: 'dg-hunk-row' }, line.text)
918
+ }
919
+ if (line.kind === 'meta' || line.kind === 'note') {
920
+ return h('div', { className: 'dg-meta-row' }, line.text)
921
+ }
922
+ const sign = line.kind === 'add' ? '+' : line.kind === 'del' ? '-' : ' '
923
+ return h('div', { className: cx('dg-line', `dg-line-${line.kind}`) },
924
+ h('span', { className: 'dg-ln' }, line.oldLine === undefined ? '' : line.oldLine),
925
+ h('span', { className: 'dg-ln' }, line.newLine === undefined ? '' : line.newLine),
926
+ h('span', { className: 'dg-sign' }, sign),
927
+ h('span', { className: 'dg-code' }, line.text))
928
+ }
929
+
930
+ function DiffFile({ file, t, showHeader }) {
931
+ const [expanded, setExpanded] = useState(false)
932
+ const source = Array.isArray(file.lines) ? file.lines : []
933
+ const visible = useMemo(
934
+ () => source.filter((line) => !(line.kind === 'meta' && HIDDEN_META.test(line.text))),
935
+ [source],
936
+ )
937
+ const limited = !expanded && visible.length > RENDER_LINES
938
+ const shown = limited ? visible.slice(0, RENDER_LINES) : visible
939
+ const hasBody = visible.length > 0
940
+ return h('div', { className: 'dg-file-block' },
941
+ showHeader
942
+ ? h('div', { className: 'dg-file-block-head' },
943
+ h(FileIcon, { size: 13 }),
944
+ h('span', { className: 'dg-file-block-path', title: file.path }, file.path),
945
+ file.originalPath !== null && file.originalPath !== undefined && file.originalPath !== file.path
946
+ ? h('span', { className: 'dg-file-block-orig' }, `← ${file.originalPath}`)
947
+ : null,
948
+ file.binary ? h('span', { className: 'dg-tag' }, t('binaryDiff')) : null)
949
+ : null,
950
+ file.binary
951
+ ? h('div', { className: 'dg-meta-row' }, t('binaryDiff'))
952
+ : hasBody
953
+ ? shown.map((line, index) => h(DiffLine, { key: index, line }))
954
+ : h('div', { className: 'dg-meta-row' }, t('noDiff')),
955
+ limited
956
+ ? h('div', { className: 'dg-diff-more' },
957
+ h(Button, {
958
+ variant: 'ghost',
959
+ onClick: () => setExpanded(true),
960
+ }, t('showAll', { n: visible.length })))
961
+ : null)
962
+ }
963
+
964
+ function DiffPane({
965
+ t, selected, bothGroups, snapshot, diff, diffPhase, diffError,
966
+ busy, onSelectGroup, onStage, onUnstage, onRefresh, onBack,
967
+ }) {
968
+ const isCommit = selected !== null && selected.kind === 'commit'
969
+ const title = isCommit
970
+ ? t('commitDetails', { hash: selected.hash.slice(0, 7) })
971
+ : selected !== null ? selected.path : t('selectFile')
972
+ const summary = useMemo(() => summarizePatch(diff), [diff])
973
+ const canToggle = !isCommit && bothGroups.unstaged && bothGroups.staged
974
+ const bodyRef = useRef(null)
975
+
976
+ useEffect(() => {
977
+ if (bodyRef.current !== null) {
978
+ bodyRef.current.scrollTop = 0
979
+ bodyRef.current.scrollLeft = 0
980
+ }
981
+ }, [selected])
982
+
983
+ let body
984
+ if (selected === null) {
985
+ body = h(EmptyState, {
986
+ icon: h(GitMark, { size: 22 }),
987
+ title: t('selectFile'),
988
+ text: t('selectFileHint'),
989
+ })
990
+ } else if (diffPhase === 'loading' && diff === null) {
991
+ body = h(EmptyState, { icon: h(Spinner, { size: 20 }), title: t('loading') })
992
+ } else if (diffPhase === 'error') {
993
+ body = h('div', { style: { padding: '16px' } },
994
+ h('div', { className: 'dg-banner dg-banner-error' },
995
+ h(WarningIcon, { size: 14 }),
996
+ h('span', { className: 'dg-banner-text' }, diffError ?? t('diffFailed')),
997
+ h(Button, { variant: 'ghost', onClick: onRefresh }, t('retry'))))
998
+ } else if (diff === null) {
999
+ body = h(EmptyState, { icon: h(Spinner, { size: 20 }), title: t('loading') })
1000
+ } else {
1001
+ const files = Array.isArray(diff.files) ? diff.files : []
1002
+ body = h('div', null,
1003
+ files.length === 0
1004
+ ? h(EmptyState, {
1005
+ icon: h(FileIcon, { size: 20 }),
1006
+ title: t('noDiff'),
1007
+ })
1008
+ : files.map((file, index) => h(DiffFile, {
1009
+ key: `${file.path}:${index}`,
1010
+ file,
1011
+ t,
1012
+ showHeader: isCommit || files.length > 1,
1013
+ })),
1014
+ diff.truncated ? h('div', { className: 'dg-meta-row' }, t('truncated')) : null)
1015
+ }
1016
+
1017
+ return h('section', { className: 'dg-diff' },
1018
+ h('div', { className: 'dg-diff-head' }, h('div', { className: 'dg-diff-title' },
1019
+ isCommit
1020
+ ? h(CommitIcon, { size: 14 })
1021
+ : selected !== null
1022
+ ? h(StatusBadge, {
1023
+ status: selected.status ?? 'M',
1024
+ title: t(statusKey(selected.status ?? 'M')),
1025
+ })
1026
+ : h(FileIcon, { size: 14 }),
1027
+ h('span', { className: 'dg-diff-path', title }, title),
1028
+ !isCommit && selected !== null && summary !== null && summary.added + summary.removed > 0
1029
+ ? h('span', { className: 'dg-diff-sub' }, `+${summary.added} −${summary.removed}`)
1030
+ : null,
1031
+ canToggle
1032
+ ? h('div', { className: 'dg-seg', role: 'group' },
1033
+ h('button', {
1034
+ type: 'button',
1035
+ className: 'dg-seg-btn',
1036
+ 'data-on': selected.group === 'unstaged',
1037
+ onClick: () => onSelectGroup('unstaged'),
1038
+ }, t('workingTree')),
1039
+ h('button', {
1040
+ type: 'button',
1041
+ className: 'dg-seg-btn',
1042
+ 'data-on': selected.group === 'staged',
1043
+ onClick: () => onSelectGroup('staged'),
1044
+ }, t('stagedVersion')))
1045
+ : null),
1046
+ h('div', { className: 'dg-diff-actions' },
1047
+ isCommit
1048
+ ? h(Button, { variant: 'ghost', onClick: onBack }, t('backToChanges'))
1049
+ : selected !== null
1050
+ ? (selected.group === 'staged'
1051
+ ? h(Button, {
1052
+ onClick: () => onUnstage(entryPaths(selected)),
1053
+ disabled: Boolean(busy),
1054
+ title: t('unstage'),
1055
+ }, h(MinusIcon, { size: 12 }), t('unstage'))
1056
+ : h(Button, {
1057
+ onClick: () => onStage(entryPaths(selected)),
1058
+ disabled: Boolean(busy),
1059
+ title: selected.group === 'conflicts' ? t('markResolved') : t('stage'),
1060
+ }, h(PlusIcon, { size: 12 }), selected.group === 'conflicts' ? t('markResolved') : t('stage')))
1061
+ : null,
1062
+ h(IconButton, {
1063
+ title: t('refresh'),
1064
+ onClick: onRefresh,
1065
+ disabled: Boolean(busy),
1066
+ }, busy ? h(Spinner, { size: 13 }) : h(RefreshIcon, { size: 13 })))),
1067
+ isCommit && diff !== null && diff.commit !== undefined
1068
+ ? h('div', { className: 'dg-commit-detail' },
1069
+ h('span', { className: 'dg-commit-detail-subject' }, diff.commit.subject),
1070
+ h('span', { className: 'dg-commit-detail-meta' },
1071
+ `${diff.commit.author} · ${relativeTime(diff.commit.date, t)} · ${diff.commit.short}`))
1072
+ : null,
1073
+ h('div', { className: 'dg-diff-body', ref: bodyRef }, body))
1074
+ }
1075
+
1076
+ //#endregion
1077
+
1078
+ //#region lists
1079
+
1080
+ function FileRow({
1081
+ t, entry, group, active, onSelect, onStage, onUnstage, onDiscard, busy,
1082
+ }) {
1083
+ const { dir, base } = splitPath(entry.path)
1084
+ return h('div', { className: 'dg-file', 'data-active': active ? 'true' : 'false' },
1085
+ h('button', {
1086
+ type: 'button',
1087
+ className: 'dg-file-main',
1088
+ onClick: () => onSelect(entry, group),
1089
+ title: entry.path,
1090
+ },
1091
+ h(StatusBadge, { status: entry.status, title: t(statusKey(entry.status)) }),
1092
+ h('span', { className: 'dg-file-name' },
1093
+ dir !== '' ? h('span', { className: 'dg-dir' }, dir) : null,
1094
+ base),
1095
+ entry.originalPath !== null && entry.originalPath !== undefined && entry.originalPath !== entry.path
1096
+ ? h('span', { className: 'dg-file-orig', title: entry.originalPath }, `← ${entry.originalPath}`)
1097
+ : null),
1098
+ h('div', { className: 'dg-file-actions' },
1099
+ group === 'staged'
1100
+ ? h(IconButton, {
1101
+ title: t('unstage'),
1102
+ onClick: () => onUnstage(entryPaths(entry)),
1103
+ disabled: Boolean(busy),
1104
+ }, h(MinusIcon, { size: 12 }))
1105
+ : h(IconButton, {
1106
+ title: group === 'conflicts' ? t('markResolved') : t('stage'),
1107
+ onClick: () => onStage(entryPaths(entry)),
1108
+ disabled: Boolean(busy),
1109
+ }, h(PlusIcon, { size: 12 })),
1110
+ group === 'unstaged'
1111
+ ? h(IconButton, {
1112
+ title: t('discard'),
1113
+ onClick: () => onDiscard([entry]),
1114
+ disabled: Boolean(busy),
1115
+ }, h(UndoIcon, { size: 12 }))
1116
+ : null))
1117
+ }
1118
+
1119
+ function FileSection({
1120
+ t, title, entries, open, onToggle, emptyText, actionIcon, actionTitle, onAction,
1121
+ group, selected, onSelect, onStage, onUnstage, onDiscard, busy,
1122
+ }) {
1123
+ return h('section', { className: 'dg-section' },
1124
+ h('div', { className: 'dg-section-head' },
1125
+ h('button', {
1126
+ type: 'button',
1127
+ className: 'dg-section-toggle',
1128
+ 'aria-expanded': open,
1129
+ onClick: onToggle,
1130
+ },
1131
+ open ? h(ChevronDown, { size: 11 }) : h(ChevronRight, { size: 11 }),
1132
+ h('span', { className: 'dg-section-title' }, title),
1133
+ h('span', { className: 'dg-count' }, entries.length)),
1134
+ actionIcon !== undefined
1135
+ ? h(IconButton, {
1136
+ title: actionTitle,
1137
+ onClick: onAction,
1138
+ disabled: entries.length === 0 || Boolean(busy),
1139
+ }, actionIcon)
1140
+ : null),
1141
+ open
1142
+ ? (entries.length === 0
1143
+ ? h('div', { className: 'dg-section-empty' }, emptyText)
1144
+ : entries.map((entry) => h(FileRow, {
1145
+ key: `${group}:${entry.path}`,
1146
+ t,
1147
+ entry,
1148
+ group,
1149
+ active: selected !== null && selected.kind === 'file' && selected.group === group && selected.path === entry.path,
1150
+ onSelect,
1151
+ onStage,
1152
+ onUnstage,
1153
+ onDiscard,
1154
+ busy,
1155
+ })))
1156
+ : null)
1157
+ }
1158
+
1159
+ function HistorySection({
1160
+ t, commits, open, onToggle, selected, onSelect,
1161
+ }) {
1162
+ return h('section', { className: 'dg-section' },
1163
+ h('div', { className: 'dg-section-head' },
1164
+ h('button', {
1165
+ type: 'button',
1166
+ className: 'dg-section-toggle',
1167
+ 'aria-expanded': open,
1168
+ onClick: onToggle,
1169
+ },
1170
+ open ? h(ChevronDown, { size: 11 }) : h(ChevronRight, { size: 11 }),
1171
+ h('span', { className: 'dg-section-title' }, t('history')),
1172
+ h('span', { className: 'dg-count' }, commits.length))),
1173
+ open
1174
+ ? (commits.length === 0
1175
+ ? h('div', { className: 'dg-section-empty' }, t('noCommits'))
1176
+ : commits.map((commitEntry) => h('button', {
1177
+ key: commitEntry.hash,
1178
+ type: 'button',
1179
+ className: 'dg-commit-row-button',
1180
+ 'data-active': selected !== null && selected.kind === 'commit' && selected.hash === commitEntry.hash ? 'true' : 'false',
1181
+ style: selected !== null && selected.kind === 'commit' && selected.hash === commitEntry.hash
1182
+ ? { background: 'var(--dsw-alias-bg-layer-2)' }
1183
+ : undefined,
1184
+ onClick: () => onSelect(commitEntry),
1185
+ },
1186
+ h('span', { className: 'dg-commit-line' },
1187
+ h('span', { className: 'dg-hash' }, commitEntry.short),
1188
+ h('span', { className: 'dg-subject', title: commitEntry.subject }, commitEntry.subject)),
1189
+ h('span', { className: 'dg-commit-meta' },
1190
+ `${commitEntry.author} · ${relativeTime(commitEntry.date, t)}`))))
1191
+ : null)
1192
+ }
1193
+
1194
+ //#endregion
1195
+
1196
+ //#region panel
1197
+
1198
+ function CommitBox({
1199
+ t, message, onMessage, amend, onAmend, stagedCount, unstagedCount,
1200
+ canCommit, canGenerate, generating, busy, onCommit, onStageAll, onGenerate, textareaRef,
1201
+ modelCatalog, modelSelection, modelError, onModelChange,
1202
+ }) {
1203
+ const onKeyDown = (event) => {
1204
+ if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
1205
+ event.preventDefault()
1206
+ onCommit()
1207
+ }
1208
+ }
1209
+ const models = Array.isArray(modelCatalog?.models) ? modelCatalog.models : []
1210
+ const providers = Array.isArray(modelCatalog?.providers) ? modelCatalog.providers : []
1211
+ const selectedKey = modelSelection === null ? '' : modelKey(modelSelection.provider, modelSelection.model)
1212
+ const defaultSelection = modelCatalog?.default ?? null
1213
+ const defaultModel = defaultSelection === null
1214
+ ? null
1215
+ : models.find((model) => model.provider === defaultSelection.provider && model.model === defaultSelection.model) ?? null
1216
+ const defaultLabel = defaultModel === null
1217
+ ? t('modelDefault')
1218
+ : `${t('modelDefault')} · ${defaultModel.name}`
1219
+ const modelDisabled = modelCatalog === null || models.length === 0
1220
+ const modelTitle = modelError !== null && modelError !== undefined
1221
+ ? t('modelsUnavailable')
1222
+ : modelCatalog === null
1223
+ ? t('modelsLoading')
1224
+ : models.length === 0 ? t('modelsUnavailable') : t('modelHint')
1225
+ return h('div', { className: 'dg-commit' },
1226
+ h('div', { className: 'dg-model-row' },
1227
+ h('span', { className: 'dg-model-label' }, t('aiModel')),
1228
+ h('select', {
1229
+ className: 'dg-model-select',
1230
+ value: selectedKey,
1231
+ disabled: modelDisabled,
1232
+ title: modelTitle,
1233
+ 'aria-label': t('aiModel'),
1234
+ onChange: (event) => {
1235
+ const value = event.target.value
1236
+ if (value === '') {
1237
+ onModelChange(null)
1238
+ return
1239
+ }
1240
+ const parsed = parseModelKey(value)
1241
+ if (parsed !== null) onModelChange(parsed)
1242
+ },
1243
+ },
1244
+ h('option', { value: '' }, defaultLabel),
1245
+ providers.map((provider) => {
1246
+ const group = models.filter((model) => model.provider === provider.id)
1247
+ if (group.length === 0) return null
1248
+ return h('optgroup', { key: provider.id, label: provider.name },
1249
+ group.map((model) => h('option', {
1250
+ key: modelKey(provider.id, model.model),
1251
+ value: modelKey(provider.id, model.model),
1252
+ }, model.name)))
1253
+ }))),
1254
+ h('textarea', {
1255
+ ref: textareaRef,
1256
+ className: 'dg-textarea',
1257
+ value: message,
1258
+ placeholder: t('commitPlaceholder'),
1259
+ 'aria-label': t('commitPlaceholder'),
1260
+ rows: 3,
1261
+ spellCheck: false,
1262
+ onChange: (event) => onMessage(event.target.value),
1263
+ onKeyDown,
1264
+ }),
1265
+ h('div', { className: 'dg-commit-row' },
1266
+ h('label', { className: 'dg-check', title: t('amendHint') },
1267
+ h('input', {
1268
+ type: 'checkbox',
1269
+ checked: amend,
1270
+ onChange: (event) => onAmend(event.target.checked),
1271
+ }),
1272
+ t('amend')),
1273
+ h('span', { className: 'dg-commit-count' }, t('stagedCount', { n: stagedCount }))),
1274
+ h('div', { className: 'dg-commit-actions' },
1275
+ h(Button, {
1276
+ variant: 'ghost',
1277
+ onClick: onGenerate,
1278
+ disabled: generating || Boolean(busy) || !canGenerate,
1279
+ title: generating
1280
+ ? t('generatingMessage')
1281
+ : canGenerate ? t('generateHint') : t('noChangesHint'),
1282
+ },
1283
+ generating ? h(Spinner, { size: 12 }) : h(SparklesIcon, { size: 12 }),
1284
+ t('generateMessage')),
1285
+ unstagedCount > 0
1286
+ ? h(Button, {
1287
+ variant: 'ghost',
1288
+ onClick: onStageAll,
1289
+ disabled: Boolean(busy),
1290
+ title: t('stageAll'),
1291
+ }, t('stageAll'))
1292
+ : null,
1293
+ h(Button, {
1294
+ variant: 'primary',
1295
+ onClick: onCommit,
1296
+ disabled: !canCommit,
1297
+ title: stagedCount === 0
1298
+ ? t('nothingStaged')
1299
+ : message.trim() === '' ? t('commitMessageRequired') : undefined,
1300
+ }, busy === t('committing') ? h(Spinner, { size: 12 }) : h(CommitIcon, { size: 12 }), t('commit'))))
1301
+ }
1302
+
1303
+ function DiscardDialog({ t, targets, onCancel, onConfirm, busy }) {
1304
+ const cancelRef = useRef(null)
1305
+ useEffect(() => {
1306
+ cancelRef.current?.focus?.()
1307
+ }, [])
1308
+ useEffect(() => {
1309
+ const onKeyDown = (event) => {
1310
+ if (event.key === 'Escape') onCancel()
1311
+ }
1312
+ document.addEventListener('keydown', onKeyDown)
1313
+ return () => document.removeEventListener('keydown', onKeyDown)
1314
+ }, [onCancel])
1315
+ const untracked = targets.some((entry) => entry.untracked === true)
1316
+ return h('div', {
1317
+ className: 'dg-modal-backdrop',
1318
+ onMouseDown: (event) => {
1319
+ if (event.target === event.currentTarget) onCancel()
1320
+ },
1321
+ },
1322
+ h('div', {
1323
+ className: 'dg-modal',
1324
+ role: 'dialog',
1325
+ 'aria-modal': 'true',
1326
+ 'aria-label': t('discardTitle'),
1327
+ },
1328
+ h('span', { className: 'dg-modal-title' }, t('discardTitle')),
1329
+ h('span', { className: 'dg-modal-text' }, untracked ? t('discardUntrackedText') : t('discardText')),
1330
+ h('span', { className: 'dg-modal-path' },
1331
+ targets.length === 1 ? targets[0].path : t('filesCount', { n: targets.length })),
1332
+ h('div', { className: 'dg-modal-actions' },
1333
+ h('button', {
1334
+ type: 'button',
1335
+ ref: cancelRef,
1336
+ className: 'dg-btn',
1337
+ onClick: onCancel,
1338
+ }, t('cancel')),
1339
+ h('button', {
1340
+ type: 'button',
1341
+ className: 'dg-btn dg-btn-danger',
1342
+ onClick: onConfirm,
1343
+ disabled: Boolean(busy),
1344
+ }, t('discardConfirm')))))
1345
+ }
1346
+
1347
+ function UpstreamDialog({
1348
+ t, repo, remotes, remote, branch, branches, phase, error, busy,
1349
+ onRemote, onBranch, onCancel, onSave,
1350
+ }) {
1351
+ const cancelRef = useRef(null)
1352
+ useEffect(() => {
1353
+ cancelRef.current?.focus?.()
1354
+ }, [])
1355
+ useEffect(() => {
1356
+ const onKeyDown = (event) => {
1357
+ if (event.key === 'Escape') onCancel()
1358
+ }
1359
+ document.addEventListener('keydown', onKeyDown)
1360
+ return () => document.removeEventListener('keydown', onKeyDown)
1361
+ }, [onCancel])
1362
+ const canSave = remote !== '' && branch !== '' && branches.includes(branch) && phase === 'ready' && !busy
1363
+ return h('div', {
1364
+ className: 'dg-modal-backdrop',
1365
+ onMouseDown: (event) => {
1366
+ if (event.target === event.currentTarget) onCancel()
1367
+ },
1368
+ },
1369
+ h('div', {
1370
+ className: 'dg-modal',
1371
+ role: 'dialog',
1372
+ 'aria-modal': 'true',
1373
+ 'aria-label': t('setUpstreamTitle'),
1374
+ },
1375
+ h('span', { className: 'dg-modal-title' }, t('setUpstreamTitle')),
1376
+ h('span', { className: 'dg-modal-text' }, t('setUpstreamText', { branch: repo?.branch ?? '' })),
1377
+ remotes.length === 0
1378
+ ? h('span', { className: 'dg-modal-text' }, t('noRemotes'))
1379
+ : h(React.Fragment, null,
1380
+ h('label', { className: 'dg-field' },
1381
+ h('span', { className: 'dg-field-label' }, t('remote')),
1382
+ h('select', {
1383
+ className: 'dg-input dg-select',
1384
+ value: remote,
1385
+ disabled: Boolean(busy),
1386
+ onChange: (event) => onRemote(event.target.value),
1387
+ },
1388
+ remotes.map((entry) => h('option', { key: entry.name, value: entry.name },
1389
+ entry.url ? `${entry.name} — ${entry.url}` : entry.name)))),
1390
+ h('label', { className: 'dg-field' },
1391
+ h('span', { className: 'dg-field-label' }, t('remoteBranch')),
1392
+ h('select', {
1393
+ className: 'dg-input dg-select',
1394
+ value: branch,
1395
+ disabled: Boolean(busy) || phase === 'loading' || branches.length === 0,
1396
+ onChange: (event) => onBranch(event.target.value),
1397
+ },
1398
+ phase === 'loading'
1399
+ ? h('option', { value: '' }, t('loadingBranches'))
1400
+ : branches.length === 0
1401
+ ? h('option', { value: '' }, t('noRemoteBranches'))
1402
+ : branches.map((name) => h('option', { key: name, value: name }, name)))),
1403
+ repo?.branch && phase === 'ready' && branches.length > 0 && !branches.includes(repo.branch)
1404
+ ? h('span', { className: 'dg-modal-text' }, t('upstreamPushHint', { branch: repo.branch }))
1405
+ : null),
1406
+ error !== null ? h('span', { className: 'dg-modal-error' }, error) : null,
1407
+ h('div', { className: 'dg-modal-actions' },
1408
+ h('button', {
1409
+ type: 'button',
1410
+ ref: cancelRef,
1411
+ className: 'dg-btn',
1412
+ onClick: onCancel,
1413
+ }, t('cancel')),
1414
+ h('button', {
1415
+ type: 'button',
1416
+ className: 'dg-btn dg-btn-primary',
1417
+ onClick: onSave,
1418
+ disabled: !canSave,
1419
+ }, busy === t('savingUpstream') ? h(Spinner, { size: 12 }) : null, t('save')))))
1420
+ }
1421
+
1422
+ function DeleteBranchDialog({ t, branch, onCancel, onConfirm, busy }) {
1423
+ const cancelRef = useRef(null)
1424
+ useEffect(() => {
1425
+ cancelRef.current?.focus?.()
1426
+ }, [])
1427
+ useEffect(() => {
1428
+ const onKeyDown = (event) => {
1429
+ if (event.key === 'Escape') onCancel()
1430
+ }
1431
+ document.addEventListener('keydown', onKeyDown)
1432
+ return () => document.removeEventListener('keydown', onKeyDown)
1433
+ }, [onCancel])
1434
+ return h('div', {
1435
+ className: 'dg-modal-backdrop',
1436
+ onMouseDown: (event) => {
1437
+ if (event.target === event.currentTarget) onCancel()
1438
+ },
1439
+ },
1440
+ h('div', {
1441
+ className: 'dg-modal',
1442
+ role: 'dialog',
1443
+ 'aria-modal': 'true',
1444
+ 'aria-label': t('deleteBranchTitle'),
1445
+ },
1446
+ h('span', { className: 'dg-modal-title' }, t('deleteBranchTitle')),
1447
+ h('span', { className: 'dg-modal-text' }, t('deleteBranchText', { branch })),
1448
+ h('div', { className: 'dg-modal-actions' },
1449
+ h('button', {
1450
+ type: 'button',
1451
+ ref: cancelRef,
1452
+ className: 'dg-btn',
1453
+ onClick: onCancel,
1454
+ }, t('cancel')),
1455
+ h('button', {
1456
+ type: 'button',
1457
+ className: 'dg-btn dg-btn-danger',
1458
+ onClick: onConfirm,
1459
+ disabled: Boolean(busy),
1460
+ }, t('delete')))))
1461
+ }
1462
+
1463
+ function RemoteManagerDialog({
1464
+ t, remotes, name, url, onName, onUrl, onAdd, onRemove, onFetch, onClose, busy,
1465
+ }) {
1466
+ const closeRef = useRef(null)
1467
+ useEffect(() => {
1468
+ closeRef.current?.focus?.()
1469
+ }, [])
1470
+ useEffect(() => {
1471
+ const onKeyDown = (event) => {
1472
+ if (event.key === 'Escape') onClose()
1473
+ }
1474
+ document.addEventListener('keydown', onKeyDown)
1475
+ return () => document.removeEventListener('keydown', onKeyDown)
1476
+ }, [onClose])
1477
+ const canAdd = name.trim() !== '' && url.trim() !== '' && !busy
1478
+ return h('div', {
1479
+ className: 'dg-modal-backdrop',
1480
+ onMouseDown: (event) => {
1481
+ if (event.target === event.currentTarget) onClose()
1482
+ },
1483
+ },
1484
+ h('div', {
1485
+ className: 'dg-modal',
1486
+ role: 'dialog',
1487
+ 'aria-modal': 'true',
1488
+ 'aria-label': t('remotesTitle'),
1489
+ },
1490
+ h('span', { className: 'dg-modal-title' }, t('remotesTitle')),
1491
+ h('span', { className: 'dg-modal-text' }, t('remotesText')),
1492
+ remotes.length === 0
1493
+ ? h('span', { className: 'dg-modal-text' }, t('noRemotesConfigured'))
1494
+ : h('div', { className: 'dg-remote-list' },
1495
+ remotes.map((remote) => h('div', { className: 'dg-remote-row', key: remote.name },
1496
+ h('div', { className: 'dg-remote-info' },
1497
+ h('span', { className: 'dg-remote-name' }, remote.name),
1498
+ h('span', { className: 'dg-remote-url', title: remote.url }, remote.url)),
1499
+ h('button', {
1500
+ type: 'button',
1501
+ className: 'dg-branch-delete',
1502
+ title: t('removeRemote'),
1503
+ 'aria-label': t('removeRemote'),
1504
+ disabled: Boolean(busy),
1505
+ onClick: () => onRemove(remote.name),
1506
+ }, h(TrashIcon, { size: 12 }))))),
1507
+ h('span', { className: 'dg-modal-text' }, t('remoteInUseWarning')),
1508
+ h('label', { className: 'dg-field' },
1509
+ h('span', { className: 'dg-field-label' }, t('remoteName')),
1510
+ h('input', {
1511
+ className: 'dg-input dg-select',
1512
+ value: name,
1513
+ placeholder: 'origin',
1514
+ 'aria-label': t('remoteName'),
1515
+ disabled: Boolean(busy),
1516
+ onChange: (event) => onName(event.target.value),
1517
+ })),
1518
+ h('label', { className: 'dg-field' },
1519
+ h('span', { className: 'dg-field-label' }, t('remoteUrl')),
1520
+ h('input', {
1521
+ className: 'dg-input dg-select',
1522
+ value: url,
1523
+ placeholder: t('remoteUrlPlaceholder'),
1524
+ 'aria-label': t('remoteUrl'),
1525
+ disabled: Boolean(busy),
1526
+ onChange: (event) => onUrl(event.target.value),
1527
+ })),
1528
+ h('div', { className: 'dg-modal-actions' },
1529
+ h('button', {
1530
+ type: 'button',
1531
+ className: 'dg-btn',
1532
+ onClick: onFetch,
1533
+ disabled: Boolean(busy),
1534
+ }, t('fetch')),
1535
+ h('button', {
1536
+ type: 'button',
1537
+ className: 'dg-btn dg-btn-primary',
1538
+ onClick: onAdd,
1539
+ disabled: !canAdd,
1540
+ }, busy === t('addingRemote') ? h(Spinner, { size: 12 }) : null, t('addRemote')),
1541
+ h('button', {
1542
+ type: 'button',
1543
+ ref: closeRef,
1544
+ className: 'dg-btn',
1545
+ onClick: onClose,
1546
+ }, t('close')))))
1547
+ }
1548
+
1549
+ function RepoManager({
1550
+ t, workspaceTitle, workspacePath, discovered, enabled, scanPhase, scanError, scanTruncated,
1551
+ onToggle, onSelectAll, onClear, onRescan, onClose,
1552
+ }) {
1553
+ const closeRef = useRef(null)
1554
+ useEffect(() => {
1555
+ closeRef.current?.focus?.()
1556
+ }, [])
1557
+ useEffect(() => {
1558
+ const onKeyDown = (event) => {
1559
+ if (event.key === 'Escape') onClose()
1560
+ }
1561
+ document.addEventListener('keydown', onKeyDown)
1562
+ return () => document.removeEventListener('keydown', onKeyDown)
1563
+ }, [onClose])
1564
+ const selected = enabled ?? []
1565
+ return h('div', {
1566
+ className: 'dg-modal-backdrop',
1567
+ onMouseDown: (event) => {
1568
+ if (event.target === event.currentTarget) onClose()
1569
+ },
1570
+ },
1571
+ h('div', {
1572
+ className: 'dg-modal dg-modal-wide',
1573
+ role: 'dialog',
1574
+ 'aria-modal': 'true',
1575
+ 'aria-label': t('repositoriesTitle', { workspace: workspaceTitle }),
1576
+ },
1577
+ h('span', { className: 'dg-modal-title' }, t('repositoriesTitle', { workspace: workspaceTitle })),
1578
+ h('span', { className: 'dg-modal-text' }, t('repositoriesHint')),
1579
+ h('div', { className: 'dg-manager-meta' },
1580
+ h('span', null, t('detectedRepos', { n: discovered.length })),
1581
+ scanPhase === 'loading' ? h(Spinner, { size: 12 }) : null),
1582
+ scanPhase === 'loading' && discovered.length === 0
1583
+ ? h('div', { className: 'dg-repo-list' },
1584
+ h('div', { className: 'dg-repo-row' }, h(Spinner, { size: 14 }), h('span', { className: 'dg-repo-name' }, t('scanning'))))
1585
+ : discovered.length === 0
1586
+ ? h('div', { className: 'dg-repo-list' },
1587
+ h('div', { className: 'dg-repo-row' }, h('span', { className: 'dg-repo-name' }, t('noRepositoriesFound'))))
1588
+ : h('div', { className: 'dg-repo-list' },
1589
+ discovered.map((repoEntry) => h('label', { key: repoEntry.path, className: 'dg-repo-row' },
1590
+ h('input', {
1591
+ type: 'checkbox',
1592
+ checked: selected.some((path) => samePath(path, repoEntry.path)),
1593
+ onChange: () => onToggle(repoEntry),
1594
+ }),
1595
+ h('span', { className: 'dg-repo-main' },
1596
+ h('span', { className: 'dg-repo-name' },
1597
+ repoEntry.relativePath === '.' ? t('rootRepository') : repoEntry.name),
1598
+ h('span', { className: 'dg-repo-path', title: repoEntry.path },
1599
+ repoEntry.relativePath === '.' ? workspacePath : repoEntry.relativePath))))),
1600
+ scanTruncated ? h('span', { className: 'dg-manager-meta' }, t('scanTruncated')) : null,
1601
+ scanError !== null
1602
+ ? h('span', { className: 'dg-banner dg-banner-error' }, h('span', { className: 'dg-banner-text' }, scanError))
1603
+ : null,
1604
+ h('div', { className: 'dg-manager-actions' },
1605
+ h(Button, { onClick: onRescan, disabled: scanPhase === 'loading' }, t('scanAgain')),
1606
+ h(Button, { onClick: onSelectAll, disabled: discovered.length === 0 || scanPhase === 'loading' }, t('selectAll')),
1607
+ h(Button, { onClick: onClear, disabled: selected.length === 0 }, t('clearSelection')),
1608
+ h('span', { className: 'dg-manager-spacer' }),
1609
+ h('button', {
1610
+ type: 'button',
1611
+ ref: closeRef,
1612
+ className: 'dg-btn dg-btn-primary',
1613
+ onClick: onClose,
1614
+ }, t('close')))))
1615
+ }
1616
+
1617
+ function GitPanel({ t, call, getLocaleId }) {
1618
+ const [repos, setRepos] = useState(null)
1619
+ const [reposNonce, setReposNonce] = useState(0)
1620
+ const [workspacePath, setWorkspacePath] = useState(() => readLocal(WORKSPACE_KEY) ?? readLocal(REPO_KEY))
1621
+ const [discovered, setDiscovered] = useState([])
1622
+ const [scanPhase, setScanPhase] = useState('idle')
1623
+ const [scanError, setScanError] = useState(null)
1624
+ const [scanTruncated, setScanTruncated] = useState(false)
1625
+ const [scanNonce, setScanNonce] = useState(0)
1626
+ const [enabled, setEnabled] = useState(null)
1627
+ const [activeRepoPath, setActiveRepoPath] = useState(null)
1628
+ const [managerOpen, setManagerOpen] = useState(false)
1629
+ const [snapshot, setSnapshot] = useState(null)
1630
+ const [phase, setPhase] = useState('loading')
1631
+ const [error, setError] = useState(null)
1632
+ const [notice, setNotice] = useState(null)
1633
+ const [busy, setBusy] = useState(null)
1634
+ const [selected, setSelected] = useState(null)
1635
+ const [diff, setDiff] = useState(null)
1636
+ const [diffPhase, setDiffPhase] = useState('idle')
1637
+ const [diffError, setDiffError] = useState(null)
1638
+ const [diffNonce, setDiffNonce] = useState(0)
1639
+ const [message, setMessage] = useState('')
1640
+ const [generatingMessage, setGeneratingMessage] = useState(false)
1641
+ const [amend, setAmend] = useState(false)
1642
+ const [menu, setMenu] = useState(null)
1643
+ const [branchDraft, setBranchDraft] = useState('')
1644
+ const [discardTargets, setDiscardTargets] = useState(null)
1645
+ const [openSections, setOpenSections] = useState({ conflicts: true, staged: true, changes: true, history: true })
1646
+ const [modelCatalog, setModelCatalog] = useState(null)
1647
+ const [modelSelection, setModelSelection] = useState(readModelSelection)
1648
+ const [modelError, setModelError] = useState(null)
1649
+ const [upstreamOpen, setUpstreamOpen] = useState(false)
1650
+ const [upstreamRemote, setUpstreamRemote] = useState('')
1651
+ const [upstreamBranch, setUpstreamBranch] = useState('')
1652
+ const [upstreamBranches, setUpstreamBranches] = useState([])
1653
+ const [upstreamPhase, setUpstreamPhase] = useState('idle')
1654
+ const [upstreamError, setUpstreamError] = useState(null)
1655
+ const [deleteTarget, setDeleteTarget] = useState(null)
1656
+ const [remoteManagerOpen, setRemoteManagerOpen] = useState(false)
1657
+ const [remoteName, setRemoteName] = useState('origin')
1658
+ const [remoteUrl, setRemoteUrl] = useState('')
1659
+
1660
+ const busyRef = useRef(null)
1661
+ busyRef.current = busy
1662
+ const stateSeq = useRef(0)
1663
+ const statePending = useRef(0)
1664
+ const diffSeq = useRef(0)
1665
+ const sideRef = useRef(null)
1666
+ const messageRef = useRef(null)
1667
+ const messageSeq = useRef(0)
1668
+ const enabledRef = useRef(enabled)
1669
+ enabledRef.current = enabled
1670
+ const activeRepoRef = useRef(activeRepoPath)
1671
+ activeRepoRef.current = activeRepoPath
1672
+ const scannedWorkspaceRef = useRef(null)
1673
+
1674
+ /** A persisted model is usable only while the catalog still offers it. */
1675
+ const effectiveModel = useMemo(() => {
1676
+ if (modelSelection === null) return null
1677
+ const models = Array.isArray(modelCatalog?.models) ? modelCatalog.models : null
1678
+ if (models === null) return null
1679
+ return models.some((model) => model.provider === modelSelection.provider && model.model === modelSelection.model)
1680
+ ? modelSelection
1681
+ : null
1682
+ }, [modelCatalog, modelSelection])
1683
+
1684
+ const changeModel = useCallback((selection) => {
1685
+ setModelSelection(selection)
1686
+ writeModelSelection(selection)
1687
+ }, [])
1688
+
1689
+ useEffect(() => {
1690
+ if (sideRef.current !== null) sideRef.current.scrollTop = 0
1691
+ }, [activeRepoPath])
1692
+
1693
+ const loadState = useCallback(async ({ quiet = false } = {}) => {
1694
+ if (!activeRepoPath) return null
1695
+ if (quiet && statePending.current > 0) return null
1696
+ const seq = ++stateSeq.current
1697
+ statePending.current += 1
1698
+ if (!quiet) setPhase((current) => (current === 'ready' ? current : 'loading'))
1699
+ try {
1700
+ const value = await call('state', { cwd: activeRepoPath })
1701
+ if (seq !== stateSeq.current) return null
1702
+ setSnapshot(value)
1703
+ setPhase('ready')
1704
+ if (!quiet) setError(null)
1705
+ return value
1706
+ } catch (failure) {
1707
+ if (seq !== stateSeq.current) return null
1708
+ const message = failure?.message ?? String(failure)
1709
+ if (quiet) {
1710
+ console.warn('[dsh-git] background refresh failed:', message)
1711
+ return null
1712
+ }
1713
+ setPhase('error')
1714
+ setError(message)
1715
+ return null
1716
+ } finally {
1717
+ statePending.current -= 1
1718
+ }
1719
+ }, [call, activeRepoPath])
1720
+
1721
+ // 1. Read the Workspace roster once, then pick the remembered workspace.
1722
+ useEffect(() => {
1723
+ let alive = true
1724
+ call('repos', {}).then((value) => {
1725
+ if (!alive) return
1726
+ const list = Array.isArray(value?.workspaces) ? value.workspaces : []
1727
+ setRepos(list)
1728
+ setWorkspacePath((current) => {
1729
+ const remembered = current === null ? undefined : list.find((repo) => samePath(repo.path, current))
1730
+ return remembered !== undefined ? remembered.path : (list[0]?.path ?? null)
1731
+ })
1732
+ }).catch((failure) => {
1733
+ if (!alive) return
1734
+ setRepos([])
1735
+ setPhase('error')
1736
+ setError(failure?.message ?? String(failure))
1737
+ })
1738
+ return () => { alive = false }
1739
+ }, [call, reposNonce])
1740
+
1741
+ useEffect(() => {
1742
+ if (workspacePath) writeLocal(WORKSPACE_KEY, workspacePath)
1743
+ }, [workspacePath])
1744
+
1745
+ // 1b. Read the model catalog used by the commit-message picker.
1746
+ useEffect(() => {
1747
+ let alive = true
1748
+ call('models', {}).then((value) => {
1749
+ if (!alive) return
1750
+ setModelCatalog(value !== null && typeof value === 'object' ? value : null)
1751
+ setModelError(null)
1752
+ }).catch((failure) => {
1753
+ if (!alive) return
1754
+ setModelCatalog(null)
1755
+ setModelError(failure?.message ?? String(failure))
1756
+ })
1757
+ return () => { alive = false }
1758
+ }, [call])
1759
+
1760
+ // 1c. Load the remote branches while the upstream dialog is open.
1761
+ useEffect(() => {
1762
+ if (!upstreamOpen || !activeRepoPath || upstreamRemote === '') return undefined
1763
+ let alive = true
1764
+ setUpstreamPhase('loading')
1765
+ setUpstreamError(null)
1766
+ call('remoteBranches', { cwd: activeRepoPath, remote: upstreamRemote }).then((value) => {
1767
+ if (!alive) return
1768
+ const list = Array.isArray(value?.branches)
1769
+ ? value.branches.filter((name) => typeof name === 'string' && name !== '')
1770
+ : []
1771
+ setUpstreamBranches(list)
1772
+ setUpstreamPhase('ready')
1773
+ setUpstreamBranch((current) => {
1774
+ if (current !== '' && list.includes(current)) return current
1775
+ const currentBranch = snapshot?.repo?.branch
1776
+ if (typeof currentBranch === 'string' && list.includes(currentBranch)) return currentBranch
1777
+ return list[0] ?? ''
1778
+ })
1779
+ }).catch((failure) => {
1780
+ if (!alive) return
1781
+ setUpstreamBranches([])
1782
+ setUpstreamPhase('error')
1783
+ setUpstreamError(failure?.message ?? String(failure))
1784
+ })
1785
+ return () => { alive = false }
1786
+ }, [activeRepoPath, call, snapshot?.repo?.branch, upstreamOpen, upstreamRemote])
1787
+
1788
+ // 2a. Reset the page when the Workspace changes and restore its selection.
1789
+ useEffect(() => {
1790
+ setSnapshot(null)
1791
+ setSelected(null)
1792
+ setDiff(null)
1793
+ setDiffPhase('idle')
1794
+ setDiffError(null)
1795
+ setAmend(false)
1796
+ setMenu(null)
1797
+ setDiscardTargets(null)
1798
+ setManagerOpen(false)
1799
+ setDiscovered([])
1800
+ setScanPhase('idle')
1801
+ setScanError(null)
1802
+ setScanTruncated(false)
1803
+ setEnabled(readEnabledList(workspacePath))
1804
+ setActiveRepoPath(readActiveRepo(workspacePath))
1805
+ messageSeq.current += 1
1806
+ setGeneratingMessage(false)
1807
+ if (!workspacePath) {
1808
+ setPhase('ready')
1809
+ return
1810
+ }
1811
+ setPhase('loading')
1812
+ }, [workspacePath])
1813
+
1814
+ // 2b. Read the active repository.
1815
+ useEffect(() => {
1816
+ setSnapshot(null)
1817
+ setSelected(null)
1818
+ setDiff(null)
1819
+ setDiffPhase('idle')
1820
+ setDiffError(null)
1821
+ setAmend(false)
1822
+ setMenu(null)
1823
+ setDiscardTargets(null)
1824
+ messageSeq.current += 1
1825
+ setGeneratingMessage(false)
1826
+ if (!activeRepoPath) {
1827
+ setPhase('ready')
1828
+ return
1829
+ }
1830
+ setMessage(readLocal(DRAFT_PREFIX + activeRepoPath) ?? '')
1831
+ setPhase('loading')
1832
+ void loadState()
1833
+ }, [activeRepoPath, loadState])
1834
+
1835
+ // 2c. Discover the repositories below the selected Workspace.
1836
+ useEffect(() => {
1837
+ if (!workspacePath) return undefined
1838
+ let alive = true
1839
+ setScanPhase('loading')
1840
+ setScanError(null)
1841
+ call('scan', { cwd: workspacePath }).then((value) => {
1842
+ if (!alive) return
1843
+ const list = Array.isArray(value?.repos) ? value.repos : []
1844
+ const sameWorkspace = scannedWorkspaceRef.current === workspacePath
1845
+ const saved = sameWorkspace ? enabledRef.current : readEnabledList(workspacePath)
1846
+ const nextEnabled = saved === null
1847
+ ? list.map((repo) => repo.path)
1848
+ : saved.filter((candidate) => list.some((repo) => samePath(repo.path, candidate)))
1849
+ setDiscovered(list)
1850
+ setScanTruncated(value?.truncated === true)
1851
+ setScanPhase('ready')
1852
+ setEnabled(nextEnabled)
1853
+ writeEnabledList(workspacePath, nextEnabled)
1854
+ const savedActive = sameWorkspace ? activeRepoRef.current : readActiveRepo(workspacePath)
1855
+ const nextActive = savedActive !== null && nextEnabled.some((candidate) => samePath(candidate, savedActive))
1856
+ ? savedActive
1857
+ : (nextEnabled[0] ?? null)
1858
+ setActiveRepoPath(nextActive)
1859
+ writeActiveRepo(workspacePath, nextActive)
1860
+ scannedWorkspaceRef.current = workspacePath
1861
+ }).catch((failure) => {
1862
+ if (!alive) return
1863
+ setScanPhase('error')
1864
+ setScanError(failure?.message ?? String(failure))
1865
+ })
1866
+ return () => { alive = false }
1867
+ }, [workspacePath, scanNonce, call])
1868
+
1869
+ // 3. Keep a quiet poll while the page is visible, and refresh on focus.
1870
+ useEffect(() => {
1871
+ if (!activeRepoPath) return undefined
1872
+ const timer = setInterval(() => {
1873
+ if (document.visibilityState !== 'visible' || busyRef.current) return
1874
+ void loadState({ quiet: true })
1875
+ }, 5000)
1876
+ return () => clearInterval(timer)
1877
+ }, [activeRepoPath, loadState])
1878
+
1879
+ useEffect(() => {
1880
+ if (!activeRepoPath) return undefined
1881
+ const onFocus = () => {
1882
+ if (!busyRef.current) void loadState({ quiet: true })
1883
+ }
1884
+ window.addEventListener('focus', onFocus)
1885
+ return () => window.removeEventListener('focus', onFocus)
1886
+ }, [activeRepoPath, loadState])
1887
+
1888
+ // 4. Read the selected patch; the nonce lets the refresh control repeat it.
1889
+ useEffect(() => {
1890
+ if (selected === null || !activeRepoPath) {
1891
+ setDiff(null)
1892
+ setDiffPhase('idle')
1893
+ setDiffError(null)
1894
+ return
1895
+ }
1896
+ const seq = ++diffSeq.current
1897
+ setDiffPhase('loading')
1898
+ setDiffError(null)
1899
+ const request = selected.kind === 'commit'
1900
+ ? call('show', { cwd: activeRepoPath, hash: selected.hash })
1901
+ : call('diff', {
1902
+ cwd: activeRepoPath,
1903
+ path: selected.path,
1904
+ group: selected.group,
1905
+ originalPath: selected.originalPath ?? null,
1906
+ })
1907
+ request.then((value) => {
1908
+ if (seq !== diffSeq.current) return
1909
+ setDiff(value)
1910
+ setDiffPhase('ready')
1911
+ }).catch((failure) => {
1912
+ if (seq !== diffSeq.current) return
1913
+ setDiffError(failure?.message ?? String(failure))
1914
+ setDiffPhase('error')
1915
+ })
1916
+ }, [selected, activeRepoPath, call, diffNonce])
1917
+
1918
+ // 5. Keep the selection on the same file when it moves between groups.
1919
+ useEffect(() => {
1920
+ if (selected === null || selected.kind !== 'file' || snapshot === null) return
1921
+ const listOf = (group) => (
1922
+ group === 'staged'
1923
+ ? (snapshot.staged ?? [])
1924
+ : group === 'conflicts'
1925
+ ? (snapshot.conflicts ?? [])
1926
+ : (snapshot.unstaged ?? [])
1927
+ )
1928
+ if (listOf(selected.group).some((entry) => entry.path === selected.path)) return
1929
+ for (const group of ['staged', 'unstaged', 'conflicts']) {
1930
+ if (group === selected.group) continue
1931
+ const match = listOf(group).find((entry) => entry.path === selected.path)
1932
+ if (match !== undefined) {
1933
+ setSelected({
1934
+ kind: 'file',
1935
+ group,
1936
+ path: match.path,
1937
+ originalPath: match.originalPath ?? null,
1938
+ status: match.status,
1939
+ })
1940
+ return
1941
+ }
1942
+ }
1943
+ setSelected(null)
1944
+ }, [snapshot, selected])
1945
+
1946
+ useEffect(() => {
1947
+ if (!notice) return undefined
1948
+ const timer = setTimeout(() => setNotice(null), 5000)
1949
+ return () => clearTimeout(timer)
1950
+ }, [notice])
1951
+
1952
+ const run = useCallback(async (label, action, successText) => {
1953
+ setBusy(label)
1954
+ busyRef.current = label
1955
+ setError(null)
1956
+ try {
1957
+ const value = await action()
1958
+ const next = await loadState()
1959
+ if (successText !== undefined && successText !== null) {
1960
+ setNotice({
1961
+ kind: 'ok',
1962
+ text: typeof successText === 'function' ? successText(value, next) : successText,
1963
+ })
1964
+ }
1965
+ return value
1966
+ } catch (failure) {
1967
+ setNotice(null)
1968
+ setError(failure?.message ?? String(failure))
1969
+ return undefined
1970
+ } finally {
1971
+ setBusy(null)
1972
+ busyRef.current = null
1973
+ }
1974
+ }, [loadState])
1975
+
1976
+ const repo = snapshot?.repo ?? null
1977
+ const staged = snapshot?.staged ?? []
1978
+ const unstaged = snapshot?.unstaged ?? []
1979
+ const conflicts = snapshot?.conflicts ?? []
1980
+ const branches = snapshot?.branches ?? []
1981
+ const commits = snapshot?.commits ?? []
1982
+ const stagedCount = staged.length
1983
+ const unstagedCount = unstaged.length
1984
+ const canGenerate = stagedCount + unstagedCount + conflicts.length > 0
1985
+ const canCommit = stagedCount > 0 && message.trim() !== '' && busy === null && !generatingMessage
1986
+
1987
+ const workspaceEntry = (repos ?? []).find((entry) => samePath(entry.path, workspacePath))
1988
+ const workspaceTitle = workspaceEntry?.title ?? baseName(workspacePath ?? '')
1989
+ const loadedRepos = discovered.filter((entry) => (
1990
+ (enabled ?? []).some((path) => samePath(path, entry.path))
1991
+ ))
1992
+ const activeEntry = discovered.find((entry) => samePath(entry.path, activeRepoPath))
1993
+ const activeLabel = activeEntry !== undefined
1994
+ ? (activeEntry.relativePath === '.' ? t('rootRepository') : activeEntry.relativePath)
1995
+ : (repo?.name ?? baseName(activeRepoPath ?? ''))
1996
+ const repoRoot = repo?.root ?? activeRepoPath ?? workspacePath ?? ''
1997
+
1998
+ const openUpstream = useCallback(() => {
1999
+ setMenu(null)
2000
+ const remotes = Array.isArray(snapshot?.remotes) ? snapshot.remotes : []
2001
+ const preferred = remotes.find((entry) => entry.name === 'origin') ?? remotes[0] ?? null
2002
+ const currentUpstream = typeof repo?.upstream === 'string' ? repo.upstream : null
2003
+ const separator = currentUpstream === null ? -1 : currentUpstream.indexOf('/')
2004
+ const currentRemote = separator > 0 ? currentUpstream.slice(0, separator) : ''
2005
+ const currentBranch = separator > 0 ? currentUpstream.slice(separator + 1) : ''
2006
+ const knownRemote = remotes.some((entry) => entry.name === currentRemote)
2007
+ setUpstreamRemote(knownRemote ? currentRemote : (preferred?.name ?? ''))
2008
+ setUpstreamBranch(knownRemote ? currentBranch : '')
2009
+ setUpstreamBranches([])
2010
+ setUpstreamPhase('idle')
2011
+ setUpstreamError(null)
2012
+ setUpstreamOpen(true)
2013
+ }, [repo, snapshot])
2014
+
2015
+ const saveUpstream = useCallback(async () => {
2016
+ if (
2017
+ !activeRepoPath
2018
+ || repo === null
2019
+ || repo.branch === null
2020
+ || upstreamRemote === ''
2021
+ || upstreamBranch === ''
2022
+ ) return
2023
+ const value = await run(
2024
+ t('savingUpstream'),
2025
+ () => call('setUpstream', {
2026
+ cwd: activeRepoPath,
2027
+ branch: repo.branch,
2028
+ remote: upstreamRemote,
2029
+ remoteBranch: upstreamBranch,
2030
+ }),
2031
+ (result) => t('upstreamSet', { upstream: result?.upstream ?? `${upstreamRemote}/${upstreamBranch}` }),
2032
+ )
2033
+ if (value !== undefined) {
2034
+ setUpstreamOpen(false)
2035
+ await loadState({ quiet: true })
2036
+ }
2037
+ }, [activeRepoPath, call, loadState, repo, run, t, upstreamBranch, upstreamRemote])
2038
+
2039
+ const askDeleteBranch = useCallback((branch) => {
2040
+ setMenu(null)
2041
+ setDeleteTarget(branch)
2042
+ }, [])
2043
+
2044
+ const openRemoteManager = useCallback(() => {
2045
+ setMenu(null)
2046
+ setRemoteName('origin')
2047
+ setRemoteUrl('')
2048
+ setRemoteManagerOpen(true)
2049
+ }, [])
2050
+
2051
+ const addRemote = useCallback(async () => {
2052
+ if (!activeRepoPath || remoteName.trim() === '' || remoteUrl.trim() === '') return
2053
+ const name = remoteName.trim()
2054
+ const value = await run(
2055
+ t('addingRemote'),
2056
+ () => call('addRemote', { cwd: activeRepoPath, name, url: remoteUrl.trim() }),
2057
+ t('remoteAdded', { name }),
2058
+ )
2059
+ if (value !== undefined) {
2060
+ setRemoteName('origin')
2061
+ setRemoteUrl('')
2062
+ await loadState({ quiet: true })
2063
+ }
2064
+ }, [activeRepoPath, call, loadState, remoteName, remoteUrl, run, t])
2065
+
2066
+ const removeRemote = useCallback(async (name) => {
2067
+ if (!activeRepoPath) return
2068
+ const value = await run(
2069
+ t('removingRemote'),
2070
+ () => call('removeRemote', { cwd: activeRepoPath, name }),
2071
+ t('remoteRemoved', { name }),
2072
+ )
2073
+ if (value !== undefined) {
2074
+ await loadState({ quiet: true })
2075
+ }
2076
+ }, [activeRepoPath, call, loadState, run, t])
2077
+
2078
+ const publishBranch = useCallback(async () => {
2079
+ if (!activeRepoPath || repo === null || repo.branch === null) return
2080
+ const value = await run(
2081
+ t('publishingBranch'),
2082
+ () => call('push', { cwd: activeRepoPath }),
2083
+ t('branchPublished', { branch: repo.branch }),
2084
+ )
2085
+ if (value !== undefined) {
2086
+ await loadState({ quiet: true })
2087
+ }
2088
+ }, [activeRepoPath, call, loadState, repo, run, t])
2089
+
2090
+ const confirmDeleteBranch = useCallback(async () => {
2091
+ const branch = deleteTarget
2092
+ if (branch === null) return
2093
+ const value = await run(
2094
+ t('deletingBranch'),
2095
+ () => call('deleteBranch', { cwd: activeRepoPath, branch }),
2096
+ t('branchDeleted', { branch }),
2097
+ )
2098
+ if (value !== undefined) {
2099
+ setDeleteTarget(null)
2100
+ await loadState({ quiet: true })
2101
+ }
2102
+ }, [activeRepoPath, call, deleteTarget, loadState, run, t])
2103
+
2104
+ const selectFile = useCallback((entry, group) => {
2105
+ setSelected({
2106
+ kind: 'file',
2107
+ group,
2108
+ path: entry.path,
2109
+ originalPath: entry.originalPath ?? null,
2110
+ status: entry.status,
2111
+ })
2112
+ }, [])
2113
+
2114
+ const selectCommit = useCallback((entry) => {
2115
+ setSelected({ kind: 'commit', hash: entry.hash, short: entry.short })
2116
+ }, [])
2117
+
2118
+ const selectGroup = useCallback((group) => {
2119
+ if (selected === null || selected.kind !== 'file') return
2120
+ const list = group === 'staged' ? staged : unstaged
2121
+ const entry = list.find((candidate) => candidate.path === selected.path)
2122
+ if (entry !== undefined) selectFile(entry, group)
2123
+ }, [selected, staged, unstaged, selectFile])
2124
+
2125
+ const stagePaths = useCallback((paths) => run(
2126
+ t('stage'),
2127
+ () => call('stage', { cwd: activeRepoPath, paths }),
2128
+ t('stagedNotice'),
2129
+ ), [activeRepoPath, call, run, t])
2130
+
2131
+ const stageAll = useCallback(() => run(
2132
+ t('stageAll'),
2133
+ () => call('stage', { cwd: activeRepoPath, paths: unstaged.flatMap(entryPaths) }),
2134
+ t('stagedAllNotice'),
2135
+ ), [activeRepoPath, call, run, t, unstaged])
2136
+
2137
+ const unstagePaths = useCallback((paths) => run(
2138
+ t('unstage'),
2139
+ () => call('unstage', { cwd: activeRepoPath, paths }),
2140
+ t('unstagedNotice'),
2141
+ ), [activeRepoPath, call, run, t])
2142
+
2143
+ const unstageAll = useCallback(() => run(
2144
+ t('unstageAll'),
2145
+ () => call('unstage', { cwd: activeRepoPath, paths: staged.flatMap(entryPaths) }),
2146
+ t('unstagedAllNotice'),
2147
+ ), [activeRepoPath, call, run, t, staged])
2148
+
2149
+ const askDiscard = useCallback((entries) => {
2150
+ setDiscardTargets(entries)
2151
+ }, [])
2152
+
2153
+ const confirmDiscard = useCallback(async () => {
2154
+ const targets = discardTargets
2155
+ if (targets === null) return
2156
+ const paths = targets.flatMap(entryPaths)
2157
+ setDiscardTargets(null)
2158
+ const value = await run(
2159
+ t('discarding'),
2160
+ () => call('discard', { cwd: activeRepoPath, paths }),
2161
+ t('discarded'),
2162
+ )
2163
+ if (value !== undefined && selected !== null && selected.kind === 'file' && paths.includes(selected.path)) {
2164
+ setSelected(null)
2165
+ }
2166
+ }, [activeRepoPath, call, discardTargets, run, selected, t])
2167
+
2168
+ const commitChanges = useCallback(async () => {
2169
+ if (message.trim() === '') {
2170
+ setError(t('commitMessageRequired'))
2171
+ return
2172
+ }
2173
+ if (stagedCount === 0) {
2174
+ setError(t('nothingStaged'))
2175
+ return
2176
+ }
2177
+ const value = await run(
2178
+ t('committing'),
2179
+ () => call('commit', {
2180
+ cwd: activeRepoPath,
2181
+ message,
2182
+ amend,
2183
+ }),
2184
+ (result) => t('commitSuccess', { hash: result?.hash ?? '' }),
2185
+ )
2186
+ if (value !== undefined) {
2187
+ setMessage('')
2188
+ writeLocal(DRAFT_PREFIX + activeRepoPath, '')
2189
+ setAmend(false)
2190
+ }
2191
+ }, [activeRepoPath, amend, call, message, run, stagedCount, t])
2192
+
2193
+ const generateMessage = useCallback(async () => {
2194
+ if (!activeRepoPath || generatingMessage) return
2195
+ const seq = ++messageSeq.current
2196
+ setGeneratingMessage(true)
2197
+ setError(null)
2198
+ try {
2199
+ const locale = typeof getLocaleId === 'function'
2200
+ ? getLocaleId()
2201
+ : ((typeof navigator !== 'undefined' && navigator.language) || 'en')
2202
+ const payload = { cwd: activeRepoPath, locale }
2203
+ if (effectiveModel !== null) {
2204
+ payload.provider = effectiveModel.provider
2205
+ payload.model = effectiveModel.model
2206
+ }
2207
+ const value = await call('message', payload)
2208
+ if (seq !== messageSeq.current || activeRepoPath !== activeRepoRef.current) return
2209
+ const text = String(value?.message ?? '').trim()
2210
+ if (text === '') throw new Error(t('messageEmpty'))
2211
+ setMessage(text)
2212
+ writeLocal(DRAFT_PREFIX + activeRepoPath, text)
2213
+ setTimeout(() => messageRef.current?.focus?.(), 0)
2214
+ } catch (failure) {
2215
+ if (seq !== messageSeq.current || activeRepoPath !== activeRepoRef.current) return
2216
+ setError(failure?.message ?? String(failure))
2217
+ } finally {
2218
+ if (seq === messageSeq.current) setGeneratingMessage(false)
2219
+ }
2220
+ }, [activeRepoPath, call, effectiveModel, generatingMessage, getLocaleId, t])
2221
+
2222
+ const switchBranch = useCallback(async (branch) => {
2223
+ setMenu(null)
2224
+ const value = await run(
2225
+ t('switchBranch'),
2226
+ () => call('checkout', { cwd: activeRepoPath, branch }),
2227
+ t('branchSwitched', { branch }),
2228
+ )
2229
+ if (value !== undefined) setSelected(null)
2230
+ }, [activeRepoPath, call, run, t])
2231
+
2232
+ const makeBranch = useCallback(async () => {
2233
+ const name = branchDraft.trim()
2234
+ if (name === '') {
2235
+ setError(t('branchRequired'))
2236
+ return
2237
+ }
2238
+ setMenu(null)
2239
+ setBranchDraft('')
2240
+ const value = await run(
2241
+ t('newBranch'),
2242
+ () => call('createBranch', { cwd: activeRepoPath, branch: name }),
2243
+ t('branchCreated', { branch: name }),
2244
+ )
2245
+ if (value !== undefined) setSelected(null)
2246
+ }, [activeRepoPath, branchDraft, call, run, t])
2247
+
2248
+ const sync = useCallback((endpoint, label, success) => run(
2249
+ label,
2250
+ () => call(endpoint, { cwd: activeRepoPath }),
2251
+ success,
2252
+ ), [activeRepoPath, call, run])
2253
+
2254
+ const initialize = useCallback(async () => {
2255
+ const value = await run(
2256
+ t('initializing'),
2257
+ () => call('init', { cwd: workspacePath }),
2258
+ t('initialized'),
2259
+ )
2260
+ if (value !== undefined) setScanNonce((current) => current + 1)
2261
+ }, [call, run, t, workspacePath])
2262
+
2263
+ const rescan = useCallback(() => setScanNonce((current) => current + 1), [])
2264
+
2265
+ const refreshAll = useCallback(() => {
2266
+ void loadState()
2267
+ setDiffNonce((value) => value + 1)
2268
+ }, [loadState])
2269
+
2270
+ const retry = useCallback(() => {
2271
+ if (repos === null || repos.length === 0) {
2272
+ setPhase('loading')
2273
+ setReposNonce((value) => value + 1)
2274
+ return
2275
+ }
2276
+ if (scanPhase === 'error' || discovered.length === 0 || activeRepoPath === null) {
2277
+ setScanNonce((value) => value + 1)
2278
+ return
2279
+ }
2280
+ void loadState()
2281
+ }, [activeRepoPath, discovered.length, loadState, repos, scanPhase])
2282
+
2283
+ const toggleSection = useCallback((key) => {
2284
+ setOpenSections((current) => ({ ...current, [key]: !current[key] }))
2285
+ }, [])
2286
+
2287
+ const onMessage = useCallback((value) => {
2288
+ setMessage(value)
2289
+ if (activeRepoPath) writeLocal(DRAFT_PREFIX + activeRepoPath, value)
2290
+ }, [activeRepoPath])
2291
+
2292
+ const toggleRepo = useCallback((repoEntry) => {
2293
+ if (!workspacePath) return
2294
+ const current = enabledRef.current ?? []
2295
+ const isEnabled = current.some((path) => samePath(path, repoEntry.path))
2296
+ const next = isEnabled
2297
+ ? current.filter((path) => !samePath(path, repoEntry.path))
2298
+ : [...current, repoEntry.path]
2299
+ setEnabled(next)
2300
+ writeEnabledList(workspacePath, next)
2301
+ const active = activeRepoRef.current
2302
+ if (active === null || !next.some((path) => samePath(path, active))) {
2303
+ const pick = next[0] ?? null
2304
+ setActiveRepoPath(pick)
2305
+ writeActiveRepo(workspacePath, pick)
2306
+ }
2307
+ }, [workspacePath])
2308
+
2309
+ const selectAllRepos = useCallback(() => {
2310
+ if (!workspacePath) return
2311
+ const next = discovered.map((entry) => entry.path)
2312
+ setEnabled(next)
2313
+ writeEnabledList(workspacePath, next)
2314
+ const active = activeRepoRef.current
2315
+ if (active === null || !next.some((path) => samePath(path, active))) {
2316
+ const pick = next[0] ?? null
2317
+ setActiveRepoPath(pick)
2318
+ writeActiveRepo(workspacePath, pick)
2319
+ }
2320
+ }, [discovered, workspacePath])
2321
+
2322
+ const clearRepos = useCallback(() => {
2323
+ if (!workspacePath) return
2324
+ setEnabled([])
2325
+ writeEnabledList(workspacePath, [])
2326
+ setActiveRepoPath(null)
2327
+ writeActiveRepo(workspacePath, null)
2328
+ }, [workspacePath])
2329
+
2330
+ const chooseRepo = useCallback((path) => {
2331
+ setActiveRepoPath(path)
2332
+ if (workspacePath) writeActiveRepo(workspacePath, path)
2333
+ setMenu(null)
2334
+ }, [workspacePath])
2335
+
2336
+ const chooseWorkspace = useCallback((path) => {
2337
+ setWorkspacePath(path)
2338
+ setMenu(null)
2339
+ }, [])
2340
+
2341
+ const selectedEntry = useMemo(() => {
2342
+ if (selected === null || selected.kind !== 'file') return null
2343
+ const list = selected.group === 'staged' ? staged : unstaged
2344
+ return list.find((entry) => entry.path === selected.path) ?? null
2345
+ }, [selected, staged, unstaged])
2346
+
2347
+ const bothGroups = useMemo(() => ({
2348
+ staged: selected !== null && selected.kind === 'file' && staged.some((entry) => entry.path === selected.path),
2349
+ unstaged: selected !== null && selected.kind === 'file' && unstaged.some((entry) => entry.path === selected.path),
2350
+ }), [selected, staged, unstaged])
2351
+
2352
+ const workspaceMenuOpen = menu === 'workspace'
2353
+ const repoMenuOpen = menu === 'repo'
2354
+ const branchMenuOpen = menu === 'branch'
2355
+ const closeMenu = useCallback(() => setMenu(null), [])
2356
+
2357
+ // ---- render ---------------------------------------------------------
2358
+
2359
+ if (repos !== null && repos.length === 0 && error === null) {
2360
+ return h('div', { className: 'dg-root' },
2361
+ h(EmptyState, {
2362
+ icon: h(GitMark, { size: 22 }),
2363
+ title: t('noWorkspaces'),
2364
+ text: t('noWorkspacesHint'),
2365
+ }))
2366
+ }
2367
+
2368
+ const header = h('header', { className: 'dg-header' },
2369
+ h('div', { className: 'dg-heading' },
2370
+ h('div', { className: 'dg-title-row' },
2371
+ h('span', { className: 'dg-glyph' }, h(GitMark, { size: 18 })),
2372
+ h('h1', { className: 'dg-title' }, t('panelTitle')),
2373
+ h('span', { className: 'dg-menu-anchor' },
2374
+ h('button', {
2375
+ type: 'button',
2376
+ className: 'dg-chip',
2377
+ 'aria-haspopup': 'menu',
2378
+ 'aria-expanded': workspaceMenuOpen,
2379
+ title: workspacePath ?? '',
2380
+ onClick: () => setMenu(workspaceMenuOpen ? null : 'workspace'),
2381
+ },
2382
+ h(FolderIcon, { size: 12 }),
2383
+ h('span', { className: 'dg-chip-text' }, workspaceTitle || t('chooseWorkspace')),
2384
+ h(ChevronDown, { size: 11 })),
2385
+ h(Menu, { open: workspaceMenuOpen, onClose: closeMenu },
2386
+ h('div', { className: 'dg-menu-label' }, t('workspace')),
2387
+ (repos ?? []).map((entry) => h('button', {
2388
+ key: entry.path,
2389
+ type: 'button',
2390
+ role: 'menuitem',
2391
+ className: 'dg-menu-item',
2392
+ 'data-current': samePath(entry.path, workspacePath) ? 'true' : 'false',
2393
+ onClick: () => chooseWorkspace(entry.path),
2394
+ },
2395
+ h('span', { className: 'dg-menu-check' },
2396
+ samePath(entry.path, workspacePath) ? h(CheckIcon, { size: 12 }) : null),
2397
+ h('span', { className: 'dg-menu-item-main' },
2398
+ h('span', { className: 'dg-menu-item-title' }, entry.title || baseName(entry.path)),
2399
+ h('span', { className: 'dg-menu-item-path', title: entry.path }, entry.path)))))),
2400
+ h('span', { className: 'dg-menu-anchor' },
2401
+ h('button', {
2402
+ type: 'button',
2403
+ className: 'dg-chip',
2404
+ 'aria-haspopup': 'menu',
2405
+ 'aria-expanded': repoMenuOpen,
2406
+ title: activeRepoPath ?? workspacePath ?? '',
2407
+ onClick: () => setMenu(repoMenuOpen ? null : 'repo'),
2408
+ },
2409
+ h(GitMark, { size: 12 }),
2410
+ h('span', { className: 'dg-chip-text' }, activeLabel || t('noRepositoriesLoaded')),
2411
+ h(ChevronDown, { size: 11 })),
2412
+ h(Menu, { open: repoMenuOpen, onClose: closeMenu },
2413
+ h('div', { className: 'dg-menu-label' }, t('loadedRepos')),
2414
+ loadedRepos.length === 0
2415
+ ? h('div', { className: 'dg-menu-empty' }, t('noRepositoriesLoaded'))
2416
+ : loadedRepos.map((entry) => h('button', {
2417
+ key: entry.path,
2418
+ type: 'button',
2419
+ role: 'menuitem',
2420
+ className: 'dg-menu-item',
2421
+ 'data-current': samePath(entry.path, activeRepoPath) ? 'true' : 'false',
2422
+ onClick: () => chooseRepo(entry.path),
2423
+ },
2424
+ h('span', { className: 'dg-menu-check' },
2425
+ samePath(entry.path, activeRepoPath) ? h(CheckIcon, { size: 12 }) : null),
2426
+ h('span', { className: 'dg-menu-item-main' },
2427
+ h('span', { className: 'dg-menu-item-title' },
2428
+ entry.relativePath === '.' ? t('rootRepository') : entry.relativePath),
2429
+ h('span', { className: 'dg-menu-item-path', title: entry.path }, entry.path)))),
2430
+ h('div', { className: 'dg-menu-sep' }),
2431
+ h('button', {
2432
+ type: 'button',
2433
+ className: 'dg-menu-item',
2434
+ onClick: () => {
2435
+ setManagerOpen(true)
2436
+ setMenu(null)
2437
+ },
2438
+ },
2439
+ h('span', { className: 'dg-menu-check' }),
2440
+ h('span', { className: 'dg-menu-item-main' },
2441
+ h('span', { className: 'dg-menu-item-title' }, t('manageRepos')))))),
2442
+ repo !== null
2443
+ ? h('span', { className: 'dg-menu-anchor' },
2444
+ h('button', {
2445
+ type: 'button',
2446
+ className: 'dg-chip',
2447
+ 'aria-haspopup': 'dialog',
2448
+ 'aria-expanded': branchMenuOpen,
2449
+ title: repo.branch ?? t('detachedHead'),
2450
+ onClick: () => setMenu(branchMenuOpen ? null : 'branch'),
2451
+ },
2452
+ h(GitMark, { size: 12 }),
2453
+ h('span', { className: 'dg-chip-text' }, repo.branch ?? t('detachedHead')),
2454
+ repo.ahead > 0 ? h('span', { className: 'dg-chip-meta', title: t('aheadCount', { n: repo.ahead }) }, `↑${repo.ahead}`) : null,
2455
+ repo.behind > 0 ? h('span', { className: 'dg-chip-meta', title: t('behindCount', { n: repo.behind }) }, `↓${repo.behind}`) : null,
2456
+ h(ChevronDown, { size: 11 })),
2457
+ h(Menu, {
2458
+ open: branchMenuOpen,
2459
+ onClose: closeMenu,
2460
+ role: 'dialog',
2461
+ label: t('switchBranch'),
2462
+ },
2463
+ h('div', { className: 'dg-menu-label' }, t('switchBranch')),
2464
+ branches.length === 0
2465
+ ? h('div', { className: 'dg-menu-empty' }, t('noBranches'))
2466
+ : branches.map((branch) => h('div', {
2467
+ key: branch.name,
2468
+ className: 'dg-branch-row',
2469
+ },
2470
+ h('button', {
2471
+ type: 'button',
2472
+ className: 'dg-menu-item dg-branch-switch',
2473
+ 'data-current': branch.current ? 'true' : 'false',
2474
+ onClick: () => {
2475
+ if (branch.current) setMenu(null)
2476
+ else void switchBranch(branch.name)
2477
+ },
2478
+ },
2479
+ h('span', { className: 'dg-menu-check' }, branch.current ? h(CheckIcon, { size: 12 }) : null),
2480
+ h('span', { className: 'dg-menu-item-main' },
2481
+ h('span', { className: 'dg-menu-item-title' }, branch.name),
2482
+ h('span', { className: 'dg-menu-item-path' },
2483
+ branch.upstream ?? t('noUpstream')))),
2484
+ branch.current
2485
+ ? null
2486
+ : h('button', {
2487
+ type: 'button',
2488
+ className: 'dg-branch-delete',
2489
+ title: t('deleteBranch'),
2490
+ 'aria-label': t('deleteBranch'),
2491
+ onClick: () => askDeleteBranch(branch.name),
2492
+ }, h(TrashIcon, { size: 12 })))),
2493
+ repo.branch !== null && repo.upstream === null
2494
+ ? h('button', {
2495
+ type: 'button',
2496
+ className: 'dg-menu-item',
2497
+ onClick: () => void publishBranch(),
2498
+ },
2499
+ h('span', { className: 'dg-menu-check' }),
2500
+ h('span', { className: 'dg-menu-item-main' },
2501
+ h('span', { className: 'dg-menu-item-title' }, t('publishBranch')),
2502
+ h('span', { className: 'dg-menu-item-path' }, t('publishBranchHint'))))
2503
+ : null,
2504
+ repo.branch !== null
2505
+ ? h('button', {
2506
+ type: 'button',
2507
+ className: 'dg-menu-item',
2508
+ onClick: openUpstream,
2509
+ },
2510
+ h('span', { className: 'dg-menu-check' }),
2511
+ h('span', { className: 'dg-menu-item-main' },
2512
+ h('span', { className: 'dg-menu-item-title' }, t('setUpstream')),
2513
+ h('span', { className: 'dg-menu-item-path' },
2514
+ repo.upstream ?? t('noUpstream'))))
2515
+ : null,
2516
+ h('button', {
2517
+ type: 'button',
2518
+ className: 'dg-menu-item',
2519
+ onClick: openRemoteManager,
2520
+ },
2521
+ h('span', { className: 'dg-menu-check' }),
2522
+ h('span', { className: 'dg-menu-item-main' },
2523
+ h('span', { className: 'dg-menu-item-title' }, t('manageRemotes')))),
2524
+ h('div', { className: 'dg-menu-sep' }),
2525
+ h('div', { className: 'dg-menu-label' }, t('newBranch')),
2526
+ h('div', { className: 'dg-menu-input-row' },
2527
+ h('input', {
2528
+ className: 'dg-input',
2529
+ value: branchDraft,
2530
+ placeholder: t('newBranchPlaceholder'),
2531
+ 'aria-label': t('newBranchPlaceholder'),
2532
+ onChange: (event) => setBranchDraft(event.target.value),
2533
+ onKeyDown: (event) => {
2534
+ if (event.key === 'Enter') {
2535
+ event.preventDefault()
2536
+ void makeBranch()
2537
+ }
2538
+ },
2539
+ }),
2540
+ h(Button, {
2541
+ variant: 'primary',
2542
+ onClick: () => void makeBranch(),
2543
+ disabled: branchDraft.trim() === '' || Boolean(busy),
2544
+ }, t('create')))))
2545
+ : null),
2546
+ h('p', { className: 'dg-subtitle', title: repoRoot }, repoRoot)),
2547
+ h('div', { className: 'dg-toolbar' },
2548
+ repo !== null
2549
+ ? h(IconButton, {
2550
+ title: t('fetch'),
2551
+ onClick: () => void sync('fetch', t('fetch'), t('fetchDone')),
2552
+ disabled: Boolean(busy),
2553
+ }, h(CloudIcon, { size: 14 }))
2554
+ : null,
2555
+ repo !== null
2556
+ ? h(IconButton, {
2557
+ title: t('pull'),
2558
+ onClick: () => void sync('pull', t('pull'), t('pullDone')),
2559
+ disabled: Boolean(busy),
2560
+ }, h(ArrowDownIcon, { size: 14 }),
2561
+ repo.behind > 0 ? h('span', { className: 'dg-badge' }, repo.behind) : null)
2562
+ : null,
2563
+ repo !== null
2564
+ ? h(IconButton, {
2565
+ title: t('push'),
2566
+ onClick: () => void sync('push', t('push'), t('pushDone')),
2567
+ disabled: Boolean(busy),
2568
+ }, h(ArrowUpIcon, { size: 14 }),
2569
+ repo.ahead > 0 ? h('span', { className: 'dg-badge' }, repo.ahead) : null)
2570
+ : null,
2571
+ busy !== null
2572
+ ? h('span', { className: 'dg-busy', title: busy }, h(Spinner, { size: 12 }), h('span', null, busy))
2573
+ : null,
2574
+ h(IconButton, {
2575
+ title: t('manageRepos'),
2576
+ onClick: () => setManagerOpen(true),
2577
+ disabled: Boolean(busy),
2578
+ }, h(ListIcon, { size: 14 })),
2579
+ h(IconButton, {
2580
+ title: t('refresh'),
2581
+ onClick: refreshAll,
2582
+ disabled: Boolean(busy),
2583
+ }, busy ? h(Spinner, { size: 13 }) : h(RefreshIcon, { size: 14 }))))
2584
+
2585
+ const banners = []
2586
+ if (error !== null && snapshot !== null) {
2587
+ banners.push(h('div', { key: 'error', className: 'dg-banner dg-banner-error' },
2588
+ h(WarningIcon, { size: 14 }),
2589
+ h('span', { className: 'dg-banner-text' }, error),
2590
+ h(IconButton, {
2591
+ title: t('dismiss'),
2592
+ onClick: () => setError(null),
2593
+ }, h(CloseIcon, { size: 12 }))))
2594
+ }
2595
+ if (scanError !== null && discovered.length > 0) {
2596
+ banners.push(h('div', { key: 'scan-error', className: 'dg-banner dg-banner-error' },
2597
+ h(WarningIcon, { size: 14 }),
2598
+ h('span', { className: 'dg-banner-text' }, scanError),
2599
+ h(Button, { variant: 'ghost', onClick: rescan }, t('scanAgain'))))
2600
+ }
2601
+ if (notice !== null) {
2602
+ banners.push(h('div', { key: 'notice', className: 'dg-banner dg-banner-ok' },
2603
+ h(CheckIcon, { size: 14 }),
2604
+ h('span', { className: 'dg-banner-text' }, notice.text)))
2605
+ }
2606
+
2607
+ let body
2608
+ if (scanPhase === 'loading' && discovered.length === 0) {
2609
+ body = h(EmptyState, { icon: h(Spinner, { size: 20 }), title: t('scanning') })
2610
+ } else if (scanPhase === 'error' && discovered.length === 0) {
2611
+ body = h(EmptyState, {
2612
+ icon: h(WarningIcon, { size: 22 }),
2613
+ title: t('loadingFailed'),
2614
+ text: scanError ?? '',
2615
+ children: h(Button, { onClick: rescan }, t('scanAgain')),
2616
+ })
2617
+ } else if (scanPhase === 'ready' && discovered.length === 0) {
2618
+ body = h(EmptyState, {
2619
+ icon: h(GitMark, { size: 22 }),
2620
+ title: t('noRepositoriesFound'),
2621
+ text: t('noRepositoriesHint'),
2622
+ children: h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '8px' } },
2623
+ h('span', { className: 'dg-empty-path', title: workspacePath ?? '' }, workspacePath ?? ''),
2624
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
2625
+ h(Button, { onClick: rescan }, t('scanAgain')),
2626
+ h(Button, {
2627
+ variant: 'primary',
2628
+ onClick: () => void initialize(),
2629
+ disabled: Boolean(busy),
2630
+ }, t('initRepository')))),
2631
+ })
2632
+ } else if (discovered.length > 0 && (enabled ?? []).length === 0) {
2633
+ body = h(EmptyState, {
2634
+ icon: h(GitMark, { size: 22 }),
2635
+ title: t('noRepositoriesLoaded'),
2636
+ text: t('loadRepositoriesHint'),
2637
+ children: h(Button, {
2638
+ variant: 'primary',
2639
+ onClick: () => setManagerOpen(true),
2640
+ }, t('manageRepos')),
2641
+ })
2642
+ } else if (snapshot === null) {
2643
+ body = phase === 'error'
2644
+ ? h(EmptyState, {
2645
+ icon: h(WarningIcon, { size: 22 }),
2646
+ title: t('loadingFailed'),
2647
+ text: error ?? '',
2648
+ children: h(Button, { onClick: retry }, t('retry')),
2649
+ })
2650
+ : h(EmptyState, { icon: h(Spinner, { size: 20 }), title: t('loading') })
2651
+ } else if (repo === null) {
2652
+ body = h(EmptyState, {
2653
+ icon: h(WarningIcon, { size: 22 }),
2654
+ title: t('notARepository'),
2655
+ text: t('notARepositoryHint'),
2656
+ children: h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '8px' } },
2657
+ h('span', { className: 'dg-empty-path', title: repoRoot }, repoRoot),
2658
+ h(Button, { onClick: rescan }, t('scanAgain'))),
2659
+ })
2660
+ } else {
2661
+ body = h('div', { className: 'dg-body' },
2662
+ h('aside', { className: 'dg-side' },
2663
+ h(CommitBox, {
2664
+ t,
2665
+ message,
2666
+ onMessage,
2667
+ amend,
2668
+ onAmend: setAmend,
2669
+ stagedCount,
2670
+ unstagedCount,
2671
+ canCommit,
2672
+ canGenerate,
2673
+ generating: generatingMessage,
2674
+ busy,
2675
+ onCommit: () => void commitChanges(),
2676
+ onStageAll: () => void stageAll(),
2677
+ onGenerate: () => void generateMessage(),
2678
+ textareaRef: messageRef,
2679
+ modelCatalog,
2680
+ modelSelection: effectiveModel,
2681
+ modelError,
2682
+ onModelChange: changeModel,
2683
+ }),
2684
+ h('div', { className: 'dg-side-scroll', ref: sideRef },
2685
+ h(FileSection, {
2686
+ t,
2687
+ title: t('mergeChanges'),
2688
+ entries: conflicts,
2689
+ open: openSections.conflicts,
2690
+ onToggle: () => toggleSection('conflicts'),
2691
+ emptyText: t('noConflicts'),
2692
+ group: 'conflicts',
2693
+ selected,
2694
+ onSelect: selectFile,
2695
+ onStage: stagePaths,
2696
+ onUnstage: unstagePaths,
2697
+ onDiscard: askDiscard,
2698
+ busy,
2699
+ }),
2700
+ h(FileSection, {
2701
+ t,
2702
+ title: t('stagedChanges'),
2703
+ entries: staged,
2704
+ open: openSections.staged,
2705
+ onToggle: () => toggleSection('staged'),
2706
+ emptyText: t('noStaged'),
2707
+ actionIcon: h(MinusIcon, { size: 12 }),
2708
+ actionTitle: t('unstageAll'),
2709
+ onAction: () => void unstageAll(),
2710
+ group: 'staged',
2711
+ selected,
2712
+ onSelect: selectFile,
2713
+ onStage: stagePaths,
2714
+ onUnstage: unstagePaths,
2715
+ onDiscard: askDiscard,
2716
+ busy,
2717
+ }),
2718
+ h(FileSection, {
2719
+ t,
2720
+ title: t('changes'),
2721
+ entries: unstaged,
2722
+ open: openSections.changes,
2723
+ onToggle: () => toggleSection('changes'),
2724
+ emptyText: t('noChanges'),
2725
+ actionIcon: h(PlusIcon, { size: 12 }),
2726
+ actionTitle: t('stageAll'),
2727
+ onAction: () => void stageAll(),
2728
+ group: 'unstaged',
2729
+ selected,
2730
+ onSelect: selectFile,
2731
+ onStage: stagePaths,
2732
+ onUnstage: unstagePaths,
2733
+ onDiscard: askDiscard,
2734
+ busy,
2735
+ }),
2736
+ h(HistorySection, {
2737
+ t,
2738
+ commits,
2739
+ open: openSections.history,
2740
+ onToggle: () => toggleSection('history'),
2741
+ selected,
2742
+ onSelect: selectCommit,
2743
+ }))),
2744
+ h(DiffPane, {
2745
+ t,
2746
+ selected,
2747
+ bothGroups,
2748
+ snapshot,
2749
+ diff,
2750
+ diffPhase,
2751
+ diffError,
2752
+ busy,
2753
+ onSelectGroup: selectGroup,
2754
+ onStage: stagePaths,
2755
+ onUnstage: unstagePaths,
2756
+ onRefresh: refreshAll,
2757
+ onBack: () => setSelected(null),
2758
+ }))
2759
+ }
2760
+
2761
+ return h('div', { className: 'dg-root' },
2762
+ header,
2763
+ banners.length > 0 ? h('div', { className: 'dg-banners' }, banners) : null,
2764
+ body,
2765
+ discardTargets !== null
2766
+ ? h(DiscardDialog, {
2767
+ t,
2768
+ targets: discardTargets,
2769
+ onCancel: () => setDiscardTargets(null),
2770
+ onConfirm: () => void confirmDiscard(),
2771
+ busy,
2772
+ })
2773
+ : null,
2774
+ upstreamOpen
2775
+ ? h(UpstreamDialog, {
2776
+ t,
2777
+ repo,
2778
+ remotes: Array.isArray(snapshot?.remotes) ? snapshot.remotes : [],
2779
+ remote: upstreamRemote,
2780
+ branch: upstreamBranch,
2781
+ branches: upstreamBranches,
2782
+ phase: upstreamPhase,
2783
+ error: upstreamError,
2784
+ busy,
2785
+ onRemote: (value) => {
2786
+ setUpstreamRemote(value)
2787
+ setUpstreamBranch('')
2788
+ },
2789
+ onBranch: setUpstreamBranch,
2790
+ onCancel: () => setUpstreamOpen(false),
2791
+ onSave: () => void saveUpstream(),
2792
+ })
2793
+ : null,
2794
+ deleteTarget !== null
2795
+ ? h(DeleteBranchDialog, {
2796
+ t,
2797
+ branch: deleteTarget,
2798
+ onCancel: () => setDeleteTarget(null),
2799
+ onConfirm: () => void confirmDeleteBranch(),
2800
+ busy,
2801
+ })
2802
+ : null,
2803
+ remoteManagerOpen
2804
+ ? h(RemoteManagerDialog, {
2805
+ t,
2806
+ remotes: Array.isArray(snapshot?.remotes) ? snapshot.remotes : [],
2807
+ name: remoteName,
2808
+ url: remoteUrl,
2809
+ onName: setRemoteName,
2810
+ onUrl: setRemoteUrl,
2811
+ onAdd: () => void addRemote(),
2812
+ onRemove: (name) => void removeRemote(name),
2813
+ onFetch: () => void sync('fetch', t('fetch'), t('fetchDone')),
2814
+ onClose: () => setRemoteManagerOpen(false),
2815
+ busy,
2816
+ })
2817
+ : null,
2818
+ managerOpen
2819
+ ? h(RepoManager, {
2820
+ t,
2821
+ workspaceTitle,
2822
+ workspacePath,
2823
+ discovered,
2824
+ enabled,
2825
+ scanPhase,
2826
+ scanError,
2827
+ scanTruncated,
2828
+ onToggle: toggleRepo,
2829
+ onSelectAll: selectAllRepos,
2830
+ onClear: clearRepos,
2831
+ onRescan: rescan,
2832
+ onClose: () => setManagerOpen(false),
2833
+ })
2834
+ : null)
2835
+ }
2836
+
2837
+ //#endregion
2838
+
2839
+ //#region registration
2840
+
2841
+ /**
2842
+ * Keep a render defect visible instead of leaving the main column blank.
2843
+ *
2844
+ * The slot registry removes an entry whose component throws; a boundary at
2845
+ * the registration root turns that blank page into the message and a retry.
2846
+ */
2847
+ class PanelBoundary extends React.Component {
2848
+ constructor(props) {
2849
+ super(props)
2850
+ this.state = { error: null }
2851
+ }
2852
+
2853
+ static getDerivedStateFromError(error) {
2854
+ return { error }
2855
+ }
2856
+
2857
+ componentDidCatch(error, info) {
2858
+ console.error('[dsh-git] panel render failed', error, info)
2859
+ }
2860
+
2861
+ render() {
2862
+ if (this.state.error === null) return h(GitPanel, this.props)
2863
+ let title = 'Git panel failed to render'
2864
+ let retry = 'Retry'
2865
+ try {
2866
+ const translated = this.props.t?.('renderFailed')
2867
+ if (typeof translated === 'string' && translated !== '') title = translated
2868
+ const retryText = this.props.t?.('retry')
2869
+ if (typeof retryText === 'string' && retryText !== '') retry = retryText
2870
+ } catch {
2871
+ /* the translator itself may be the failing dependency */
2872
+ }
2873
+ return h('div', { className: 'dg-root' },
2874
+ h(EmptyState, {
2875
+ icon: h(WarningIcon, { size: 22 }),
2876
+ title,
2877
+ text: String(this.state.error?.message ?? this.state.error),
2878
+ children: h(Button, {
2879
+ onClick: () => this.setState({ error: null }),
2880
+ }, retry),
2881
+ }))
2882
+ }
2883
+ }
2884
+
2885
+ /** Sidebar rail icon; the owner supplies the button, label, and active state. */
2886
+ function PanelIcon({ size = 20, active }) {
2887
+ return h('span', {
2888
+ style: {
2889
+ display: 'inline-flex',
2890
+ alignItems: 'center',
2891
+ justifyContent: 'center',
2892
+ color: active ? 'var(--dsw-alias-brand-primary)' : 'inherit',
2893
+ },
2894
+ }, h(GitMark, { size }))
2895
+ }
2896
+
2897
+ function apply(ctx) {
2898
+ const translate = (key, params) => {
2899
+ const locale = ctx.get('locale')
2900
+ if (locale !== undefined) {
2901
+ try {
2902
+ const value = locale.bind(NS)(key, params)
2903
+ if (typeof value === 'string' && value !== key) return value
2904
+ } catch {
2905
+ /* fall through to the bundled dictionary */
2906
+ }
2907
+ }
2908
+ const template = EN[key] ?? key
2909
+ if (params === undefined || params === null) return template
2910
+ return template.replace(/\{(\w+)\}/g, (match, name) => (
2911
+ params[name] === undefined || params[name] === null ? match : String(params[name])
2912
+ ))
2913
+ }
2914
+
2915
+ ctx.effect(() => {
2916
+ const tag = document.createElement('style')
2917
+ tag.dataset.plugin = 'dsh-git'
2918
+ tag.dataset.pluginCss = `${NS}/client.css`
2919
+ tag.textContent = CSS
2920
+ document.head.appendChild(tag)
2921
+ return () => tag.remove()
2922
+ }, 'dsh-git: stylesheet')
2923
+
2924
+ ctx.inject(['locale'], (localeCtx) => {
2925
+ const locale = localeCtx.locale
2926
+ const disposers = []
2927
+ try {
2928
+ disposers.push(locale.register(NS, 'en', EN))
2929
+ } catch { /* a duplicate registration is harmless */ }
2930
+ try {
2931
+ disposers.push(locale.register(NS, 'zh', ZH))
2932
+ } catch { /* see above */ }
2933
+ return () => {
2934
+ for (const dispose of disposers) {
2935
+ try { dispose() } catch { /* already disposed */ }
2936
+ }
2937
+ }
2938
+ })
2939
+
2940
+ const currentLocaleId = () => {
2941
+ try {
2942
+ const locale = ctx.get('locale')
2943
+ const snapshot = locale?.getLocale?.() ?? locale?.getSnapshot?.()
2944
+ if (typeof snapshot?.id === 'string' && snapshot.id !== '') return snapshot.id
2945
+ if (typeof snapshot?.locale === 'string' && snapshot.locale !== '') return snapshot.locale
2946
+ } catch {
2947
+ /* fall through to the browser language */
2948
+ }
2949
+ return (typeof navigator !== 'undefined' && navigator.language) || 'en'
2950
+ }
2951
+
2952
+ const call = async (endpoint, payload) => {
2953
+ if (ctx.get('connection') === undefined) throw new Error(translate('panelUnavailable'))
2954
+ let response
2955
+ try {
2956
+ response = await fetch(ROUTE, {
2957
+ method: 'POST',
2958
+ headers: { 'content-type': 'application/json' },
2959
+ body: JSON.stringify({ endpoint, payload: payload ?? {} }),
2960
+ })
2961
+ } catch (failure) {
2962
+ throw new Error(translate('routeUnreachable', { message: String(failure?.message ?? failure) }))
2963
+ }
2964
+ if (!response.ok) throw new Error(translate('httpError', { status: response.status }))
2965
+ const result = await response.json().catch(() => null)
2966
+ if (result?.ok === true) return result.value
2967
+ throw new Error(result?.error?.message ?? translate('refused'))
2968
+ }
2969
+
2970
+ const face = () => ({ t: translate, call, getLocaleId: currentLocaleId })
2971
+
2972
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
2973
+ name: 'sidebar.panellist',
2974
+ id: PANEL_ID,
2975
+ order: 5,
2976
+ label: () => translate('panelTitle'),
2977
+ locale: NS,
2978
+ inject: face,
2979
+ }, PanelIcon))
2980
+
2981
+ ctx.slots.inject('main', () => ctx.slots.register({
2982
+ name: 'main',
2983
+ key: PANEL_ID,
2984
+ locale: NS,
2985
+ inject: face,
2986
+ }, PanelBoundary))
2987
+ }
2988
+
2989
+ return { inject: ['slots', 'connection'], apply }
2990
+ },
2991
+ })