dsh-git-ui 0.0.2 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,10 +15,17 @@ import { useEffect, useLayoutEffect, useRef, useState } from 'react'
15
15
  import { createPortal } from 'react-dom'
16
16
  import type { JSX } from 'react'
17
17
  import { completedTurnCount, type TurnSignalSnapshot } from './turn-signal.ts'
18
- import type { GitObservable, GitView } from './controller.ts'
18
+ import { Button } from '@deepseek-ai/dsh-client-ui-primitives'
19
+ import type { GitObservable, GitQueryOutcome, GitView } from './controller.ts'
19
20
  import { GitCenter } from './GitCenter.tsx'
20
- import type { GitAction, GitActionResult } from '../host/types.ts'
21
+ import { fileIconForPath, FolderIcon, AlertIcon, CloseIcon, RollbackIcon, StageIcon, UnstageIcon } from './icons.tsx'
22
+ import type { GitAction, GitActionResult, GitBranch, GitOperationErrorCode, GitQueryRequest } from '../host/types.ts'
21
23
  import type { GitKey } from './locales.ts'
24
+ import { SelectMenu } from './select-menu.tsx'
25
+ import { splitChangePath } from './file-tree.ts'
26
+ import { shouldClosePopup } from './popup-close.ts'
27
+ import { diffBaseOf } from './changes-diff.ts'
28
+ import { errorText, errorAction } from './error-text.ts'
22
29
  import * as css from './styles.ts'
23
30
 
24
31
  // Inject the plugin's interaction styles once (idempotent, browser-only).
@@ -35,6 +42,8 @@ export interface GitInjected {
35
42
  refresh: () => Promise<void>
36
43
  /** Execute one management action (host returns a fresh snapshot). */
37
44
  run: (action: GitAction) => Promise<GitActionResult>
45
+ /** Run one read-only query (history / diff / show / branches). */
46
+ query: (query: GitQueryRequest['query']) => Promise<GitQueryOutcome>
38
47
  }
39
48
 
40
49
  /** Selector hook shape the slot runtime binds from `hooks.git`. */
@@ -57,16 +66,7 @@ export interface GitPillProps extends GitInjected {
57
66
  readonly t: (key: GitKey) => string
58
67
  }
59
68
 
60
- /** Status chip colors for the changed-file list. */
61
- const CHIP_COLORS: Record<string, string> = {
62
- added: '#2e7d32',
63
- modified: '#b26a00',
64
- deleted: '#c62828',
65
- renamed: '#1565c0',
66
- untracked: '#6a6a6a',
67
- conflicted: '#d32f2f',
68
- typechange: '#7b1fa2',
69
- }
69
+ /** 状态字符映射(配色见 styles.chipStyles,全语义 token)。 */
70
70
 
