dsh-gufa-code 1.3.67 → 1.3.69

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 CHANGED
@@ -16,7 +16,7 @@ const GUFA_NS = 'gufa-code'
16
16
  const G = {}
17
17
  G.NS = GUFA_NS
18
18
  /** 客户端构建标记(排查页面是否加载了新代码时看标题栏) */
19
- G.BUILD = '1.3.67'
19
+ G.BUILD = '1.3.69'
20
20
  G.PANEL_ID = 'gufa-code'
21
21
  /** 从哪个工作区点进来的(工作区菜单/节点按钮写入,App 启动时消费)。 */
22
22
  G.pendingEntryWorkspace = null
@@ -8180,6 +8180,20 @@ G.GitPanel = function GitPanel(props) {
8180
8180
  h(G.Button, { disabled: pending || message.trim() === '', primary: true, onClick: commit }, pending ? h(G.Spinner) : null, t('git.commit')),
8181
8181
  )
8182
8182
  : null,
8183
+ staged.length > 0 ? h('div', { className: 'gufa-hint' }, `${t('git.staged')} (${staged.length})`) : null,
8184
+ ...staged.map((change) =>
8185
+ h(G.GitChangeRow, {
8186
+ key: `s:${change.path}`,
8187
+ change,
8188
+ pending,
8189
+ staged: true,
8190
+ onOpen: () => props.onOpenDiff?.(change),
8191
+ onContextMenu: (event, rowChange) => setRowMenu({ ...clampMenuPosition(event.clientX, event.clientY, 200, 200), change: rowChange }),
8192
+ onAction: () => void act(async () => G.api('git.unstage', { root, paths: [change.path] })),
8193
+ actionLabel: t('git.unstage'),
8194
+ actionIcon: 'minus',
8195
+ }),
8196
+ ),
8183
8197
  unstaged.length > 0 ? h('div', { className: 'gufa-hint' }, `${t('git.unstaged')} (${unstaged.length})`) : null,
8184
8198
  ...unstaged.map((change) =>
8185
8199
  h(G.GitChangeRow, {
@@ -8195,20 +8209,6 @@ G.GitPanel = function GitPanel(props) {
8195
8209
  actionIcon: 'plus',
8196
8210
  }),
8197
8211
  ),
8198
- staged.length > 0 ? h('div', { className: 'gufa-hint' }, `${t('git.staged')} (${staged.length})`) : null,
8199
- ...staged.map((change) =>
8200
- h(G.GitChangeRow, {
8201
- key: `s:${change.path}`,
8202
- change,
8203
- pending,
8204
- staged: true,
8205
- onOpen: () => props.onOpenDiff?.(change),
8206
- onContextMenu: (event, rowChange) => setRowMenu({ ...clampMenuPosition(event.clientX, event.clientY, 200, 200), change: rowChange }),
8207
- onAction: () => void act(async () => G.api('git.unstage', { root, paths: [change.path] })),
8208
- actionLabel: t('git.unstage'),
8209
- actionIcon: 'minus',
8210
- }),
8211
- ),
8212
8212
  ),
8213
8213
  ),
8214
8214
  headMenu === null
@@ -9259,6 +9259,162 @@ function gufaPlaceDockedConversation(root, host, options) {
9259
9259
  return true
9260
9260
  }
9261
9261
 
