dsh-gufa-code 1.3.68 → 1.3.78

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/README.md CHANGED
@@ -41,6 +41,7 @@ dsh plugin add dsh-gufa-code
41
41
  - Monaco 编辑器(离线随包分发,无需联网下载);
42
42
  - 多标签、按扩展名语法高亮、面包屑、状态栏(分支 / 行列 / 保存状态);
43
43
  - 保存走磁盘版本冲突检测 + 原子写;未保存标记;
44
+ - **⌘/Ctrl + 点击跳转定义 / 方法实现**:优先走 Monaco 语言服务;目标文件没在 Monaco 里打开、或语言没有内置语言服务时,自动用项目级定义搜索兜底(函数 / 类 / 方法 / const / type 等声明),单结果直接跳,多结果弹「跳转到定义」列表;
44
45
  - **全局搜索 / 替换**(左栏放大镜 / `⌘⇧F`):整个项目的文本搜索,支持区分大小写、正则、包含/排除文件(glob);结果按文件分组、高亮匹配,点击跳转行列;替换栏支持保留大小写(AB)、全部替换(需确认)、按文件替换(悬停文件头铅笔)、按单行匹配替换与忽略(悬停结果行);替换前会自动保存未落盘的编辑器内容;Git 项目用 `git ls-files` 枚举文件(尊重 `.gitignore`、含未跟踪文件),非 Git 项目遍历目录并自动跳过 `node_modules` 等依赖/缓存目录;摸鱼悬浮窗里同样可用;
45
46
  - 资源管理器右键:新建 / 重命名 / 删除 / 复制 / 粘贴 / 打开所在文件夹 / 两文件对比;
46
47
  - **从 Finder 粘贴/拖入文件**:系统剪贴板里复制的文件可直接 ⌘V 粘进资源管理器(写入选中的目录,重名自动加「副本」),也可从 Finder 直接拖进文件树;
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.68'
19
+ G.BUILD = '1.3.78'
20
20
  G.PANEL_ID = 'gufa-code'
21
21
  /** 从哪个工作区点进来的(工作区菜单/节点按钮写入,App 启动时消费)。 */
22
22
  G.pendingEntryWorkspace = null
@@ -126,6 +126,7 @@ const DICT_ZH = {
126
126
  'shortcuts.newTerminal': '新建终端',
127
127
  'shortcuts.help': '打开 / 关闭本快捷键列表',
128
128
  'shortcuts.editorTitle': '编辑器(Monaco / VS Code 同款键位)',
129
+ 'editor.gotoDefinition': '跳转到定义',
129
130
  'editorKeys.comment': '切换行注释',
130
131
  'editorKeys.blockComment': '切换块注释',
131
132
  'editorKeys.nextOccurrence': '选中下一个相同内容(多光标)',
@@ -382,6 +383,7 @@ const DICT_EN = {
382
383
  'shortcuts.newTerminal': 'New terminal',
383
384
  'shortcuts.help': 'Show / hide this shortcut list',
384
385
  'shortcuts.editorTitle': 'Editor (Monaco / VS Code keybindings)',
386
+ 'editor.gotoDefinition': 'Go to definition',
385
387
  'editorKeys.comment': 'Toggle line comment',
386
388
  'editorKeys.blockComment': 'Toggle block comment',
387
389
  'editorKeys.nextOccurrence': 'Add next occurrence to multi-cursor',
@@ -3092,6 +3094,98 @@ G.FooterAction = function FooterAction(props) {
3092
3094
  /* ignore */
3093
3095
  }
3094
3096
  })
3097
+
3098
+ /* Cmd/Ctrl+点击跳转定义:先走 Monaco 语言服务;没有提供者(未打开的文件、
3099
+ 非 TS/JS 语言等)时回退到 Host 的项目级定义搜索,单结果直接跳,多结果弹选择。 */
3100
+ try {
3101
+ const domNode = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
3102
+ if (domNode !== null && domNode !== undefined) {
3103
+ const onDefinitionClick = async (event) => {
3104
+ try {
3105
+ const currentDom = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
3106
+ if (currentDom === null || currentDom === undefined || !(event.target instanceof Node) || !currentDom.contains(event.target)) return
3107
+ } catch {
3108
+ return
3109
+ }
3110
+ if (event.button !== 0 || event.defaultPrevented === true) return
3111
+ const primary = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
3112
+ const pressed = primary ? event.metaKey === true : event.ctrlKey === true
3113
+ if (!pressed || event.altKey === true || event.shiftKey === true) return
3114
+ if (event.target instanceof Element && event.target.closest('a') !== null) return
3115
+ let target = null
3116
+ try {
3117
+ target = typeof instance.getTargetAtClientPoint === 'function' ? instance.getTargetAtClientPoint(event.clientX, event.clientY) : null
3118
+ } catch {
3119
+ target = null
3120
+ }
3121
+ const position = target !== null && target !== undefined ? target.position : null
3122
+ const model = instance.getModel()
3123
+ if (position === null || position === undefined || model === null || model === undefined) return
3124
+ let wordInfo = null
3125
+ try {
3126
+ wordInfo = typeof model.getWordAtPosition === 'function' ? model.getWordAtPosition(position) : null
3127
+ } catch {
3128
+ wordInfo = null
3129
+ }
3130
+ const word = wordInfo !== null && wordInfo !== undefined && typeof wordInfo.word === 'string' ? wordInfo.word : ''
3131
+ if (word.length < 2) return
3132
+ const path = modelPathRef.current
3133
+ const root = modelsRootRef.current
3134
+ if (path === null || root === null || root === '') return
3135
+ try {
3136
+ event.preventDefault()
3137
+ event.stopPropagation()
3138
+ } catch {
3139
+ /* ignore */
3140
+ }
3141
+ const beforePath = modelPathRef.current
3142
+ const beforePosition = instance.getPosition()
3143
+ try {
3144
+ const action = typeof instance.getAction === 'function' ? instance.getAction('editor.action.revealDefinition') : null
3145
+ if (action !== null && action !== undefined) {
3146
+ const supported = typeof action.isSupported === 'function' ? action.isSupported() : true
3147
+ if (supported !== false) await action.run()
3148
+ }
3149
+ } catch {
3150
+ /* ignore */
3151
+ }
3152
+ await new Promise((resolve) => { window.setTimeout(resolve, 160) })
3153
+ let monacoHandled = false
3154
+ try {
3155
+ const afterPosition = instance.getPosition()
3156
+ monacoHandled = modelPathRef.current !== beforePath
3157
+ || (beforePosition !== null && beforePosition !== undefined && afterPosition !== null && afterPosition !== undefined
3158
+ && (afterPosition.lineNumber !== beforePosition.lineNumber || afterPosition.column !== beforePosition.column))
3159
+ || document.querySelector('.monaco-editor .peekview-widget, .monaco-editor .reference-zone-widget') !== null
3160
+ } catch {
3161
+ monacoHandled = false
3162
+ }
3163
+ if (monacoHandled) return
3164
+ try {
3165
+ const result = await G.api('code.definition', {
3166
+ root,
3167
+ path,
3168
+ line: position.lineNumber,
3169
+ column: position.column,
3170
+ word,
3171
+ content: model.getValue(),
3172
+ })
3173
+ const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
3174
+ if (matches.length === 0) return
3175
+ if (matches.length === 1) {
3176
+ G.bus.emit('editor:open-at', { path: matches[0].path, line: matches[0].line, column: matches[0].column })
3177
+ return
3178
+ }
3179
+ G.bus.emit('definition:pick', { word: result.word ?? word, matches, x: event.clientX, y: event.clientY })
3180
+ } catch {
3181
+ /* ignore */
3182
+ }
3183
+ }
3184
+ document.addEventListener('mousedown', onDefinitionClick, true)
3185
+ }
3186
+ } catch {
3187
+ /* ignore */
3188
+ }
3095
3189
  } catch {
3096
3190
  /* ignore */
3097
3191
  }
