dsh-gufa-code 1.3.87 → 1.3.90

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
@@ -40,8 +40,9 @@ dsh plugin add dsh-gufa-code
40
40
 
41
41
  - Monaco 编辑器(离线随包分发,无需联网下载);
42
42
  - 多标签、按扩展名语法高亮、面包屑、状态栏(分支 / 行列 / 保存状态);
43
+ - **Copilot 风格 Tab 行内补全**:光标停/打字后,基于 Harness 自己的 DeepSeek 模型(默认 `deepseek-flash`,不需要额外 Copilot 订阅)流式生成灰色 ghost text,Tab 接受、Esc 忽略;支持 JS/TS/Python/Java/Go/Rust/C++/C#/JSON/YAML/Shell 等常见语言;
43
44
  - 保存走磁盘版本冲突检测 + 原子写;未保存标记;
44
- - **⌘/Ctrl + 点击跳转定义 / 方法实现**:优先走 Monaco 语言服务;目标文件没在 Monaco 里打开、或语言没有内置语言服务时,自动用项目级定义搜索兜底(函数 / 类 / 方法 / const / type 等声明)。兜底会解析 import/require 直接定位来源文件,并跳过压缩产物/大文件;同一个文件里的声明、import 命中的定义、目录距离近的定义直接跳,只有多个真正同名的声明才弹「跳转到定义」列表,点同名属性/变量时不会拿远端无关的 const 来凑数;按住 ⌘/Ctrl 悬停时,可跳转的符号会显示下划线 + 手型光标;
45
+ - **⌘/Ctrl + 点击跳转定义 / 方法实现**:Python 走 **Pyright 语言服务(LSP)**,JS/TS 走 Monaco 内置 TypeScript 语言服务(点击前会按需把当前文件的 import 依赖加载进 Monaco,跨文件变量/函数由 TS 语言服务解析);其他语言暂用项目级定义搜索兜底;优先走 Monaco 语言服务;目标文件没在 Monaco 里打开、或语言没有内置语言服务时,自动用项目级定义搜索兜底(函数 / 类 / 方法 / const / type 等声明)。兜底会解析 import/require 直接定位来源文件,并跳过压缩产物/大文件;同一个文件里的声明、import 命中的定义、目录距离近的定义直接跳,只有多个真正同名的声明才弹「跳转到定义」列表,点同名属性/变量时不会拿远端无关的 const 来凑数;按住 ⌘/Ctrl 悬停时,可跳转的符号会显示下划线 + 手型光标;
45
46
  - **全局搜索 / 替换**(左栏放大镜 / `⌘⇧F`):整个项目的文本搜索,支持区分大小写、正则、包含/排除文件(glob);结果按文件分组、高亮匹配,点击跳转行列;替换栏支持保留大小写(AB)、全部替换(需确认)、按文件替换(悬停文件头铅笔)、按单行匹配替换与忽略(悬停结果行);替换前会自动保存未落盘的编辑器内容;Git 项目用 `git ls-files` 枚举文件(尊重 `.gitignore`、含未跟踪文件),非 Git 项目遍历目录并自动跳过 `node_modules` 等依赖/缓存目录;摸鱼悬浮窗里同样可用;
46
47
  - 资源管理器右键:新建 / 重命名 / 删除 / 复制 / 粘贴 / 打开所在文件夹 / 两文件对比;
47
48
  - **从 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.87'
19
+ G.BUILD = '1.3.90'
20
20
  G.PANEL_ID = 'gufa-code'
21
21
  /** 从哪个工作区点进来的(工作区菜单/节点按钮写入,App 启动时消费)。 */
22
22
  G.pendingEntryWorkspace = null
@@ -2750,7 +2750,8 @@ G.FooterAction = function FooterAction(props) {
2750
2750
  }
2751
2751
 
2752
2752
  /** 这些声明类型算「定义级」,多个同名时值得让用户选;普通 const/赋值等弱匹配不轻易弹列表。 */
2753
- const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export'])
2753
+ const GUFA_LSP_WARMED = new Set()
2754
+ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export', 'lsp'])
2754
2755
 
2755
2756
  /* ── model / URI ────────────────────────────────────────────────────── */
2756
2757
 
@@ -2830,6 +2831,7 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
2830
2831
  scrollbar: { verticalScrollbarSize: 10, horizontalScrollbarSize: 10, useShadows: false },
2831
2832
  mouseWheelZoom: false,
2832
2833
  contextmenu: true,
2834
+ inlineSuggest: { enabled: true, showToolbar: 'never' },
2833
2835
  }
2834
2836
  }
2835
2837
 
@@ -3118,6 +3120,81 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3118
3120
  const mac = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
3119
3121
  return mac ? event.metaKey === true : event.ctrlKey === true
3120
3122
  }