9262
+ /**
9263
+ * 停靠后的官方会话「贴底跟随」守护。
9264
+ *
9265
+ * 官方会话自己有一套 follow 策略(ChatView root 上的 `data-chat-following-tail` 属性),
9266
+ * 但在 fixed 停靠 + 频繁重排/ResizeObserver 的容器里,偶发出现「发起聊天后滚动条不在最下面」。
9267
+ * 这里只在官方自己认为处于「跟随尾部」时补一次贴底(以及刚发送消息后的 2.5s 内),
9268
+ * 用户主动滚动/官方取消跟随时绝不抢滚动条。
9269
+ */
9270
+ function gufaCreateChatFollowKeeper() {
9271
+ let scroller = null
9272
+ let observer = null
9273
+ let resizeObserver = null
9274
+ let interval = null
9275
+ let frame = 0
9276
+ let retryTimer = 0
9277
+ let forceUntil = 0
9278
+ let diagnosticsLeft = 24
9279
+ const diag = (message) => {
9280
+ if (diagnosticsLeft <= 0) return
9281
+ diagnosticsLeft -= 1
9282
+ try {
9283
+ void G.api('dev.log', { message: `chat-follow ${message}` }).catch(() => {})
9284
+ } catch {
9285
+ /* ignore */
9286
+ }
9287
+ }
9288
+
9289
+ const hasFollowAttr = () => {
9290
+ try {
9291
+ return scroller !== null && scroller.isConnected && scroller.querySelector('[data-chat-following-tail]') !== null
9292
+ } catch {
9293
+ return false
9294
+ }
9295
+ }
9296
+ const shouldFollow = () => hasFollowAttr() || Date.now() < forceUntil
9297
+ const toBottom = () => {
9298
+ if (scroller === null || !scroller.isConnected) return
9299
+ try {
9300
+ const max = scroller.scrollHeight - scroller.clientHeight
9301
+ if (max <= 0) return
9302
+ if (scroller.scrollTop < max - 2) scroller.scrollTop = max
9303
+ } catch {
9304
+ /* ignore */
9305
+ }
9306
+ }
9307
+ const hasRoom = () => {
9308
+ if (scroller === null || !scroller.isConnected) return false
9309
+ return scroller.scrollHeight - scroller.clientHeight > 1
9310
+ }
9311
+ const pump = () => {
9312
+ frame = 0
9313
+ if (document.visibilityState !== 'visible') return
9314
+ if (!shouldFollow()) return
9315
+ const before = Math.round(scroller.scrollTop)
9316
+ const max = Math.round(scroller.scrollHeight - scroller.clientHeight)
9317
+ if (scroller.scrollTop < max - 2) diag(`pump top=${before} max=${max} follow=${hasFollowAttr()} force=${Date.now() < forceUntil}`)
9318
+ toBottom()
9319
+ /* 流式内容/折叠动画/图片加载会分几帧改变高度:短时间重试几次 */
9320
+ if (retryTimer !== 0) window.clearTimeout(retryTimer)
9321
+ retryTimer = window.setTimeout(() => {
9322
+ retryTimer = 0
9323
+ if (shouldFollow() && hasRoom()) toBottom()
9324
+ }, 120)
9325
+ }
9326
+ const schedule = () => {
9327
+ if (frame !== 0) return
9328
+ frame = window.requestAnimationFrame(pump)
9329
+ }
9330
+ const onWheel = () => { forceUntil = 0 }
9331
+ const onKeyDown = (event) => {
9332
+ if (event.key !== 'Enter' || event.shiftKey === true || event.isComposing === true) return
9333
+ try {
9334
+ if (event.target instanceof Element && event.target.closest('[data-composer-input], [data-composer-seat]') !== null) {
9335
+ forceUntil = Date.now() + 2500
9336
+ schedule()
9337
+ }
9338
+ } catch {
9339
+ /* ignore */
9340
+ }
9341
+ }
9342
+ const onPointerDown = (event) => {
9343
+ try {
9344
+ if (event.target instanceof Element && event.target.closest('[data-composer-seat]') !== null) {
9345
+ forceUntil = Date.now() + 2500
9346
+ schedule()
9347
+ }
9348
+ } catch {
9349
+ /* ignore */
9350
+ }
9351
+ }
9352
+ const attach = (next) => {
9353
+ if (next === null || next === undefined || next === scroller) return
9354
+ detach()
9355
+ scroller = next
9356
+ try {
9357
+ observer = new MutationObserver(() => schedule())
9358
+ observer.observe(next, {
9359
+ childList: true,
9360
+ subtree: true,
9361
+ characterData: true,
9362
+ attributes: true,
9363
+ attributeFilter: ['data-chat-following-tail'],
9364
+ })
9365
+ } catch {
9366
+ observer = null
9367
+ }
9368
+ try {
9369
+ if (typeof ResizeObserver === 'function') {
9370
+ resizeObserver = new ResizeObserver(() => schedule())
9371
+ resizeObserver.observe(next)
9372
+ const content = next.firstElementChild
9373
+ if (content !== null && content !== undefined) resizeObserver.observe(content)
9374
+ }
9375
+ } catch {
9376
+ resizeObserver = null
9377
+ }
9378
+ /* 兜底:即使没有 DOM 变更事件,跟随期间也低频检查一次(异步高度变化) */
9379
+ interval = window.setInterval(() => {
9380
+ if (shouldFollow()) schedule()
9381
+ }, 700)
9382
+ next.addEventListener('wheel', onWheel, { passive: true })
9383
+ next.addEventListener('touchstart', onWheel, { passive: true })
9384
+ next.addEventListener('keydown', onKeyDown, true)
9385
+ next.addEventListener('pointerdown', onPointerDown, true)
9386
+ diag(`attach top=${Math.round(next.scrollTop)} max=${Math.round(next.scrollHeight - next.clientHeight)} follow=${hasFollowAttr()}`)
9387
+ schedule()
9388
+ }
9389
+ const detach = () => {
9390
+ if (frame !== 0) {
9391
+ window.cancelAnimationFrame(frame)
9392
+ frame = 0
9393
+ }
9394
+ if (retryTimer !== 0) {
9395
+ window.clearTimeout(retryTimer)
9396
+ retryTimer = 0
9397
+ }
9398
+ if (interval !== null) {
9399
+ window.clearInterval(interval)
9400
+ interval = null
9401
+ }
9402
+ observer?.disconnect()
9403
+ observer = null
9404
+ resizeObserver?.disconnect()
9405
+ resizeObserver = null
9406
+ if (scroller !== null) {
9407
+ scroller.removeEventListener('wheel', onWheel)
9408
+ scroller.removeEventListener('touchstart', onWheel)
9409
+ scroller.removeEventListener('keydown', onKeyDown, true)
9410
+ scroller.removeEventListener('pointerdown', onPointerDown, true)
9411
+ }
9412
+ scroller = null
9413
+ forceUntil = 0
9414
+ }
9415
+ return { attach, detach }
9416
+ }
9417
+
9262
9418
  /** 毫秒时间戳 → 简短相对时间(会话下拉用)。 */