@@ -9259,6 +9353,162 @@ function gufaPlaceDockedConversation(root, host, options) {
9259
9353
  return true
9260
9354
  }
9261
9355
 
9356
+ /**
9357
+ * 停靠后的官方会话「贴底跟随」守护。
9358
+ *
9359
+ * 官方会话自己有一套 follow 策略(ChatView root 上的 `data-chat-following-tail` 属性),
9360
+ * 但在 fixed 停靠 + 频繁重排/ResizeObserver 的容器里,偶发出现「发起聊天后滚动条不在最下面」。
9361
+ * 这里只在官方自己认为处于「跟随尾部」时补一次贴底(以及刚发送消息后的 2.5s 内),
9362
+ * 用户主动滚动/官方取消跟随时绝不抢滚动条。
9363
+ */
9364
+ function gufaCreateChatFollowKeeper() {
9365
+ let scroller = null
9366
+ let observer = null
9367
+ let resizeObserver = null
9368
+ let interval = null
9369
+ let frame = 0
9370
+ let retryTimer = 0
9371
+ let forceUntil = 0
9372
+ let diagnosticsLeft = 24
9373
+ const diag = (message) => {
9374
+ if (diagnosticsLeft <= 0) return
9375
+ diagnosticsLeft -= 1
9376
+ try {
9377
+ void G.api('dev.log', { message: `chat-follow ${message}` }).catch(() => {})
9378
+ } catch {
9379
+ /* ignore */
9380
+ }
9381
+ }
9382
+
9383
+ const hasFollowAttr = () => {
9384
+ try {
9385
+ return scroller !== null && scroller.isConnected && scroller.querySelector('[data-chat-following-tail]') !== null
9386
+ } catch {
9387
+ return false
9388
+ }
9389
+ }
9390
+ const shouldFollow = () => hasFollowAttr() || Date.now() < forceUntil
9391
+ const toBottom = () => {
9392
+ if (scroller === null || !scroller.isConnected) return
9393
+ try {
9394
+ const max = scroller.scrollHeight - scroller.clientHeight
9395
+ if (max <= 0) return
9396
+ if (scroller.scrollTop < max - 2) scroller.scrollTop = max
9397
+ } catch {
9398
+ /* ignore */
9399
+ }
9400
+ }
9401
+ const hasRoom = () => {
9402
+ if (scroller === null || !scroller.isConnected) return false
9403
+ return scroller.scrollHeight - scroller.clientHeight > 1
9404
+ }
9405
+ const pump = () => {
9406
+ frame = 0
9407
+ if (document.visibilityState !== 'visible') return
9408
+ if (!shouldFollow()) return
9409
+ const before = Math.round(scroller.scrollTop)
9410
+ const max = Math.round(scroller.scrollHeight - scroller.clientHeight)
9411
+ if (scroller.scrollTop < max - 2) diag(`pump top=${before} max=${max} follow=${hasFollowAttr()} force=${Date.now() < forceUntil}`)
9412
+ toBottom()
9413
+ /* 流式内容/折叠动画/图片加载会分几帧改变高度:短时间重试几次 */
9414
+ if (retryTimer !== 0) window.clearTimeout(retryTimer)
9415
+ retryTimer = window.setTimeout(() => {
9416
+ retryTimer = 0
9417
+ if (shouldFollow() && hasRoom()) toBottom()
9418
+ }, 120)
9419
+ }
9420
+ const schedule = () => {
9421
+ if (frame !== 0) return
9422
+ frame = window.requestAnimationFrame(pump)
9423
+ }
9424
+ const onWheel = () => { forceUntil = 0 }
9425
+ const onKeyDown = (event) => {
9426
+ if (event.key !== 'Enter' || event.shiftKey === true || event.isComposing === true) return
9427
+ try {
9428
+ if (event.target instanceof Element && event.target.closest('[data-composer-input], [data-composer-seat]') !== null) {
9429
+ forceUntil = Date.now() + 2500
9430
+ schedule()
9431
+ }
9432
+ } catch {
9433
+ /* ignore */
9434
+ }
9435
+ }
9436
+ const onPointerDown = (event) => {
9437
+ try {
9438
+ if (event.target instanceof Element && event.target.closest('[data-composer-seat]') !== null) {
9439
+ forceUntil = Date.now() + 2500
9440
+ schedule()
9441
+ }
9442
+ } catch {
9443
+ /* ignore */
9444
+ }
9445
+ }
9446
+ const attach = (next) => {
9447
+ if (next === null || next === undefined || next === scroller) return
9448
+ detach()
9449
+ scroller = next
9450
+ try {
9451
+ observer = new MutationObserver(() => schedule())
9452
+ observer.observe(next, {
9453
+ childList: true,
9454
+ subtree: true,
9455
+ characterData: true,
9456
+ attributes: true,
9457
+ attributeFilter: ['data-chat-following-tail'],
9458
+ })
9459
+ } catch {
9460
+ observer = null
9461
+ }
9462
+ try {
9463
+ if (typeof ResizeObserver === 'function') {
9464
+ resizeObserver = new ResizeObserver(() => schedule())
9465
+ resizeObserver.observe(next)
9466
+ const content = next.firstElementChild
9467
+ if (content !== null && content !== undefined) resizeObserver.observe(content)
9468
+ }
9469
+ } catch {
9470
+ resizeObserver = null
9471
+ }
9472
+ /* 兜底:即使没有 DOM 变更事件,跟随期间也低频检查一次(异步高度变化) */
9473
+ interval = window.setInterval(() => {
9474
+ if (shouldFollow()) schedule()
9475
+ }, 700)
9476
+ next.addEventListener('wheel', onWheel, { passive: true })
9477
+ next.addEventListener('touchstart', onWheel, { passive: true })
9478
+ next.addEventListener('keydown', onKeyDown, true)
9479
+ next.addEventListener('pointerdown', onPointerDown, true)
9480
+ diag(`attach top=${Math.round(next.scrollTop)} max=${Math.round(next.scrollHeight - next.clientHeight)} follow=${hasFollowAttr()}`)
9481
+ schedule()
9482
+ }
9483
+ const detach = () => {
9484
+ if (frame !== 0) {
9485
+ window.cancelAnimationFrame(frame)
9486
+ frame = 0
9487
+ }
9488
+ if (retryTimer !== 0) {
9489
+ window.clearTimeout(retryTimer)
9490
+ retryTimer = 0
9491
+ }
9492
+ if (interval !== null) {
9493
+ window.clearInterval(interval)
9494
+ interval = null
9495
+ }
9496
+ observer?.disconnect()
9497
+ observer = null
9498
+ resizeObserver?.disconnect()
9499
+ resizeObserver = null
9500
+ if (scroller !== null) {
9501
+ scroller.removeEventListener('wheel', onWheel)
9502
+ scroller.removeEventListener('touchstart', onWheel)
9503
+ scroller.removeEventListener('keydown', onKeyDown, true)
9504
+ scroller.removeEventListener('pointerdown', onPointerDown, true)
9505
+ }
9506
+ scroller = null
9507
+ forceUntil = 0
9508
+ }
9509
+ return { attach, detach }
9510
+ }
9511
+
9262
9512
  /** 毫秒时间戳 → 简短相对时间(会话下拉用)。 */