71
71
  const CHIP_LETTERS: Record<string, string> = {
72
72
  added: 'A', modified: 'M', deleted: 'D', renamed: 'R',
@@ -102,16 +102,14 @@ function timeAgo(iso: string, now: number, t: (key: GitKey) => string): string {
102
102
  return fill('time.daysAgo', Math.floor(seconds / 86_400))
103
103
  }
104
104
 
105
- /** The pill label for a ready snapshot. */
106
- function pillLabel(view: GitView & { state: 'ready' }, t: (key: GitKey) => string): string {
105
+ /** The pill label parts: 分支名(可 ellipsis 收缩)+ 徽标(不截断保留)。 */
106
+ function pillParts(view: GitView & { state: 'ready' }, t: (key: GitKey) => string): { branch: string; badges: string[] } {
107
107
  const s = view.snapshot
108
108
  const branch = s.branch === null
109
109
  ? `(${t('pill.detached')}) · ${s.head ?? ''}`
110
- : s.branch
111
- const base = s.unborn ? `${branch} · ${t('pill.noCommits')}` : branch
112
- const badge = dirtyBadge(view)
113
- const ahead = aheadBehind(view)
114
- return [base, badge, ahead].filter(Boolean).join(' · ')
110
+ : (s.unborn ? `${s.branch} · ${t('pill.noCommits')}` : s.branch)
111
+ const badges = [dirtyBadge(view), aheadBehind(view)].filter(Boolean)
112
+ return { branch, badges }
115
113
  }
116
114
 
117
115
  /** Dimmed pill for degraded states. */
@@ -124,40 +122,195 @@ function DegradedPill({ label, title, t }: { label: string; title?: string; t: (
124
122
  )
125
123
  }
126
124
 
127
- /** Popup body (rendered inside the portaled card): root, counts, commits, changes, refresh. */
125
+ /**
126
+ * Popup body (rendered inside the portaled card)。
127
+ * 分支管理(切换/新建)已并入本组件:头部内联切换 + 新建行上提;
128
+ * 变更行带 hover 内联操作(暂存/取消/丢弃两步)。
129
+ */
128
130
  function GitPopupBody({
129
- view, refresh, openCenter, t,
131
+ view, refresh, openCenter, onOpenDiff, run, query, t,
130
132
  }: {
131
133
  view: GitView & { state: 'ready' }
132
134
  refresh: () => Promise<void>
133
135
  openCenter: () => void
136
+ /** 变更文件点击:打开 Git 中心并定位该文件的对照视图。 */
137
+ onOpenDiff: (path: string, base: 'worktree' | 'staged') => void
138
+ run: (action: GitAction) => Promise<GitActionResult>
139
+ query: (query: GitQueryRequest['query']) => Promise<GitQueryOutcome>
134
140
  t: (key: GitKey) => string
135
141
  }): JSX.Element {
136
142
  const now = Date.now()
137
143
  const s = view.snapshot
144
+ const branchLabel = s.branch === null ? `(${t('pill.detached')})` : s.branch
145
+
146
+ /** 分支管理状态(自原 BranchQuickManage 并入):切换(头部内联)+ 新建(上提)。 */
147
+ const [branchData, setBranchData] = useState<{ current: string | null; local: readonly GitBranch[] } | null>(null)
148
+ const [busy, setBusy] = useState(false)
149
+ const [newName, setNewName] = useState('')
150
+ const [note, setNote] = useState<{ text: string; detail?: string; action?: 'open-center' } | null>(null)
151
+ // 变更行丢弃两步确认:armed 记录待确认的路径,3s 自动解除。
152
+ const [armed, setArmed] = useState<string | null>(null)
153
+
154
+ /** 操作失败 → 友好告警:业务错误用 i18n 文案 + 行动按钮,原始信息留 detail。 */
155
+ const setErrorNote = (err: { code: GitOperationErrorCode; message?: string }): void => {
156
+ setNote({
157
+ text: errorText(err.code, err.message, t),
158
+ ...(err.message === undefined ? {} : { detail: err.message }),
159
+ ...(errorAction(err.code) === null ? {} : { action: errorAction(err.code) ?? undefined }),
160
+ })
161
+ }
162
+
163
+ const reload = async (): Promise<void> => {
164
+ const outcome = await query({ kind: 'branches' })
165
+ if (outcome.ok && outcome.value.kind === 'branches') {
166
+ setBranchData({ current: outcome.value.current, local: outcome.value.local })
167
+ }
168
+ }
169
+
170
+ useEffect(() => {
171
+ void reload()
172
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- mount-only
173
+ }, [])
174
+
175
+ useEffect(() => {
176
+ if (armed === null) return
177
+ const timer = setTimeout(() => setArmed(null), 3000)
178
+ return () => clearTimeout(timer)
179
+ }, [armed])
180
+
181
+ const switchTo = async (name: string): Promise<void> => {
182
+ if (busy || name === '') return
183
+ setBusy(true)
184
+ setNote(null)
185
+ const result = await run({ kind: 'branch-checkout', name })
186
+ setBusy(false)
187
+ if (!result.ok) setErrorNote(result.error)
188
+ await reload()
189
+ }
190
+
191
+ const createAndSwitch = async (): Promise<void> => {
192
+ const name = newName.trim()
193
+ if (name === '' || busy) return
194
+ setBusy(true)
195
+ setNote(null)
196
+ const created = await run({ kind: 'branch-create', name })
197
+ if (created.ok) {
198
+ const switched = await run({ kind: 'branch-checkout', name })
199
+ if (!switched.ok) setErrorNote(switched.error)
200
+ setNewName('')
201
+ } else {
202
+ setErrorNote(created.error)
203
+ }
204
+ setBusy(false)
205
+ await reload()
206
+ }
207
+
208
+ /** 执行一条变更行操作(暂存/取消/丢弃),失败以 note 显示。 */
209
+ const runChange = async (action: GitAction, path: string): Promise<void> => {
210
+ if (busy) return
211
+ setBusy(true)
212
+ setNote(null)
213
+ const result = await run(action)
214
+ setBusy(false)
215
+ if (!result.ok) setErrorNote(result.error)
216
+ }
217
+
218
+ const stage = (path: string): void => void runChange({ kind: 'stage', paths: [path] }, path)
219
+ const unstage = (path: string): void => void runChange({ kind: 'unstage', paths: [path] }, path)
220
+ const discard = (path: string): void => {
221
+ if (busy) return
222
+ if (armed !== path) { setArmed(path); return }
223
+ setArmed(null)
224
+ void runChange({ kind: 'discard', paths: [path] }, path)
225
+ }
226
+
138
227
  return (
139
228
  <>
140
- <h4 style={css.popupTitle}>{t('popup.title')}</h4>
141
- <div style={css.rootLine} title={s.root}>{s.root}</div>
142
- <div style={css.countGrid}>
229
+ <header style={css.popupHeader}>
230
+ <div style={css.popupHeaderMain}>
231
+ <span style={s.dirty ? css.dotDirty : css.dot} aria-hidden="true" />
232
+ {branchData === null ? (
233
+ <span style={css.popupHeaderBranch}>{branchLabel}</span>
234
+ ) : (
235
+ <SelectMenu
236
+ value={branchData.current ?? ''}
237
+ options={[
238
+ // 游离 HEAD:注入伪选项让头部显示游离标签,仍可下拉切换本地分支。
239
+ ...(branchData.current === null ? [{ value: '', label: branchLabel }] : []),
240
+ ...branchData.local.map((b) => ({ value: b.name, label: b.name })),
241
+ ]}
242
+ onSelect={(name) => void switchTo(name)}
243
+ ariaLabel={t('center.currentBranch')}
244
+ buttonStyle={css.popupBranchMenu}
245
+ />
246
+ )}
247
+ {s.unborn && <span style={css.popupBadge}>{t('pill.noCommits')}</span>}
248
+ {s.dirty && <span style={css.popupBadge}>{dirtyBadge(view)}</span>}
249
+ {(s.ahead > 0 || s.behind > 0) && <span style={css.popupBadge}>{aheadBehind(view)}</span>}
250
+ </div>
251
+ <div style={css.popupHeaderRoot} title={s.root}>
252
+ <FolderIcon />
253
+ <span style={css.popupHeaderRootText}>{s.root}</span>
254
+ </div>
255
+ </header>
256
+ <div style={css.popupStatusBar}>
143
257
  {([
144
258
  ['popup.staged', s.staged], ['popup.modified', s.modified], ['popup.untracked', s.untracked],
145
- ['popup.ahead', s.ahead], ['popup.behind', s.behind],
146
259
  ] as const).map(([key, value]) => (
147
- <div key={key} style={css.countCell}>
148
- <div style={css.countValue}>{value}</div>
149
- <div style={css.countLabel}>{t(key)}</div>
150
- </div>
260
+ <span key={key} style={css.popupStatItem}>
261
+ <span style={css.popupStatValue}>{value}</span>
262
+ <span style={css.popupStatLabel}>{t(key)}</span>
263
+ </span>
151
264
  ))}
152
265
  </div>
266
+ <div style={css.popupBranchOps}>
267
+ <input
268
+ className="dsh-git-ui__branch-input"
269
+ style={css.branchNameInput}
270
+ placeholder={t('center.branchName')}
271
+ value={newName}
272
+ disabled={busy}
273
+ onChange={(e) => setNewName(e.target.value)}
274
+ onKeyDown={(e) => { if (e.key === 'Enter') void createAndSwitch() }}
275
+ />
276
+ <Button size="sm" disabled={busy || newName.trim() === ''} onClick={() => void createAndSwitch()}>
277
+ {t('center.createAndSwitch')}
278
+ </Button>
279
+ </div>
280
+ {note !== null && (
281
+ <div style={css.popupNote} role="alert">
282
+ <span style={css.popupNoteIcon} aria-hidden="true"><AlertIcon /></span>
283
+ <span style={css.popupNoteText} title={note.detail}>{note.text}</span>
284
+ {note.action === 'open-center' && (
285
+ <button type="button" className="dsh-git-ui__change-link" style={css.popupNoteAction} onClick={openCenter}>
286
+ {t('error.handleChanges')}
287
+ </button>
288
+ )}
289
+ <button
290
+ type="button"
291
+ className="dsh-git-ui__icon-btn"
292
+ style={css.popupNoteClose}
293
+ title={t('center.close')}
294
+ aria-label={t('center.close')}
295
+ onClick={() => setNote(null)}
296
+ >
297
+ <CloseIcon />
298
+ </button>
299
+ </div>
300
+ )}
153
301
  <div style={css.sectionTitle}>{t('popup.recentCommits')}</div>
154
302
  {s.recentCommits.length === 0
155
303
  ? <div style={css.emptyNote}>{t('popup.emptyCommits')}</div>
156
- : s.recentCommits.map((commit) => (
157
- <div key={commit.hash} style={css.commitRow}>
158
- <span style={css.commitHash}>{commit.shortHash}</span>
159
- <span style={css.commitSubject} title={commit.subject}>{commit.subject}</span>
160
- <span style={css.commitMeta}>{commit.author} · {timeAgo(commit.dateIso, now, t)}</span>
304
+ : s.recentCommits.slice(0, 3).map((commit) => (
305
+ <div key={commit.hash} className="dsh-git-ui__row" style={css.commitRow}>
306
+ <div style={css.commitSubjectPop} title={commit.subject}>{commit.subject}</div>
307
+ <div style={css.commitMetaLine}>
308
+ <span style={css.commitHash}>{commit.shortHash}</span>
309
+ <span style={css.commitDot}>·</span>
310
+ <span style={css.commitMeta}>{commit.author}</span>
311
+ <span style={css.commitDot}>·</span>
312
+ <span style={css.commitMeta}>{timeAgo(commit.dateIso, now, t)}</span>
313
+ </div>
161
314
  </div>
162
315
  ))}
163
316
  <div style={css.sectionTitle}>{t('popup.changes')}</div>
@@ -165,17 +318,75 @@ function GitPopupBody({
165
318
  ? <div style={css.emptyNote}>{t('popup.empty')}</div>
166
319
  : (
167
320
  <>
168
- {s.changes.map((change) => (
169
- <div key={change.path} style={css.changeRow}>
170
- <span
171
- style={{ ...css.changeChip, background: CHIP_COLORS[change.status] ?? '#888' }}
172
- title={change.status}
173
- >
174
- {CHIP_LETTERS[change.status] ?? '•'}
175
- </span>
176
- <span style={css.changePath} title={change.path}>{change.path}</span>
177
- </div>
178
- ))}
321
+ {s.changes.map((change) => {
322
+ const { name, dir, isDir } = splitChangePath(change.path, change.isDirectory)
323
+ const untracked = change.status === 'untracked'
324
+ return (
325
+ <div key={change.path} className="dsh-git-ui__row" style={css.changeRow}>
326
+ <span
327
+ style={{ ...css.changeChip, ...(css.chipStyles[change.status] ?? css.chipStyles.untracked) }}
328
+ title={change.status}
329
+ >
330
+ {CHIP_LETTERS[change.status] ?? '•'}
331
+ </span>
332
+ <span style={css.rowFileIcon} aria-hidden="true">
333
+ {isDir ? <FolderIcon /> : fileIconForPath(change.path)}
334
+ </span>
335
+ {isDir ? (
336
+ // 目录条目:点击打开 Git 中心变更页(目录无 diff 语义,展开后选具体文件)。
337
+ <button
338
+ type="button"
339
+ className="dsh-git-ui__change-link"
340
+ style={css.changeNamePopBtn}
341
+ title={change.path}
342
+ aria-label={`${name} — ${t('center.open')}`}
343
+ onClick={openCenter}
344
+ >
345
+ {name}
346
+ </button>
347
+ ) : (
348
+ // 文件条目:点击打开 Git 中心并直接展示该文件对照。
349
+ <button
350
+ type="button"
351
+ className="dsh-git-ui__change-link"
352
+ style={css.changeNamePopBtn}
353
+ title={change.path}
354
+ aria-label={`${name} — ${t('changes.actionDiff')}`}
355
+ onClick={() => onOpenDiff(change.path, diffBaseOf(change))}
356
+ >
357
+ {name}
358
+ </button>
359
+ )}
360
+ {dir !== '' ? <span style={css.changeDirPop}>{dir}</span> : <span style={{ flex: '1 1 0%', minWidth: 0 }} />}
361
+ <span className="dsh-git-ui__row-actions" style={css.rowActions}>
362
+ {change.staged
363
+ ? (
364
+ <button type="button" className="dsh-git-ui__icon-btn" style={css.rowIconButton} title={t('center.unstage')} aria-label={t('center.unstage')} disabled={busy} onClick={() => unstage(change.path)}>
365
+ <UnstageIcon />
366
+ </button>
367
+ )
368
+ : (
369
+ <button type="button" className="dsh-git-ui__icon-btn" style={css.rowIconButton} title={t('center.stage')} aria-label={t('center.stage')} disabled={busy} onClick={() => stage(change.path)}>
370
+ <StageIcon />
371
+ </button>
372
+ )}
373
+ {!untracked && (
374
+ <button
375
+ type="button"
376
+ className="dsh-git-ui__icon-btn"
377
+ style={armed === change.path ? { ...css.rowIconButton, color: 'var(--dsw-alias-state-error-primary)' } : css.rowIconButton}
378
+ title={armed === change.path ? t('center.confirmDiscard') : t('center.discard')}
379
+ aria-label={armed === change.path ? t('center.confirmDiscard') : t('center.discard')}
380
+ disabled={busy}
381
+ onClick={() => discard(change.path)}
382
+ >
383
+ <RollbackIcon />
384
+ </button>
385
+ )}
386
+ </span>
387
+ </div>
388
+ )
389
+ })}
179
390
  {s.truncated && (
180
391
  <div style={css.emptyNote}>{t('popup.changesTruncated').replace('{count}', String(s.changes.length))}</div>
181
392
  )}
@@ -183,11 +394,11 @@ function GitPopupBody({
183
394
  )}
184
395
  <div style={css.footerRow}>
185
396
  <span style={css.checkedAt}>{t('popup.checkedAt').replace('{time}', new Date(s.checkedAt).toLocaleTimeString())}</span>
186
- <span style={{ display: 'inline-flex', gap: 4, alignItems: 'center' }}>
187
- <button type="button" className="dsh-git-ui__refresh" style={css.refreshButton} onClick={openCenter}>
397
+ <span style={css.footerActions}>
398
+ <PopRefresher refresh={refresh} t={t} />
399
+ <button type="button" className="dsh-git-ui__footer-primary" style={{ ...css.refreshButton, ...css.footerPrimary, padding: '4px 10px' }} onClick={openCenter}>
188
400
  {t('center.open')}
189
401
  </button>
190
- <PopRefresher refresh={refresh} t={t} />
191
402
  </span>
192
403
  </div>
193
404
  </>
@@ -220,7 +431,7 @@ const VIEW_GUTTER = 8
220
431
  * The header utility entry: a branch pill that opens a portaled detail popup
221
432
  * and the Git center management panel.
222
433
  */
223
- export function GitPill({ useGit, useSession, refresh, run, t }: GitPillProps): JSX.Element | null {
434
+ export function GitPill({ useGit, useSession, refresh, run, query, t }: GitPillProps): JSX.Element | null {
224
435
  // The selector hook requires a selector function (with-selector calls it
225
436
  // unconditionally); identity selection reads the whole view snapshot.
226
437
  const view = useGit((view) => view)
@@ -251,6 +462,16 @@ export function GitPill({ useGit, useSession, refresh, run, t }: GitPillProps):
251
462
  const [open, setOpen] = useState(false)
252
463
  const [centerOpen, setCenterOpen] = useState(false)
253
464
  const [pos, setPos] = useState<{ top: number; left: number } | null>(null)
465
+ /** 从 pill 变更行点击「打开 Git 中心并定位该文件 diff」的请求。 */
466
+ const [centerRequest, setCenterRequest] = useState<{ path: string; base: 'worktree' | 'staged' } | null>(null)
467
+
468
+ /** 打开 Git 中心并直接定位到该文件的对照视图(关 popup、切 changes 标签、查询 diff)。 */
469
+ const openDiffInCenter = (path: string, base: 'worktree' | 'staged'): void => {
470
+ setCenterRequest({ path, base })
471
+ setOpen(false)
472
+ setPos(null)
473
+ setCenterOpen(true)
474
+ }
254
475
 
255
476
  useEffect(() => {
256
477
  // First mount only: kick the controller once (single-flight; a cold
@@ -302,10 +523,7 @@ export function GitPill({ useGit, useSession, refresh, run, t }: GitPillProps):
302
523
  if (!open) return
303
524
  const close = (): void => { setOpen(false); setPos(null) }
304
525
  const onDown = (e: MouseEvent): void => {
305
- const target = e.target as Node
306
- if (wrapRef.current?.contains(target) ?? false) return
307
- if (popRef.current?.contains(target) ?? false) return
308
- close()
526
+ if (shouldClosePopup(e.target, wrapRef.current, popRef.current)) close()
309
527
  }
310
528
  const onKey = (e: KeyboardEvent): void => { if (e.key === 'Escape') close() }
311
529
  document.addEventListener('mousedown', onDown)
@@ -335,6 +553,7 @@ export function GitPill({ useGit, useSession, refresh, run, t }: GitPillProps):
335
553
  }
336
554
 
337
555
  const dirty = display.snapshot.dirty
556
+ const parts = pillParts(display, t)
338
557
  return (
339
558
  <span ref={wrapRef} style={{ display: 'inline-flex' }}>
340
559
  <button
@@ -344,10 +563,11 @@ export function GitPill({ useGit, useSession, refresh, run, t }: GitPillProps):
344
563
  onClick={() => setOpen(!open)}
345
564
  aria-haspopup="dialog"
346
565
  aria-expanded={open}
347
- title={`${display.snapshot.root}\n${pillLabel(display, t)}`}
566
+ title={`${display.snapshot.root}\n${[parts.branch, ...parts.badges].filter(Boolean).join(' · ')}`}
348
567
  >
349
568
  <span style={dirty ? css.dotDirty : css.dot} aria-hidden="true" />
350
- <span>{pillLabel(display, t)}</span>
569
+ <span style={css.pillBranch}>{parts.branch}</span>
570
+ {parts.badges.length > 0 && <span style={css.pillBadges}>{parts.badges.join(' · ')}</span>}
351
571
  </button>
352
572
  {open && pos !== null && createPortal(
353
573
  <div
@@ -361,6 +581,9 @@ export function GitPill({ useGit, useSession, refresh, run, t }: GitPillProps):
361
581
  view={display}
362
582
  refresh={refresh}
363
583
  openCenter={() => { setOpen(false); setPos(null); setCenterOpen(true) }}
584
+ onOpenDiff={openDiffInCenter}
585
+ run={run}
586
+ query={query}
364
587
  t={t}
365
588
  />
366
589
  </div>,
@@ -371,7 +594,9 @@ export function GitPill({ useGit, useSession, refresh, run, t }: GitPillProps):
371
594
  onClose={() => setCenterOpen(false)}
372
595
  snapshot={display.snapshot}
373
596
  run={run}
597
+ query={query}
374
598
  t={t}
599
+ openRequest={centerRequest}
375
600
  />
376
601
  </span>
377
602
  )
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Changes 差异视图的选择态协调(纯函数,可单元测试)。
3
+ *
4
+ * 快照变化后(轮询 / 管理操作成功),正在对照的文件可能消失,也可能在
5
+ * 已暂存/未暂存两侧之间迁移(混合态拆分出的双条目)。
6
+ * `reconcileDiffSelection` 给出视图应维持的选择态:
7
+ * - null → 文件已不在变更清单,关闭对照;
8
+ * - 基线不变的选择 → 保持当前基线(MM 双条目优先复用原基线);
9
+ * - 基线变更的选择 → 按文件当前所属侧重取。
10
+ * 无论基线是否变化,调用方都应重取差异内容——操作可能刚改变了同一文件。
11
+ */
12
+
13
+ /** 正在对照查看的文件(base 由打开行时的暂存态决定)。 */
14
+ export interface DiffSelection {
15
+ readonly path: string
16
+ readonly base: 'worktree' | 'staged'
17
+ }
18
+
19
+ /** 变更行结构面(与宿主 GitChange 同构)。 */
20
+ export interface ChangeLike {
21
+ readonly path: string
22
+ readonly status: string
23
+ readonly staged: boolean
24
+ }
25
+
26
+ /** 变更行对应的差异基线:未跟踪与未暂存侧 → 工作区;已暂存侧 → 暂存区。 */
27
+ export function diffBaseOf(change: ChangeLike): 'worktree' | 'staged' {
28
+ if (change.status === 'untracked') return 'worktree'
29
+ return change.staged ? 'staged' : 'worktree'
30
+ }
31
+
32
+ /** 按新的变更清单协调当前选择态;语义见模块注释。 */
33
+ export function reconcileDiffSelection(
34
+ selection: DiffSelection,
35
+ changes: readonly ChangeLike[],
36
+ ): DiffSelection | null {
37
+ const entries = changes.filter((c) => c.path === selection.path)
38
+ if (entries.length === 0) return null
39
+ const sameBase = entries.find((c) => diffBaseOf(c) === selection.base)
40
+ if (sameBase !== undefined) return { path: selection.path, base: selection.base }
41
+ return { path: selection.path, base: diffBaseOf(entries[0]!) }
42
+ }
43
+
44
+ /**
45
+ * 上一个/下一个更改的循环导航:`entries` 为导航序列(分组顺序),
46
+ * `current` 为空时定位第一条;当前项不在序列中时按首项计;
47
+ * `delta` 取 ±1(模长度循环,首尾相接)。空序列返回 null。
48
+ */
49
+ export function stepDiffSelection(
50
+ entries: readonly ChangeLike[],
51
+ current: DiffSelection | null,
52
+ delta: number,
53
+ ): DiffSelection | null {
54
+ if (entries.length === 0) return null
55
+ if (current === null) {
56
+ const first = entries[0]!
57
+ return { path: first.path, base: diffBaseOf(first) }
58
+ }
59
+ const found = entries.findIndex((c) => c.path === current.path && diffBaseOf(c) === current.base)
60
+ const index = found === -1 ? 0 : found
61
+ const next = entries[(index + delta + entries.length) % entries.length]!
62
+ return { path: next.path, base: diffBaseOf(next) }
63
+ }
@@ -5,7 +5,7 @@
5
5
  * connection reset, `dispose()` on slot teardown (clears the timer and
6
6
  * rejects nothing — in-flight work settles into a withdrawn view).
7
7
  */
8
- import type { GitActionResult, GitActionRequest, GitSnapshot, GitSnapshotFailure, GitSnapshotRequest, GitSnapshotResult } from '../host/types.ts'
8
+ import type { GitActionResult, GitActionRequest, GitQueryRequest, GitQueryResponse, GitSnapshot, GitSnapshotFailure, GitSnapshotRequest, GitSnapshotResult } from '../host/types.ts'
9
9
 
10
10
  /** The observable view contract components consume (useSyncExternalStore shape). */
11
11
  export interface GitObservable<V> {
@@ -36,8 +36,14 @@ export type GitRemoteEnvelope<T> =
36
36
  export interface GitRemoteLike {
37
37
  snapshot(request: GitSnapshotRequest): Promise<GitRemoteEnvelope<GitSnapshotResult>>
38
38
  run(request: GitActionRequest): Promise<GitRemoteEnvelope<GitActionResult>>
39
+ query(request: GitQueryRequest): Promise<GitRemoteEnvelope<GitQueryResponse>>
39
40
  }
40
41
 
42
+ /** Simplified query outcome for the UI (envelope + business errors unwrapped). */
43
+ export type GitQueryOutcome =
44
+ | { readonly ok: true; readonly value: Extract<GitQueryResponse, { ok: true }>['value'] }
45
+ | { readonly ok: false; readonly message: string }
46
+
41
47
  /** Failure codes that mean "no working directory to watch" — degrade to a
42
48
  * low-frequency probe instead of a normal poll. */
43
49
  const TERMINAL_CODES: ReadonlySet<string> = new Set(['cwd-unavailable', 'session-not-found'])
@@ -173,6 +179,35 @@ export class GitController implements GitObservable<GitView> {
173
179
  return promise
174
180
  }
175
181
 
182
+ /**
183
+ * Run one read-only query (history / diff / show / branches). The view is
184
+ * untouched — the result goes straight back to the caller. Queues behind
185
+ * any in-flight refresh/run like everything else (single-flight).
186
+ */
187
+ query(query: GitQueryRequest['query']): Promise<GitQueryOutcome> {
188
+ if (this.inflight !== undefined) return this.inflight.then(() => this.query(query))
189
+ if (this.disposed) return Promise.resolve({ ok: false, message: 'controller disposed' })
190
+ const promise = this.remote.query({ sessionId: this.sessionId, query })
191
+ .then((result): GitQueryOutcome => {
192
+ if (!result.ok) {
193
+ const detail = [result.error.code, result.error.message].filter(Boolean).join(': ')
194
+ return { ok: false, message: detail || 'rpc failure' }
195
+ }
196
+ const inner = result.value
197
+ if (inner.ok) return { ok: true, value: inner.value }
198
+ return { ok: false, message: inner.error.message ?? inner.error.code }
199
+ })
200
+ .catch((error: unknown): GitQueryOutcome => {
201
+ return { ok: false, message: error instanceof Error ? error.message : String(error) }
202
+ })
203
+ .finally(() => {
204
+ this.inflight = undefined
205
+ if (!this.disposed) this.schedulePoll()
206
+ })
207
+ this.inflight = promise.then(() => undefined)
208
+ return promise
209
+ }
210
+
176
211
  /** Tear down: stop the timer; in-flight work settles into a no-op. */
177
212
  dispose(): void {
178
213
  this.disposed = true
@@ -0,0 +1,21 @@
1
+ import type { GitKey } from './locales.ts'
2
+ import type { GitOperationErrorCode } from '../host/types.ts'
3
+
4
+ /**
5
+ * 操作错误 → 展示文案。可预期的业务错误(如切换分支被未提交变更阻止)
6
+ * 映射本地化友好文案;其余错误回退原始 git message(无 message 时用 code)。
7
+ * 原始信息由调用方经 errorTextDetail 保留,供 title 等按需展示。
8
+ */
9
+ export function errorText(code: GitOperationErrorCode, message: string | undefined, t: (key: GitKey) => string): string {
10
+ switch (code) {
11
+ case 'local-changes-block':
12
+ return t('error.localChangesBlock')
13
+ default:
14
+ return message ?? code
15
+ }
16
+ }
17
+
18
+ /** 该错误是否应附带「处理变更」行动(打开 Git 中心变更页)。 */
19
+ export function errorAction(code: GitOperationErrorCode): 'open-center' | null {
20
+ return code === 'local-changes-block' ? 'open-center' : null
21
+ }