9263
9419
  function gufaRelativeTime(timestamp) {
9264
9420
  const delta = Date.now() - timestamp
@@ -9421,6 +9577,8 @@ G.ChatDock = function ChatDock(props) {
9421
9577
  const theme = props.theme === 'light' ? 'light' : 'dark'
9422
9578
  const hostRef = useRef(null)
9423
9579
  const dockRef = useRef({ root: null, saved: null })
9580
+ const followRef = useRef(null)
9581
+ if (followRef.current === null) followRef.current = gufaCreateChatFollowKeeper()
9424
9582
  const tickRef = useRef(null)
9425
9583
  const startedRef = useRef(0)
9426
9584
  const [phase, setPhase] = useState('searching')
@@ -9439,6 +9597,7 @@ G.ChatDock = function ChatDock(props) {
9439
9597
  if (host === null) return
9440
9598
  const root = gufaFindConversationRoot()
9441
9599
  if (root === null) {
9600
+ followRef.current?.detach()
9442
9601
  if (dockRef.current.root !== null) undock()
9443
9602
  setPhase((previous) => {
9444
9603
  if (previous === 'docked') return 'searching'
@@ -9452,6 +9611,12 @@ G.ChatDock = function ChatDock(props) {
9452
9611
  dockRef.current = { root, saved: gufaSnapshotDockTarget(root) }
9453
9612
  }
9454
9613
  if (gufaPlaceDockedConversation(root, host, { translucent: props.backdrop === true })) {
9614
+ try {
9615
+ const scroller = root.querySelector(GUFA_CONVERSATION_SCROLL_SELECTOR)
9616
+ if (scroller !== null && scroller !== undefined) followRef.current?.attach(scroller)
9617
+ } catch {
9618
+ /* ignore */
9619
+ }
9455
9620
  setPhase((previous) => (previous === 'docked' ? previous : 'docked'))
9456
9621
  }
9457
9622
  }, [active, undock, props.backdrop])
@@ -9490,6 +9655,7 @@ G.ChatDock = function ChatDock(props) {
9490
9655
  observer?.disconnect()
9491
9656
  resizeObserver?.disconnect()
9492
9657
  window.removeEventListener('resize', onWindowResize)
9658
+ followRef.current?.detach()
9493
9659
  undock()
9494
9660
  }
9495
9661
  }, [active, undock])
@@ -10816,6 +10982,25 @@ G.GufaApp = function GufaApp(props) {
10816
10982
  return map
10817
10983
  }, [gitStatus])
10818
10984
 
10985
+ /* 暂存/取消暂存/提交后,已失效的 diff 标签自动关闭:
10986
+ 工作树 diff 只在文件仍有未暂存改动时有效,暂存区 diff 只在文件仍在暂存区时有效。 */
10987
+ useEffect(() => {
10988
+ if (project === null || project.isGit !== true || gitStatus === null) return
10989
+ const changes = Array.isArray(gitStatus.changes) ? gitStatus.changes : []
10990
+ const stagedPaths = new Set(changes.filter((item) => item?.staged === true).map((item) => item.path))
10991
+ const unstagedPaths = new Set(changes.filter((item) => item?.staged !== true).map((item) => item.path))
10992
+ const current = tabsRef.current ?? []
10993
+ const kept = current.filter((tab) => {
10994
+ if (tab === null || tab === undefined || tab.kind !== 'diff') return true
10995
+ if (tab.diff === null || tab.diff === undefined || tab.diff.compare === true) return true
10996
+ if (tab.diff.staged === true) return stagedPaths.has(tab.path)
10997
+ return unstagedPaths.has(tab.path)
10998
+ })
10999
+ if (kept.length === current.length) return
11000
+ setTabs(kept)
11001
+ setActivePath((active) => (active !== null && kept.some((tab) => tab.path === active) ? active : (kept.length > 0 ? kept[kept.length - 1].path : null)))
11002
+ }, [gitStatus, project])
11003
+
10819
11004
  /* ── 文件打开 / 保存 / 关闭 ─────────────────────────────────────────── */
10820
11005
  const openFile = useCallback(async (path) => {
10821
11006
  if (project === null) return
@@ -11243,7 +11428,13 @@ G.GufaApp = function GufaApp(props) {
11243
11428
  return
11244
11429
  }
11245
11430
  try {
11246
- const file = await G.api('fs.read', { root: project.root, path: change.path })
11431
+ /* 文件可能已删除(工作树删掉/暂存区删除):读不到就按空处理,仍然展示差异 */
11432
+ let file = null
11433
+ try {
11434
+ file = await G.api('fs.read', { root: project.root, path: change.path })
11435
+ } catch {
11436
+ file = null
11437
+ }
11247
11438
  let left = ''
11248
11439
  try {
11249
11440
  const shown = await G.api('git.show', {
@@ -11255,16 +11446,26 @@ G.GufaApp = function GufaApp(props) {
11255
11446
  } catch {
11256
11447
  left = ''
11257
11448
  }
11449
+ let rightContent = typeof file?.content === 'string' ? file.content : ''
11450
+ if (change.staged === true) {
11451
+ /* 暂存区 diff = HEAD ↔ 索引;右侧必须用索引内容,而不是工作树(工作树可能还有未暂存改动) */
11452
+ try {
11453
+ const indexDoc = await G.api('git.show', { root: project.root, path: change.path, rev: 'index' })
11454
+ rightContent = typeof indexDoc.text === 'string' ? indexDoc.text : ''
11455
+ } catch {
11456
+ rightContent = ''
11457
+ }
11458
+ }
11258
11459
  const tab = {
11259
11460
  path: change.path,
11260
11461
  title: `${G.basename(change.path)}(${change.staged === true ? '暂存区' : '工作树'})`,
11261
11462
  kind: 'diff',
11262
- content: file.content ?? '',
11263
- savedContent: file.content ?? '',
11264
- revision: file.revision,
11463
+ content: rightContent,
11464
+ savedContent: rightContent,
11465
+ revision: file?.revision,
11265
11466
  dirty: false,
11266
- language: file.language ?? 'plaintext',
11267
- size: file.size,
11467
+ language: file?.language ?? 'plaintext',
11468
+ size: file?.size,
11268
11469
  diff: { left, staged: change.staged === true, editable: change.staged !== true },
11269
11470
  diffKey: Date.now(),
11270
11471
  }
@@ -11338,6 +11539,9 @@ G.GufaApp = function GufaApp(props) {
11338
11539
  if (project === null) return
11339
11540
  try {
11340
11541
  await G.api('git.stage', { root: project.root, paths: [path] })
11542
+ /* 暂存后这个文件已经没有「工作树 vs 索引」差异:关掉当前 diff 标签,刷新后也不会再出现在未暂存区 */
11543
+ setTabs((current) => current.filter((tab) => !(tab.path === path && tab.kind === 'diff' && tab.diff !== null && tab.diff !== undefined && tab.diff.staged !== true)))
11544
+ setActivePath((active) => (active === path ? null : active))
11341
11545
  setGitRefreshToken((token) => token + 1)
11342
11546
  void refreshGit()
11343
11547
  } catch (error) {
@@ -7,8 +7,8 @@
7
7
  <key>CFBundleDisplayName</key><string>古法编程悬浮层</string>
8
8
  <key>CFBundleExecutable</key><string>gufa-float</string>
9
9
  <key>CFBundlePackageType</key><string>APPL</string>
10
- <key>CFBundleShortVersionString</key><string>1.3.67</string>
11
- <key>CFBundleVersion</key><string>1.3.67</string>
10
+ <key>CFBundleShortVersionString</key><string>1.3.69</string>
11
+ <key>CFBundleVersion</key><string>1.3.69</string>
12
12
  <key>LSUIElement</key><true/>
13
13
  <key>NSHighResolutionCapable</key><true/>
14
14
  <key>NSPrincipalClass</key><string>NSApplication</string>
package/host/git.js CHANGED
@@ -217,7 +217,7 @@ export function register(router, env) {
217
217
  const project = await projectOf(env, body)
218
218
  const path = typeof body.path === 'string' ? body.path : ''
219
219
  if (path === '' || path.startsWith('/') || path.includes('..')) throw badRequest('path is invalid')
220
- const rev = body.rev === 'head' ? 'HEAD' : ':'
220
+ const rev = body.rev === 'head' ? 'HEAD:' : ':'
221
221
  let text = ''
222
222
  let missing = false
223
223
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.67",
3
+ "version": "1.3.69",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
@@ -152,6 +152,10 @@ try {
152
152
  check('working tree clean after commit', clean.changes.length === 0, JSON.stringify(clean.changes))
153
153
  const log = await call(router, 'git.log', { root, limit: 5 })
154
154
  check('commit in log', log.commits.length === 1 && log.commits[0].subject === 'feat: selftest')
155
+ const headShow = await call(router, 'git.show', { root, path: 'src/main.ts', rev: 'head' })
156
+ check('git.show HEAD content', headShow.text === 'const answer = 42\n', JSON.stringify(headShow.text))
157
+ const indexShow = await call(router, 'git.show', { root, path: 'src/main.ts', rev: 'index' })
158
+ check('git.show index content', indexShow.text === 'const answer = 42\n', JSON.stringify(indexShow.text))
155
159
  const gitSearch = await call(router, 'fs.search', { root, query: 'answer' })
156
160
  check('search uses git file list', gitSearch.viaGit === true, String(gitSearch.viaGit))
157
161
  check('search finds committed file', gitSearch.files.some((file) => file.path === 'src/main.ts'))
@@ -1347,6 +1347,20 @@ G.GitPanel = function GitPanel(props) {
1347
1347
  h(G.Button, { disabled: pending || message.trim() === '', primary: true, onClick: commit }, pending ? h(G.Spinner) : null, t('git.commit')),
1348
1348
  )
1349
1349
  : null,
1350
+ staged.length > 0 ? h('div', { className: 'gufa-hint' }, `${t('git.staged')} (${staged.length})`) : null,
1351
+ ...staged.map((change) =>
1352
+ h(G.GitChangeRow, {
1353
+ key: `s:${change.path}`,
1354
+ change,
1355
+ pending,
1356
+ staged: true,
1357
+ onOpen: () => props.onOpenDiff?.(change),
1358
+ onContextMenu: (event, rowChange) => setRowMenu({ ...clampMenuPosition(event.clientX, event.clientY, 200, 200), change: rowChange }),
1359
+ onAction: () => void act(async () => G.api('git.unstage', { root, paths: [change.path] })),
1360
+ actionLabel: t('git.unstage'),
1361
+ actionIcon: 'minus',
1362
+ }),
1363
+ ),
1350
1364
  unstaged.length > 0 ? h('div', { className: 'gufa-hint' }, `${t('git.unstaged')} (${unstaged.length})`) : null,
1351
1365
  ...unstaged.map((change) =>
1352
1366
  h(G.GitChangeRow, {
@@ -1362,20 +1376,6 @@ G.GitPanel = function GitPanel(props) {
1362
1376
  actionIcon: 'plus',
1363
1377
  }),
1364
1378
  ),
1365
- staged.length > 0 ? h('div', { className: 'gufa-hint' }, `${t('git.staged')} (${staged.length})`) : null,
1366
- ...staged.map((change) =>
1367
- h(G.GitChangeRow, {
1368
- key: `s:${change.path}`,
1369
- change,
1370
- pending,
1371
- staged: true,
1372
- onOpen: () => props.onOpenDiff?.(change),
1373
- onContextMenu: (event, rowChange) => setRowMenu({ ...clampMenuPosition(event.clientX, event.clientY, 200, 200), change: rowChange }),
1374
- onAction: () => void act(async () => G.api('git.unstage', { root, paths: [change.path] })),
1375
- actionLabel: t('git.unstage'),
1376
- actionIcon: 'minus',
1377
- }),
1378
- ),
1379
1379
  ),
1380
1380
  ),
1381
1381
  headMenu === null
@@ -107,6 +107,162 @@ function gufaPlaceDockedConversation(root, host, options) {
107
107
  return true
108
108
  }
109
109
 
110
+ /**
111
+ * 停靠后的官方会话「贴底跟随」守护。
112
+ *
113
+ * 官方会话自己有一套 follow 策略(ChatView root 上的 `data-chat-following-tail` 属性),
114
+ * 但在 fixed 停靠 + 频繁重排/ResizeObserver 的容器里,偶发出现「发起聊天后滚动条不在最下面」。
115
+ * 这里只在官方自己认为处于「跟随尾部」时补一次贴底(以及刚发送消息后的 2.5s 内),
116
+ * 用户主动滚动/官方取消跟随时绝不抢滚动条。
117
+ */
118
+ function gufaCreateChatFollowKeeper() {
119
+ let scroller = null
120
+ let observer = null
121
+ let resizeObserver = null
122
+ let interval = null
123
+ let frame = 0
124
+ let retryTimer = 0
125
+ let forceUntil = 0
126
+ let diagnosticsLeft = 24
127
+ const diag = (message) => {
128
+ if (diagnosticsLeft <= 0) return
129
+ diagnosticsLeft -= 1
130
+ try {
131
+ void G.api('dev.log', { message: `chat-follow ${message}` }).catch(() => {})
132
+ } catch {
133
+ /* ignore */
134
+ }
135
+ }
136
+
137
+ const hasFollowAttr = () => {
138
+ try {
139
+ return scroller !== null && scroller.isConnected && scroller.querySelector('[data-chat-following-tail]') !== null
140
+ } catch {
141
+ return false
142
+ }
143
+ }
144
+ const shouldFollow = () => hasFollowAttr() || Date.now() < forceUntil
145
+ const toBottom = () => {
146
+ if (scroller === null || !scroller.isConnected) return
147
+ try {
148
+ const max = scroller.scrollHeight - scroller.clientHeight
149
+ if (max <= 0) return
150
+ if (scroller.scrollTop < max - 2) scroller.scrollTop = max
151
+ } catch {
152
+ /* ignore */
153
+ }
154
+ }
155
+ const hasRoom = () => {
156
+ if (scroller === null || !scroller.isConnected) return false
157
+ return scroller.scrollHeight - scroller.clientHeight > 1
158
+ }
159
+ const pump = () => {
160
+ frame = 0
161
+ if (document.visibilityState !== 'visible') return
162
+ if (!shouldFollow()) return
163
+ const before = Math.round(scroller.scrollTop)
164
+ const max = Math.round(scroller.scrollHeight - scroller.clientHeight)
165
+ if (scroller.scrollTop < max - 2) diag(`pump top=${before} max=${max} follow=${hasFollowAttr()} force=${Date.now() < forceUntil}`)
166
+ toBottom()
167
+ /* 流式内容/折叠动画/图片加载会分几帧改变高度:短时间重试几次 */
168
+ if (retryTimer !== 0) window.clearTimeout(retryTimer)
169
+ retryTimer = window.setTimeout(() => {
170
+ retryTimer = 0
171
+ if (shouldFollow() && hasRoom()) toBottom()
172
+ }, 120)
173
+ }
174
+ const schedule = () => {
175
+ if (frame !== 0) return
176
+ frame = window.requestAnimationFrame(pump)
177
+ }
178
+ const onWheel = () => { forceUntil = 0 }
179
+ const onKeyDown = (event) => {
180
+ if (event.key !== 'Enter' || event.shiftKey === true || event.isComposing === true) return
181
+ try {
182
+ if (event.target instanceof Element && event.target.closest('[data-composer-input], [data-composer-seat]') !== null) {
183
+ forceUntil = Date.now() + 2500
184
+ schedule()
185
+ }
186
+ } catch {
187
+ /* ignore */
188
+ }
189
+ }
190
+ const onPointerDown = (event) => {
191
+ try {
192
+ if (event.target instanceof Element && event.target.closest('[data-composer-seat]') !== null) {
193
+ forceUntil = Date.now() + 2500
194
+ schedule()
195
+ }
196
+ } catch {
197
+ /* ignore */
198
+ }
199
+ }
200
+ const attach = (next) => {
201
+ if (next === null || next === undefined || next === scroller) return
202
+ detach()
203
+ scroller = next
204
+ try {
205
+ observer = new MutationObserver(() => schedule())
206
+ observer.observe(next, {
207
+ childList: true,
208
+ subtree: true,
209
+ characterData: true,
210
+ attributes: true,
211
+ attributeFilter: ['data-chat-following-tail'],
212
+ })
213
+ } catch {
214
+ observer = null
215
+ }
216
+ try {
217
+ if (typeof ResizeObserver === 'function') {
218
+ resizeObserver = new ResizeObserver(() => schedule())
219
+ resizeObserver.observe(next)
220
+ const content = next.firstElementChild
221
+ if (content !== null && content !== undefined) resizeObserver.observe(content)
222
+ }
223
+ } catch {
224
+ resizeObserver = null
225
+ }
226
+ /* 兜底:即使没有 DOM 变更事件,跟随期间也低频检查一次(异步高度变化) */
227
+ interval = window.setInterval(() => {
228
+ if (shouldFollow()) schedule()
229
+ }, 700)
230
+ next.addEventListener('wheel', onWheel, { passive: true })
231
+ next.addEventListener('touchstart', onWheel, { passive: true })
232
+ next.addEventListener('keydown', onKeyDown, true)
233
+ next.addEventListener('pointerdown', onPointerDown, true)
234
+ diag(`attach top=${Math.round(next.scrollTop)} max=${Math.round(next.scrollHeight - next.clientHeight)} follow=${hasFollowAttr()}`)
235
+ schedule()
236
+ }
237
+ const detach = () => {
238
+ if (frame !== 0) {
239
+ window.cancelAnimationFrame(frame)
240
+ frame = 0
241
+ }
242
+ if (retryTimer !== 0) {
243
+ window.clearTimeout(retryTimer)
244
+ retryTimer = 0
245
+ }
246
+ if (interval !== null) {
247
+ window.clearInterval(interval)
248
+ interval = null
249
+ }
250
+ observer?.disconnect()
251
+ observer = null
252
+ resizeObserver?.disconnect()
253
+ resizeObserver = null
254
+ if (scroller !== null) {
255
+ scroller.removeEventListener('wheel', onWheel)
256
+ scroller.removeEventListener('touchstart', onWheel)
257
+ scroller.removeEventListener('keydown', onKeyDown, true)
258
+ scroller.removeEventListener('pointerdown', onPointerDown, true)
259
+ }
260
+ scroller = null
261
+ forceUntil = 0
262
+ }
263
+ return { attach, detach }
264
+ }
265
+
110
266
  /** 毫秒时间戳 → 简短相对时间(会话下拉用)。 */
111
267
  function gufaRelativeTime(timestamp) {
112
268
  const delta = Date.now() - timestamp
@@ -269,6 +425,8 @@ G.ChatDock = function ChatDock(props) {
269
425
  const theme = props.theme === 'light' ? 'light' : 'dark'
270
426
  const hostRef = useRef(null)
271
427
  const dockRef = useRef({ root: null, saved: null })
428
+ const followRef = useRef(null)
429
+ if (followRef.current === null) followRef.current = gufaCreateChatFollowKeeper()
272
430
  const tickRef = useRef(null)
273
431
  const startedRef = useRef(0)
274
432
  const [phase, setPhase] = useState('searching')
@@ -287,6 +445,7 @@ G.ChatDock = function ChatDock(props) {
287
445
  if (host === null) return
288
446
  const root = gufaFindConversationRoot()
289
447
  if (root === null) {
448
+ followRef.current?.detach()
290
449
  if (dockRef.current.root !== null) undock()
291
450
  setPhase((previous) => {
292
451
  if (previous === 'docked') return 'searching'
@@ -300,6 +459,12 @@ G.ChatDock = function ChatDock(props) {
300
459
  dockRef.current = { root, saved: gufaSnapshotDockTarget(root) }
301
460
  }
302
461
  if (gufaPlaceDockedConversation(root, host, { translucent: props.backdrop === true })) {
462
+ try {
463
+ const scroller = root.querySelector(GUFA_CONVERSATION_SCROLL_SELECTOR)
464
+ if (scroller !== null && scroller !== undefined) followRef.current?.attach(scroller)
465
+ } catch {
466
+ /* ignore */
467
+ }
303
468
  setPhase((previous) => (previous === 'docked' ? previous : 'docked'))
304
469
  }
305
470
  }, [active, undock, props.backdrop])
@@ -338,6 +503,7 @@ G.ChatDock = function ChatDock(props) {
338
503
  observer?.disconnect()
339
504
  resizeObserver?.disconnect()
340
505
  window.removeEventListener('resize', onWindowResize)
506
+ followRef.current?.detach()
341
507
  undock()
342
508
  }
343
509
  }, [active, undock])
@@ -453,6 +453,25 @@ G.GufaApp = function GufaApp(props) {
453
453
  return map
454
454
  }, [gitStatus])
455
455
 
456
+ /* 暂存/取消暂存/提交后,已失效的 diff 标签自动关闭:
457
+ 工作树 diff 只在文件仍有未暂存改动时有效,暂存区 diff 只在文件仍在暂存区时有效。 */
458
+ useEffect(() => {
459
+ if (project === null || project.isGit !== true || gitStatus === null) return
460
+ const changes = Array.isArray(gitStatus.changes) ? gitStatus.changes : []
461
+ const stagedPaths = new Set(changes.filter((item) => item?.staged === true).map((item) => item.path))
462
+ const unstagedPaths = new Set(changes.filter((item) => item?.staged !== true).map((item) => item.path))
463
+ const current = tabsRef.current ?? []
464
+ const kept = current.filter((tab) => {
465
+ if (tab === null || tab === undefined || tab.kind !== 'diff') return true
466
+ if (tab.diff === null || tab.diff === undefined || tab.diff.compare === true) return true
467
+ if (tab.diff.staged === true) return stagedPaths.has(tab.path)
468
+ return unstagedPaths.has(tab.path)
469
+ })
470
+ if (kept.length === current.length) return
471
+ setTabs(kept)
472
+ setActivePath((active) => (active !== null && kept.some((tab) => tab.path === active) ? active : (kept.length > 0 ? kept[kept.length - 1].path : null)))
473
+ }, [gitStatus, project])
474
+
456
475
  /* ── 文件打开 / 保存 / 关闭 ─────────────────────────────────────────── */
457
476
  const openFile = useCallback(async (path) => {
458
477
  if (project === null) return
@@ -880,7 +899,13 @@ G.GufaApp = function GufaApp(props) {
880
899
  return
881
900
  }
882
901
  try {
883
- const file = await G.api('fs.read', { root: project.root, path: change.path })
902
+ /* 文件可能已删除(工作树删掉/暂存区删除):读不到就按空处理,仍然展示差异 */
903
+ let file = null
904
+ try {
905
+ file = await G.api('fs.read', { root: project.root, path: change.path })
906
+ } catch {
907
+ file = null
908
+ }
884
909
  let left = ''
885
910
  try {
886
911
  const shown = await G.api('git.show', {
@@ -892,16 +917,26 @@ G.GufaApp = function GufaApp(props) {
892
917
  } catch {
893
918
  left = ''
894
919
  }
920
+ let rightContent = typeof file?.content === 'string' ? file.content : ''
921
+ if (change.staged === true) {
922
+ /* 暂存区 diff = HEAD ↔ 索引;右侧必须用索引内容,而不是工作树(工作树可能还有未暂存改动) */
923
+ try {
924
+ const indexDoc = await G.api('git.show', { root: project.root, path: change.path, rev: 'index' })
925
+ rightContent = typeof indexDoc.text === 'string' ? indexDoc.text : ''
926
+ } catch {
927
+ rightContent = ''
928
+ }
929
+ }
895
930
  const tab = {
896
931
  path: change.path,
897
932
  title: `${G.basename(change.path)}(${change.staged === true ? '暂存区' : '工作树'})`,
898
933
  kind: 'diff',
899
- content: file.content ?? '',
900
- savedContent: file.content ?? '',
901
- revision: file.revision,
934
+ content: rightContent,
935
+ savedContent: rightContent,
936
+ revision: file?.revision,
902
937
  dirty: false,
903
- language: file.language ?? 'plaintext',
904
- size: file.size,
938
+ language: file?.language ?? 'plaintext',
939
+ size: file?.size,
905
940
  diff: { left, staged: change.staged === true, editable: change.staged !== true },
906
941
  diffKey: Date.now(),
907
942
  }
@@ -975,6 +1010,9 @@ G.GufaApp = function GufaApp(props) {
975
1010
  if (project === null) return
976
1011
  try {
977
1012
  await G.api('git.stage', { root: project.root, paths: [path] })
1013
+ /* 暂存后这个文件已经没有「工作树 vs 索引」差异:关掉当前 diff 标签,刷新后也不会再出现在未暂存区 */
1014
+ setTabs((current) => current.filter((tab) => !(tab.path === path && tab.kind === 'diff' && tab.diff !== null && tab.diff !== undefined && tab.diff.staged !== true)))
1015
+ setActivePath((active) => (active === path ? null : active))
978
1016
  setGitRefreshToken((token) => token + 1)
979
1017
  void refreshGit()
980
1018
  } catch (error) {