dsh-gufa-code 1.3.87 → 1.3.88

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,7 +41,7 @@ dsh plugin add dsh-gufa-code
41
41
  - Monaco 编辑器(离线随包分发,无需联网下载);
42
42
  - 多标签、按扩展名语法高亮、面包屑、状态栏(分支 / 行列 / 保存状态);
43
43
  - 保存走磁盘版本冲突检测 + 原子写;未保存标记;
44
- - **⌘/Ctrl + 点击跳转定义 / 方法实现**:优先走 Monaco 语言服务;目标文件没在 Monaco 里打开、或语言没有内置语言服务时,自动用项目级定义搜索兜底(函数 / 类 / 方法 / const / type 等声明)。兜底会解析 import/require 直接定位来源文件,并跳过压缩产物/大文件;同一个文件里的声明、import 命中的定义、目录距离近的定义直接跳,只有多个真正同名的声明才弹「跳转到定义」列表,点同名属性/变量时不会拿远端无关的 const 来凑数;按住 ⌘/Ctrl 悬停时,可跳转的符号会显示下划线 + 手型光标;
44
+ - **⌘/Ctrl + 点击跳转定义 / 方法实现**:Python 走 **Pyright 语言服务(LSP)**,JS/TS 走 Monaco 内置 TypeScript 语言服务(点击前会按需把当前文件的 import 依赖加载进 Monaco,跨文件变量/函数由 TS 语言服务解析);其他语言暂用项目级定义搜索兜底;优先走 Monaco 语言服务;目标文件没在 Monaco 里打开、或语言没有内置语言服务时,自动用项目级定义搜索兜底(函数 / 类 / 方法 / const / type 等声明)。兜底会解析 import/require 直接定位来源文件,并跳过压缩产物/大文件;同一个文件里的声明、import 命中的定义、目录距离近的定义直接跳,只有多个真正同名的声明才弹「跳转到定义」列表,点同名属性/变量时不会拿远端无关的 const 来凑数;按住 ⌘/Ctrl 悬停时,可跳转的符号会显示下划线 + 手型光标;
45
45
  - **全局搜索 / 替换**(左栏放大镜 / `⌘⇧F`):整个项目的文本搜索,支持区分大小写、正则、包含/排除文件(glob);结果按文件分组、高亮匹配,点击跳转行列;替换栏支持保留大小写(AB)、全部替换(需确认)、按文件替换(悬停文件头铅笔)、按单行匹配替换与忽略(悬停结果行);替换前会自动保存未落盘的编辑器内容;Git 项目用 `git ls-files` 枚举文件(尊重 `.gitignore`、含未跟踪文件),非 Git 项目遍历目录并自动跳过 `node_modules` 等依赖/缓存目录;摸鱼悬浮窗里同样可用;
46
46
  - 资源管理器右键:新建 / 重命名 / 删除 / 复制 / 粘贴 / 打开所在文件夹 / 两文件对比;
47
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.87'
19
+ G.BUILD = '1.3.88'
20
20
  G.PANEL_ID = 'gufa-code'
21
21
  /** 从哪个工作区点进来的(工作区菜单/节点按钮写入,App 启动时消费)。 */
22
22
  G.pendingEntryWorkspace = null
@@ -2750,7 +2750,7 @@ 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_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export', 'lsp'])
2754
2754
 
2755
2755
  /* ── model / URI ────────────────────────────────────────────────────── */
2756
2756
 
@@ -3118,6 +3118,81 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3118
3118
  const mac = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
3119
3119
  return mac ? event.metaKey === true : event.ctrlKey === true
3120
3120
  }