3123
+ /* JS/TS:把当前文件的 import 依赖按需加载成 Monaco model,让 TS 语言服务
3124
+ 能解析跨文件定义;否则 Monaco 只认识已经打开过的标签。 */
3125
+ const tsPreloadState = { seen: new Set() }
3126
+ const preloadTsDependencies = async (model, path, root) => {
3127
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
3128
+ if (language !== 'typescript' && language !== 'javascript') return
3129
+ const version = typeof model.getVersionId === 'function' ? model.getVersionId() : 0
3130
+ const key = `${path}|${version}`
3131
+ if (tsPreloadState.seen.has(key) || tsPreloadState.seen.size > 200) return
3132
+ tsPreloadState.seen.add(key)
3133
+ let content = ''
3134
+ try {
3135
+ content = model.getValue()
3136
+ } catch {
3137
+ return
3138
+ }
3139
+ const specs = []
3140
+ for (const pattern of [/import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g, /require\(\s*['"]([^'"]+)['"]\s*\)/g]) {
3141
+ let match = null
3142
+ while ((match = pattern.exec(content)) !== null) {
3143
+ if (typeof match[1] === 'string' && match[1].startsWith('.')) specs.push(match[1])
3144
+ }
3145
+ }
3146
+ const baseDir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''
3147
+ const candidates = (spec) => {
3148
+ const raw = `${baseDir}${baseDir === '' ? '' : '/'}${spec}`
3149
+ const parts = []
3150
+ for (const part of raw.split('/')) {
3151
+ if (part === '' || part === '.') continue
3152
+ if (part === '..') parts.pop()
3153
+ else parts.push(part)
3154
+ }
3155
+ const base = parts.join('/')
3156
+ return [base, `${base}.ts`, `${base}.tsx`, `${base}.js`, `${base}.jsx`, `${base}.mjs`, `${base}.cjs`, `${base}.d.ts`, `${base}/index.ts`, `${base}/index.js`, `${base}/index.tsx`]
3157
+ }
3158
+ for (const spec of [...new Set(specs)].slice(0, 30)) {
3159
+ for (const rel of candidates(spec)) {
3160
+ try {
3161
+ const doc = await G.api('fs.read', { root, path: rel })
3162
+ const uri = gufaModelUri(monaco, root, rel)
3163
+ if (monaco.editor.getModel(uri) === null) {
3164
+ monaco.editor.createModel(String(doc.content ?? ''), gufaResolveLanguage(monaco, doc.language), uri)
3165
+ }
3166
+ break
3167
+ } catch {
3168
+ /* 尝试下一个候选 */
3169
+ }
3170
+ }
3171
+ }
3172
+ }
3173
+ const queryDefinitions = (position, word, model, path, root) => {
3174
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
3175
+ if (language === 'python') {
3176
+ return G.api('lsp.definition', {
3177
+ root,
3178
+ path,
3179
+ line: position.lineNumber,
3180
+ column: position.column,
3181
+ language: 'python',
3182
+ content: model.getValue(),
3183
+ }).then((value) => ({
3184
+ matches: value !== null && value !== undefined && Array.isArray(value.matches) ? value.matches : [],
3185
+ current: value !== null && value !== undefined && value.current !== undefined ? value.current : undefined,
3186
+ word,
3187
+ }))
3188
+ }
3189
+ return G.api('code.definition', {
3190
+ root,
3191
+ path,
3192
+ line: position.lineNumber,
3193
+ column: position.column,
3194
+ word,
3195
+ content: model.getValue(),
3196
+ })
3197
+ }
3121
3198
  const decideDefinition = (result) => {
3122
3199
  const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
3123
3200
  if (matches.length === 0) return { kind: 'none' }
@@ -3139,14 +3216,6 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3139
3216
  if (distinctFiles.size === 1) return { kind: 'open', match: declCluster[0] }
3140
3217
  return { kind: 'pick', matches: declCluster }
3141
3218
  }
3142
- const queryDefinitions = (position, word, model, path, root) => G.api('code.definition', {
3143
- root,
3144
- path,
3145
- line: position.lineNumber,
3146
- column: position.column,
3147
- word,
3148
- content: model.getValue(),
3149
- })
3150
3219
 
3151
3220
  /* ── Cmd 悬停:可跳转时下划线 + 手型光标 ─────────────── */
3152
3221
  const hover = { meta: false, timer: 0, seq: 0, cache: new Map(), decorationIds: [], lastClient: null, lastPosition: null, lastWordInfo: null, lastKey: '' }
@@ -3346,6 +3415,11 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3346
3415
  } catch {
3347
3416
  /* ignore */
3348
3417
  }
3418
+ try {
3419
+ await preloadTsDependencies(model, path, root)
3420
+ } catch {
3421
+ /* ignore */
3422
+ }
3349
3423
  const beforePath = modelPathRef.current
3350
3424
  const beforePosition = instance.getPosition()
3351
3425
  try {
@@ -3413,6 +3487,83 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3413
3487
  } catch {
3414
3488
  /* ignore */
3415
3489
  }
3490
+ /* ── Copilot 风格 Tab 行内补全(复用 Harness 模型服务) ───────── */
3491
+ try {
3492
+ if (typeof monaco.languages.registerInlineCompletionsProvider === 'function') {
3493
+ const inlineLanguages = ['python', 'javascript', 'typescript', 'javascriptreact', 'typescriptreact', 'java', 'go', 'rust', 'csharp', 'cpp', 'c', 'shell', 'json', 'yaml', 'sql', 'html', 'css']
3494
+ const inlineCache = new Map()
3495
+ let inlineLastRequestAt = 0
3496
+ const inlineProvider = {
3497
+ provideInlineCompletions(model, position, context, token) {
3498
+ const path = modelPathRef.current
3499
+ const root = modelsRootRef.current
3500
+ if (path === null || path === undefined || root === null || root === undefined || root === '') {
3501
+ return Promise.resolve({ items: [] })
3502
+ }
3503
+ if (token !== null && token !== undefined && token.isCancellationRequested === true) return Promise.resolve({ items: [] })
3504
+ return new Promise((resolve) => {
3505
+ let settled = false
3506
+ const finish = (value) => {
3507
+ if (settled) return
3508
+ settled = true
3509
+ resolve(value)
3510
+ }
3511
+ const timer = window.setTimeout(() => {
3512
+ void (async () => {
3513
+ try {
3514
+ if (token !== null && token !== undefined && token.isCancellationRequested === true) return finish({ items: [] })
3515
+ const now = Date.now()
3516
+ if (now - inlineLastRequestAt < 500) return finish({ items: [] })
3517
+ inlineLastRequestAt = now
3518
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
3519
+ if (!inlineLanguages.includes(language)) return finish({ items: [] })
3520
+ const lineCount = model.getLineCount()
3521
+ const startLine = Math.max(1, position.lineNumber - 140)
3522
+ const endLine = Math.min(lineCount, position.lineNumber + 30)
3523
+ const endColumn = model.getLineMaxColumn(endLine)
3524
+ let prefix = ''
3525
+ let suffix = ''
3526
+ try {
3527
+ prefix = model.getValueInRange(new monaco.Range(startLine, 1, position.lineNumber, position.column)).slice(-3200)
3528
+ suffix = model.getValueInRange(new monaco.Range(position.lineNumber, position.column, endLine, endColumn)).slice(0, 800)
3529
+ } catch {
3530
+ return finish({ items: [] })
3531
+ }
3532
+ const version = typeof model.getVersionId === 'function' ? model.getVersionId() : 0
3533
+ const cacheKey = `${path}|${version}|${position.lineNumber}:${position.column}|${language}`
3534
+ const cached = inlineCache.get(cacheKey)
3535
+ if (cached !== undefined) return finish(cached)
3536
+ const value = await G.api('completion.suggest', { root, path, language, prefix, suffix })
3537
+ if (token !== null && token !== undefined && token.isCancellationRequested === true) return finish({ items: [] })
3538
+ const text = value !== null && value !== undefined && typeof value.text === 'string' ? value.text : ''
3539
+ const result = text === ''
3540
+ ? { items: [] }
3541
+ : { items: [{ insertText: text, range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column) }] }
3542
+ if (inlineCache.size > 30) inlineCache.clear()
3543
+ inlineCache.set(cacheKey, result)
3544
+ finish(result)
3545
+ } catch {
3546
+ finish({ items: [] })
3547
+ }
3548
+ })()
3549
+ }, 260)
3550
+ if (token !== null && token !== undefined && typeof token.onCancellationRequested === 'function') {
3551
+ token.onCancellationRequested(() => {
3552
+ window.clearTimeout(timer)
3553
+ finish({ items: [] })
3554
+ })
3555
+ }
3556
+ })
3557
+ },
3558
+ freeInlineCompletions() {},
3559
+ }
3560
+ const inlineDisposable = monaco.languages.registerInlineCompletionsProvider(inlineLanguages, inlineProvider)
3561
+ if (inlineDisposable !== null && inlineDisposable !== undefined && typeof inlineDisposable.dispose === 'function') subscriptions.push(inlineDisposable)
3562
+ }
3563
+ } catch {
3564
+ /* ignore */
3565
+ }
3566
+
3416
3567
  G.__gufaEditorDebug = {
3417
3568
  focus: () => {
3418
3569
  try {
@@ -3646,6 +3797,11 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3646
3797
  /* ignore */
3647
3798
  }
3648
3799
  }
3800
+ /* 打开 Python 文件时预热 pyright,避免第一次 Cmd+点击等语言服务启动 */
3801
+ if (targetTab.language === 'python' && !GUFA_LSP_WARMED.has(root)) {
3802
+ GUFA_LSP_WARMED.add(root)
3803
+ void G.api('lsp.warm', { root }).catch(() => { GUFA_LSP_WARMED.delete(root) })
3804
+ }
3649
3805
  /* 打开/切换文件不抢焦点:只有用户点击编辑区时才进入键盘编辑 */
3650
3806
  }
