dsh-gufa-code 1.3.88 → 1.3.91

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.
@@ -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.88</string>
11
- <key>CFBundleVersion</key><string>1.3.88</string>
10
+ <key>CFBundleShortVersionString</key><string>1.3.91</string>
11
+ <key>CFBundleVersion</key><string>1.3.91</string>
12
12
  <key>LSUIElement</key><true/>
13
13
  <key>NSHighResolutionCapable</key><true/>
14
14
  <key>NSPrincipalClass</key><string>NSApplication</string>
@@ -23,6 +23,21 @@
23
23
  - LSP 细节:server→client 请求(workspace/configuration、registerCapability、workDoneProgress)必须回 null,否则 Pyright 初始化会挂住;`textDocument/definition` 返回 LocationLink 也要归一化(targetUri/targetRange)。
24
24
  - fs.js 热重载只重载 fs.js 本身,`lsp.js` 是静态 import 缓存的;session 在模块级 Map 里,改 lsp.js 需要重启 Host 才生效(不影响功能)。
25
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
+
33
+ ## 0.8 代码引用/拖拽引用(原 dsh-drag-ref 已并入)
34
+
35
+ - 原先独立插件 dsh-drag-ref 的复制代码引用、拖文件到输入框、chip 点击跳回能力已并入 `src/client/58b-drag-ref.js`,profile 里不再装独立插件;两边同时装会重复 `copy` 监听。
36
+ - 复制语义:**跨行选区一律算引用**(首行/末行只选半行也可以,行范围按实际首尾行);**单行必须整行选中**才生成引用,否则不拦截、按普通文本复制。
37
+ - 成功复制/插入/拖动/跳转一律不弹 toast(用户明确讨厌成功提示),只有失败才提示;toast 复用 `G.refToast`。
38
+ - 古法 IDE 内点击引用 chip:优先 `G.bus.emit('editor:open-at')` 打开自己的 Monaco 标签,再 `selectRange` 选中行范围;不要依赖 DSH 侧边栏资源路由。
39
+ - 行范围引用格式 `@path Lx-Ly`;chip 标签里存路径+行号用于点击定位,`localStorage` key 使用 `gufa-code.refs.v1`。
40
+
26
41
  ## 1. 弹窗/菜单层级:只有一个正确做法(反复踩过多次,最终定案)
27
42
 
28
43
  **现象**:弹窗被右侧「古法 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
@@ -13,6 +13,7 @@ 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
15
  import { registerLsp } from './lsp.js'
16
+ import { registerCompletion } from './completion.js'
16
17
 
17
18
  const TEXT_LIMIT = 4 * 1024 * 1024
18
19
  const runCommand = promisify(execFile)