3121
+ /* JS/TS:把当前文件的 import 依赖按需加载成 Monaco model,让 TS 语言服务
3122
+ 能解析跨文件定义;否则 Monaco 只认识已经打开过的标签。 */
3123
+ const tsPreloadState = { seen: new Set() }
3124
+ const preloadTsDependencies = async (model, path, root) => {
3125
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
3126
+ if (language !== 'typescript' && language !== 'javascript') return
3127
+ const version = typeof model.getVersionId === 'function' ? model.getVersionId() : 0
3128
+ const key = `${path}|${version}`
3129
+ if (tsPreloadState.seen.has(key) || tsPreloadState.seen.size > 200) return
3130
+ tsPreloadState.seen.add(key)
3131
+ let content = ''
3132
+ try {
3133
+ content = model.getValue()
3134
+ } catch {
3135
+ return
3136
+ }
3137
+ const specs = []
3138
+ for (const pattern of [/import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g, /require\(\s*['"]([^'"]+)['"]\s*\)/g]) {
3139
+ let match = null
3140
+ while ((match = pattern.exec(content)) !== null) {
3141
+ if (typeof match[1] === 'string' && match[1].startsWith('.')) specs.push(match[1])
3142
+ }
3143
+ }
3144
+ const baseDir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''
3145
+ const candidates = (spec) => {
3146
+ const raw = `${baseDir}${baseDir === '' ? '' : '/'}${spec}`
3147
+ const parts = []
3148
+ for (const part of raw.split('/')) {
3149
+ if (part === '' || part === '.') continue
3150
+ if (part === '..') parts.pop()
3151
+ else parts.push(part)
3152
+ }
3153
+ const base = parts.join('/')
3154
+ 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`]
3155
+ }
3156
+ for (const spec of [...new Set(specs)].slice(0, 30)) {
3157
+ for (const rel of candidates(spec)) {
3158
+ try {
3159
+ const doc = await G.api('fs.read', { root, path: rel })
3160
+ const uri = gufaModelUri(monaco, root, rel)
3161
+ if (monaco.editor.getModel(uri) === null) {
3162
+ monaco.editor.createModel(String(doc.content ?? ''), gufaResolveLanguage(monaco, doc.language), uri)
3163
+ }
3164
+ break
3165
+ } catch {
3166
+ /* 尝试下一个候选 */
3167
+ }
3168
+ }
3169
+ }
3170
+ }
3171
+ const queryDefinitions = (position, word, model, path, root) => {
3172
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
3173
+ if (language === 'python') {
3174
+ return G.api('lsp.definition', {
3175
+ root,
3176
+ path,
3177
+ line: position.lineNumber,
3178
+ column: position.column,
3179
+ language: 'python',
3180
+ content: model.getValue(),
3181
+ }).then((value) => ({
3182
+ matches: value !== null && value !== undefined && Array.isArray(value.matches) ? value.matches : [],
3183
+ current: value !== null && value !== undefined && value.current !== undefined ? value.current : undefined,
3184
+ word,
3185
+ }))
3186
+ }
3187
+ return G.api('code.definition', {
3188
+ root,
3189
+ path,
3190
+ line: position.lineNumber,
3191
+ column: position.column,
3192
+ word,
3193
+ content: model.getValue(),
3194
+ })
3195
+ }
3121
3196
  const decideDefinition = (result) => {
3122
3197
  const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
3123
3198
  if (matches.length === 0) return { kind: 'none' }
@@ -3139,14 +3214,6 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3139
3214
  if (distinctFiles.size === 1) return { kind: 'open', match: declCluster[0] }
3140
3215
  return { kind: 'pick', matches: declCluster }
3141
3216
  }
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
3217
 
3151
3218
  /* ── Cmd 悬停:可跳转时下划线 + 手型光标 ─────────────── */
3152
3219
  const hover = { meta: false, timer: 0, seq: 0, cache: new Map(), decorationIds: [], lastClient: null, lastPosition: null, lastWordInfo: null, lastKey: '' }
@@ -3346,6 +3413,11 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3346
3413
  } catch {
3347
3414
  /* ignore */
3348
3415
  }
3416
+ try {
3417
+ await preloadTsDependencies(model, path, root)
3418
+ } catch {
3419
+ /* ignore */
3420
+ }
3349
3421
  const beforePath = modelPathRef.current
3350
3422
  const beforePosition = instance.getPosition()
3351
3423
  try {
@@ -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.88</string>
11
+ <key>CFBundleVersion</key><string>1.3.88</string>
12
12
  <key>LSUIElement</key><true/>
13
13
  <key>NSHighResolutionCapable</key><true/>
14
14
  <key>NSPrincipalClass</key><string>NSApplication</string>
@@ -15,6 +15,14 @@
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
+
18
26
  ## 1. 弹窗/菜单层级:只有一个正确做法(反复踩过多次,最终定案)
19
27
 
20
28
  **现象**:弹窗被右侧「古法 AI」聊天栏压住、只显示一半、关闭按钮点不到;或者反过来把官方设置/会话弹窗盖住。
package/host/fs.js CHANGED
@@ -12,6 +12,7 @@ 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'
15
16
 
16
17
  const TEXT_LIMIT = 4 * 1024 * 1024
17
18
  const runCommand = promisify(execFile)
@@ -244,6 +245,9 @@ async function listProjectCandidates(root, project, maxScanned) {
244
245
  }
245
246
 
246
247
  export function register(router, env) {
248
+ /* Python 语言服务(LSP/pyright):/lsp/definition API;Cmd+点击与悬停由客户端调用 */
249
+ registerLsp(router, env)
250
+
247
251
  /* 代码导航(Cmd+点击跳定义):实现放在 code.js,但 Host 热重载只按 host/*.js 的 mtime
248
252
  触发,因此这里用带 mtime 的 query 动态 import,code.js 改动后下一次请求就能热生效。 */
249
253
  router.method('code.definition', async (body) => {
package/host/lsp.js ADDED
@@ -0,0 +1,350 @@
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 status(body, env) {
324
+ const entry = pyrightEntry()
325
+ const available = await fileExists(entry)
326
+ let version = ''
327
+ try {
328
+ const pkg = JSON.parse(await readFile(resolve(packageRoot, 'node_modules', 'pyright', 'package.json'), 'utf8'))
329
+ version = String(pkg.version ?? '')
330
+ } catch {
331
+ version = ''
332
+ }
333
+ void body
334
+ void env
335
+ return {
336
+ available,
337
+ server: 'pyright',
338
+ version,
339
+ languages: available ? ['python'] : [],
340
+ hint: available ? '' : '缺少 pyright 语言服务;重新安装插件或运行 npm install pyright',
341
+ }
342
+ }
343
+
344
+ export function registerLsp(router, env) {
345
+ router.method('lsp.status', (body) => status(body, env))
346
+ router.method('lsp.definition', (body) => definition(body, env))
347
+ }
348
+
349
+ /* 供未来其他 host 模块复用 */
350
+ 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.88",
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,7 @@
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_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export', 'lsp'])
404
404
 
405
405
  /* ── model / URI ────────────────────────────────────────────────────── */
406
406
 
@@ -768,6 +768,81 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
768
768
  const mac = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
769
769
  return mac ? event.metaKey === true : event.ctrlKey === true
770
770
  }
771
+ /* JS/TS:把当前文件的 import 依赖按需加载成 Monaco model,让 TS 语言服务
772
+ 能解析跨文件定义;否则 Monaco 只认识已经打开过的标签。 */
773
+ const tsPreloadState = { seen: new Set() }
774
+ const preloadTsDependencies = async (model, path, root) => {
775
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
776
+ if (language !== 'typescript' && language !== 'javascript') return
777
+ const version = typeof model.getVersionId === 'function' ? model.getVersionId() : 0
778
+ const key = `${path}|${version}`
779
+ if (tsPreloadState.seen.has(key) || tsPreloadState.seen.size > 200) return
780
+ tsPreloadState.seen.add(key)
781
+ let content = ''
782
+ try {
783
+ content = model.getValue()
784
+ } catch {
785
+ return
786
+ }
787
+ const specs = []
788
+ for (const pattern of [/import\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g, /require\(\s*['"]([^'"]+)['"]\s*\)/g]) {
789
+ let match = null
790
+ while ((match = pattern.exec(content)) !== null) {
791
+ if (typeof match[1] === 'string' && match[1].startsWith('.')) specs.push(match[1])
792
+ }
793
+ }
794
+ const baseDir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''
795
+ const candidates = (spec) => {
796
+ const raw = `${baseDir}${baseDir === '' ? '' : '/'}${spec}`
797
+ const parts = []
798
+ for (const part of raw.split('/')) {
799
+ if (part === '' || part === '.') continue
800
+ if (part === '..') parts.pop()
801
+ else parts.push(part)
802
+ }
803
+ const base = parts.join('/')
804
+ 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`]
805
+ }
806
+ for (const spec of [...new Set(specs)].slice(0, 30)) {
807
+ for (const rel of candidates(spec)) {
808
+ try {
809
+ const doc = await G.api('fs.read', { root, path: rel })
810
+ const uri = gufaModelUri(monaco, root, rel)
811
+ if (monaco.editor.getModel(uri) === null) {
812
+ monaco.editor.createModel(String(doc.content ?? ''), gufaResolveLanguage(monaco, doc.language), uri)
813
+ }
814
+ break
815
+ } catch {
816
+ /* 尝试下一个候选 */
817
+ }
818
+ }
819
+ }
820
+ }
821
+ const queryDefinitions = (position, word, model, path, root) => {
822
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
823
+ if (language === 'python') {
824
+ return G.api('lsp.definition', {
825
+ root,
826
+ path,
827
+ line: position.lineNumber,
828
+ column: position.column,
829
+ language: 'python',
830
+ content: model.getValue(),
831
+ }).then((value) => ({
832
+ matches: value !== null && value !== undefined && Array.isArray(value.matches) ? value.matches : [],
833
+ current: value !== null && value !== undefined && value.current !== undefined ? value.current : undefined,
834
+ word,
835
+ }))
836
+ }
837
+ return G.api('code.definition', {
838
+ root,
839
+ path,
840
+ line: position.lineNumber,
841
+ column: position.column,
842
+ word,
843
+ content: model.getValue(),
844
+ })
845
+ }
771
846
  const decideDefinition = (result) => {
772
847
  const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
773
848
  if (matches.length === 0) return { kind: 'none' }
@@ -789,14 +864,6 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
789
864
  if (distinctFiles.size === 1) return { kind: 'open', match: declCluster[0] }
790
865
  return { kind: 'pick', matches: declCluster }
791
866
  }
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
867
 
801
868
  /* ── Cmd 悬停:可跳转时下划线 + 手型光标 ─────────────── */
802
869
  const hover = { meta: false, timer: 0, seq: 0, cache: new Map(), decorationIds: [], lastClient: null, lastPosition: null, lastWordInfo: null, lastKey: '' }
@@ -996,6 +1063,11 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
996
1063
  } catch {
997
1064
  /* ignore */
998
1065
  }
1066
+ try {
1067
+ await preloadTsDependencies(model, path, root)
1068
+ } catch {
1069
+ /* ignore */
1070
+ }
999
1071
  const beforePath = modelPathRef.current
1000
1072
  const beforePosition = instance.getPosition()
1001
1073
  try {