3651
3807
  } else if (targetTab !== null) {
@@ -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.87</string>
11
- <key>CFBundleVersion</key><string>1.3.87</string>
10
+ <key>CFBundleShortVersionString</key><string>1.3.90</string>
11
+ <key>CFBundleVersion</key><string>1.3.90</string>
12
12
  <key>LSUIElement</key><true/>
13
13
  <key>NSHighResolutionCapable</key><true/>
14
14
  <key>NSPrincipalClass</key><string>NSApplication</string>
@@ -15,6 +15,21 @@
15
15
  - Host `code.definition` 注册在 `host/fs.js` 里,用带 mtime query 的动态 import 加载 `host/code.js`——Host 热重载只按 `MODULE_FILES`(host/*.js)的 mtime 触发,静态 import code.js 会一直吃老缓存。
16
16
  - 兜底匹配会解析 import/require 来源(+220 分)、跳过压缩/生成的大文件(单行超长、>512KB)、按目录距离降权;**不要一有多结果就弹列表**:同文件/import/唯一候选直接跳,`function/class/method/type` 之外的弱匹配先要求分数 ≥50 且领先第二名 ≥10,否则静默;只有多个真正同名声明(不同文件、强类型)才弹 picker(最多 8 条)。
17
17
 
18
+ ## 0.6 语言服务(LSP / Python)与 JS/TS 预加载
19
+
20
+ - Python 定义跳转走 **Pyright LSP**:npm 依赖 `pyright`,Host 用 `spawn(process.execPath, [node_modules/pyright/langserver.index.js, '--stdio'])` 以 JSON-RPC over stdio 管理 initialize/didOpen/didChange/textDocument/definition;client 通过 `lsp.definition` API 调用,不在 renderer 里实现 LSP。
21
+ - pyright 是 optional 安装时自动补的:宿主先找 `node_modules/pyright`,缺失时 `npm install pyright` 兜底一次;Python 第一次点击会有 2~5s 语言服务初始化延迟。
22
+ - JS/TS 用 Monaco 内置 TS worker;它只认识**已加载进 Monaco 的 model**,所以 Cmd+点击前要把当前文件的相对 import 依赖按需 `fs.read` + `createModel` 预加载,跨文件定义/变量才能解析。系统库(lib.d.ts)由 TS worker 自带的 lib 处理。
23
+ - LSP 细节:server→client 请求(workspace/configuration、registerCapability、workDoneProgress)必须回 null,否则 Pyright 初始化会挂住;`textDocument/definition` 返回 LocationLink 也要归一化(targetUri/targetRange)。
24
+ - fs.js 热重载只重载 fs.js 本身,`lsp.js` 是静态 import 缓存的;session 在模块级 Map 里,改 lsp.js 需要重启 Host 才生效(不影响功能)。
25
+
26
+ ## 0.7 Copilot 风格 Tab 行内补全(1.3.89)
27
+
28
+ - 不依赖 Copilot/Codeium 等外部订阅:直接复用 Harness 的 `ctx.llm` 服务(`llm.stream`),provider/model 取 `ctx.get('agentDefaultModel').currentSelection()`,默认 `deepseek-official/deepseek-flash`,约 1s 返回。
29
+ - 客户端 Monaco:`editor options inlineSuggest.enabled=true` + `monaco.languages.registerInlineCompletionsProvider`,返回单条 `insertText`,Monaco 自带 Tab 接受;不要自己绑 Tab,否则会和缩进冲突。
30
+ - 必须做防串扰:`provideInlineCompletions` 里 260ms 防抖 + 全局 500ms 限流 + `token.isCancellationRequested` 取消 + 按 `path/version/position` 缓存;否则每敲一个字符都打模型、又慢又费 token。
31
+ - Host prompt 只带 `prefix`(末尾 3200 字)和 `suffix`(800 字),`maxTokens 160`、`temperature 0.2`;返回前剥掉 markdown 围栏。上下文太大不仅慢,而且容易让模型续写整段而不是补一行。
32
+
18
33
  ## 1. 弹窗/菜单层级:只有一个正确做法(反复踩过多次,最终定案)
19
34
 
20
35
  **现象**:弹窗被右侧「古法 AI」聊天栏压住、只显示一半、关闭按钮点不到;或者反过来把官方设置/会话弹窗盖住。
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Tab 行内补全:借用 Harness 自己的模型服务(ctx.llm),不需要额外 Copilot 订阅。
3
+ *
4
+ * 客户端 Monaco 在光标处请求 `completion.suggest`,Host 拼一小段 FIM 风格 prompt,
5
+ * 用当前默认模型(ctx.agentDefaultModel)流式生成,只回插入文本。为了保持轻量,
6
+ * prompt 只带光标前后有限上下文、maxTokens 很小,客户端做防抖/限流/取消。
7
+ */
8
+ import { ApiError, badRequest } from './context.js'
9
+
10
+ const SYSTEM_PROMPT = [
11
+ 'You are an inline code completion engine inside an IDE.',
12
+ 'Given the code before and after the cursor, predict the exact text the developer would type next.',
13
+ 'Return ONLY the insertion text: no markdown fences, no comments explaining, no repetition of existing text.',
14
+ 'Keep it short (usually one line to a few lines). Match the indentation of the surrounding code.',
15
+ ].join(' ')
16
+
17
+ const SUPPORTED = new Set([
18
+ 'python', 'javascript', 'typescript', 'javascriptreact', 'typescriptreact',
19
+ 'json', 'markdown', 'css', 'scss', 'less', 'html', 'java', 'go', 'rust',
20
+ 'csharp', 'cpp', 'c', 'shell', 'yaml', 'sql', 'php', 'ruby',
21
+ ])
22
+
23
+ function sanitize(text) {
24
+ let value = String(text ?? '')
25
+ /* 去掉模型偶尔带出的 markdown 围栏 */
26
+ value = value.replace(/^```[a-zA-Z0-9_-]*\r?\n?/, '').replace(/\r?\n?```\s*$/, '')
27
+ /* 只取第一段有意义的插入内容,去掉结尾整行解释 */
28
+ value = value.replace(/\r\n/g, '\n')
29
+ const lines = value.split('\n')
30
+ while (lines.length > 0 && lines[0].trim() === '') lines.shift()
31
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '') lines.pop()
32
+ value = lines.join('\n')
33
+ if (value.length > 1200) value = value.slice(0, 1200)
34
+ return value
35
+ }
36
+
37
+ function selectionOf(ctx) {
38
+ try {
39
+ const service = typeof ctx.get === 'function' ? ctx.get('agentDefaultModel') : undefined
40
+ if (service !== undefined && service !== null && typeof service.currentSelection === 'function') return service.currentSelection()
41
+ } catch {
42
+ /* ignore */
43
+ }
44
+ return undefined
45
+ }
46
+
47
+ export async function suggest(body, env) {
48
+ if (typeof body.prefix !== 'string' && typeof body.suffix !== 'string') throw badRequest('prefix is required')
49
+ const ctx = env.ctx
50
+ const llm = typeof ctx.get === 'function' ? ctx.get('llm') : undefined
51
+ if (llm === undefined || llm === null || typeof llm.stream !== 'function') {
52
+ throw new ApiError('llm-unavailable', '当前环境没有可用的模型服务', 503)
53
+ }
54
+ const language = typeof body.language === 'string' ? body.language : ''
55
+ if (!SUPPORTED.has(language)) return { skipped: true, text: '' }
56
+ const path = typeof body.path === 'string' ? body.path : ''
57
+ const prefix = String(body.prefix ?? '').slice(-6000)
58
+ const suffix = String(body.suffix ?? '').slice(0, 2000)
59
+ const fallback = selectionOf(ctx)
60
+ const provider = typeof body.provider === 'string' && body.provider !== '' ? body.provider : fallback?.provider
61
+ const model = typeof body.model === 'string' && body.model !== '' ? body.model : fallback?.model
62
+ if (typeof provider !== 'string' || provider === '' || typeof model !== 'string' || model === '') {
63
+ throw new ApiError('llm-model-unavailable', '没有可用的默认模型', 503)
64
+ }
65
+ const userPrompt = [
66
+ `File: ${path || '(untitled)'}`,
67
+ `Language: ${language}`,
68
+ '',
69
+ 'Code before cursor:',
70
+ '<<<',
71
+ prefix,
72
+ '>>>',
73
+ '',
74
+ 'Code after cursor:',
75
+ '<<<',
76
+ suffix,
77
+ '>>>',
78
+ '',
79
+ 'Insertion:',
80
+ ].join('\n')
81
+
82
+ const controller = new AbortController()
83
+ const timer = setTimeout(() => controller.abort(), 9000)
84
+ let text = ''
85
+ let failure = null
86
+ const startedAt = Date.now()
87
+ try {
88
+ const stream = llm.stream({
89
+ provider,
90
+ model,
91
+ system: SYSTEM_PROMPT,
92
+ messages: [{ role: 'user', content: [{ type: 'text', text: userPrompt }] }],
93
+ maxTokens: 160,
94
+ temperature: 0.2,
95
+ stop: ['\n\n\n'],
96
+ signal: controller.signal,
97
+ })
98
+ for await (const chunk of stream) {
99
+ if (chunk === null || typeof chunk !== 'object') continue
100
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text
101
+ if (chunk.type === 'reasoning-delta') continue
102
+ if (chunk.type === 'finish') {
103
+ const reason = chunk.reason
104
+ if (reason !== null && typeof reason === 'object' && (reason.kind === 'error' || reason.kind === 'aborted')) {
105
+ failure = reason.failure ?? { message: reason.kind }
106
+ }
107
+ break
108
+ }
109
+ }
110
+ } catch (error) {
111
+ failure = { message: String(error?.message ?? error) }
112
+ } finally {
113
+ clearTimeout(timer)
114
+ }
115
+ if (failure !== null && failure !== undefined) {
116
+ const message = typeof failure.message === 'string' ? failure.message : '模型调用失败'
117
+ if (controller.signal.aborted) throw new ApiError('llm-timeout', '补全请求超时', 504)
118
+ throw new ApiError('llm-failed', `补全模型调用失败:${message}`, 502)
119
+ }
120
+ return {
121
+ provider,
122
+ model,
123
+ text: sanitize(text),
124
+ latencyMs: Date.now() - startedAt,
125
+ }
126
+ }
127
+
128
+ export function registerCompletion(router, env) {
129
+ router.method('completion.suggest', (body) => suggest(body, env))
130
+ }
package/host/fs.js CHANGED
@@ -12,6 +12,8 @@ import { constants } from 'node:fs'
12
12
  import { tmpdir } from 'node:os'
13
13
  import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
14
14
  import { ApiError, badRequest } from './context.js'
15
+ import { registerLsp } from './lsp.js'
16
+ import { registerCompletion } from './completion.js'
15
17
 
16
18
  const TEXT_LIMIT = 4 * 1024 * 1024
17
19
  const runCommand = promisify(execFile)
@@ -244,6 +246,12 @@ async function listProjectCandidates(root, project, maxScanned) {
244
246
  }
245
247
 
246
248
  export function register(router, env) {
249
+ /* Python 语言服务(LSP/pyright):/lsp/definition API;Cmd+点击与悬停由客户端调用 */
250
+ registerLsp(router, env)
251
+
252
+ /* Tab 行内补全:借用 Harness 自己的模型服务 */
253
+ registerCompletion(router, env)
254
+
247
255
  /* 代码导航(Cmd+点击跳定义):实现放在 code.js,但 Host 热重载只按 host/*.js 的 mtime
248
256
  触发,因此这里用带 mtime 的 query 动态 import,code.js 改动后下一次请求就能热生效。 */
249
257
  router.method('code.definition', async (body) => {
package/host/lsp.js ADDED
@@ -0,0 +1,358 @@
1
+ /**
2
+ * 语言服务桥(LSP):给 IDE 的 Cmd/Ctrl+点击、悬停提供真正的语言级定义。
3
+ *
4
+ * 目前接 Pyright(Python):npm 依赖 `pyright`,Host 以子进程方式启动
5
+ * `node node_modules/pyright/langserver.index.js --stdio`,用 JSON-RPC over stdio
6
+ * 管理 initialize / didOpen / didChange / textDocument/definition,返回项目内
7
+ * 定义位置。浏览器侧不直连 LSP,而是通过 `lsp.definition` API 调用,避免在
8
+ * renderer 里再实现一遍 JSON-RPC。
9
+ */
10
+ import { spawn } from 'node:child_process'
11
+ import { readFile, stat } from 'node:fs/promises'
12
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
13
+ import { fileURLToPath, pathToFileURL } from 'node:url'
14
+
15
+ import { ApiError, badRequest } from './context.js'
16
+
17
+ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
18
+
19
+ /** root → session */
20
+ const sessions = new Map()
21
+ let installPromise = null
22
+
23
+ function pyrightEntry() {
24
+ return resolve(packageRoot, 'node_modules', 'pyright', 'langserver.index.js')
25
+ }
26
+
27
+ async function fileExists(file) {
28
+ try {
29
+ await stat(file)
30
+ return true
31
+ } catch {
32
+ return false
33
+ }
34
+ }
35
+
36
+ /** 缺依赖时按用户授权做一次自动安装(npm 依赖 pyright)。 */
37
+ async function ensurePyright() {
38
+ const entry = pyrightEntry()
39
+ if (await fileExists(entry)) return entry
40
+ if (installPromise === null) {
41
+ installPromise = (async () => {
42
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'
43
+ await new Promise((resolvePromise, rejectPromise) => {
44
+ const child = spawn(npm, ['install', 'pyright', '--no-audit', '--no-fund'], {
45
+ cwd: packageRoot,
46
+ env: process.env,
47
+ stdio: ['ignore', 'ignore', 'pipe'],
48
+ })
49
+ let stderr = ''
50
+ child.stderr?.on('data', (chunk) => { stderr += String(chunk) })
51
+ const timer = setTimeout(() => {
52
+ try { child.kill('SIGKILL') } catch { /* ignore */ }
53
+ rejectPromise(new Error('安装 pyright 超时(npm install)'))
54
+ }, 180000)
55
+ child.on('error', (error) => {
56
+ clearTimeout(timer)
57
+ rejectPromise(new Error(`无法执行 npm:${error.message}`))
58
+ })
59
+ child.on('exit', (code) => {
60
+ clearTimeout(timer)
61
+ if (code === 0) resolvePromise()
62
+ else rejectPromise(new Error(`npm install pyright 失败(exit ${code}):${stderr.slice(-400)}`))
63
+ })
64
+ })
65
+ if (!(await fileExists(entry))) throw new Error('pyright 安装完成但找不到 langserver.index.js')
66
+ return entry
67
+ })().finally(() => { installPromise = null })
68
+ }
69
+ return await installPromise
70
+ }
71
+
72
+ class JsonRpcClient {
73
+ constructor(child, root, name) {
74
+ this.child = child
75
+ this.root = root
76
+ this.name = name
77
+ this.buffer = Buffer.alloc(0)
78
+ this.nextId = 1
79
+ this.pending = new Map()
80
+ this.stderr = ''
81
+ this.closed = false
82
+ child.stdout.on('data', (chunk) => this.onData(chunk))
83
+ child.stderr?.on('data', (chunk) => {
84
+ this.stderr += String(chunk)
85
+ if (this.stderr.length > 16000) this.stderr = this.stderr.slice(-8000)
86
+ })
87
+ child.on('exit', (code) => {
88
+ this.closed = true
89
+ const failure = new ApiError('lsp-exited', `语言服务进程已退出(code ${code})${this.stderr.slice(-300)}`, 500)
90
+ for (const entry of this.pending.values()) entry.reject(failure)
91
+ this.pending.clear()
92
+ })
93
+ child.on('error', (error) => {
94
+ this.closed = true
95
+ const failure = new ApiError('lsp-error', `语言服务进程错误:${error.message}`, 500)
96
+ for (const entry of this.pending.values()) entry.reject(failure)
97
+ this.pending.clear()
98
+ })
99
+ }
100
+
101
+ onData(chunk) {
102
+ this.buffer = Buffer.concat([this.buffer, chunk])
103
+ for (;;) {
104
+ const headerEnd = this.buffer.indexOf('\r\n\r\n')
105
+ if (headerEnd < 0) return
106
+ const header = this.buffer.subarray(0, headerEnd).toString('utf8')
107
+ const lengthMatch = /content-length:\s*(\d+)/i.exec(header)
108
+ if (lengthMatch === null) {
109
+ this.buffer = this.buffer.subarray(headerEnd + 4)
110
+ continue
111
+ }
112
+ const length = Number(lengthMatch[1])
113
+ const total = headerEnd + 4 + length
114
+ if (this.buffer.length < total) return
115
+ const body = this.buffer.subarray(headerEnd + 4, total).toString('utf8')
116
+ this.buffer = this.buffer.subarray(total)
117
+ let message = null
118
+ try {
119
+ message = JSON.parse(body)
120
+ } catch {
121
+ continue
122
+ }
123
+ this.dispatch(message)
124
+ }
125
+ }
126
+
127
+ dispatch(message) {
128
+ if (message === null || typeof message !== 'object') return
129
+ if (typeof message.id === 'number' && (message.result !== undefined || message.error !== undefined)) {
130
+ const entry = this.pending.get(message.id)
131
+ if (entry === undefined) return
132
+ this.pending.delete(message.id)
133
+ clearTimeout(entry.timer)
134
+ if (message.error !== undefined) entry.reject(new ApiError('lsp-error', String(message.error?.message ?? '语言服务返回错误'), 500))
135
+ else entry.resolve(message.result ?? null)
136
+ return
137
+ }
138
+ if (typeof message.method === 'string' && message.id !== undefined) {
139
+ /* 服务端 → 客户端请求 */
140
+ let result = null
141
+ if (message.method === 'workspace/configuration') {
142
+ const items = Array.isArray(message.params?.items) ? message.params.items : []
143
+ result = items.map(() => null)
144
+ } else if (message.method === 'workspace/workspaceFolders') {
145
+ result = [{ uri: pathToFileURL(this.root).href, name: this.root.split(sep).filter(Boolean).at(-1) ?? 'workspace' }]
146
+ } else if (message.method === 'client/registerCapability' || message.method === 'window/workDoneProgress/create') {
147
+ result = null
148
+ }
149
+ this.send({ jsonrpc: '2.0', id: message.id, result })
150
+ return
151
+ }
152
+ /* 通知:忽略,但要消费 */
153
+ }
154
+
155
+ send(message) {
156
+ if (this.closed) return
157
+ try {
158
+ const body = JSON.stringify(message)
159
+ this.child.stdin.write(`Content-Length: ${Buffer.byteLength(body, 'utf8')}\r\n\r\n${body}`)
160
+ } catch {
161
+ /* broken pipe */
162
+ }
163
+ }
164
+
165
+ notify(method, params) {
166
+ this.send({ jsonrpc: '2.0', method, params })
167
+ }
168
+
169
+ request(method, params, timeoutMs = 20000) {
170
+ if (this.closed) return Promise.reject(new ApiError('lsp-exited', '语言服务进程已退出', 500))
171
+ const id = this.nextId++
172
+ return new Promise((resolvePromise, rejectPromise) => {
173
+ const timer = setTimeout(() => {
174
+ this.pending.delete(id)
175
+ rejectPromise(new ApiError('lsp-timeout', `语言服务响应超时(${method})`, 504))
176
+ }, timeoutMs)
177
+ this.pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer })
178
+ this.send({ jsonrpc: '2.0', id, method, params })
179
+ })
180
+ }
181
+ }
182
+
183
+ function inside(root, target) {
184
+ const rel = relative(root, target)
185
+ return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel))
186
+ }
187
+
188
+ async function startSession(root) {
189
+ const entry = await ensurePyright()
190
+ const child = spawn(process.execPath, [entry, '--stdio'], {
191
+ cwd: root,
192
+ env: { ...process.env, PYTHONUNBUFFERED: '1' },
193
+ stdio: ['pipe', 'pipe', 'pipe'],
194
+ })
195
+ const rpc = new JsonRpcClient(child, root, 'pyright')
196
+ const session = { root, child, rpc, ready: null, documents: new Map() }
197
+ session.ready = (async () => {
198
+ const rootUri = pathToFileURL(root).href
199
+ await rpc.request('initialize', {
200
+ processId: process.pid,
201
+ rootPath: root,
202
+ rootUri,
203
+ workspaceFolders: [{ uri: rootUri, name: root.split(sep).filter(Boolean).at(-1) ?? 'workspace' }],
204
+ capabilities: {
205
+ workspace: { workspaceFolders: true, configuration: true },
206
+ textDocument: {
207
+ synchronization: { dynamicRegistration: false, willSave: false, didSave: false },
208
+ definition: { linkSupport: true },
209
+ hover: { contentFormat: ['markdown', 'plaintext'] },
210
+ publishDiagnostics: { relatedInformation: false },
211
+ },
212
+ },
213
+ clientInfo: { name: 'gufa-code', version: '1.0.0' },
214
+ }, 30000)
215
+ rpc.notify('initialized', {})
216
+ return true
217
+ })()
218
+ session.ready.catch(() => {
219
+ try { child.kill('SIGKILL') } catch { /* ignore */ }
220
+ sessions.delete(root)
221
+ })
222
+ return session
223
+ }
224
+
225
+ async function getSession(root) {
226
+ let session = sessions.get(root)
227
+ if (session !== undefined && session.rpc.closed !== true) {
228
+ await session.ready
229
+ return session
230
+ }
231
+ if (session !== undefined) sessions.delete(root)
232
+ session = await startSession(root)
233
+ sessions.set(root, session)
234
+ await session.ready
235
+ return session
236
+ }
237
+
238
+ function syncDocument(session, absolutePath, content) {
239
+ const uri = pathToFileURL(absolutePath).href
240
+ const existing = session.documents.get(uri)
241
+ if (existing === undefined) {
242
+ const document = { uri, version: 1, content }
243
+ session.documents.set(uri, document)
244
+ session.rpc.notify('textDocument/didOpen', {
245
+ textDocument: { uri, languageId: 'python', version: 1, text: content },
246
+ })
247
+ return
248
+ }
249
+ if (existing.content !== content) {
250
+ existing.version += 1
251
+ existing.content = content
252
+ session.rpc.notify('textDocument/didChange', {
253
+ textDocument: { uri, version: existing.version },
254
+ contentChanges: [{ text: content }],
255
+ })
256
+ }
257
+ }
258
+
259
+ function normalizeLocations(root, result) {
260
+ const raw = Array.isArray(result) ? result : (result === null || result === undefined ? [] : [result])
261
+ const matches = []
262
+ const seen = new Set()
263
+ for (const item of raw) {
264
+ if (item === null || typeof item !== 'object') continue
265
+ const uri = typeof item.uri === 'string' ? item.uri : (typeof item.targetUri === 'string' ? item.targetUri : '')
266
+ const range = item.range !== null && typeof item.range === 'object' ? item.range : (item.targetRange ?? null)
267
+ if (uri === '' || range === null || typeof range !== 'object') continue
268
+ let absolute = ''
269
+ try {
270
+ absolute = fileURLToPath(uri)
271
+ } catch {
272
+ continue
273
+ }
274
+ if (!inside(root, absolute)) continue
275
+ const rel = relative(root, absolute).split(sep).join('/')
276
+ const line = Number(range.start?.line)
277
+ const character = Number(range.start?.character)
278
+ if (!Number.isFinite(line) || !Number.isFinite(character)) continue
279
+ const key = `${rel}:${line}:${character}`
280
+ if (seen.has(key)) continue
281
+ seen.add(key)
282
+ matches.push({ path: rel, line: line + 1, column: character + 1, kind: 'lsp', score: 100, preview: '' })
283
+ }
284
+ return matches
285
+ }
286
+
287
+ async function definition(body, env) {
288
+ if (typeof body.root !== 'string' || body.root === '') throw badRequest('root is required')
289
+ const project = env.projects.ensure(body.root)
290
+ const root = project.root
291
+ const rawPath = typeof body.path === 'string' ? body.path : ''
292
+ if (rawPath === '') throw badRequest('path is required')
293
+ const line = Number(body.line)
294
+ const column = Number(body.column)
295
+ if (!Number.isInteger(line) || line < 1 || !Number.isInteger(column) || column < 1) throw badRequest('line/column is invalid')
296
+ const absolute = resolve(root, rawPath)
297
+ if (!inside(root, absolute)) throw new ApiError('path-outside', '路径超出项目范围', 403)
298
+ let content = typeof body.content === 'string' ? body.content : ''
299
+ if (content === '') {
300
+ try {
301
+ content = await readFile(absolute, 'utf8')
302
+ } catch {
303
+ throw new ApiError('not-found', `文件不存在:${rawPath}`, 404)
304
+ }
305
+ }
306
+ const session = await getSession(root)
307
+ syncDocument(session, absolute, content)
308
+ const uri = pathToFileURL(absolute).href
309
+ let result = null
310
+ try {
311
+ result = await session.rpc.request('textDocument/definition', {
312
+ textDocument: { uri },
313
+ position: { line: line - 1, character: column - 1 },
314
+ }, 25000)
315
+ } catch (error) {
316
+ if (error instanceof ApiError) throw error
317
+ throw new ApiError('lsp-failed', `语言服务查询失败:${String(error?.message ?? error)}`, 500)
318
+ }
319
+ const matches = normalizeLocations(root, result)
320
+ return { matches, current: { path: relative(root, absolute).split(sep).join('/'), line, column }, language: 'python', server: 'pyright' }
321
+ }
322
+
323
+ async function warm(body, env) {
324
+ if (typeof body.root !== 'string' || body.root === '') throw badRequest('root is required')
325
+ const project = env.projects.ensure(body.root)
326
+ await getSession(project.root)
327
+ return { ready: true, server: 'pyright', languages: ['python'] }
328
+ }
329
+
330
+ async function status(body, env) {
331
+ const entry = pyrightEntry()
332
+ const available = await fileExists(entry)
333
+ let version = ''
334
+ try {
335
+ const pkg = JSON.parse(await readFile(resolve(packageRoot, 'node_modules', 'pyright', 'package.json'), 'utf8'))
336
+ version = String(pkg.version ?? '')
337
+ } catch {
338
+ version = ''
339
+ }
340
+ void body
341
+ void env
342
+ return {
343
+ available,
344
+ server: 'pyright',
345
+ version,
346
+ languages: available ? ['python'] : [],
347
+ hint: available ? '' : '缺少 pyright 语言服务;重新安装插件或运行 npm install pyright',
348
+ }
349
+ }
350
+
351
+ export function registerLsp(router, env) {
352
+ router.method('lsp.status', (body) => status(body, env))
353
+ router.method('lsp.warm', (body) => warm(body, env))
354
+ router.method('lsp.definition', (body) => definition(body, env))
355
+ }
356
+
357
+ /* 供未来其他 host 模块复用 */
358
+ export { normalizeLocations }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.87",
3
+ "version": "1.3.90",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
@@ -40,6 +40,7 @@
40
40
  "desktop"