@@ -248,6 +249,9 @@ export function register(router, env) {
248
249
  /* Python 语言服务(LSP/pyright):/lsp/definition API;Cmd+点击与悬停由客户端调用 */
249
250
  registerLsp(router, env)
250
251
 
252
+ /* Tab 行内补全:借用 Harness 自己的模型服务 */
253
+ registerCompletion(router, env)
254
+
251
255
  /* 代码导航(Cmd+点击跳定义):实现放在 code.js,但 Host 热重载只按 host/*.js 的 mtime
252
256
  触发,因此这里用带 mtime 的 query 动态 import,code.js 改动后下一次请求就能热生效。 */
253
257
  router.method('code.definition', async (body) => {
package/host/lsp.js CHANGED
@@ -320,6 +320,13 @@ async function definition(body, env) {
320
320
  return { matches, current: { path: relative(root, absolute).split(sep).join('/'), line, column }, language: 'python', server: 'pyright' }
321
321
  }
322
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
+
323
330
  async function status(body, env) {
324
331
  const entry = pyrightEntry()
325
332
  const available = await fileExists(entry)
@@ -343,6 +350,7 @@ async function status(body, env) {
343
350
 
344
351
  export function registerLsp(router, env) {
345
352
  router.method('lsp.status', (body) => status(body, env))
353
+ router.method('lsp.warm', (body) => warm(body, env))
346
354
  router.method('lsp.definition', (body) => definition(body, env))
347
355
  }
348
356
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.88",
3
+ "version": "1.3.91",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
@@ -400,6 +400,7 @@
400
400
  }
401
401
 
402
402
  /** 这些声明类型算「定义级」,多个同名时值得让用户选;普通 const/赋值等弱匹配不轻易弹列表。 */
403
+ const GUFA_LSP_WARMED = new Set()
403
404
  const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export', 'lsp'])
404
405
 
405
406
  /* ── model / URI ────────────────────────────────────────────────────── */
@@ -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
 
@@ -531,6 +533,7 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
531
533
  const viewStatesRef = useRef(new Map()) /* path -> editor view state(滚动/光标) */
532
534
  const lastPropContentRef = useRef(new Map()) /* path -> 最近一次同步过的 props content */
533
535
  const modelsRootRef = useRef(root) /* model 所属项目根:root 变了必须重建 */
536
+ const tsPreloadRef = useRef(null) /* 后台预加载 import 依赖(JS/TS) */
534
537
  const modelPathRef = useRef(null) /* 当前挂在 editor 上的 tab path */
535
538
  const suppressChangeRef = useRef(false) /* 程序化 setValue 时抑制 onChange 回环 */
536
539
  const propsRef = useRef(props)
@@ -818,6 +821,7 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
818
821
  }
819
822
  }
820
823
  }
824
+ tsPreloadRef.current = preloadTsDependencies
821
825
  const queryDefinitions = (position, word, model, path, root) => {
822
826
  const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
823
827
  if (language === 'python') {
@@ -1135,6 +1139,83 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
1135
1139
  } catch {
1136
1140
  /* ignore */
1137
1141
  }
1142
+ /* ── Copilot 风格 Tab 行内补全(复用 Harness 模型服务) ───────── */
1143
+ try {
1144
+ if (typeof monaco.languages.registerInlineCompletionsProvider === 'function') {
1145
+ const inlineLanguages = ['python', 'javascript', 'typescript', 'javascriptreact', 'typescriptreact', 'java', 'go', 'rust', 'csharp', 'cpp', 'c', 'shell', 'json', 'yaml', 'sql', 'html', 'css']
1146
+ const inlineCache = new Map()
1147
+ let inlineLastRequestAt = 0
1148
+ const inlineProvider = {
1149
+ provideInlineCompletions(model, position, context, token) {
1150
+ const path = modelPathRef.current
1151
+ const root = modelsRootRef.current
1152
+ if (path === null || path === undefined || root === null || root === undefined || root === '') {
1153
+ return Promise.resolve({ items: [] })
1154
+ }
1155
+ if (token !== null && token !== undefined && token.isCancellationRequested === true) return Promise.resolve({ items: [] })
1156
+ return new Promise((resolve) => {
1157
+ let settled = false
1158
+ const finish = (value) => {
1159
+ if (settled) return
1160
+ settled = true
1161
+ resolve(value)
1162
+ }
1163
+ const timer = window.setTimeout(() => {
1164
+ void (async () => {
1165
+ try {
1166
+ if (token !== null && token !== undefined && token.isCancellationRequested === true) return finish({ items: [] })
1167
+ const now = Date.now()
1168
+ if (now - inlineLastRequestAt < 500) return finish({ items: [] })
1169
+ inlineLastRequestAt = now
1170
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
1171
+ if (!inlineLanguages.includes(language)) return finish({ items: [] })
1172
+ const lineCount = model.getLineCount()
1173
+ const startLine = Math.max(1, position.lineNumber - 140)
1174
+ const endLine = Math.min(lineCount, position.lineNumber + 30)
1175
+ const endColumn = model.getLineMaxColumn(endLine)
1176
+ let prefix = ''
1177
+ let suffix = ''
1178
+ try {
1179
+ prefix = model.getValueInRange(new monaco.Range(startLine, 1, position.lineNumber, position.column)).slice(-3200)
1180
+ suffix = model.getValueInRange(new monaco.Range(position.lineNumber, position.column, endLine, endColumn)).slice(0, 800)
1181
+ } catch {
1182
+ return finish({ items: [] })
1183
+ }
1184
+ const version = typeof model.getVersionId === 'function' ? model.getVersionId() : 0
1185
+ const cacheKey = `${path}|${version}|${position.lineNumber}:${position.column}|${language}`
1186
+ const cached = inlineCache.get(cacheKey)
1187
+ if (cached !== undefined) return finish(cached)
1188
+ const value = await G.api('completion.suggest', { root, path, language, prefix, suffix })
1189
+ if (token !== null && token !== undefined && token.isCancellationRequested === true) return finish({ items: [] })
1190
+ const text = value !== null && value !== undefined && typeof value.text === 'string' ? value.text : ''
1191
+ const result = text === ''
1192
+ ? { items: [] }
1193
+ : { items: [{ insertText: text, range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column) }] }
1194
+ if (inlineCache.size > 30) inlineCache.clear()
1195
+ inlineCache.set(cacheKey, result)
1196
+ finish(result)
1197
+ } catch {
1198
+ finish({ items: [] })
1199
+ }
1200
+ })()
1201
+ }, 260)
1202
+ if (token !== null && token !== undefined && typeof token.onCancellationRequested === 'function') {
1203
+ token.onCancellationRequested(() => {
1204
+ window.clearTimeout(timer)
1205
+ finish({ items: [] })
1206
+ })
1207
+ }
1208
+ })
1209
+ },
1210
+ freeInlineCompletions() {},
1211
+ }
1212
+ const inlineDisposable = monaco.languages.registerInlineCompletionsProvider(inlineLanguages, inlineProvider)
1213
+ if (inlineDisposable !== null && inlineDisposable !== undefined && typeof inlineDisposable.dispose === 'function') subscriptions.push(inlineDisposable)
1214
+ }
1215
+ } catch {
1216
+ /* ignore */
1217
+ }
1218
+
1138
1219
  G.__gufaEditorDebug = {
1139
1220
  focus: () => {
1140
1221
  try {
@@ -1368,6 +1449,23 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
1368
1449
  /* ignore */
1369
1450
  }
1370
1451
  }
1452
+ /* 打开 Python 文件时预热 pyright,避免第一次 Cmd+点击等语言服务启动 */
1453
+ if (targetTab.language === 'python' && !GUFA_LSP_WARMED.has(root)) {
1454
+ GUFA_LSP_WARMED.add(root)
1455
+ void G.api('lsp.warm', { root }).catch(() => { GUFA_LSP_WARMED.delete(root) })
1456
+ }
1457
+ /* JS/TS:切到文件后后台预加载 import 依赖,点 Cmd+点击时 Monaco 已有跨文件 model,少等网络 */
1458
+ if (targetTab.language === 'typescript' || targetTab.language === 'javascript') {
1459
+ const modelForPreload = targetModel
1460
+ const pathForPreload = targetTab.path
1461
+ window.setTimeout(() => {
1462
+ try {
1463
+ if (tsPreloadRef.current !== null) void tsPreloadRef.current(modelForPreload, pathForPreload, root)
1464
+ } catch {
1465
+ /* ignore */
1466
+ }
1467
+ }, 200)
1468
+ }
1371
1469
  /* 打开/切换文件不抢焦点:只有用户点击编辑区时才进入键盘编辑 */
1372
1470
  }
1373
1471
  } else if (targetTab !== null) {