dsh-remote 0.8.83 → 0.8.84
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/LICENSE +21 -21
- package/README.en.md +480 -480
- package/README.md +538 -538
- package/cordis.patch.yml +9 -9
- package/lib/audit.js +45 -45
- package/lib/binding.js +172 -172
- package/lib/client.js +4265 -4265
- package/lib/credential.js +263 -263
- package/lib/errors.js +141 -141
- package/lib/exec-job.js +242 -242
- package/lib/file-reference.js +457 -457
- package/lib/forwards.js +258 -258
- package/lib/host-api.js +822 -822
- package/lib/hostkey.js +108 -108
- package/lib/http-transport.js +201 -201
- package/lib/ignore.js +202 -202
- package/lib/index.js +5016 -5016
- package/lib/instructions-dynamic.js +415 -415
- package/lib/instructions.js +288 -288
- package/lib/open-folder.js +56 -56
- package/lib/openssh.js +881 -881
- package/lib/paths.js +292 -292
- package/lib/pool.js +970 -970
- package/lib/registry.js +296 -296
- package/lib/remote-fs.js +173 -173
- package/lib/remote-sandbox.js +183 -183
- package/lib/remote-shell-child.cjs +400 -400
- package/lib/remote-shell.js +697 -697
- package/lib/routes-fs.js +245 -245
- package/lib/routes-term.js +169 -169
- package/lib/routes-update.js +143 -143
- package/lib/search.js +235 -235
- package/lib/sftp-surface.js +119 -119
- package/lib/sshconfig.js +779 -779
- package/lib/sync.js +350 -350
- package/lib/tasks.js +95 -95
- package/lib/telemetry.js +247 -247
- package/lib/terminal.js +205 -205
- package/lib/tui/flow.js +130 -130
- package/lib/tui/format.js +380 -380
- package/lib/tui/i18n.js +350 -350
- package/lib/tui/index.js +531 -531
- package/lib/tui/provider.js +344 -344
- package/lib/tui/scene.js +986 -986
- package/lib/update.js +472 -472
- package/lib/web-attach.js +850 -850
- package/lib/workspace-cleanup.js +337 -337
- package/package.json +100 -100
package/lib/tui/index.js
CHANGED
|
@@ -1,531 +1,531 @@
|
|
|
1
|
-
// dsh-remote TUI 接入层入口:命令 / 全屏场景 / 工作区 provider / 状态行。
|
|
2
|
-
//
|
|
3
|
-
// 设计要点(见 docs/tui.md §4 与 .cache/recon/tui-seams.md):
|
|
4
|
-
// · 所有 TUI 服务用 `ctx.get(name, false)` **软探测**;Web profile / headless
|
|
5
|
-
// profile 里这些服务永远不存在,插件必须静默降级、不注册任何东西。
|
|
6
|
-
// · cordis 各行并发激活,`ctx.get` 在 apply 执行时可能还没就位;而 `ctx.inject`
|
|
7
|
-
// 会让整段 fiber 永久 pending。因此统一用 `whenService()`:服务已在则立即
|
|
8
|
-
// 执行,否则监听 `internal/service` 事件,到位后一次性执行。
|
|
9
|
-
// · `installTui` 同步返回、不 await、绝不抛错:内部 try/catch + logger.warn。
|
|
10
|
-
// · 每个注册返回的 disposer 都用 `ctx.effect(() => () => dispose())` 绑定生命周期。
|
|
11
|
-
|
|
12
|
-
import os from 'node:os'
|
|
13
|
-
import path from 'node:path'
|
|
14
|
-
import { resolveMirror } from '../binding.js'
|
|
15
|
-
import { createI18n } from './i18n.js'
|
|
16
|
-
import { clipCells } from './format.js'
|
|
17
|
-
import { createWorkspaceProvider, matchMachineForMirror } from './provider.js'
|
|
18
|
-
import { createSceneComponent } from './scene.js'
|
|
19
|
-
import { runDialogFlow } from './flow.js'
|
|
20
|
-
|
|
21
|
-
/** 场景 id(kebab-case,全局唯一)。 */
|
|
22
|
-
export const SCENE_ID = 'dsh-remote'
|
|
23
|
-
/** slash 命令名(dsh-commands 要求 /^[a-z][a-z0-9_-]*$/)。 */
|
|
24
|
-
export const COMMAND_NAME = 'dsh-remote'
|
|
25
|
-
/** 状态行字段 key。 */
|
|
26
|
-
const STATUS_KEY = 'dsh-remote'
|
|
27
|
-
/** 状态行字段的固定外观(docs/tui.md §4.4)。 */
|
|
28
|
-
const STATUS_OPTIONS = { slot: 'right-head', tone: 'accent', maxCells: 22 }
|
|
29
|
-
|
|
30
|
-
/** `ctx.get` 的软封装:ctx 缺失、服务缺失、代理抛错一律当“不存在”。 */
|
|
31
|
-
function getService(ctx, name) {
|
|
32
|
-
try {
|
|
33
|
-
if (!ctx || typeof ctx.get !== 'function') return undefined
|
|
34
|
-
const service = ctx.get(name, false)
|
|
35
|
-
return service === null ? undefined : service
|
|
36
|
-
} catch {
|
|
37
|
-
return undefined
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** logger.warn 的软封装(logging 失败绝不影响注册流程)。 */
|
|
42
|
-
function warn(ctx, message, error) {
|
|
43
|
-
try {
|
|
44
|
-
const logger = getService(ctx, 'logger')
|
|
45
|
-
if (!logger || typeof logger.warn !== 'function') return
|
|
46
|
-
const detail = error && (error.message || error)
|
|
47
|
-
logger.warn(`[dsh-remote] tui: ${message}${detail ? ': ' + detail : ''}`)
|
|
48
|
-
} catch { /* logging is best-effort */ }
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** 把 disposer 绑到当前 context 的生命周期上(ctx.effect 缺失时静默跳过)。 */
|
|
52
|
-
function bindEffect(ctx, dispose) {
|
|
53
|
-
if (typeof dispose !== 'function') return
|
|
54
|
-
try {
|
|
55
|
-
if (!ctx || typeof ctx.effect !== 'function') return
|
|
56
|
-
ctx.effect(() => () => {
|
|
57
|
-
try { dispose() } catch { /* teardown is best-effort */ }
|
|
58
|
-
})
|
|
59
|
-
} catch (error) {
|
|
60
|
-
warn(ctx, 'effect binding failed', error)
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* 服务到位后再执行回调(只执行一次)。
|
|
66
|
-
*
|
|
67
|
-
* cordis 的 `internal/service` 事件在服务变化时同步发出(见
|
|
68
|
-
* @deepseek-ai/cordis lib/index.js 的 notify())。若服务在 apply 时已经就位,
|
|
69
|
-
* 直接同步执行;否则等事件。回调异常被吞掉并 warn —— 一个 TUI 接缝注册失败
|
|
70
|
-
* 不能让插件(以及整个宿主)崩掉。
|
|
71
|
-
*
|
|
72
|
-
* @param {object} ctx - cordis context。
|
|
73
|
-
* @param {string} name - 服务名(`tuiScenes` / `commands` / …)。
|
|
74
|
-
* @param {(service: object) => void} callback - 服务到位时执行一次。
|
|
75
|
-
*/
|
|
76
|
-
export function whenService(ctx, name, callback) {
|
|
77
|
-
const existing = getService(ctx, name)
|
|
78
|
-
if (existing !== undefined) {
|
|
79
|
-
try { callback(existing) } catch (error) { warn(ctx, `${name} 初始化失败`, error) }
|
|
80
|
-
return
|
|
81
|
-
}
|
|
82
|
-
if (!ctx || typeof ctx.on !== 'function') return
|
|
83
|
-
let off
|
|
84
|
-
const listener = (serviceName, value) => {
|
|
85
|
-
if (serviceName !== name) return
|
|
86
|
-
// 事件里拿到的是**裸** service 实例;经 ctx.get 再取一次才能得到 cordis 的
|
|
87
|
-
// traceable 代理(把 this.ctx 指向本插件 activation)。TUI 的
|
|
88
|
-
// tuiWorkspaces.register / tuiScenes.register 会校验调用方身份,直接用裸
|
|
89
|
-
// 实例会把归属记到服务自己的 fiber 上,所以优先用代理。
|
|
90
|
-
const traced = getService(ctx, name)
|
|
91
|
-
if (traced === undefined && !value) return
|
|
92
|
-
try { if (typeof off === 'function') off() } catch { /* already removed */ }
|
|
93
|
-
off = undefined
|
|
94
|
-
const service = traced === undefined ? value : traced
|
|
95
|
-
if (!service) return
|
|
96
|
-
try { callback(service) } catch (error) { warn(ctx, `${name} 初始化失败`, error) }
|
|
97
|
-
}
|
|
98
|
-
try {
|
|
99
|
-
off = ctx.on('internal/service', listener)
|
|
100
|
-
} catch (error) {
|
|
101
|
-
warn(ctx, `无法监听 ${name} 服务`, error)
|
|
102
|
-
return
|
|
103
|
-
}
|
|
104
|
-
bindEffect(ctx, () => { if (typeof off === 'function') off() })
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* 安装 TUI 适配层。
|
|
109
|
-
*
|
|
110
|
-
* @param {object} ctx - 插件自己的 cordis context。
|
|
111
|
-
* @param {object} api - 宿主进程内 API(`ctx.dshRemote`,apiVersion 1)。
|
|
112
|
-
* @param {object} [config] - 行 config(tui / tuiProviderListRecent /
|
|
113
|
-
* tuiProviderRecentLimit / tuiAutoSwitchWorkspace / tuiLang)。
|
|
114
|
-
* @returns {void} 同步返回,永不 reject / throw。
|
|
115
|
-
*/
|
|
116
|
-
export function installTui(ctx, api, config) {
|
|
117
|
-
try {
|
|
118
|
-
if (config && config.tui === false) return
|
|
119
|
-
if (!api || api.apiVersion !== 1) return
|
|
120
|
-
if (!ctx || typeof ctx.get !== 'function') return
|
|
121
|
-
|
|
122
|
-
const i18n = createI18n(config && (config.tuiLang || config.lang))
|
|
123
|
-
const sceneComponent = createSceneComponent({
|
|
124
|
-
api,
|
|
125
|
-
config: config || {},
|
|
126
|
-
i18n,
|
|
127
|
-
notify: (text, options) => {
|
|
128
|
-
const toast = getService(ctx, 'tuiToast')
|
|
129
|
-
if (toast && typeof toast.show === 'function') {
|
|
130
|
-
try { toast.show(text, options); return } catch { /* fall through */ }
|
|
131
|
-
}
|
|
132
|
-
warn(ctx, String(text))
|
|
133
|
-
},
|
|
134
|
-
})
|
|
135
|
-
|
|
136
|
-
// ── 内部可变状态(全是本插件生命周期内的单例) ────────────────────────
|
|
137
|
-
let provider = null
|
|
138
|
-
let workspacesSeen = false
|
|
139
|
-
let commandsSeen = null
|
|
140
|
-
let commandWanted = false
|
|
141
|
-
let commandRegistered = false
|
|
142
|
-
let tuiActive = false
|
|
143
|
-
let statusService = null
|
|
144
|
-
let statusFieldDispose = null
|
|
145
|
-
let statusRefreshToken = 0
|
|
146
|
-
/** 最近进入 store 的会话 / 最近收到用户输入的会话(见 activeSessionCwd)。 */
|
|
147
|
-
let activeSessionId = null
|
|
148
|
-
let lastUserSessionId = null
|
|
149
|
-
/** 宿主每次会话切换都会用新 cwd 调 provider.describe():那是“当前会话”的
|
|
150
|
-
* 可靠提示(sessions 事件覆盖不到 live 会话切换)。见 noteHostSessionCwd。 */
|
|
151
|
-
let hostSessionCwd = ''
|
|
152
|
-
/** 插件卸载后,仍在 await 的刷新不得再写底栏。 */
|
|
153
|
-
let disposed = false
|
|
154
|
-
/** 上一次写入的 text/detail:相同值不重复 setField(宿主会无条件 emit 并记账)。 */
|
|
155
|
-
let lastStatusWrite = null
|
|
156
|
-
bindEffect(ctx, () => { disposed = true })
|
|
157
|
-
|
|
158
|
-
const ensureProvider = () => {
|
|
159
|
-
if (!provider) {
|
|
160
|
-
provider = createWorkspaceProvider({
|
|
161
|
-
api,
|
|
162
|
-
config: config || {},
|
|
163
|
-
logger: getService(ctx, 'logger'),
|
|
164
|
-
onDescribe: noteHostSessionCwd,
|
|
165
|
-
})
|
|
166
|
-
}
|
|
167
|
-
return provider
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/** 注册 `/dsh-remote`(只会注册一次;失败时允许后续重试)。 */
|
|
171
|
-
const registerCommand = (commands) => {
|
|
172
|
-
if (commandRegistered || !commands || typeof commands.register !== 'function') return
|
|
173
|
-
commandRegistered = true
|
|
174
|
-
let dispose
|
|
175
|
-
try {
|
|
176
|
-
dispose = commands.register({
|
|
177
|
-
name: COMMAND_NAME,
|
|
178
|
-
description: i18n.t('cmd.description'),
|
|
179
|
-
handler: async (invocation) => {
|
|
180
|
-
try {
|
|
181
|
-
const scenes = getService(ctx, 'tuiScenes')
|
|
182
|
-
if (scenes && typeof scenes.open === 'function') {
|
|
183
|
-
let opened = false
|
|
184
|
-
try { opened = scenes.open(SCENE_ID) === true } catch (error) { warn(ctx, '场景打开失败', error) }
|
|
185
|
-
if (opened) return { kind: 'success' }
|
|
186
|
-
}
|
|
187
|
-
const dialogs = getService(ctx, 'tuiDialogs')
|
|
188
|
-
if (dialogs) {
|
|
189
|
-
const result = await runDialogFlow({
|
|
190
|
-
api,
|
|
191
|
-
dialogs,
|
|
192
|
-
i18n,
|
|
193
|
-
channel: invocation && invocation.channel,
|
|
194
|
-
})
|
|
195
|
-
// `runDialogFlow` returns undefined ONLY when the dialog seam
|
|
196
|
-
// lacks select/input/confirm (cancellation returns a success
|
|
197
|
-
// result) — reporting that as success would look like a no-op.
|
|
198
|
-
return result || { kind: 'error', text: i18n.t('cmd.unavailable') }
|
|
199
|
-
}
|
|
200
|
-
return { kind: 'error', text: i18n.t('cmd.unavailable') }
|
|
201
|
-
} catch (error) {
|
|
202
|
-
return { kind: 'error', text: i18n.t('cmd.failed', { err: String((error && error.message) || error) }) }
|
|
203
|
-
}
|
|
204
|
-
},
|
|
205
|
-
})
|
|
206
|
-
} catch (error) {
|
|
207
|
-
commandRegistered = false
|
|
208
|
-
warn(ctx, '命令注册失败', error)
|
|
209
|
-
return
|
|
210
|
-
}
|
|
211
|
-
bindEffect(ctx, dispose)
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/** 有任意 TUI UI 接缝时才开始“激活”(命令注册 / api 订阅 / 状态行)。 */
|
|
215
|
-
const ensureCommand = () => {
|
|
216
|
-
commandWanted = true
|
|
217
|
-
if (commandsSeen) registerCommand(commandsSeen)
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
/** 状态行字段:只在服务形状符合契约时写入,否则整段跳过(不猜 API)。
|
|
221
|
-
* `detail` 是鼠标悬停时补在空闲提示行上的说明(宿主按 `inactiveShimmer`
|
|
222
|
-
* 渲染,单行、上限 160 cells,与其它底栏字段的 hover 效果一致)。
|
|
223
|
-
* 宿主对 detail 只按 160 cells 截断、不做“适配当前宽度”的 truncate,超宽会
|
|
224
|
-
* wrap 进看不见的第二行;所以按终端宽度自己裁:状态行内宽是 columns-2
|
|
225
|
-
* (宿主 paddingX=1),再给右侧 MiniWake/activity 预留 16 格,下限 8。 */
|
|
226
|
-
const applyStatusField = (text, detail) => {
|
|
227
|
-
if (disposed) return
|
|
228
|
-
if (!statusService || typeof statusService.setField !== 'function') return
|
|
229
|
-
try {
|
|
230
|
-
const columns = Number(process.stdout && process.stdout.columns) || 80
|
|
231
|
-
const clipped = detail ? clipCells(detail, Math.max(8, columns - 18)) : ''
|
|
232
|
-
// 相同值不重复写:宿主 store 会对同 text 的 setField 也 emit,并往
|
|
233
|
-
// append-only 的 effect-ledger 记一笔。从未写过时也不要发“空清除”。
|
|
234
|
-
const previous = lastStatusWrite
|
|
235
|
-
if (previous && previous.text === text && previous.detail === clipped) return
|
|
236
|
-
if (!previous && text === undefined && !clipped) return
|
|
237
|
-
lastStatusWrite = { text, detail: clipped }
|
|
238
|
-
const options = clipped ? { ...STATUS_OPTIONS, detail: clipped } : STATUS_OPTIONS
|
|
239
|
-
// 第 4 个参数是插件自己的 ctx(只用于 effect ledger 归属,可省略)。
|
|
240
|
-
const next = statusService.setField(STATUS_KEY, text, options, ctx)
|
|
241
|
-
if (statusFieldDispose) {
|
|
242
|
-
const previous = statusFieldDispose
|
|
243
|
-
statusFieldDispose = null
|
|
244
|
-
try { previous() } catch { /* already cleared */ }
|
|
245
|
-
}
|
|
246
|
-
if (typeof next === 'function') statusFieldDispose = next
|
|
247
|
-
} catch (error) {
|
|
248
|
-
warn(ctx, '状态行更新失败', error)
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/** 子代理会话也会进 store、也会发 `user/message`,但它不是用户在看的会话。 */
|
|
253
|
-
const isSubagentSession = (session) => {
|
|
254
|
-
const origin = session && session.header && session.header.origin
|
|
255
|
-
return origin === 'subagent'
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
/** 本进程的 live 会话(不含子代理)。`null` = 宿主没有 sessions 服务(旧组合),
|
|
259
|
-
* `[]` = 服务在但读不到/读抛错 → 调用方按“没有远程会话”处理。 */
|
|
260
|
-
const liveSessions = () => {
|
|
261
|
-
const sessions = getService(ctx, 'sessions')
|
|
262
|
-
if (!sessions || typeof sessions.list !== 'function') return null
|
|
263
|
-
try {
|
|
264
|
-
const list = sessions.list()
|
|
265
|
-
if (!Array.isArray(list)) return []
|
|
266
|
-
return list.filter((one) => one && one.header && one.header.cwd && !isSubagentSession(one))
|
|
267
|
-
} catch (error) {
|
|
268
|
-
warn(ctx, '会话列表读取失败', error)
|
|
269
|
-
return []
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/** 当前 TUI 会话的 cwd。
|
|
274
|
-
*
|
|
275
|
-
* TUI 进程里可以同时有多个 live session(挂载中的会话 + parked 后台会话),
|
|
276
|
-
* 而“切到已挂载会话”不会发 session/* 事件。插件拿不到宿主 channel,按可靠性
|
|
277
|
-
* 依次采信:① 宿主切换会话时传入 provider.describe() 的 cwd(只在这种情况下
|
|
278
|
-
* 才算数,并交叉校验它确实属于某个 live 会话);② 最近进入/用户说过话的
|
|
279
|
-
* 会话;③ store 里最后进入的会话。 */
|
|
280
|
-
const activeSessionCwd = () => {
|
|
281
|
-
const list = liveSessions()
|
|
282
|
-
if (list === null) return { supported: false, cwd: '' }
|
|
283
|
-
const cwds = new Set(list.map((one) => String(one.header.cwd)))
|
|
284
|
-
if (hostSessionCwd && cwds.has(hostSessionCwd)) return { supported: true, cwd: hostSessionCwd }
|
|
285
|
-
const cwdOf = (id) => {
|
|
286
|
-
if (!id) return ''
|
|
287
|
-
const one = list.find((candidate) => String(candidate.id) === String(id))
|
|
288
|
-
return one ? String(one.header.cwd) : ''
|
|
289
|
-
}
|
|
290
|
-
let cwd = cwdOf(activeSessionId) || cwdOf(lastUserSessionId)
|
|
291
|
-
if (!cwd && list.length > 0) cwd = String(list[list.length - 1].header.cwd)
|
|
292
|
-
return { supported: true, cwd }
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
/** 宿主在会话切换/工作区描述时把当前 cwd 交给 provider.describe();记下来,
|
|
296
|
-
* 由 activeSessionCwd 交叉校验后使用。 */
|
|
297
|
-
const noteHostSessionCwd = (cwd) => {
|
|
298
|
-
const value = String(cwd || '')
|
|
299
|
-
if (!value || value === hostSessionCwd) return
|
|
300
|
-
hostSessionCwd = value
|
|
301
|
-
void refreshStatusField()
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
/** `$DSH_HOME`:宿主的 `dshHomePath` 服务是**函数**(`(...segments) => path`),
|
|
305
|
-
* 老版本/测试里也可能是字符串或 `{path}`;都没有时退回环境变量/`~/.dsh`。 */
|
|
306
|
-
const dshHomePath = () => {
|
|
307
|
-
const service = getService(ctx, 'dshHomePath')
|
|
308
|
-
if (typeof service === 'function') {
|
|
309
|
-
try {
|
|
310
|
-
const home = service()
|
|
311
|
-
if (typeof home === 'string' && home) return home
|
|
312
|
-
} catch { /* fall through to the string forms */ }
|
|
313
|
-
}
|
|
314
|
-
if (typeof service === 'string' && service) return service
|
|
315
|
-
if (service && typeof service.path === 'string' && service.path) return service.path
|
|
316
|
-
return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/** 会话在远程镜像里 → `{label, detail}`;本地会话 / 无会话 → ''。
|
|
320
|
-
* `detail` 供底栏 hover 使用:完整机器名 + `user@host:port` + 远端路径。
|
|
321
|
-
* `null` 表示宿主没有 sessions 服务(旧组合),调用方退回旧行为。 */
|
|
322
|
-
const remoteSessionLabel = (machines) => {
|
|
323
|
-
const { supported, cwd } = activeSessionCwd()
|
|
324
|
-
if (!supported) return null
|
|
325
|
-
if (!cwd) return ''
|
|
326
|
-
let resolved
|
|
327
|
-
try {
|
|
328
|
-
resolved = resolveMirror(cwd, path.join(dshHomePath(), 'remote-workspaces'))
|
|
329
|
-
} catch {
|
|
330
|
-
return ''
|
|
331
|
-
}
|
|
332
|
-
const machine = resolved && resolved.machine
|
|
333
|
-
if (!machine || !resolved.remotePath) return ''
|
|
334
|
-
// 与 provider 的机器匹配共用一套规则:ssh-config 别名机按 alias 命中,
|
|
335
|
-
// 字面机按 host/port/username 命中。
|
|
336
|
-
const match = matchMachineForMirror(machines, machine)
|
|
337
|
-
const label = String(((match && (match.name || match.host)) || machine.alias || machine.host || '')).trim()
|
|
338
|
-
const parts = []
|
|
339
|
-
if (label) parts.push(i18n.t('status.detailMachine', { name: label }))
|
|
340
|
-
parts.push(i18n.t('status.detailTarget', {
|
|
341
|
-
user: machine.username || '',
|
|
342
|
-
host: machine.host || '',
|
|
343
|
-
port: Number(machine.port) || 22,
|
|
344
|
-
}))
|
|
345
|
-
parts.push(i18n.t('status.detailRemote', { path: resolved.remotePath }))
|
|
346
|
-
return { label, detail: parts.filter(Boolean).join(' · ') }
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
/** 读当前机器名并写状态行;旧结果(token 过期)直接丢弃。
|
|
350
|
-
*
|
|
351
|
-
* 只在**当前会话的 cwd 落在远程镜像里**时显示(用户报告的“本地目录也显示
|
|
352
|
-
* 服务器名”就是待机机器被无条件写进底栏)。没有 sessions 服务的旧组合
|
|
353
|
-
* 退回旧行为,不猜。 */
|
|
354
|
-
const refreshStatusField = async () => {
|
|
355
|
-
if (!statusService || typeof statusService.setField !== 'function') return
|
|
356
|
-
if (typeof api.listMachines !== 'function') return
|
|
357
|
-
const token = ++statusRefreshToken
|
|
358
|
-
let machines = []
|
|
359
|
-
let currentId = null
|
|
360
|
-
try {
|
|
361
|
-
const result = await api.listMachines()
|
|
362
|
-
machines = Array.isArray(result && result.machines) ? result.machines : []
|
|
363
|
-
currentId = result && result.currentId !== undefined ? result.currentId : null
|
|
364
|
-
} catch (error) {
|
|
365
|
-
warn(ctx, '状态行读取机器列表失败', error)
|
|
366
|
-
// 读不到机器列表时不要留下旧机器名(那正是“待机机器占底栏”的观感来源)。
|
|
367
|
-
applyStatusField(undefined)
|
|
368
|
-
return
|
|
369
|
-
}
|
|
370
|
-
if (token !== statusRefreshToken || disposed) return
|
|
371
|
-
const current = machines.find((machine) => machine && machine.id === currentId)
|
|
372
|
-
const remote = remoteSessionLabel(machines)
|
|
373
|
-
const label = remote === null
|
|
374
|
-
? (current ? String(current.name || current.host || '').trim() : '')
|
|
375
|
-
: remote.label
|
|
376
|
-
applyStatusField(label || undefined, remote && remote.detail)
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
/** 会话事件合并刷新:会话进入/结束、用户在哪说话都会改变“当前会话”。
|
|
380
|
-
* 500ms 合并避免连续事件重复跑 listMachines。 */
|
|
381
|
-
const SESSION_REFRESH_MS = 500
|
|
382
|
-
let sessionRefreshTimer = null
|
|
383
|
-
const scheduleStatusRefresh = () => {
|
|
384
|
-
if (sessionRefreshTimer) return
|
|
385
|
-
sessionRefreshTimer = setTimeout(() => {
|
|
386
|
-
sessionRefreshTimer = null
|
|
387
|
-
void refreshStatusField()
|
|
388
|
-
}, SESSION_REFRESH_MS)
|
|
389
|
-
if (typeof sessionRefreshTimer.unref === 'function') sessionRefreshTimer.unref()
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
/** 任意 TUI 接缝出现后:订阅宿主变更(刷新 provider 缓存 + 状态行)。 */
|
|
393
|
-
const markTuiActive = () => {
|
|
394
|
-
if (tuiActive) return
|
|
395
|
-
tuiActive = true
|
|
396
|
-
if (typeof api.subscribe === 'function') {
|
|
397
|
-
let dispose
|
|
398
|
-
try {
|
|
399
|
-
dispose = api.subscribe(() => {
|
|
400
|
-
if (workspacesSeen && provider) {
|
|
401
|
-
try { void provider.refresh() } catch (error) { warn(ctx, 'provider 刷新失败', error) }
|
|
402
|
-
}
|
|
403
|
-
void refreshStatusField()
|
|
404
|
-
})
|
|
405
|
-
} catch (error) {
|
|
406
|
-
warn(ctx, 'api.subscribe 失败', error)
|
|
407
|
-
}
|
|
408
|
-
bindEffect(ctx, dispose)
|
|
409
|
-
}
|
|
410
|
-
// 会话进入/结束、用户发消息都会改变“当前会话”,据此刷新底栏字段。
|
|
411
|
-
if (typeof ctx.on === 'function') {
|
|
412
|
-
const disposers = []
|
|
413
|
-
const subscribe = (event, listener) => {
|
|
414
|
-
try {
|
|
415
|
-
const dispose = ctx.on(event, listener)
|
|
416
|
-
if (typeof dispose === 'function') disposers.push(dispose)
|
|
417
|
-
} catch (error) {
|
|
418
|
-
warn(ctx, `会话事件订阅失败(${event})`, error)
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
subscribe('session/created', (session) => {
|
|
422
|
-
if (!session || session.id == null || isSubagentSession(session)) return
|
|
423
|
-
activeSessionId = String(session.id)
|
|
424
|
-
scheduleStatusRefresh()
|
|
425
|
-
})
|
|
426
|
-
subscribe('session/disposed', (session) => {
|
|
427
|
-
if (!session || session.id == null || isSubagentSession(session)) return
|
|
428
|
-
const id = String(session.id)
|
|
429
|
-
if (id === activeSessionId) {
|
|
430
|
-
activeSessionId = lastUserSessionId && lastUserSessionId !== id ? lastUserSessionId : null
|
|
431
|
-
}
|
|
432
|
-
if (id === lastUserSessionId) lastUserSessionId = null
|
|
433
|
-
if (hostSessionCwd && !activeSessionId) hostSessionCwd = ''
|
|
434
|
-
scheduleStatusRefresh()
|
|
435
|
-
})
|
|
436
|
-
subscribe('session/event', (session, event) => {
|
|
437
|
-
if (!event || event.type !== 'user/message' || isSubagentSession(session)) return
|
|
438
|
-
if (!session || session.id == null) return
|
|
439
|
-
lastUserSessionId = String(session.id)
|
|
440
|
-
activeSessionId = String(session.id)
|
|
441
|
-
scheduleStatusRefresh()
|
|
442
|
-
})
|
|
443
|
-
bindEffect(ctx, () => {
|
|
444
|
-
if (sessionRefreshTimer) {
|
|
445
|
-
clearTimeout(sessionRefreshTimer)
|
|
446
|
-
sessionRefreshTimer = null
|
|
447
|
-
}
|
|
448
|
-
for (const dispose of disposers) {
|
|
449
|
-
try { dispose() } catch { /* teardown is best-effort */ }
|
|
450
|
-
}
|
|
451
|
-
})
|
|
452
|
-
}
|
|
453
|
-
// 终端变窄/变宽后详情要重新裁:否则旧字符串会 wrap 进看不见的第二行。
|
|
454
|
-
if (process.stdout && typeof process.stdout.on === 'function') {
|
|
455
|
-
const onResize = () => scheduleStatusRefresh()
|
|
456
|
-
try {
|
|
457
|
-
process.stdout.on('resize', onResize)
|
|
458
|
-
bindEffect(ctx, () => process.stdout.removeListener('resize', onResize))
|
|
459
|
-
} catch (error) {
|
|
460
|
-
warn(ctx, '终端 resize 订阅失败', error)
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
void refreshStatusField()
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
// ── 服务到位后注册(顺序无关;命令只在 TUI 接缝出现后注册) ───────────
|
|
467
|
-
whenService(ctx, 'commands', (commands) => {
|
|
468
|
-
commandsSeen = commands
|
|
469
|
-
if (commandWanted) registerCommand(commands)
|
|
470
|
-
})
|
|
471
|
-
|
|
472
|
-
whenService(ctx, 'tuiScenes', (scenes) => {
|
|
473
|
-
if (!scenes || typeof scenes.register !== 'function') return
|
|
474
|
-
ensureCommand()
|
|
475
|
-
markTuiActive()
|
|
476
|
-
let dispose
|
|
477
|
-
try {
|
|
478
|
-
dispose = scenes.register({ id: SCENE_ID, title: 'Remote', component: sceneComponent }, ctx)
|
|
479
|
-
} catch (error) {
|
|
480
|
-
warn(ctx, '场景注册失败', error)
|
|
481
|
-
return
|
|
482
|
-
}
|
|
483
|
-
bindEffect(ctx, dispose)
|
|
484
|
-
})
|
|
485
|
-
|
|
486
|
-
whenService(ctx, 'tuiDialogs', (dialogs) => {
|
|
487
|
-
if (!dialogs) return
|
|
488
|
-
ensureCommand()
|
|
489
|
-
markTuiActive()
|
|
490
|
-
})
|
|
491
|
-
|
|
492
|
-
whenService(ctx, 'tuiWorkspaces', (workspaces) => {
|
|
493
|
-
if (!workspaces || typeof workspaces.register !== 'function') return
|
|
494
|
-
workspacesSeen = true
|
|
495
|
-
markTuiActive()
|
|
496
|
-
const instance = ensureProvider()
|
|
497
|
-
let dispose
|
|
498
|
-
try {
|
|
499
|
-
// register 在无 live activation 时会**同步抛错**,必须包 try/catch。
|
|
500
|
-
dispose = workspaces.register(instance)
|
|
501
|
-
} catch (error) {
|
|
502
|
-
warn(ctx, '工作区 provider 注册失败', error)
|
|
503
|
-
return
|
|
504
|
-
}
|
|
505
|
-
bindEffect(ctx, dispose)
|
|
506
|
-
// 后台预热,绝不阻塞 apply / 首个 UI 帧。
|
|
507
|
-
try {
|
|
508
|
-
queueMicrotask(() => { void instance.refresh() })
|
|
509
|
-
} catch (error) {
|
|
510
|
-
warn(ctx, 'provider 预热失败', error)
|
|
511
|
-
}
|
|
512
|
-
})
|
|
513
|
-
|
|
514
|
-
whenService(ctx, 'tuiStatus', (status) => {
|
|
515
|
-
if (!status || typeof status.setField !== 'function') return
|
|
516
|
-
statusService = status
|
|
517
|
-
markTuiActive()
|
|
518
|
-
bindEffect(ctx, () => {
|
|
519
|
-
if (!statusFieldDispose) return
|
|
520
|
-
const dispose = statusFieldDispose
|
|
521
|
-
statusFieldDispose = null
|
|
522
|
-
dispose()
|
|
523
|
-
})
|
|
524
|
-
void refreshStatusField()
|
|
525
|
-
})
|
|
526
|
-
} catch (error) {
|
|
527
|
-
warn(ctx, 'installTui 初始化失败', error)
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
export default installTui
|
|
1
|
+
// dsh-remote TUI 接入层入口:命令 / 全屏场景 / 工作区 provider / 状态行。
|
|
2
|
+
//
|
|
3
|
+
// 设计要点(见 docs/tui.md §4 与 .cache/recon/tui-seams.md):
|
|
4
|
+
// · 所有 TUI 服务用 `ctx.get(name, false)` **软探测**;Web profile / headless
|
|
5
|
+
// profile 里这些服务永远不存在,插件必须静默降级、不注册任何东西。
|
|
6
|
+
// · cordis 各行并发激活,`ctx.get` 在 apply 执行时可能还没就位;而 `ctx.inject`
|
|
7
|
+
// 会让整段 fiber 永久 pending。因此统一用 `whenService()`:服务已在则立即
|
|
8
|
+
// 执行,否则监听 `internal/service` 事件,到位后一次性执行。
|
|
9
|
+
// · `installTui` 同步返回、不 await、绝不抛错:内部 try/catch + logger.warn。
|
|
10
|
+
// · 每个注册返回的 disposer 都用 `ctx.effect(() => () => dispose())` 绑定生命周期。
|
|
11
|
+
|
|
12
|
+
import os from 'node:os'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
import { resolveMirror } from '../binding.js'
|
|
15
|
+
import { createI18n } from './i18n.js'
|
|
16
|
+
import { clipCells } from './format.js'
|
|
17
|
+
import { createWorkspaceProvider, matchMachineForMirror } from './provider.js'
|
|
18
|
+
import { createSceneComponent } from './scene.js'
|
|
19
|
+
import { runDialogFlow } from './flow.js'
|
|
20
|
+
|
|
21
|
+
/** 场景 id(kebab-case,全局唯一)。 */
|
|
22
|
+
export const SCENE_ID = 'dsh-remote'
|
|
23
|
+
/** slash 命令名(dsh-commands 要求 /^[a-z][a-z0-9_-]*$/)。 */
|
|
24
|
+
export const COMMAND_NAME = 'dsh-remote'
|
|
25
|
+
/** 状态行字段 key。 */
|
|
26
|
+
const STATUS_KEY = 'dsh-remote'
|
|
27
|
+
/** 状态行字段的固定外观(docs/tui.md §4.4)。 */
|
|
28
|
+
const STATUS_OPTIONS = { slot: 'right-head', tone: 'accent', maxCells: 22 }
|
|
29
|
+
|
|
30
|
+
/** `ctx.get` 的软封装:ctx 缺失、服务缺失、代理抛错一律当“不存在”。 */
|
|
31
|
+
function getService(ctx, name) {
|
|
32
|
+
try {
|
|
33
|
+
if (!ctx || typeof ctx.get !== 'function') return undefined
|
|
34
|
+
const service = ctx.get(name, false)
|
|
35
|
+
return service === null ? undefined : service
|
|
36
|
+
} catch {
|
|
37
|
+
return undefined
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** logger.warn 的软封装(logging 失败绝不影响注册流程)。 */
|
|
42
|
+
function warn(ctx, message, error) {
|
|
43
|
+
try {
|
|
44
|
+
const logger = getService(ctx, 'logger')
|
|
45
|
+
if (!logger || typeof logger.warn !== 'function') return
|
|
46
|
+
const detail = error && (error.message || error)
|
|
47
|
+
logger.warn(`[dsh-remote] tui: ${message}${detail ? ': ' + detail : ''}`)
|
|
48
|
+
} catch { /* logging is best-effort */ }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 把 disposer 绑到当前 context 的生命周期上(ctx.effect 缺失时静默跳过)。 */
|
|
52
|
+
function bindEffect(ctx, dispose) {
|
|
53
|
+
if (typeof dispose !== 'function') return
|
|
54
|
+
try {
|
|
55
|
+
if (!ctx || typeof ctx.effect !== 'function') return
|
|
56
|
+
ctx.effect(() => () => {
|
|
57
|
+
try { dispose() } catch { /* teardown is best-effort */ }
|
|
58
|
+
})
|
|
59
|
+
} catch (error) {
|
|
60
|
+
warn(ctx, 'effect binding failed', error)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 服务到位后再执行回调(只执行一次)。
|
|
66
|
+
*
|
|
67
|
+
* cordis 的 `internal/service` 事件在服务变化时同步发出(见
|
|
68
|
+
* @deepseek-ai/cordis lib/index.js 的 notify())。若服务在 apply 时已经就位,
|
|
69
|
+
* 直接同步执行;否则等事件。回调异常被吞掉并 warn —— 一个 TUI 接缝注册失败
|
|
70
|
+
* 不能让插件(以及整个宿主)崩掉。
|
|
71
|
+
*
|
|
72
|
+
* @param {object} ctx - cordis context。
|
|
73
|
+
* @param {string} name - 服务名(`tuiScenes` / `commands` / …)。
|
|
74
|
+
* @param {(service: object) => void} callback - 服务到位时执行一次。
|
|
75
|
+
*/
|
|
76
|
+
export function whenService(ctx, name, callback) {
|
|
77
|
+
const existing = getService(ctx, name)
|
|
78
|
+
if (existing !== undefined) {
|
|
79
|
+
try { callback(existing) } catch (error) { warn(ctx, `${name} 初始化失败`, error) }
|
|
80
|
+
return
|
|
81
|
+
}
|
|
82
|
+
if (!ctx || typeof ctx.on !== 'function') return
|
|
83
|
+
let off
|
|
84
|
+
const listener = (serviceName, value) => {
|
|
85
|
+
if (serviceName !== name) return
|
|
86
|
+
// 事件里拿到的是**裸** service 实例;经 ctx.get 再取一次才能得到 cordis 的
|
|
87
|
+
// traceable 代理(把 this.ctx 指向本插件 activation)。TUI 的
|
|
88
|
+
// tuiWorkspaces.register / tuiScenes.register 会校验调用方身份,直接用裸
|
|
89
|
+
// 实例会把归属记到服务自己的 fiber 上,所以优先用代理。
|
|
90
|
+
const traced = getService(ctx, name)
|
|
91
|
+
if (traced === undefined && !value) return
|
|
92
|
+
try { if (typeof off === 'function') off() } catch { /* already removed */ }
|
|
93
|
+
off = undefined
|
|
94
|
+
const service = traced === undefined ? value : traced
|
|
95
|
+
if (!service) return
|
|
96
|
+
try { callback(service) } catch (error) { warn(ctx, `${name} 初始化失败`, error) }
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
off = ctx.on('internal/service', listener)
|
|
100
|
+
} catch (error) {
|
|
101
|
+
warn(ctx, `无法监听 ${name} 服务`, error)
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
bindEffect(ctx, () => { if (typeof off === 'function') off() })
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 安装 TUI 适配层。
|
|
109
|
+
*
|
|
110
|
+
* @param {object} ctx - 插件自己的 cordis context。
|
|
111
|
+
* @param {object} api - 宿主进程内 API(`ctx.dshRemote`,apiVersion 1)。
|
|
112
|
+
* @param {object} [config] - 行 config(tui / tuiProviderListRecent /
|
|
113
|
+
* tuiProviderRecentLimit / tuiAutoSwitchWorkspace / tuiLang)。
|
|
114
|
+
* @returns {void} 同步返回,永不 reject / throw。
|
|
115
|
+
*/
|
|
116
|
+
export function installTui(ctx, api, config) {
|
|
117
|
+
try {
|
|
118
|
+
if (config && config.tui === false) return
|
|
119
|
+
if (!api || api.apiVersion !== 1) return
|
|
120
|
+
if (!ctx || typeof ctx.get !== 'function') return
|
|
121
|
+
|
|
122
|
+
const i18n = createI18n(config && (config.tuiLang || config.lang))
|
|
123
|
+
const sceneComponent = createSceneComponent({
|
|
124
|
+
api,
|
|
125
|
+
config: config || {},
|
|
126
|
+
i18n,
|
|
127
|
+
notify: (text, options) => {
|
|
128
|
+
const toast = getService(ctx, 'tuiToast')
|
|
129
|
+
if (toast && typeof toast.show === 'function') {
|
|
130
|
+
try { toast.show(text, options); return } catch { /* fall through */ }
|
|
131
|
+
}
|
|
132
|
+
warn(ctx, String(text))
|
|
133
|
+
},
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
// ── 内部可变状态(全是本插件生命周期内的单例) ────────────────────────
|
|
137
|
+
let provider = null
|
|
138
|
+
let workspacesSeen = false
|
|
139
|
+
let commandsSeen = null
|
|
140
|
+
let commandWanted = false
|
|
141
|
+
let commandRegistered = false
|
|
142
|
+
let tuiActive = false
|
|
143
|
+
let statusService = null
|
|
144
|
+
let statusFieldDispose = null
|
|
145
|
+
let statusRefreshToken = 0
|
|
146
|
+
/** 最近进入 store 的会话 / 最近收到用户输入的会话(见 activeSessionCwd)。 */
|
|
147
|
+
let activeSessionId = null
|
|
148
|
+
let lastUserSessionId = null
|
|
149
|
+
/** 宿主每次会话切换都会用新 cwd 调 provider.describe():那是“当前会话”的
|
|
150
|
+
* 可靠提示(sessions 事件覆盖不到 live 会话切换)。见 noteHostSessionCwd。 */
|
|
151
|
+
let hostSessionCwd = ''
|
|
152
|
+
/** 插件卸载后,仍在 await 的刷新不得再写底栏。 */
|
|
153
|
+
let disposed = false
|
|
154
|
+
/** 上一次写入的 text/detail:相同值不重复 setField(宿主会无条件 emit 并记账)。 */
|
|
155
|
+
let lastStatusWrite = null
|
|
156
|
+
bindEffect(ctx, () => { disposed = true })
|
|
157
|
+
|
|
158
|
+
const ensureProvider = () => {
|
|
159
|
+
if (!provider) {
|
|
160
|
+
provider = createWorkspaceProvider({
|
|
161
|
+
api,
|
|
162
|
+
config: config || {},
|
|
163
|
+
logger: getService(ctx, 'logger'),
|
|
164
|
+
onDescribe: noteHostSessionCwd,
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
return provider
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 注册 `/dsh-remote`(只会注册一次;失败时允许后续重试)。 */
|
|
171
|
+
const registerCommand = (commands) => {
|
|
172
|
+
if (commandRegistered || !commands || typeof commands.register !== 'function') return
|
|
173
|
+
commandRegistered = true
|
|
174
|
+
let dispose
|
|
175
|
+
try {
|
|
176
|
+
dispose = commands.register({
|
|
177
|
+
name: COMMAND_NAME,
|
|
178
|
+
description: i18n.t('cmd.description'),
|
|
179
|
+
handler: async (invocation) => {
|
|
180
|
+
try {
|
|
181
|
+
const scenes = getService(ctx, 'tuiScenes')
|
|
182
|
+
if (scenes && typeof scenes.open === 'function') {
|
|
183
|
+
let opened = false
|
|
184
|
+
try { opened = scenes.open(SCENE_ID) === true } catch (error) { warn(ctx, '场景打开失败', error) }
|
|
185
|
+
if (opened) return { kind: 'success' }
|
|
186
|
+
}
|
|
187
|
+
const dialogs = getService(ctx, 'tuiDialogs')
|
|
188
|
+
if (dialogs) {
|
|
189
|
+
const result = await runDialogFlow({
|
|
190
|
+
api,
|
|
191
|
+
dialogs,
|
|
192
|
+
i18n,
|
|
193
|
+
channel: invocation && invocation.channel,
|
|
194
|
+
})
|
|
195
|
+
// `runDialogFlow` returns undefined ONLY when the dialog seam
|
|
196
|
+
// lacks select/input/confirm (cancellation returns a success
|
|
197
|
+
// result) — reporting that as success would look like a no-op.
|
|
198
|
+
return result || { kind: 'error', text: i18n.t('cmd.unavailable') }
|
|
199
|
+
}
|
|
200
|
+
return { kind: 'error', text: i18n.t('cmd.unavailable') }
|
|
201
|
+
} catch (error) {
|
|
202
|
+
return { kind: 'error', text: i18n.t('cmd.failed', { err: String((error && error.message) || error) }) }
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
})
|
|
206
|
+
} catch (error) {
|
|
207
|
+
commandRegistered = false
|
|
208
|
+
warn(ctx, '命令注册失败', error)
|
|
209
|
+
return
|
|
210
|
+
}
|
|
211
|
+
bindEffect(ctx, dispose)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** 有任意 TUI UI 接缝时才开始“激活”(命令注册 / api 订阅 / 状态行)。 */
|
|
215
|
+
const ensureCommand = () => {
|
|
216
|
+
commandWanted = true
|
|
217
|
+
if (commandsSeen) registerCommand(commandsSeen)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** 状态行字段:只在服务形状符合契约时写入,否则整段跳过(不猜 API)。
|
|
221
|
+
* `detail` 是鼠标悬停时补在空闲提示行上的说明(宿主按 `inactiveShimmer`
|
|
222
|
+
* 渲染,单行、上限 160 cells,与其它底栏字段的 hover 效果一致)。
|
|
223
|
+
* 宿主对 detail 只按 160 cells 截断、不做“适配当前宽度”的 truncate,超宽会
|
|
224
|
+
* wrap 进看不见的第二行;所以按终端宽度自己裁:状态行内宽是 columns-2
|
|
225
|
+
* (宿主 paddingX=1),再给右侧 MiniWake/activity 预留 16 格,下限 8。 */
|
|
226
|
+
const applyStatusField = (text, detail) => {
|
|
227
|
+
if (disposed) return
|
|
228
|
+
if (!statusService || typeof statusService.setField !== 'function') return
|
|
229
|
+
try {
|
|
230
|
+
const columns = Number(process.stdout && process.stdout.columns) || 80
|
|
231
|
+
const clipped = detail ? clipCells(detail, Math.max(8, columns - 18)) : ''
|
|
232
|
+
// 相同值不重复写:宿主 store 会对同 text 的 setField 也 emit,并往
|
|
233
|
+
// append-only 的 effect-ledger 记一笔。从未写过时也不要发“空清除”。
|
|
234
|
+
const previous = lastStatusWrite
|
|
235
|
+
if (previous && previous.text === text && previous.detail === clipped) return
|
|
236
|
+
if (!previous && text === undefined && !clipped) return
|
|
237
|
+
lastStatusWrite = { text, detail: clipped }
|
|
238
|
+
const options = clipped ? { ...STATUS_OPTIONS, detail: clipped } : STATUS_OPTIONS
|
|
239
|
+
// 第 4 个参数是插件自己的 ctx(只用于 effect ledger 归属,可省略)。
|
|
240
|
+
const next = statusService.setField(STATUS_KEY, text, options, ctx)
|
|
241
|
+
if (statusFieldDispose) {
|
|
242
|
+
const previous = statusFieldDispose
|
|
243
|
+
statusFieldDispose = null
|
|
244
|
+
try { previous() } catch { /* already cleared */ }
|
|
245
|
+
}
|
|
246
|
+
if (typeof next === 'function') statusFieldDispose = next
|
|
247
|
+
} catch (error) {
|
|
248
|
+
warn(ctx, '状态行更新失败', error)
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** 子代理会话也会进 store、也会发 `user/message`,但它不是用户在看的会话。 */
|
|
253
|
+
const isSubagentSession = (session) => {
|
|
254
|
+
const origin = session && session.header && session.header.origin
|
|
255
|
+
return origin === 'subagent'
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** 本进程的 live 会话(不含子代理)。`null` = 宿主没有 sessions 服务(旧组合),
|
|
259
|
+
* `[]` = 服务在但读不到/读抛错 → 调用方按“没有远程会话”处理。 */
|
|
260
|
+
const liveSessions = () => {
|
|
261
|
+
const sessions = getService(ctx, 'sessions')
|
|
262
|
+
if (!sessions || typeof sessions.list !== 'function') return null
|
|
263
|
+
try {
|
|
264
|
+
const list = sessions.list()
|
|
265
|
+
if (!Array.isArray(list)) return []
|
|
266
|
+
return list.filter((one) => one && one.header && one.header.cwd && !isSubagentSession(one))
|
|
267
|
+
} catch (error) {
|
|
268
|
+
warn(ctx, '会话列表读取失败', error)
|
|
269
|
+
return []
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** 当前 TUI 会话的 cwd。
|
|
274
|
+
*
|
|
275
|
+
* TUI 进程里可以同时有多个 live session(挂载中的会话 + parked 后台会话),
|
|
276
|
+
* 而“切到已挂载会话”不会发 session/* 事件。插件拿不到宿主 channel,按可靠性
|
|
277
|
+
* 依次采信:① 宿主切换会话时传入 provider.describe() 的 cwd(只在这种情况下
|
|
278
|
+
* 才算数,并交叉校验它确实属于某个 live 会话);② 最近进入/用户说过话的
|
|
279
|
+
* 会话;③ store 里最后进入的会话。 */
|
|
280
|
+
const activeSessionCwd = () => {
|
|
281
|
+
const list = liveSessions()
|
|
282
|
+
if (list === null) return { supported: false, cwd: '' }
|
|
283
|
+
const cwds = new Set(list.map((one) => String(one.header.cwd)))
|
|
284
|
+
if (hostSessionCwd && cwds.has(hostSessionCwd)) return { supported: true, cwd: hostSessionCwd }
|
|
285
|
+
const cwdOf = (id) => {
|
|
286
|
+
if (!id) return ''
|
|
287
|
+
const one = list.find((candidate) => String(candidate.id) === String(id))
|
|
288
|
+
return one ? String(one.header.cwd) : ''
|
|
289
|
+
}
|
|
290
|
+
let cwd = cwdOf(activeSessionId) || cwdOf(lastUserSessionId)
|
|
291
|
+
if (!cwd && list.length > 0) cwd = String(list[list.length - 1].header.cwd)
|
|
292
|
+
return { supported: true, cwd }
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** 宿主在会话切换/工作区描述时把当前 cwd 交给 provider.describe();记下来,
|
|
296
|
+
* 由 activeSessionCwd 交叉校验后使用。 */
|
|
297
|
+
const noteHostSessionCwd = (cwd) => {
|
|
298
|
+
const value = String(cwd || '')
|
|
299
|
+
if (!value || value === hostSessionCwd) return
|
|
300
|
+
hostSessionCwd = value
|
|
301
|
+
void refreshStatusField()
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** `$DSH_HOME`:宿主的 `dshHomePath` 服务是**函数**(`(...segments) => path`),
|
|
305
|
+
* 老版本/测试里也可能是字符串或 `{path}`;都没有时退回环境变量/`~/.dsh`。 */
|
|
306
|
+
const dshHomePath = () => {
|
|
307
|
+
const service = getService(ctx, 'dshHomePath')
|
|
308
|
+
if (typeof service === 'function') {
|
|
309
|
+
try {
|
|
310
|
+
const home = service()
|
|
311
|
+
if (typeof home === 'string' && home) return home
|
|
312
|
+
} catch { /* fall through to the string forms */ }
|
|
313
|
+
}
|
|
314
|
+
if (typeof service === 'string' && service) return service
|
|
315
|
+
if (service && typeof service.path === 'string' && service.path) return service.path
|
|
316
|
+
return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** 会话在远程镜像里 → `{label, detail}`;本地会话 / 无会话 → ''。
|
|
320
|
+
* `detail` 供底栏 hover 使用:完整机器名 + `user@host:port` + 远端路径。
|
|
321
|
+
* `null` 表示宿主没有 sessions 服务(旧组合),调用方退回旧行为。 */
|
|
322
|
+
const remoteSessionLabel = (machines) => {
|
|
323
|
+
const { supported, cwd } = activeSessionCwd()
|
|
324
|
+
if (!supported) return null
|
|
325
|
+
if (!cwd) return ''
|
|
326
|
+
let resolved
|
|
327
|
+
try {
|
|
328
|
+
resolved = resolveMirror(cwd, path.join(dshHomePath(), 'remote-workspaces'))
|
|
329
|
+
} catch {
|
|
330
|
+
return ''
|
|
331
|
+
}
|
|
332
|
+
const machine = resolved && resolved.machine
|
|
333
|
+
if (!machine || !resolved.remotePath) return ''
|
|
334
|
+
// 与 provider 的机器匹配共用一套规则:ssh-config 别名机按 alias 命中,
|
|
335
|
+
// 字面机按 host/port/username 命中。
|
|
336
|
+
const match = matchMachineForMirror(machines, machine)
|
|
337
|
+
const label = String(((match && (match.name || match.host)) || machine.alias || machine.host || '')).trim()
|
|
338
|
+
const parts = []
|
|
339
|
+
if (label) parts.push(i18n.t('status.detailMachine', { name: label }))
|
|
340
|
+
parts.push(i18n.t('status.detailTarget', {
|
|
341
|
+
user: machine.username || '',
|
|
342
|
+
host: machine.host || '',
|
|
343
|
+
port: Number(machine.port) || 22,
|
|
344
|
+
}))
|
|
345
|
+
parts.push(i18n.t('status.detailRemote', { path: resolved.remotePath }))
|
|
346
|
+
return { label, detail: parts.filter(Boolean).join(' · ') }
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** 读当前机器名并写状态行;旧结果(token 过期)直接丢弃。
|
|
350
|
+
*
|
|
351
|
+
* 只在**当前会话的 cwd 落在远程镜像里**时显示(用户报告的“本地目录也显示
|
|
352
|
+
* 服务器名”就是待机机器被无条件写进底栏)。没有 sessions 服务的旧组合
|
|
353
|
+
* 退回旧行为,不猜。 */
|
|
354
|
+
const refreshStatusField = async () => {
|
|
355
|
+
if (!statusService || typeof statusService.setField !== 'function') return
|
|
356
|
+
if (typeof api.listMachines !== 'function') return
|
|
357
|
+
const token = ++statusRefreshToken
|
|
358
|
+
let machines = []
|
|
359
|
+
let currentId = null
|
|
360
|
+
try {
|
|
361
|
+
const result = await api.listMachines()
|
|
362
|
+
machines = Array.isArray(result && result.machines) ? result.machines : []
|
|
363
|
+
currentId = result && result.currentId !== undefined ? result.currentId : null
|
|
364
|
+
} catch (error) {
|
|
365
|
+
warn(ctx, '状态行读取机器列表失败', error)
|
|
366
|
+
// 读不到机器列表时不要留下旧机器名(那正是“待机机器占底栏”的观感来源)。
|
|
367
|
+
applyStatusField(undefined)
|
|
368
|
+
return
|
|
369
|
+
}
|
|
370
|
+
if (token !== statusRefreshToken || disposed) return
|
|
371
|
+
const current = machines.find((machine) => machine && machine.id === currentId)
|
|
372
|
+
const remote = remoteSessionLabel(machines)
|
|
373
|
+
const label = remote === null
|
|
374
|
+
? (current ? String(current.name || current.host || '').trim() : '')
|
|
375
|
+
: remote.label
|
|
376
|
+
applyStatusField(label || undefined, remote && remote.detail)
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** 会话事件合并刷新:会话进入/结束、用户在哪说话都会改变“当前会话”。
|
|
380
|
+
* 500ms 合并避免连续事件重复跑 listMachines。 */
|
|
381
|
+
const SESSION_REFRESH_MS = 500
|
|
382
|
+
let sessionRefreshTimer = null
|
|
383
|
+
const scheduleStatusRefresh = () => {
|
|
384
|
+
if (sessionRefreshTimer) return
|
|
385
|
+
sessionRefreshTimer = setTimeout(() => {
|
|
386
|
+
sessionRefreshTimer = null
|
|
387
|
+
void refreshStatusField()
|
|
388
|
+
}, SESSION_REFRESH_MS)
|
|
389
|
+
if (typeof sessionRefreshTimer.unref === 'function') sessionRefreshTimer.unref()
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 任意 TUI 接缝出现后:订阅宿主变更(刷新 provider 缓存 + 状态行)。 */
|
|
393
|
+
const markTuiActive = () => {
|
|
394
|
+
if (tuiActive) return
|
|
395
|
+
tuiActive = true
|
|
396
|
+
if (typeof api.subscribe === 'function') {
|
|
397
|
+
let dispose
|
|
398
|
+
try {
|
|
399
|
+
dispose = api.subscribe(() => {
|
|
400
|
+
if (workspacesSeen && provider) {
|
|
401
|
+
try { void provider.refresh() } catch (error) { warn(ctx, 'provider 刷新失败', error) }
|
|
402
|
+
}
|
|
403
|
+
void refreshStatusField()
|
|
404
|
+
})
|
|
405
|
+
} catch (error) {
|
|
406
|
+
warn(ctx, 'api.subscribe 失败', error)
|
|
407
|
+
}
|
|
408
|
+
bindEffect(ctx, dispose)
|
|
409
|
+
}
|
|
410
|
+
// 会话进入/结束、用户发消息都会改变“当前会话”,据此刷新底栏字段。
|
|
411
|
+
if (typeof ctx.on === 'function') {
|
|
412
|
+
const disposers = []
|
|
413
|
+
const subscribe = (event, listener) => {
|
|
414
|
+
try {
|
|
415
|
+
const dispose = ctx.on(event, listener)
|
|
416
|
+
if (typeof dispose === 'function') disposers.push(dispose)
|
|
417
|
+
} catch (error) {
|
|
418
|
+
warn(ctx, `会话事件订阅失败(${event})`, error)
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
subscribe('session/created', (session) => {
|
|
422
|
+
if (!session || session.id == null || isSubagentSession(session)) return
|
|
423
|
+
activeSessionId = String(session.id)
|
|
424
|
+
scheduleStatusRefresh()
|
|
425
|
+
})
|
|
426
|
+
subscribe('session/disposed', (session) => {
|
|
427
|
+
if (!session || session.id == null || isSubagentSession(session)) return
|
|
428
|
+
const id = String(session.id)
|
|
429
|
+
if (id === activeSessionId) {
|
|
430
|
+
activeSessionId = lastUserSessionId && lastUserSessionId !== id ? lastUserSessionId : null
|
|
431
|
+
}
|
|
432
|
+
if (id === lastUserSessionId) lastUserSessionId = null
|
|
433
|
+
if (hostSessionCwd && !activeSessionId) hostSessionCwd = ''
|
|
434
|
+
scheduleStatusRefresh()
|
|
435
|
+
})
|
|
436
|
+
subscribe('session/event', (session, event) => {
|
|
437
|
+
if (!event || event.type !== 'user/message' || isSubagentSession(session)) return
|
|
438
|
+
if (!session || session.id == null) return
|
|
439
|
+
lastUserSessionId = String(session.id)
|
|
440
|
+
activeSessionId = String(session.id)
|
|
441
|
+
scheduleStatusRefresh()
|
|
442
|
+
})
|
|
443
|
+
bindEffect(ctx, () => {
|
|
444
|
+
if (sessionRefreshTimer) {
|
|
445
|
+
clearTimeout(sessionRefreshTimer)
|
|
446
|
+
sessionRefreshTimer = null
|
|
447
|
+
}
|
|
448
|
+
for (const dispose of disposers) {
|
|
449
|
+
try { dispose() } catch { /* teardown is best-effort */ }
|
|
450
|
+
}
|
|
451
|
+
})
|
|
452
|
+
}
|
|
453
|
+
// 终端变窄/变宽后详情要重新裁:否则旧字符串会 wrap 进看不见的第二行。
|
|
454
|
+
if (process.stdout && typeof process.stdout.on === 'function') {
|
|
455
|
+
const onResize = () => scheduleStatusRefresh()
|
|
456
|
+
try {
|
|
457
|
+
process.stdout.on('resize', onResize)
|
|
458
|
+
bindEffect(ctx, () => process.stdout.removeListener('resize', onResize))
|
|
459
|
+
} catch (error) {
|
|
460
|
+
warn(ctx, '终端 resize 订阅失败', error)
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
void refreshStatusField()
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// ── 服务到位后注册(顺序无关;命令只在 TUI 接缝出现后注册) ───────────
|
|
467
|
+
whenService(ctx, 'commands', (commands) => {
|
|
468
|
+
commandsSeen = commands
|
|
469
|
+
if (commandWanted) registerCommand(commands)
|
|
470
|
+
})
|
|
471
|
+
|
|
472
|
+
whenService(ctx, 'tuiScenes', (scenes) => {
|
|
473
|
+
if (!scenes || typeof scenes.register !== 'function') return
|
|
474
|
+
ensureCommand()
|
|
475
|
+
markTuiActive()
|
|
476
|
+
let dispose
|
|
477
|
+
try {
|
|
478
|
+
dispose = scenes.register({ id: SCENE_ID, title: 'Remote', component: sceneComponent }, ctx)
|
|
479
|
+
} catch (error) {
|
|
480
|
+
warn(ctx, '场景注册失败', error)
|
|
481
|
+
return
|
|
482
|
+
}
|
|
483
|
+
bindEffect(ctx, dispose)
|
|
484
|
+
})
|
|
485
|
+
|
|
486
|
+
whenService(ctx, 'tuiDialogs', (dialogs) => {
|
|
487
|
+
if (!dialogs) return
|
|
488
|
+
ensureCommand()
|
|
489
|
+
markTuiActive()
|
|
490
|
+
})
|
|
491
|
+
|
|
492
|
+
whenService(ctx, 'tuiWorkspaces', (workspaces) => {
|
|
493
|
+
if (!workspaces || typeof workspaces.register !== 'function') return
|
|
494
|
+
workspacesSeen = true
|
|
495
|
+
markTuiActive()
|
|
496
|
+
const instance = ensureProvider()
|
|
497
|
+
let dispose
|
|
498
|
+
try {
|
|
499
|
+
// register 在无 live activation 时会**同步抛错**,必须包 try/catch。
|
|
500
|
+
dispose = workspaces.register(instance)
|
|
501
|
+
} catch (error) {
|
|
502
|
+
warn(ctx, '工作区 provider 注册失败', error)
|
|
503
|
+
return
|
|
504
|
+
}
|
|
505
|
+
bindEffect(ctx, dispose)
|
|
506
|
+
// 后台预热,绝不阻塞 apply / 首个 UI 帧。
|
|
507
|
+
try {
|
|
508
|
+
queueMicrotask(() => { void instance.refresh() })
|
|
509
|
+
} catch (error) {
|
|
510
|
+
warn(ctx, 'provider 预热失败', error)
|
|
511
|
+
}
|
|
512
|
+
})
|
|
513
|
+
|
|
514
|
+
whenService(ctx, 'tuiStatus', (status) => {
|
|
515
|
+
if (!status || typeof status.setField !== 'function') return
|
|
516
|
+
statusService = status
|
|
517
|
+
markTuiActive()
|
|
518
|
+
bindEffect(ctx, () => {
|
|
519
|
+
if (!statusFieldDispose) return
|
|
520
|
+
const dispose = statusFieldDispose
|
|
521
|
+
statusFieldDispose = null
|
|
522
|
+
dispose()
|
|
523
|
+
})
|
|
524
|
+
void refreshStatusField()
|
|
525
|
+
})
|
|
526
|
+
} catch (error) {
|
|
527
|
+
warn(ctx, 'installTui 初始化失败', error)
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
export default installTui
|