41
41
  ],
42
42
  "dependencies": {
43
+ "pyright": "^1.1.414",
43
44
  "ws": "^8.22.0"
44
45
  },
45
46
  "dsh": {
@@ -400,7 +400,8 @@
400
400
  }
401
401
 
402
402
  /** 这些声明类型算「定义级」,多个同名时值得让用户选;普通 const/赋值等弱匹配不轻易弹列表。 */
403
- const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export'])
403
+ const GUFA_LSP_WARMED = new Set()
404
+ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export', 'lsp'])
404
405
 
405
406
  /* ── model / URI ────────────────────────────────────────────────────── */
406
407
 
@@ -480,6 +481,7 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
480
481
  scrollbar: { verticalScrollbarSize: 10, horizontalScrollbarSize: 10, useShadows: false },
481
482
  mouseWheelZoom: false,
482
483
  contextmenu: true,
484
+ inlineSuggest: { enabled: true, showToolbar: 'never' },
483
485
  }
484
486
  }
485
487
 
@@ -768,6 +770,81 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
768
770
  const mac = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
769
771
  return mac ? event.metaKey === true : event.ctrlKey === true
770
772
  }
773
+ /* JS/TS:把当前文件的 import 依赖按需加载成 Monaco model,让 TS 语言服务
774
+ 能解析跨文件定义;否则 Monaco 只认识已经打开过的标签。 */
775
+ const tsPreloadState = { seen: new Set() }
776
+ const preloadTsDependencies = async (model, path, root) => {
777
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
778
+ if (language !== 'typescript' && language !== 'javascript') return
779
+ const version = typeof model.getVersionId === 'function' ? model.getVersionId() : 0
780
+ const key = `${path}|${version}`
781
+ if (tsPreloadState.seen.has(key) || tsPreloadState.seen.size > 200) return
782
+ tsPreloadState.seen.add(key)
783
+ let content = ''
784
+ try {
785
+ content = model.getValue()
786
+ } catch {
787
+ return
788
+ }
789
+ const specs = []
790
+ for (const pattern of [/import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g, /require\(\s*['"]([^'"]+)['"]\s*\)/g]) {
791
+ let match = null
792
+ while ((match = pattern.exec(content)) !== null) {
793
+ if (typeof match[1] === 'string' && match[1].startsWith('.')) specs.push(match[1])
794
+ }
795
+ }
796
+ const baseDir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''
797
+ const candidates = (spec) => {
798
+ const raw = `${baseDir}${baseDir === '' ? '' : '/'}${spec}`
799
+ const parts = []
800
+ for (const part of raw.split('/')) {
801
+ if (part === '' || part === '.') continue
802
+ if (part === '..') parts.pop()
803
+ else parts.push(part)
804
+ }
805
+ const base = parts.join('/')
806
+ return [base, `${base}.ts`, `${base}.tsx`, `${base}.js`, `${base}.jsx`, `${base}.mjs`, `${base}.cjs`, `${base}.d.ts`, `${base}/index.ts`, `${base}/index.js`, `${base}/index.tsx`]
807
+ }
808
+ for (const spec of [...new Set(specs)].slice(0, 30)) {
809
+ for (const rel of candidates(spec)) {
810
+ try {
811
+ const doc = await G.api('fs.read', { root, path: rel })
812
+ const uri = gufaModelUri(monaco, root, rel)
813
+ if (monaco.editor.getModel(uri) === null) {
814
+ monaco.editor.createModel(String(doc.content ?? ''), gufaResolveLanguage(monaco, doc.language), uri)
815
+ }
816
+ break
817
+ } catch {
818
+ /* 尝试下一个候选 */
819
+ }
820
+ }
821
+ }
822
+ }
823
+ const queryDefinitions = (position, word, model, path, root) => {
824
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
825
+ if (language === 'python') {
826
+ return G.api('lsp.definition', {
827
+ root,
828
+ path,
829
+ line: position.lineNumber,
830
+ column: position.column,
831
+ language: 'python',
832
+ content: model.getValue(),
833
+ }).then((value) => ({
834
+ matches: value !== null && value !== undefined && Array.isArray(value.matches) ? value.matches : [],
835
+ current: value !== null && value !== undefined && value.current !== undefined ? value.current : undefined,
836
+ word,
837
+ }))
838
+ }
839
+ return G.api('code.definition', {
840
+ root,
841
+ path,
842
+ line: position.lineNumber,
843
+ column: position.column,
844
+ word,
845
+ content: model.getValue(),
846
+ })
847
+ }
771
848
  const decideDefinition = (result) => {
772
849
  const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
773
850
  if (matches.length === 0) return { kind: 'none' }
@@ -789,14 +866,6 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
789
866
  if (distinctFiles.size === 1) return { kind: 'open', match: declCluster[0] }
790
867
  return { kind: 'pick', matches: declCluster }
791
868
  }