9263
9513
  function gufaRelativeTime(timestamp) {
9264
9514
  const delta = Date.now() - timestamp
@@ -9421,6 +9671,8 @@ G.ChatDock = function ChatDock(props) {
9421
9671
  const theme = props.theme === 'light' ? 'light' : 'dark'
9422
9672
  const hostRef = useRef(null)
9423
9673
  const dockRef = useRef({ root: null, saved: null })
9674
+ const followRef = useRef(null)
9675
+ if (followRef.current === null) followRef.current = gufaCreateChatFollowKeeper()
9424
9676
  const tickRef = useRef(null)
9425
9677
  const startedRef = useRef(0)
9426
9678
  const [phase, setPhase] = useState('searching')
@@ -9439,6 +9691,7 @@ G.ChatDock = function ChatDock(props) {
9439
9691
  if (host === null) return
9440
9692
  const root = gufaFindConversationRoot()
9441
9693
  if (root === null) {
9694
+ followRef.current?.detach()
9442
9695
  if (dockRef.current.root !== null) undock()
9443
9696
  setPhase((previous) => {
9444
9697
  if (previous === 'docked') return 'searching'
@@ -9452,6 +9705,12 @@ G.ChatDock = function ChatDock(props) {
9452
9705
  dockRef.current = { root, saved: gufaSnapshotDockTarget(root) }
9453
9706
  }
9454
9707
  if (gufaPlaceDockedConversation(root, host, { translucent: props.backdrop === true })) {
9708
+ try {
9709
+ const scroller = root.querySelector(GUFA_CONVERSATION_SCROLL_SELECTOR)
9710
+ if (scroller !== null && scroller !== undefined) followRef.current?.attach(scroller)
9711
+ } catch {
9712
+ /* ignore */
9713
+ }
9455
9714
  setPhase((previous) => (previous === 'docked' ? previous : 'docked'))
9456
9715
  }
9457
9716
  }, [active, undock, props.backdrop])
@@ -9490,6 +9749,7 @@ G.ChatDock = function ChatDock(props) {
9490
9749
  observer?.disconnect()
9491
9750
  resizeObserver?.disconnect()
9492
9751
  window.removeEventListener('resize', onWindowResize)
9752
+ followRef.current?.detach()
9493
9753
  undock()
9494
9754
  }
9495
9755
  }, [active, undock])
@@ -10630,6 +10890,7 @@ G.GufaApp = function GufaApp(props) {
10630
10890
  const gitInFlightRef = useRef(false)
10631
10891
  const [modal, setModal] = useState(null)
10632
10892
  const [shortcutsOpen, setShortcutsOpen] = useState(false)
10893
+ const [definitionPicker, setDefinitionPicker] = useState(null)
10633
10894
  const [trashUndo, setTrashUndo] = useState([])
10634
10895
  const [branchMenu, setBranchMenu] = useState(null)
10635
10896
  const [workspaceDialog, setWorkspaceDialog] = useState(null)
@@ -10873,6 +11134,28 @@ G.GufaApp = function GufaApp(props) {
10873
11134
  }, 120)
10874
11135
  }, [openFile])
10875
11136
 
11137
+ /* Cmd/Ctrl+点击定义:编辑器 → App 跳转 / 多结果选择(兜底搜索在 host/code.js) */
11138
+ useEffect(() => {
11139
+ if (G.bus === null || G.bus === undefined || typeof G.bus.on !== 'function') return undefined
11140
+ const offOpen = G.bus.on('editor:open-at', (detail) => {
11141
+ if (detail === null || detail === undefined || typeof detail.path !== 'string') return
11142
+ void openFileAt(detail.path, detail.line, detail.column)
11143
+ })
11144
+ const offPick = G.bus.on('definition:pick', (detail) => {
11145
+ if (detail === null || detail === undefined || !Array.isArray(detail.matches) || detail.matches.length === 0) return
11146
+ setDefinitionPicker({
11147
+ word: typeof detail.word === 'string' ? detail.word : '',
11148
+ matches: detail.matches,
11149
+ x: Number.isFinite(Number(detail.x)) ? Number(detail.x) : 240,
11150
+ y: Number.isFinite(Number(detail.y)) ? Number(detail.y) : 200,
11151
+ })
11152
+ })
11153
+ return () => {
11154
+ offOpen?.()
11155
+ offPick?.()
11156
+ }
11157
+ }, [openFileAt])
11158
+
10876
11159
  /* 原子恢复标签集合:按快照顺序、去重、最后激活指定文件(避免 openFile 并发产生重复标签) */