792
- const queryDefinitions = (position, word, model, path, root) => G.api('code.definition', {
793
- root,
794
- path,
795
- line: position.lineNumber,
796
- column: position.column,
797
- word,
798
- content: model.getValue(),
799
- })
800
869
 
801
870
  /* ── Cmd 悬停:可跳转时下划线 + 手型光标 ─────────────── */
802
871
  const hover = { meta: false, timer: 0, seq: 0, cache: new Map(), decorationIds: [], lastClient: null, lastPosition: null, lastWordInfo: null, lastKey: '' }
@@ -996,6 +1065,11 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
996
1065
  } catch {
997
1066
  /* ignore */
998
1067
  }
1068
+ try {
1069
+ await preloadTsDependencies(model, path, root)
1070
+ } catch {
1071
+ /* ignore */
1072
+ }
999
1073
  const beforePath = modelPathRef.current
1000
1074
  const beforePosition = instance.getPosition()
1001
1075
  try {
@@ -1063,6 +1137,83 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
1063
1137
  } catch {
1064
1138
  /* ignore */
1065
1139
  }
1140
+ /* ── Copilot 风格 Tab 行内补全(复用 Harness 模型服务) ───────── */
1141
+ try {
1142
+ if (typeof monaco.languages.registerInlineCompletionsProvider === 'function') {
1143
+ const inlineLanguages = ['python', 'javascript', 'typescript', 'javascriptreact', 'typescriptreact', 'java', 'go', 'rust', 'csharp', 'cpp', 'c', 'shell', 'json', 'yaml', 'sql', 'html', 'css']
1144
+ const inlineCache = new Map()
1145
+ let inlineLastRequestAt = 0
1146
+ const inlineProvider = {
1147
+ provideInlineCompletions(model, position, context, token) {
1148
+ const path = modelPathRef.current
1149
+ const root = modelsRootRef.current
1150
+ if (path === null || path === undefined || root === null || root === undefined || root === '') {
1151
+ return Promise.resolve({ items: [] })
1152
+ }
1153
+ if (token !== null && token !== undefined && token.isCancellationRequested === true) return Promise.resolve({ items: [] })
1154
+ return new Promise((resolve) => {
1155
+ let settled = false
1156
+ const finish = (value) => {
1157
+ if (settled) return
1158
+ settled = true
1159
+ resolve(value)
1160
+ }
1161
+ const timer = window.setTimeout(() => {
1162
+ void (async () => {
1163
+ try {
1164
+ if (token !== null && token !== undefined && token.isCancellationRequested === true) return finish({ items: [] })
1165
+ const now = Date.now()
1166
+ if (now - inlineLastRequestAt < 500) return finish({ items: [] })
1167
+ inlineLastRequestAt = now
1168
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
1169
+ if (!inlineLanguages.includes(language)) return finish({ items: [] })
1170
+ const lineCount = model.getLineCount()
1171
+ const startLine = Math.max(1, position.lineNumber - 140)
1172
+ const endLine = Math.min(lineCount, position.lineNumber + 30)
1173
+ const endColumn = model.getLineMaxColumn(endLine)
1174
+ let prefix = ''
1175
+ let suffix = ''
1176
+ try {
1177
+ prefix = model.getValueInRange(new monaco.Range(startLine, 1, position.lineNumber, position.column)).slice(-3200)
1178
+ suffix = model.getValueInRange(new monaco.Range(position.lineNumber, position.column, endLine, endColumn)).slice(0, 800)
1179
+ } catch {
1180
+ return finish({ items: [] })
1181
+ }
1182
+ const version = typeof model.getVersionId === 'function' ? model.getVersionId() : 0
1183
+ const cacheKey = `${path}|${version}|${position.lineNumber}:${position.column}|${language}`
1184
+ const cached = inlineCache.get(cacheKey)
1185
+ if (cached !== undefined) return finish(cached)
1186
+ const value = await G.api('completion.suggest', { root, path, language, prefix, suffix })
1187
+ if (token !== null && token !== undefined && token.isCancellationRequested === true) return finish({ items: [] })
1188
+ const text = value !== null && value !== undefined && typeof value.text === 'string' ? value.text : ''
1189
+ const result = text === ''
1190
+ ? { items: [] }
1191
+ : { items: [{ insertText: text, range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column) }] }
1192
+ if (inlineCache.size > 30) inlineCache.clear()
1193
+ inlineCache.set(cacheKey, result)
1194
+ finish(result)
1195
+ } catch {
1196
+ finish({ items: [] })
1197
+ }
1198
+ })()
1199
+ }, 260)
1200
+ if (token !== null && token !== undefined && typeof token.onCancellationRequested === 'function') {
1201
+ token.onCancellationRequested(() => {
1202
+ window.clearTimeout(timer)
1203
+ finish({ items: [] })
1204
+ })
1205
+ }
1206
+ })
1207
+ },
1208
+ freeInlineCompletions() {},
1209
+ }
1210
+ const inlineDisposable = monaco.languages.registerInlineCompletionsProvider(inlineLanguages, inlineProvider)
1211
+ if (inlineDisposable !== null && inlineDisposable !== undefined && typeof inlineDisposable.dispose === 'function') subscriptions.push(inlineDisposable)
1212
+ }
1213
+ } catch {
1214
+ /* ignore */
1215
+ }
1216
+
1066
1217
  G.__gufaEditorDebug = {
1067
1218
  focus: () => {
1068
1219
  try {
@@ -1296,6 +1447,11 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
1296
1447
  /* ignore */
1297
1448
  }
1298
1449
  }
1450
+ /* 打开 Python 文件时预热 pyright,避免第一次 Cmd+点击等语言服务启动 */
1451
+ if (targetTab.language === 'python' && !GUFA_LSP_WARMED.has(root)) {
1452
+ GUFA_LSP_WARMED.add(root)
1453
+ void G.api('lsp.warm', { root }).catch(() => { GUFA_LSP_WARMED.delete(root) })
1454
+ }
1299
1455
  /* 打开/切换文件不抢焦点:只有用户点击编辑区时才进入键盘编辑 */
1300
1456
  }
1301
1457
  } else if (targetTab !== null) {