10877
11160
  const applyTabs = useCallback(async (paths, active) => {
10878
11161
  if (project === null || !Array.isArray(paths)) return
@@ -12964,6 +13247,45 @@ G.GufaApp = function GufaApp(props) {
12964
13247
  ),
12965
13248
  ),
12966
13249
  typeof G.UsageDock === 'function' ? h(G.UsageDock, { active: true }) : null,
13250
+ G.portal(definitionPicker === null
13251
+ ? null
13252
+ : h(
13253
+ 'div',
13254
+ { style: { position: 'fixed', inset: 0, zIndex: 2147483120 }, onMouseDown: () => setDefinitionPicker(null) },
13255
+ h(
13256
+ 'div',
13257
+ {
13258
+ className: 'gufa-menu',
13259
+ style: {
13260
+ position: 'fixed',
13261
+ left: `${Math.max(8, Math.min(definitionPicker.x, (typeof window !== 'undefined' ? window.innerWidth : 1200) - 380))}px`,
13262
+ top: `${Math.max(8, Math.min(definitionPicker.y, (typeof window !== 'undefined' ? window.innerHeight : 800) - 60))}px`,
13263
+ minWidth: '340px',
13264
+ maxWidth: '520px',
13265
+ maxHeight: '420px',
13266
+ overflowY: 'auto',
13267
+ },
13268
+ onMouseDown: (event) => event.stopPropagation(),
13269
+ },
13270
+ h(
13271
+ 'div',
13272
+ { style: { padding: '4px 9px 6px', fontSize: '11px', color: 'var(--gufa-text-dim)' } },
13273
+ `${t('editor.gotoDefinition')}:${definitionPicker.word}`,
13274
+ ),
13275
+ ...definitionPicker.matches.slice(0, 15).map((item, index) =>
13276
+ h(G.MenuItem, {
13277
+ key: `${item.path}:${item.line}:${item.column}:${index}`,
13278
+ icon: 'code',
13279
+ label: `${G.basename(item.path)} · ${G.dirname(item.path) === '' ? '.' : G.dirname(item.path)} :${item.line}`,
13280
+ onClick: () => {
13281
+ setDefinitionPicker(null)
13282
+ void openFileAt(item.path, item.line, item.column)
13283
+ },
13284
+ }),
13285
+ ),
13286
+ ),
13287
+ ),
13288
+ ),
12967
13289
  G.portal(workspaceDialog === null
12968
13290
  ? null
12969
13291
  : h(
@@ -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.68</string>
11
- <key>CFBundleVersion</key><string>1.3.68</string>
10
+ <key>CFBundleShortVersionString</key><string>1.3.78</string>
11
+ <key>CFBundleVersion</key><string>1.3.78</string>
12
12
  <key>LSUIElement</key><true/>
13
13
  <key>NSHighResolutionCapable</key><true/>
14
14
  <key>NSPrincipalClass</key><string>NSApplication</string>
package/host/code.js ADDED
@@ -0,0 +1,283 @@
1
+ /**
2
+ * 代码导航:Cmd/Ctrl+点击「跳转到定义 / 方法实现」的 Host 侧兜底实现。
3
+ *
4
+ * Monaco 自带的语言服务只覆盖已加载到 Monaco 的 model(以及 TS/JS 打开过的文件),
5
+ * 对未打开的文件、Python/Go/Rust 等没有内置语言服务的语言就找不到定义。这里做一个
6
+ * 项目级的轻量定义搜索:只匹配声明形态(function/class/const/def/func/fn/method/type…),
7
+ * 优先当前文件,其次同类语言文件,返回带行列号的结果供客户端跳转或列表选择。
8
+ */
9
+ import { execFile } from 'node:child_process'
10
+ import { readFile, readdir, stat } from 'node:fs/promises'
11
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path'
12
+ import { promisify } from 'node:util'
13
+
14
+ import { ApiError, badRequest } from './context.js'
15
+
16
+ const runCommand = promisify(execFile)
17
+ const MAX_FILE_SIZE = 1024 * 1024
18
+ const MAX_SCANNED = 3000
19
+ const TIME_BUDGET = 7000
20
+ const MAX_MATCHES = 30
21
+ const EXCLUDED = new Set([
22
+ 'node_modules', '.git', 'dist', 'build', 'out', '.next', 'vendor', 'target', '.venv', 'venv',
23
+ '__pycache__', '.idea', '.cache', '.turbo', '.svelte-kit', '.nuxt', '.output', 'coverage',
24
+ '.gradle', 'DerivedData', 'Pods', '.tox', '.mypy_cache', '.pytest_cache', '.ruff_cache',
25
+ '.electron-cache', '.npm-cache', '.pip-cache', '.yarn', '.pnpm-store', '.pnpm',
26
+ ])
27
+ const EXCLUDED_PREFIXES = ['.venv', '.npm-cache', '.pip-cache', '.electron-cache', '.pnpm', '.yarn', '.cache']
28
+ const SKIP_EXT = new Set([
29
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'icns', 'bmp', 'tiff', 'pdf', 'zip', 'gz', 'tgz', 'tar', '7z', 'rar', 'dmg', 'iso',
30
+ 'mp4', 'mp3', 'wav', 'mov', 'avi', 'mkv', 'flac', 'jar', 'class', 'o', 'a', 'so', 'dylib', 'dll', 'exe', 'bin', 'dat',
31
+ 'woff', 'woff2', 'ttf', 'otf', 'eot', 'wasm', 'pyc', 'node',
32
+ ])
33
+
34
+ function escapeRegExp(text) {
35
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
36
+ }
37
+
38
+ function extensionOf(rel) {
39
+ const name = String(rel).split('/').pop() ?? ''
40
+ const dot = name.lastIndexOf('.')
41
+ return dot <= 0 ? '' : name.slice(dot + 1).toLowerCase()
42
+ }
43
+
44
+ function isExcludedDir(name) {
45
+ if (EXCLUDED.has(name)) return true
46
+ for (const prefix of EXCLUDED_PREFIXES) if (String(name).startsWith(prefix)) return true
47
+ return false
48
+ }
49
+
50
+ function lineColumnAt(text, index) {
51
+ let line = 1
52
+ let lastNewline = -1
53
+ for (let i = 0; i < index && i < text.length; i += 1) {
54
+ if (text.charCodeAt(i) === 10) {
55
+ line += 1
56
+ lastNewline = i
57
+ }
58
+ }
59
+ return { line, column: index - lastNewline }
60
+ }
61
+
62
+ function extractWord(lineText, column) {
63
+ const text = String(lineText ?? '')
64
+ const position = Math.max(0, Math.min(text.length - 1, column - 1))
65
+ const isWord = (char) => /[A-Za-z0-9_$]/.test(char)
66
+ if (!isWord(text[position] ?? '')) {
67
+ /* 在附近找最近的标识符字符(Cmd 点击可能落在词边上) */
68
+ let left = position
69
+ while (left >= 0 && !isWord(text[left])) left -= 1
70
+ if (left < 0) return ''
71
+ let right = position
72
+ while (right < text.length && isWord(text[right])) right += 1
73
+ return text.slice(left, right)
74
+ }
75
+ let start = position
76
+ while (start > 0 && isWord(text[start - 1])) start -= 1
77
+ let end = position
78
+ while (end < text.length && isWord(text[end])) end += 1
79
+ return text.slice(start, end)
80
+ }
81
+
82
+ /** 定义形态:返回 [{kind, weight, regex}],regex 需含一个捕获组交出定义词位置。 */
83
+ function definitionPatterns(word) {
84
+ const escaped = escapeRegExp(word)
85
+ return [
86
+ { kind: 'function', weight: 22, regex: new RegExp(`\\bfunction\\s+(${escaped})\\b`) },
87
+ { kind: 'class', weight: 22, regex: new RegExp(`\\bclass\\s+(${escaped})\\b`) },
88
+ { kind: 'def', weight: 22, regex: new RegExp(`\\bdef\\s+(${escaped})\\b`) },
89
+ { kind: 'func', weight: 22, regex: new RegExp(`\\bfunc\\s+(?:\\([^)]*\\)\\s*)?(${escaped})\\s*\\(`) },
90
+ { kind: 'fn', weight: 22, regex: new RegExp(`\\bfn\\s+(${escaped})\\s*\\(`) },
91
+ { kind: 'type', weight: 20, regex: new RegExp(`\\b(?:interface|type|enum|struct|trait|module|namespace|protocol)\\s+(${escaped})\\b`) },
92
+ { kind: 'const', weight: 16, regex: new RegExp(`\\b(?:const|let|var|val)\\s+(${escaped})\\b`) },
93
+ { kind: 'assign', weight: 14, regex: new RegExp(`\\b(${escaped})\\s*=\\s*(?:async\\s+)?(?:function|\\()`) },
94
+ { kind: 'method', weight: 18, regex: new RegExp(`^\\s*(?:(?:public|private|protected|static|final|abstract|async|synchronized|override|virtual|export|default|get|set)\\s+)*[\\w<>\\[\\],\\s.?:*&]+\\s+(${escaped})\\s*\\(`) },
95
+ { kind: 'export', weight: 18, regex: new RegExp(`\\bexport\\s+(?:default\\s+)?(?:const|let|var|function|class|async)\\s+(${escaped})\\b`) },
96
+ ]
97
+ }
98
+
99
+ function scoreMatch(match, current) {
100
+ let score = match.weight
101
+ if (match.path === current.path) score += 120
102
+ if (extensionOf(match.path) === extensionOf(current.path)) score += 6
103
+ if (match.path.startsWith(`${current.dir}/`)) score += 4
104
+ if (match.kind === 'method' || match.kind === 'function' || match.kind === 'def' || match.kind === 'func' || match.kind === 'fn') score += 4
105
+ return score
106
+ }
107
+
108
+ async function listCandidates(root, textBudgets) {
109
+ /* Git 项目用 git ls-files(尊重 .gitignore、含未跟踪文件),否则 BFS 遍历。 */
110
+ let isGit = false
111
+ try {
112
+ const dotGit = await stat(join(root, '.git'))
113
+ isGit = dotGit.isDirectory() || dotGit.isFile()
114
+ } catch {
115
+ isGit = false
116
+ }
117
+ const files = []
118
+ if (isGit) {
119
+ try {
120
+ const { stdout } = await runCommand('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
121
+ cwd: root,
122
+ maxBuffer: 64 * 1024 * 1024,
123
+ timeout: 12000,
124
+ })
125
+ for (const rel of stdout.split('\0')) {
126
+ if (rel === '' || isExcludedDir(rel.split('/').pop() ?? '')) continue
127
+ if (SKIP_EXT.has(extensionOf(rel))) continue
128
+ files.push(rel)
129
+ if (files.length >= MAX_SCANNED) break
130
+ }
131
+ files.sort((a, b) => a.localeCompare(b))
132
+ return files
133
+ } catch {
134
+ /* 回退目录遍历 */
135
+ }
136
+ }
137
+ const queue = ['']
138
+ let head = 0
139
+ while (head < queue.length && files.length < MAX_SCANNED) {
140
+ const dirRel = queue[head]
141
+ head += 1
142
+ let entries
143
+ try {
144
+ entries = await readdir(join(root, dirRel), { withFileTypes: true })
145
+ } catch {
146
+ continue
147
+ }
148
+ entries.sort((a, b) => String(a.name).localeCompare(String(b.name)))
149
+ for (const entry of entries) {
150
+ if (entry.isDirectory()) {
151
+ if (!isExcludedDir(entry.name)) queue.push(dirRel === '' ? entry.name : `${dirRel}/${entry.name}`)
152
+ continue
153
+ }
154
+ if (!entry.isFile()) continue
155
+ const rel = dirRel === '' ? entry.name : `${dirRel}/${entry.name}`
156
+ if (SKIP_EXT.has(extensionOf(rel))) continue
157
+ files.push(rel)
158
+ if (files.length >= MAX_SCANNED) break
159
+ }
160
+ }
161
+ void textBudgets
162
+ return files
163
+ }
164
+
165
+ /** 项目内相对路径解析(只读场景:拒绝绝对路径与 .. 逃逸)。 */
166
+ async function resolveInsideProject(root, raw) {
167
+ if (typeof raw !== 'string') throw badRequest('path must be a string')
168
+ if (isAbsolute(raw)) throw new ApiError('path-invalid', '不允许绝对路径', 400)
169
+ const absolute = resolve(root, raw === '' ? '.' : raw)
170
+ const rel = relative(root, absolute)
171
+ if (rel !== '' && (rel.startsWith(`..${sep}`) || rel === '..' || isAbsolute(rel))) {
172
+ throw new ApiError('path-outside', '路径超出项目范围', 403)
173
+ }
174
+ return absolute
175
+ }
176
+
177
+ /** 在一段文本里找 word 的所有声明位置。 */
178
+ function findDefinitionsInText(text, relPath, word, patterns, results, current) {
179
+ if (results.length >= MAX_MATCHES) return
180
+ const lines = String(text).split(/\r?\n/)
181
+ for (let index = 0; index < lines.length; index += 1) {
182
+ const line = lines[index]
183
+ if (!line.includes(word)) continue
184
+ for (const pattern of patterns) {
185
+ const match = pattern.regex.exec(line)
186
+ if (match === null) continue
187
+ const column = (match.index ?? 0) + match[0].indexOf(match[1]) + 1
188
+ results.push({
189
+ path: relPath,
190
+ line: index + 1,
191
+ column: Math.max(1, column),
192
+ kind: pattern.kind,
193
+ weight: pattern.weight,
194
+ preview: line.trim().slice(0, 160),
195
+ score: 0,
196
+ })
197
+ break
198
+ }
199
+ if (results.length >= MAX_MATCHES) return
200
+ }
201
+ void current
202
+ }
203
+
204
+ export function register(router, env) {
205
+ router.method('code.definition', async (body) => {
206
+ const project = env.projects.ensure(typeof body.root === 'string' ? body.root : '')
207
+ const root = project.root
208
+ const rawPath = typeof body.path === 'string' ? body.path : ''
209
+ if (rawPath === '') throw badRequest('path is required')
210
+ const line = Number(body.line)
211
+ const column = Number(body.column)
212
+ if (!Number.isInteger(line) || line < 1 || !Number.isInteger(column) || column < 1) throw badRequest('line/column is invalid')
213
+ const absolute = await resolveInsideProject(root, rawPath)
214
+ const relPath = relative(root, absolute).split(sep).join('/')
215
+ let text = ''
216
+ if (typeof body.content === 'string' && Buffer.byteLength(body.content, 'utf8') <= 4 * 1024 * 1024) {
217
+ text = body.content
218
+ } else {
219
+ try {
220
+ const info = await stat(absolute)
221
+ if (info.size <= 4 * 1024 * 1024) text = await readFile(absolute, 'utf8')
222
+ } catch {
223
+ text = ''
224
+ }
225
+ }
226
+ const lines = text.split(/\r?\n/)
227
+ const lineText = lines[line - 1] ?? ''
228
+ let word = typeof body.word === 'string' ? body.word.trim() : ''
229
+ if (word === '') word = extractWord(lineText, column)
230
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(word) || word.length < 2 || word.length > 80) {
231
+ return { word, matches: [], current: { path: relPath, line, column } }
232
+ }
233
+ const patterns = definitionPatterns(word)
234
+ const startedAt = Date.now()
235
+ const current = { path: relPath, dir: relPath.includes('/') ? relPath.slice(0, relPath.lastIndexOf('/')) : '' }
236
+ const results = []
237
+ /* 1) 当前文件(用编辑器传来的内容,能命中未保存的改动) */
238
+ findDefinitionsInText(text, relPath, word, patterns, results, current)
239
+ /* 2) 项目其它文件 */
240
+ const candidates = await listCandidates(root, null)
241
+ for (const candidate of candidates) {
242
+ if (candidate === relPath) continue
243
+ if (results.length >= MAX_MATCHES) break
244
+ if (Date.now() - startedAt > TIME_BUDGET) break
245
+ const candidateAbs = join(root, candidate)
246
+ const info = await stat(candidateAbs).catch(() => undefined)
247
+ if (info === undefined || !info.isFile() || info.size > MAX_FILE_SIZE) continue
248
+ let buffer
249
+ try {
250
+ buffer = await readFile(candidateAbs)
251
+ } catch {
252
+ continue
253
+ }
254
+ if (buffer.includes(0)) continue
255
+ const candidateText = buffer.toString('utf8')
256
+ if (!candidateText.includes(word)) continue
257
+ findDefinitionsInText(candidateText, candidate, word, patterns, results, current)
258
+ }
259
+ /* 去重 + 打分 + 排序 */
260
+ const seen = new Set()
261
+ const matches = []
262
+ for (const item of results) {
263
+ const key = `${item.path}:${item.line}:${item.column}`
264
+ if (seen.has(key)) continue
265
+ seen.add(key)
266
+ matches.push({
267
+ path: item.path,
268
+ line: item.line,
269
+ column: item.column,
270
+ kind: item.kind,
271
+ preview: item.preview,
272
+ score: scoreMatch(item, current),
273
+ })
274
+ }
275
+ matches.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path) || a.line - b.line)
276
+ return {
277
+ word,
278
+ matches: matches.slice(0, MAX_MATCHES),
279
+ current: { path: relPath, line, column },
280
+ truncated: matches.length > MAX_MATCHES,
281
+ }
282
+ })
283
+ }
package/host/fs.js CHANGED
@@ -11,6 +11,7 @@ import { constants } from 'node:fs'
11
11
  import { tmpdir } from 'node:os'
12
12
  import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
13
13
  import { ApiError, badRequest } from './context.js'
14
+ import { register as registerCodeNavigation } from './code.js'
14
15
 
15
16
  const TEXT_LIMIT = 4 * 1024 * 1024
16
17
  const runCommand = promisify(execFile)
@@ -243,6 +244,10 @@ async function listProjectCandidates(root, project, maxScanned) {
243
244
  }
244
245
 
245
246
  export function register(router, env) {
247
+ /* 代码导航(Cmd+点击跳定义)注册在 fs 模块里:host 热重载按 host/*.js 的 mtime 触发,
248
+ 如果单开一个模块,需要重启 Host 才能挂上;挂在 fs 上改代码即可热生效。 */
249
+ registerCodeNavigation(router, env)
250
+
246
251
  router.method('fs.list', async (body) => {
247
252
  const root = await projectOf(env, body)
248
253
  const absolute = await resolveProjectPath(root, typeof body.path === 'string' ? body.path : '')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.68",
3
+ "version": "1.3.78",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
@@ -12,6 +12,7 @@ import { join } from 'node:path'
12
12
  import * as assets from '../host/assets.js'
13
13
  import * as floatPlatform from '../host/float-platform.js'
14
14
  import * as chat from '../host/chat.js'
15
+ import * as code from '../host/code.js'
15
16
  import * as fs from '../host/fs.js'
16
17
  import * as git from '../host/git.js'
17
18
  import * as project from '../host/project.js'
@@ -67,7 +68,7 @@ const sandbox = mkdtempSync(join(tmpdir(), 'gufa-selftest-'))
67
68
  const projectDir = join(sandbox, 'demo-project')
68
69
  const router = makeRouter()
69
70
  const env = { ctx: { get: () => undefined }, projects: new ProjectRegistry() }
70
- for (const module of [assets, project, fs, git, ssh, terminal, chat]) module.register(router, env)
71
+ for (const module of [assets, project, fs, git, ssh, terminal, chat, code]) module.register(router, env)
71
72
 
72
73
  try {
73
74
  console.log('project.create / project.open')
@@ -217,6 +218,25 @@ try {
217
218
  const diff = await call(router, 'git.diff', { root, path: 'src/main.ts' })
218
219
  check('diff contains change', diff.patch.includes('43'))
219
220
 
221
+ console.log('code.definition')
222
+ await call(router, 'fs.create', { root, path: 'nav', kind: 'dir' })
223
+ await call(router, 'fs.create', { root, path: 'nav/defs.js', kind: 'file' })
224
+ await call(router, 'fs.write', { root, path: 'nav/defs.js', content: 'export function helperFn(){ return 1 }\n\nexport class WidgetBox {\n render(){ return 2 }\n}\n' })
225
+ await call(router, 'fs.create', { root, path: 'nav/use.js', kind: 'file' })
226
+ const useContent = 'const value = helperFn()\nconst widget = new WidgetBox()\nwidget.render()\n'
227
+ await call(router, 'fs.write', { root, path: 'nav/use.js', content: useContent })
228
+ const defsResult = await call(router, 'code.definition', { root, path: 'nav/use.js', line: 1, column: 15, word: 'helperFn', content: useContent })
229
+ check('definition finds cross-file function', defsResult.matches.some((item) => item.path === 'nav/defs.js' && item.line === 1), JSON.stringify(defsResult.matches.slice(0, 2)))
230
+ const classResult = await call(router, 'code.definition', { root, path: 'nav/use.js', line: 2, column: 20, word: 'WidgetBox', content: useContent })
231
+ check('definition finds class', classResult.matches.some((item) => item.path === 'nav/defs.js' && item.kind === 'class'), JSON.stringify(classResult.matches.slice(0, 2)))
232
+ const methodResult = await call(router, 'code.definition', { root, path: 'nav/use.js', line: 3, column: 9, word: 'render', content: useContent })
233
+ check('definition finds method', methodResult.matches.some((item) => item.path === 'nav/defs.js' && item.kind === 'method'), JSON.stringify(methodResult.matches.slice(0, 2)))
234
+ const derivedResult = await call(router, 'code.definition', { root, path: 'nav/use.js', line: 1, column: 16, content: useContent })
235
+ check('definition derives word from line/column', derivedResult.word === 'helperFn' && derivedResult.matches.length > 0, JSON.stringify(derivedResult.word))
236
+ const emptyResult = await call(router, 'code.definition', { root, path: 'nav/use.js', line: 1, column: 7, content: useContent, word: 'x' })
237
+ check('definition ignores too-short word', emptyResult.word === 'x' && emptyResult.matches.length === 0)
238
+ await call(router, 'fs.delete', { root, path: 'nav' }).catch(() => {})
239
+
220
240
  console.log('workspaces')
221
241
  const fakeSessions = new Map([
222
242
  ['s1', { id: 's1', updatedAt: 20 }],
@@ -118,6 +118,7 @@ const DICT_ZH = {
118
118
  'shortcuts.newTerminal': '新建终端',
119
119
  'shortcuts.help': '打开 / 关闭本快捷键列表',
120
120
  'shortcuts.editorTitle': '编辑器(Monaco / VS Code 同款键位)',
121
+ 'editor.gotoDefinition': '跳转到定义',
121
122
  'editorKeys.comment': '切换行注释',
122
123
  'editorKeys.blockComment': '切换块注释',
123
124
  'editorKeys.nextOccurrence': '选中下一个相同内容(多光标)',
@@ -374,6 +375,7 @@ const DICT_EN = {
374
375
  'shortcuts.newTerminal': 'New terminal',
375
376
  'shortcuts.help': 'Show / hide this shortcut list',
376
377
  'shortcuts.editorTitle': 'Editor (Monaco / VS Code keybindings)',
378
+ 'editor.gotoDefinition': 'Go to definition',
377
379
  'editorKeys.comment': 'Toggle line comment',
378
380
  'editorKeys.blockComment': 'Toggle block comment',
379
381
  'editorKeys.nextOccurrence': 'Add next occurrence to multi-cursor',
@@ -746,6 +746,98 @@
746
746
  /* ignore */
747
747
  }
748
748
  })
749
+
750
+ /* Cmd/Ctrl+点击跳转定义:先走 Monaco 语言服务;没有提供者(未打开的文件、
751
+ 非 TS/JS 语言等)时回退到 Host 的项目级定义搜索,单结果直接跳,多结果弹选择。 */
752
+ try {
753
+ const domNode = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
754
+ if (domNode !== null && domNode !== undefined) {
755
+ const onDefinitionClick = async (event) => {
756
+ try {
757
+ const currentDom = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
758
+ if (currentDom === null || currentDom === undefined || !(event.target instanceof Node) || !currentDom.contains(event.target)) return
759
+ } catch {
760
+ return
761
+ }
762
+ if (event.button !== 0 || event.defaultPrevented === true) return
763
+ const primary = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
764
+ const pressed = primary ? event.metaKey === true : event.ctrlKey === true
765
+ if (!pressed || event.altKey === true || event.shiftKey === true) return
766
+ if (event.target instanceof Element && event.target.closest('a') !== null) return
767
+ let target = null
768
+ try {
769
+ target = typeof instance.getTargetAtClientPoint === 'function' ? instance.getTargetAtClientPoint(event.clientX, event.clientY) : null
770
+ } catch {
771
+ target = null
772
+ }
773
+ const position = target !== null && target !== undefined ? target.position : null
774
+ const model = instance.getModel()
775
+ if (position === null || position === undefined || model === null || model === undefined) return
776
+ let wordInfo = null
777
+ try {
778
+ wordInfo = typeof model.getWordAtPosition === 'function' ? model.getWordAtPosition(position) : null
779
+ } catch {
780
+ wordInfo = null
781
+ }
782
+ const word = wordInfo !== null && wordInfo !== undefined && typeof wordInfo.word === 'string' ? wordInfo.word : ''
783
+ if (word.length < 2) return
784
+ const path = modelPathRef.current
785
+ const root = modelsRootRef.current
786
+ if (path === null || root === null || root === '') return
787
+ try {
788
+ event.preventDefault()
789
+ event.stopPropagation()
790
+ } catch {
791
+ /* ignore */
792
+ }
793
+ const beforePath = modelPathRef.current
794
+ const beforePosition = instance.getPosition()
795
+ try {
796
+ const action = typeof instance.getAction === 'function' ? instance.getAction('editor.action.revealDefinition') : null
797
+ if (action !== null && action !== undefined) {
798
+ const supported = typeof action.isSupported === 'function' ? action.isSupported() : true
799
+ if (supported !== false) await action.run()
800
+ }
801
+ } catch {
802
+ /* ignore */
803
+ }
804
+ await new Promise((resolve) => { window.setTimeout(resolve, 160) })
805
+ let monacoHandled = false
806
+ try {
807
+ const afterPosition = instance.getPosition()
808
+ monacoHandled = modelPathRef.current !== beforePath
809
+ || (beforePosition !== null && beforePosition !== undefined && afterPosition !== null && afterPosition !== undefined
810
+ && (afterPosition.lineNumber !== beforePosition.lineNumber || afterPosition.column !== beforePosition.column))
811
+ || document.querySelector('.monaco-editor .peekview-widget, .monaco-editor .reference-zone-widget') !== null
812
+ } catch {
813
+ monacoHandled = false
814
+ }
815
+ if (monacoHandled) return
816
+ try {
817
+ const result = await G.api('code.definition', {
818
+ root,
819
+ path,
820
+ line: position.lineNumber,
821
+ column: position.column,
822
+ word,
823
+ content: model.getValue(),
824
+ })
825
+ const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
826
+ if (matches.length === 0) return
827
+ if (matches.length === 1) {
828
+ G.bus.emit('editor:open-at', { path: matches[0].path, line: matches[0].line, column: matches[0].column })
829
+ return
830
+ }
831
+ G.bus.emit('definition:pick', { word: result.word ?? word, matches, x: event.clientX, y: event.clientY })
832
+ } catch {
833
+ /* ignore */
834
+ }
835
+ }
836
+ document.addEventListener('mousedown', onDefinitionClick, true)
837
+ }
838
+ } catch {
839
+ /* ignore */
840
+ }
749
841
  } catch {
750
842
  /* ignore */
751
843
  }
@@ -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])
@@ -267,6 +267,7 @@ G.GufaApp = function GufaApp(props) {
267
267
  const gitInFlightRef = useRef(false)
268
268
  const [modal, setModal] = useState(null)
269
269
  const [shortcutsOpen, setShortcutsOpen] = useState(false)
270
+ const [definitionPicker, setDefinitionPicker] = useState(null)
270
271
  const [trashUndo, setTrashUndo] = useState([])
271
272
  const [branchMenu, setBranchMenu] = useState(null)
272
273
  const [workspaceDialog, setWorkspaceDialog] = useState(null)
@@ -510,6 +511,28 @@ G.GufaApp = function GufaApp(props) {
510
511
  }, 120)
511
512
  }, [openFile])
512
513
 
514
+ /* Cmd/Ctrl+点击定义:编辑器 → App 跳转 / 多结果选择(兜底搜索在 host/code.js) */
515
+ useEffect(() => {
516
+ if (G.bus === null || G.bus === undefined || typeof G.bus.on !== 'function') return undefined
517
+ const offOpen = G.bus.on('editor:open-at', (detail) => {
518
+ if (detail === null || detail === undefined || typeof detail.path !== 'string') return
519
+ void openFileAt(detail.path, detail.line, detail.column)
520
+ })
521
+ const offPick = G.bus.on('definition:pick', (detail) => {
522
+ if (detail === null || detail === undefined || !Array.isArray(detail.matches) || detail.matches.length === 0) return
523
+ setDefinitionPicker({
524
+ word: typeof detail.word === 'string' ? detail.word : '',
525
+ matches: detail.matches,
526
+ x: Number.isFinite(Number(detail.x)) ? Number(detail.x) : 240,
527
+ y: Number.isFinite(Number(detail.y)) ? Number(detail.y) : 200,
528
+ })
529
+ })
530
+ return () => {
531
+ offOpen?.()
532
+ offPick?.()
533
+ }
534
+ }, [openFileAt])
535
+
513
536
  /* 原子恢复标签集合:按快照顺序、去重、最后激活指定文件(避免 openFile 并发产生重复标签) */
514
537
  const applyTabs = useCallback(async (paths, active) => {
515
538
  if (project === null || !Array.isArray(paths)) return
@@ -2601,6 +2624,45 @@ G.GufaApp = function GufaApp(props) {
2601
2624
  ),
2602
2625
  ),
2603
2626
  typeof G.UsageDock === 'function' ? h(G.UsageDock, { active: true }) : null,
2627
+ G.portal(definitionPicker === null
2628
+ ? null
2629
+ : h(
2630
+ 'div',
2631
+ { style: { position: 'fixed', inset: 0, zIndex: 2147483120 }, onMouseDown: () => setDefinitionPicker(null) },
2632
+ h(
2633
+ 'div',
2634
+ {
2635
+ className: 'gufa-menu',
2636
+ style: {
2637
+ position: 'fixed',
2638
+ left: `${Math.max(8, Math.min(definitionPicker.x, (typeof window !== 'undefined' ? window.innerWidth : 1200) - 380))}px`,
2639
+ top: `${Math.max(8, Math.min(definitionPicker.y, (typeof window !== 'undefined' ? window.innerHeight : 800) - 60))}px`,
2640
+ minWidth: '340px',
2641
+ maxWidth: '520px',
2642
+ maxHeight: '420px',
2643
+ overflowY: 'auto',
2644
+ },
2645
+ onMouseDown: (event) => event.stopPropagation(),
2646
+ },
2647
+ h(
2648
+ 'div',
2649
+ { style: { padding: '4px 9px 6px', fontSize: '11px', color: 'var(--gufa-text-dim)' } },
2650
+ `${t('editor.gotoDefinition')}:${definitionPicker.word}`,
2651
+ ),
2652
+ ...definitionPicker.matches.slice(0, 15).map((item, index) =>
2653
+ h(G.MenuItem, {
2654
+ key: `${item.path}:${item.line}:${item.column}:${index}`,
2655
+ icon: 'code',
2656
+ label: `${G.basename(item.path)} · ${G.dirname(item.path) === '' ? '.' : G.dirname(item.path)} :${item.line}`,
2657
+ onClick: () => {
2658
+ setDefinitionPicker(null)
2659
+ void openFileAt(item.path, item.line, item.column)
2660
+ },
2661
+ }),
2662
+ ),
2663
+ ),
2664
+ ),
2665
+ ),
2604
2666
  G.portal(workspaceDialog === null
2605
2667
  ? null
2606
2668
  : h(