@fefeding/aicmd 0.1.7 → 0.1.14
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/dist/public/.vite/manifest.json +17 -17
- package/dist/public/favicon.ico +0 -0
- package/dist/public/index.css +80 -0
- package/dist/public/index.js +149 -23
- package/dist/public/views.css +309 -221
- package/dist/public/views.js +1743 -1605
- package/dist/public/vue.js +5120 -5120
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +13 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.ts +12 -1
- package/dist/server/model/connection.entity.d.ts +4 -0
- package/dist/server/model/connection.entity.d.ts.map +1 -1
- package/dist/server/model/connection.entity.js +4 -0
- package/dist/server/model/connection.entity.js.map +1 -1
- package/dist/server/model/connection.entity.ts +6 -0
- package/dist/server/service/ai.service.d.ts +17 -1
- package/dist/server/service/ai.service.d.ts.map +1 -1
- package/dist/server/service/ai.service.js +189 -106
- package/dist/server/service/ai.service.js.map +1 -1
- package/dist/server/service/ai.service.ts +198 -114
- package/dist/server/service/connection.service.d.ts +13 -2
- package/dist/server/service/connection.service.d.ts.map +1 -1
- package/dist/server/service/connection.service.js +153 -19
- package/dist/server/service/connection.service.js.map +1 -1
- package/dist/server/service/connection.service.ts +163 -22
- package/dist/server/service/ssh.service.d.ts +39 -0
- package/dist/server/service/ssh.service.d.ts.map +1 -1
- package/dist/server/service/ssh.service.js +419 -9
- package/dist/server/service/ssh.service.js.map +1 -1
- package/dist/server/service/ssh.service.ts +425 -9
- package/dist/server/utils/data-dir.d.ts +7 -0
- package/dist/server/utils/data-dir.d.ts.map +1 -1
- package/dist/server/utils/data-dir.js +38 -2
- package/dist/server/utils/data-dir.js.map +1 -1
- package/dist/server/utils/data-dir.ts +33 -2
- package/dist/view/index.html +19 -21
- package/electron/main.js +73 -11
- package/electron/preload.js +34 -0
- package/electron/updater.js +181 -0
- package/package.json +6 -4
- package/server.js +128 -3
- package/view/index.html +0 -9
- package/view/modules/header.tpl +0 -14
- package/view/modules/initial_state.tpl +0 -20
|
@@ -61,15 +61,22 @@ class SSHService {
|
|
|
61
61
|
pendingMOTDCaptures = new Map();
|
|
62
62
|
/** Session 元数据持久化文件路径 */
|
|
63
63
|
sessionsFilePath;
|
|
64
|
+
/** 是否曾在本实例创建过 session(用于区分主进程/渲染进程实例,仅主进程实例执行定时清理) */
|
|
65
|
+
hasCreatedSession = false;
|
|
66
|
+
/** 定时清理僵尸 session 的定时器 */
|
|
67
|
+
cleanupTimer = null;
|
|
64
68
|
constructor(connectionService) {
|
|
65
69
|
this.connectionService = connectionService;
|
|
66
70
|
this.sessionsFilePath = (0, data_dir_1.getDataPath)('sessions.json');
|
|
67
71
|
this.loadSessionsFromDisk();
|
|
72
|
+
this.startPeriodicCleanup();
|
|
68
73
|
}
|
|
69
74
|
/**
|
|
70
75
|
* 创建会话(自动判断 SSH 或本地 shell)
|
|
71
76
|
*/
|
|
72
77
|
async createSession(sessionId, connectionId, cols = 80, rows = 24, name) {
|
|
78
|
+
// 标记本实例曾创建过 session(用于定时清理判断)
|
|
79
|
+
this.hasCreatedSession = true;
|
|
73
80
|
// 如果已存在同 ID 的会话,先关闭
|
|
74
81
|
if (this.sessions.has(sessionId)) {
|
|
75
82
|
this.closeSession(sessionId);
|
|
@@ -127,7 +134,13 @@ class SSHService {
|
|
|
127
134
|
this.saveSessionsToDisk();
|
|
128
135
|
// SSH 会话:后台自动捕获 MOTD 作为系统信息
|
|
129
136
|
if (session.type === 'ssh') {
|
|
130
|
-
|
|
137
|
+
// Skip MOTD capture for startup script sessions (jump host) - system info collected on demand
|
|
138
|
+
if (!connection.startupScript?.trim()) {
|
|
139
|
+
this.startMOTDCapture(sessionId);
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
console.log(`[SSH] Skipping MOTD capture for jump host session ${sessionId}, will collect on demand`);
|
|
143
|
+
}
|
|
131
144
|
}
|
|
132
145
|
return session;
|
|
133
146
|
}
|
|
@@ -146,6 +159,10 @@ class SSHService {
|
|
|
146
159
|
if (nodePty) {
|
|
147
160
|
try {
|
|
148
161
|
const isWindows = process.platform === 'win32';
|
|
162
|
+
// Windows: 设置 UTF-8 代码页环境变量,避免中文乱码
|
|
163
|
+
if (isWindows) {
|
|
164
|
+
cleanEnv.CHCP = '65001';
|
|
165
|
+
}
|
|
149
166
|
const ptyProcess = nodePty.spawn(shell, isWindows && shell.includes('powershell') ? ['-NoLogo'] : [], {
|
|
150
167
|
name: isWindows ? 'xterm' : 'xterm-256color',
|
|
151
168
|
cols,
|
|
@@ -163,6 +180,17 @@ class SSHService {
|
|
|
163
180
|
createdAt: new Date(),
|
|
164
181
|
};
|
|
165
182
|
this.sessions.set(sessionId, session);
|
|
183
|
+
// Windows: 启动时执行 chcp 65001 设置 UTF-8 编码
|
|
184
|
+
if (isWindows) {
|
|
185
|
+
setTimeout(() => {
|
|
186
|
+
ptyProcess.write('chcp 65001\r\n');
|
|
187
|
+
// PowerShell: 额外设置输出编码
|
|
188
|
+
if (shell.includes('powershell')) {
|
|
189
|
+
ptyProcess.write('[Console]::OutputEncoding = [Text.Encoding]::UTF8\r\n');
|
|
190
|
+
}
|
|
191
|
+
ptyProcess.write('cls\r\n');
|
|
192
|
+
}, 100);
|
|
193
|
+
}
|
|
166
194
|
ptyProcess.onExit(() => {
|
|
167
195
|
this.sessions.delete(sessionId);
|
|
168
196
|
});
|
|
@@ -216,11 +244,16 @@ class SSHService {
|
|
|
216
244
|
}, 30000);
|
|
217
245
|
client.on('ready', () => {
|
|
218
246
|
clearTimeout(timeout);
|
|
219
|
-
|
|
247
|
+
const shellOpts = {
|
|
220
248
|
term: 'xterm-256color',
|
|
221
249
|
cols,
|
|
222
250
|
rows,
|
|
223
|
-
}
|
|
251
|
+
};
|
|
252
|
+
// Enable SSH agent forwarding in the shell session
|
|
253
|
+
if (connection.forwardAgent) {
|
|
254
|
+
shellOpts.agentForward = true;
|
|
255
|
+
}
|
|
256
|
+
client.shell(shellOpts, (err, stream) => {
|
|
224
257
|
if (err) {
|
|
225
258
|
client.end();
|
|
226
259
|
reject(err);
|
|
@@ -239,6 +272,17 @@ class SSHService {
|
|
|
239
272
|
stream.on('close', () => {
|
|
240
273
|
this.sessions.delete(sessionId);
|
|
241
274
|
});
|
|
275
|
+
// Execute startup script if configured (e.g. jump host SSH hop)
|
|
276
|
+
if (connection.startupScript && connection.startupScript.trim()) {
|
|
277
|
+
const script = connection.startupScript.trim();
|
|
278
|
+
console.log(`[SSH] Executing startup script for session ${sessionId}: ${script.substring(0, 80)}`);
|
|
279
|
+
// Delay slightly to let the remote shell fully initialize
|
|
280
|
+
setTimeout(() => {
|
|
281
|
+
if (this.sessions.has(sessionId)) {
|
|
282
|
+
stream.write(script + '\n');
|
|
283
|
+
}
|
|
284
|
+
}, 800);
|
|
285
|
+
}
|
|
242
286
|
resolve(session);
|
|
243
287
|
});
|
|
244
288
|
}).on('error', (err) => {
|
|
@@ -331,12 +375,19 @@ class SSHService {
|
|
|
331
375
|
}
|
|
332
376
|
/**
|
|
333
377
|
* 删除会话(关闭进程并从 server 端移除 metadata)
|
|
378
|
+
* 注意:由于 Electron 主进程和渲染进程各自有独立的模块实例,
|
|
379
|
+
* 渲染进程实例的 sessionMetadata 可能不含主进程创建的 session,
|
|
380
|
+
* 因此先从磁盘重新加载以确保同步,再执行删除。
|
|
334
381
|
*/
|
|
335
382
|
deleteSession(sessionId) {
|
|
336
383
|
// 先关闭进程
|
|
337
384
|
this.closeSession(sessionId);
|
|
385
|
+
// 从磁盘重新加载元数据(确保与主进程实例同步)
|
|
386
|
+
this.loadSessionsFromDisk();
|
|
338
387
|
// 再删除元数据
|
|
388
|
+
const had = this.sessionMetadata.has(sessionId);
|
|
339
389
|
this.sessionMetadata.delete(sessionId);
|
|
390
|
+
console.log(`[SSH] deleteSession: ${sessionId}, had=${had}, remaining: ${this.sessionMetadata.size}, keys=[${Array.from(this.sessionMetadata.keys()).join(', ')}]`);
|
|
340
391
|
this.saveSessionsToDisk();
|
|
341
392
|
}
|
|
342
393
|
/**
|
|
@@ -354,6 +405,7 @@ class SSHService {
|
|
|
354
405
|
if (fs.existsSync(this.sessionsFilePath)) {
|
|
355
406
|
const raw = fs.readFileSync(this.sessionsFilePath, 'utf-8');
|
|
356
407
|
const list = JSON.parse(raw);
|
|
408
|
+
this.sessionMetadata.clear();
|
|
357
409
|
for (const item of list) {
|
|
358
410
|
this.sessionMetadata.set(item.sessionId, {
|
|
359
411
|
sessionId: item.sessionId,
|
|
@@ -364,7 +416,7 @@ class SSHService {
|
|
|
364
416
|
systemContext: item.systemContext,
|
|
365
417
|
});
|
|
366
418
|
}
|
|
367
|
-
console.log(`[SSH] Loaded ${list.length} session(s) from disk`);
|
|
419
|
+
console.log(`[SSH] Loaded ${list.length} session(s) from disk, ids=[${list.map(i => i.sessionId).join(', ')}]`);
|
|
368
420
|
}
|
|
369
421
|
}
|
|
370
422
|
catch (error) {
|
|
@@ -384,7 +436,9 @@ class SSHService {
|
|
|
384
436
|
createdAt: m.createdAt instanceof Date ? m.createdAt.toISOString() : m.createdAt,
|
|
385
437
|
systemContext: m.systemContext,
|
|
386
438
|
}));
|
|
387
|
-
|
|
439
|
+
const json = JSON.stringify(list, null, 2);
|
|
440
|
+
console.log(`[SSH] saveSessionsToDisk: ${list.length} session(s), path=${this.sessionsFilePath}`);
|
|
441
|
+
fs.writeFileSync(this.sessionsFilePath, json, 'utf-8');
|
|
388
442
|
}
|
|
389
443
|
catch (error) {
|
|
390
444
|
console.error('[SSH] Failed to save sessions to disk:', error);
|
|
@@ -394,9 +448,40 @@ class SSHService {
|
|
|
394
448
|
/**
|
|
395
449
|
* 获取会话的系统上下文(确保每次都有)
|
|
396
450
|
* 如果 session 没有缓存的环境信息,自动采集并持久化
|
|
451
|
+
* 对于 startupScript(跳板机)会话,始终主动采集以确保获取目标服务器信息
|
|
397
452
|
*/
|
|
398
453
|
async getSystemContext(sessionId) {
|
|
399
454
|
const meta = this.sessionMetadata.get(sessionId);
|
|
455
|
+
// Check if this is a jump host session (has startupScript)
|
|
456
|
+
let isJumpHost = false;
|
|
457
|
+
if (meta?.connectionId) {
|
|
458
|
+
try {
|
|
459
|
+
const conn = await this.connectionService.getConnectionById(meta.connectionId);
|
|
460
|
+
isJumpHost = !!conn?.startupScript?.trim();
|
|
461
|
+
}
|
|
462
|
+
catch { /* ignore */ }
|
|
463
|
+
}
|
|
464
|
+
// For jump host sessions, always actively collect (cached data may be from jump host, not target)
|
|
465
|
+
if (isJumpHost) {
|
|
466
|
+
// Wait for startup script SSH hop to complete before collecting.
|
|
467
|
+
// The startup script is sent at 800ms after shell ready; the SSH hop itself takes 2-5s.
|
|
468
|
+
// Without this delay, the echo command may run on the jump host before the hop completes.
|
|
469
|
+
const sessionAge = Date.now() - meta.createdAt.getTime();
|
|
470
|
+
const JUMP_HOST_SETTLE_DELAY = 8000; // 8 seconds total after session creation
|
|
471
|
+
if (sessionAge < JUMP_HOST_SETTLE_DELAY) {
|
|
472
|
+
const waitMs = JUMP_HOST_SETTLE_DELAY - sessionAge;
|
|
473
|
+
console.log(`[SSH] Jump host session ${sessionId}: waiting ${waitMs}ms for SSH hop to complete before collecting system info`);
|
|
474
|
+
await new Promise(resolve => setTimeout(resolve, waitMs));
|
|
475
|
+
}
|
|
476
|
+
console.log(`[SSH] Jump host session ${sessionId}: actively collecting target server info`);
|
|
477
|
+
const info = await this.activeCollectRemoteSystemInfo(sessionId);
|
|
478
|
+
if (info && meta) {
|
|
479
|
+
meta.systemContext = info;
|
|
480
|
+
this.saveSessionsToDisk();
|
|
481
|
+
}
|
|
482
|
+
return info;
|
|
483
|
+
}
|
|
484
|
+
// Normal sessions: use cache if available
|
|
400
485
|
if (meta?.systemContext) {
|
|
401
486
|
return meta.systemContext;
|
|
402
487
|
}
|
|
@@ -414,8 +499,8 @@ class SSHService {
|
|
|
414
499
|
// local 会话或未捕获的 SSH 会话
|
|
415
500
|
let info;
|
|
416
501
|
if (meta?.type === 'ssh') {
|
|
417
|
-
// SSH 但没有 pending
|
|
418
|
-
info = await this.
|
|
502
|
+
// SSH 但没有 pending,主动运行命令采集系统信息
|
|
503
|
+
info = await this.activeCollectRemoteSystemInfo(sessionId);
|
|
419
504
|
}
|
|
420
505
|
else {
|
|
421
506
|
info = this.collectLocalSystemInfo();
|
|
@@ -456,6 +541,57 @@ class SSHService {
|
|
|
456
541
|
return '';
|
|
457
542
|
}
|
|
458
543
|
}
|
|
544
|
+
/**
|
|
545
|
+
* Active system info collection for SSH sessions (e.g. jump host)
|
|
546
|
+
* Sends a compact command to the remote terminal and captures the output
|
|
547
|
+
*/
|
|
548
|
+
async activeCollectRemoteSystemInfo(sessionId) {
|
|
549
|
+
const marker = '__AICMD_SYS__';
|
|
550
|
+
const cmd = `echo "${marker}:$(uname -s 2>/dev/null || echo unknown):$(uname -r 2>/dev/null || echo unknown):$(hostname 2>/dev/null || echo unknown):$(whoami 2>/dev/null || echo unknown):$SHELL:$(uname -m 2>/dev/null || echo unknown)"`;
|
|
551
|
+
try {
|
|
552
|
+
// Start capture, then send the command
|
|
553
|
+
// Use longer timeout (5s) to account for slow SSH connections and MOTD output
|
|
554
|
+
const outputPromise = this.captureOutput(sessionId, 5000);
|
|
555
|
+
this.writeData(sessionId, cmd + '\n');
|
|
556
|
+
const output = await outputPromise;
|
|
557
|
+
// Clean ANSI escape codes for more reliable marker matching
|
|
558
|
+
const cleaned = output.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '').replace(/\x1B\].*?\x07/g, '').replace(/\r/g, '');
|
|
559
|
+
// Extract our marker line
|
|
560
|
+
for (const line of cleaned.split('\n')) {
|
|
561
|
+
const trimmed = line.trim();
|
|
562
|
+
// Handle possible command echo: skip lines that still contain the raw command prefix
|
|
563
|
+
if (trimmed.includes(marker + ':') && !trimmed.startsWith('echo')) {
|
|
564
|
+
const markerIdx = trimmed.indexOf(marker + ':');
|
|
565
|
+
const markerLine = trimmed.substring(markerIdx);
|
|
566
|
+
const parts = markerLine.split(':');
|
|
567
|
+
if (parts.length >= 7) {
|
|
568
|
+
const info = {
|
|
569
|
+
'OS': parts[1],
|
|
570
|
+
'Kernel': parts[2],
|
|
571
|
+
'Hostname': parts[3],
|
|
572
|
+
'User': parts[4],
|
|
573
|
+
'Shell': parts[5],
|
|
574
|
+
'Arch': parts[6] || '',
|
|
575
|
+
};
|
|
576
|
+
const lines = ['System environment info:'];
|
|
577
|
+
for (const [key, val] of Object.entries(info)) {
|
|
578
|
+
if (val && val !== 'unknown')
|
|
579
|
+
lines.push(`- ${key}: ${val}`);
|
|
580
|
+
}
|
|
581
|
+
const result = lines.join('\n');
|
|
582
|
+
console.log(`[SSH] Active system info collected for ${sessionId}:`, result);
|
|
583
|
+
return result;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
console.warn(`[SSH] Marker not found in output for ${sessionId}, marker=${marker}`);
|
|
588
|
+
return '';
|
|
589
|
+
}
|
|
590
|
+
catch (e) {
|
|
591
|
+
console.warn(`[SSH] Failed to actively collect system info for ${sessionId}:`, e);
|
|
592
|
+
return '';
|
|
593
|
+
}
|
|
594
|
+
}
|
|
459
595
|
/**
|
|
460
596
|
* 解析 SSH 登录 MOTD,提取系统环境信息
|
|
461
597
|
* 兼容 Ubuntu/Debian/CentOS/RHEL/Fedora/FreeBSD 等不同发行版格式
|
|
@@ -596,6 +732,7 @@ class SSHService {
|
|
|
596
732
|
*/
|
|
597
733
|
collectWindowsSystemInfo() {
|
|
598
734
|
const psScript = `
|
|
735
|
+
[Console]::OutputEncoding = [Text.Encoding]::UTF8;
|
|
599
736
|
$os = (Get-CimInstance Win32_OperatingSystem).Caption
|
|
600
737
|
$kernel = [System.Environment]::OSVersion.Version.ToString()
|
|
601
738
|
$hostname = $env:COMPUTERNAME
|
|
@@ -621,12 +758,12 @@ Write-Output "__PYTHON__: $pyVer"
|
|
|
621
758
|
Write-Output "__DOCKER__: $dockerVer"
|
|
622
759
|
`.trim();
|
|
623
760
|
try {
|
|
624
|
-
const result = (0, child_process_2.execSync)(`powershell.exe -NoProfile -NonInteractive -Command "${psScript.replace(/"/g, '\\"').replace(/\n/g, '; ')}"`, { encoding: 'utf-8', timeout: 10000 });
|
|
761
|
+
const result = (0, child_process_2.execSync)(`chcp 65001 >nul & powershell.exe -NoProfile -NonInteractive -Command "${psScript.replace(/"/g, '\\"').replace(/\n/g, '; ')}"`, { encoding: 'utf-8', timeout: 10000 });
|
|
625
762
|
return this.formatSystemInfo(result);
|
|
626
763
|
}
|
|
627
764
|
catch {
|
|
628
765
|
try {
|
|
629
|
-
const basic = (0, child_process_2.execSync)('systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"', {
|
|
766
|
+
const basic = (0, child_process_2.execSync)('chcp 65001 >nul & systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"', {
|
|
630
767
|
encoding: 'utf-8', timeout: 15000,
|
|
631
768
|
});
|
|
632
769
|
return `Basic system info:\n${basic}`;
|
|
@@ -766,9 +903,24 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
766
903
|
const listener = (data) => {
|
|
767
904
|
output += data;
|
|
768
905
|
};
|
|
906
|
+
// 方式1: 通过 notifyOutput 机制捕获
|
|
769
907
|
this.addOutputListener(sessionId, listener);
|
|
908
|
+
// 方式2: 直接在 SSH stream 上监听(绕过 hasBinary 检查)
|
|
909
|
+
const session = this.sessions.get(sessionId);
|
|
910
|
+
let streamHandler = null;
|
|
911
|
+
if (session?.stream) {
|
|
912
|
+
streamHandler = (chunk) => {
|
|
913
|
+
// 只捕获可打印文本部分
|
|
914
|
+
const text = chunk.toString('utf-8');
|
|
915
|
+
output += text;
|
|
916
|
+
};
|
|
917
|
+
session.stream.on('data', streamHandler);
|
|
918
|
+
}
|
|
770
919
|
setTimeout(() => {
|
|
771
920
|
this.removeOutputListener(sessionId);
|
|
921
|
+
if (streamHandler && session?.stream) {
|
|
922
|
+
session.stream.removeListener('data', streamHandler);
|
|
923
|
+
}
|
|
772
924
|
// 去除 ANSI 转义序列
|
|
773
925
|
resolve(output.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '').replace(/\x1B\].*?\x07/g, ''));
|
|
774
926
|
}, timeoutMs);
|
|
@@ -827,6 +979,264 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
827
979
|
this.closeSession(sessionId);
|
|
828
980
|
}
|
|
829
981
|
}
|
|
982
|
+
/**
|
|
983
|
+
* 获取 SSH 会话的当前工作目录(通过 shell stream 执行 pwd)
|
|
984
|
+
*/
|
|
985
|
+
async getSessionCwd(sessionId) {
|
|
986
|
+
const marker = `__AICmd_CWD_${Date.now()}__`;
|
|
987
|
+
// 前加空格避免 shell 回显(HISTCONTROL=ignorespace),先启动捕获再发命令
|
|
988
|
+
const outputPromise = this.captureOutput(sessionId, 1500);
|
|
989
|
+
this.writeData(sessionId, ` echo ${marker}:$(pwd)\n`);
|
|
990
|
+
const output = await outputPromise;
|
|
991
|
+
console.log(`[SSH] getSessionCwd: raw output: ${JSON.stringify(output.substring(0, 300))}`);
|
|
992
|
+
const cleaned = output.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '').replace(/\r/g, '');
|
|
993
|
+
for (const line of cleaned.split('\n')) {
|
|
994
|
+
const trimmed = line.trim();
|
|
995
|
+
// 只匹配以 marker 开头的行(实际输出),跳过 echo 回显行(以 echo 开头)
|
|
996
|
+
if (trimmed.startsWith(marker + ':')) {
|
|
997
|
+
const cwd = trimmed.substring(marker.length + 1).trim();
|
|
998
|
+
if (cwd && !cwd.includes('$(pwd)')) {
|
|
999
|
+
console.log(`[SSH] getSessionCwd parsed: '${cwd}' from line: '${trimmed}'`);
|
|
1000
|
+
return cwd;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
console.log(`[SSH] getSessionCwd: no marker found in cleaned output: ${JSON.stringify(cleaned.substring(0, 300))}`);
|
|
1005
|
+
return '';
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* 通过 SFTP 上传文件到远程服务器(绕过 PTY,速度快)
|
|
1009
|
+
* @param sessionId 会话 ID
|
|
1010
|
+
* @param remotePath 远程文件路径(相对路径或绝对路径)
|
|
1011
|
+
* @param base64Data 文件的 base64 编码数据
|
|
1012
|
+
* @returns 写入的字节数
|
|
1013
|
+
*/
|
|
1014
|
+
async uploadFileViaSftp(sessionId, remotePath, fileBuffer) {
|
|
1015
|
+
const session = this.sessions.get(sessionId);
|
|
1016
|
+
if (!session)
|
|
1017
|
+
throw new Error('Session not found: ' + sessionId);
|
|
1018
|
+
if (session.type !== 'ssh' || !session.client) {
|
|
1019
|
+
throw new Error('SFTP upload only supported for SSH sessions');
|
|
1020
|
+
}
|
|
1021
|
+
console.log(`[SSH] SFTP upload: ${fileBuffer.length} bytes`);
|
|
1022
|
+
// 解析相对路径:先通过 shell 获取交互式 CWD(而非 SFTP 默认的 home 目录)
|
|
1023
|
+
let fullPath = remotePath;
|
|
1024
|
+
if (!remotePath.startsWith('/')) {
|
|
1025
|
+
try {
|
|
1026
|
+
console.log(`[SSH] Getting shell CWD...`);
|
|
1027
|
+
const cwd = await this.getSessionCwd(sessionId);
|
|
1028
|
+
console.log(`[SSH] Shell CWD: '${cwd}'`);
|
|
1029
|
+
if (cwd) {
|
|
1030
|
+
fullPath = `${cwd}/${remotePath}`;
|
|
1031
|
+
}
|
|
1032
|
+
else {
|
|
1033
|
+
console.warn(`[SSH] Shell CWD empty, falling back to SFTP realpath`);
|
|
1034
|
+
// fallback: 用 SFTP realpath(默认 home 目录)
|
|
1035
|
+
fullPath = await new Promise((resolve) => {
|
|
1036
|
+
session.client.sftp((err, sftp) => {
|
|
1037
|
+
if (err) {
|
|
1038
|
+
resolve(remotePath);
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
sftp.realpath('.', (rpErr, absCwd) => {
|
|
1042
|
+
resolve(rpErr ? remotePath : `${absCwd}/${remotePath}`);
|
|
1043
|
+
});
|
|
1044
|
+
});
|
|
1045
|
+
});
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
catch (cwdErr) {
|
|
1049
|
+
console.warn(`[SSH] getSessionCwd failed: ${cwdErr.message}, using relative path`);
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
console.log(`[SSH] SFTP upload path: ${remotePath} -> ${fullPath}`);
|
|
1053
|
+
// 使用 Promise + 超时包装(120秒,大文件需要更多时间)
|
|
1054
|
+
const SFTP_TIMEOUT = 120000;
|
|
1055
|
+
return new Promise((resolve, reject) => {
|
|
1056
|
+
let done = false;
|
|
1057
|
+
const timer = setTimeout(() => {
|
|
1058
|
+
if (!done) {
|
|
1059
|
+
done = true;
|
|
1060
|
+
reject(new Error(`SFTP timeout after ${SFTP_TIMEOUT / 1000}s`));
|
|
1061
|
+
}
|
|
1062
|
+
}, SFTP_TIMEOUT);
|
|
1063
|
+
const finish = (err, bytes) => {
|
|
1064
|
+
if (done)
|
|
1065
|
+
return;
|
|
1066
|
+
done = true;
|
|
1067
|
+
clearTimeout(timer);
|
|
1068
|
+
if (err)
|
|
1069
|
+
reject(err);
|
|
1070
|
+
else
|
|
1071
|
+
resolve(bytes);
|
|
1072
|
+
};
|
|
1073
|
+
const doSftpWrite = (targetPath, callback) => {
|
|
1074
|
+
console.log(`[SSH] SFTP opening subsystem...`);
|
|
1075
|
+
session.client.sftp((sftpErr, sftp) => {
|
|
1076
|
+
if (done)
|
|
1077
|
+
return;
|
|
1078
|
+
if (sftpErr) {
|
|
1079
|
+
callback(new Error('SFTP init failed: ' + sftpErr.message));
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
console.log(`[SSH] SFTP writing ${fileBuffer.length} bytes to ${targetPath}...`);
|
|
1083
|
+
sftp.open(targetPath, 'w', (openErr, fd) => {
|
|
1084
|
+
if (done)
|
|
1085
|
+
return;
|
|
1086
|
+
if (openErr) {
|
|
1087
|
+
console.error(`[SSH] SFTP open error: ${openErr.message}`);
|
|
1088
|
+
callback(new Error('SFTP open failed: ' + openErr.message));
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
sftp.write(fd, fileBuffer, 0, fileBuffer.length, 0, (writeErr) => {
|
|
1092
|
+
if (done)
|
|
1093
|
+
return;
|
|
1094
|
+
if (writeErr) {
|
|
1095
|
+
console.error(`[SSH] SFTP write error: ${writeErr.message}`);
|
|
1096
|
+
sftp.close(fd, () => { });
|
|
1097
|
+
callback(new Error('SFTP write failed: ' + writeErr.message));
|
|
1098
|
+
return;
|
|
1099
|
+
}
|
|
1100
|
+
sftp.close(fd, (closeErr) => {
|
|
1101
|
+
if (done)
|
|
1102
|
+
return;
|
|
1103
|
+
if (closeErr) {
|
|
1104
|
+
callback(new Error('SFTP close failed: ' + closeErr.message));
|
|
1105
|
+
return;
|
|
1106
|
+
}
|
|
1107
|
+
callback(null);
|
|
1108
|
+
});
|
|
1109
|
+
});
|
|
1110
|
+
});
|
|
1111
|
+
});
|
|
1112
|
+
};
|
|
1113
|
+
// 先尝试直接写入目标路径
|
|
1114
|
+
doSftpWrite(fullPath, (err) => {
|
|
1115
|
+
if (done)
|
|
1116
|
+
return;
|
|
1117
|
+
if (!err) {
|
|
1118
|
+
// 直接写入成功,验证文件
|
|
1119
|
+
console.log(`[SSH] SFTP direct write succeeded, verifying...`);
|
|
1120
|
+
session.client.sftp((_, sftp) => {
|
|
1121
|
+
sftp.stat(fullPath, (statErr, stats) => {
|
|
1122
|
+
if (statErr || stats.size !== fileBuffer.length) {
|
|
1123
|
+
finish(new Error('SFTP verify failed'));
|
|
1124
|
+
}
|
|
1125
|
+
else {
|
|
1126
|
+
console.log(`[SSH] SFTP upload verified: ${fullPath} (${stats.size} bytes)`);
|
|
1127
|
+
finish(null, fileBuffer.length);
|
|
1128
|
+
}
|
|
1129
|
+
});
|
|
1130
|
+
});
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
// 权限不足 → fallback: 写入 /tmp 再用 shell mv
|
|
1134
|
+
if (err.message.includes('Permission denied') || err.message.includes('permission')) {
|
|
1135
|
+
const tmpPath = `/tmp/.aicmd_upload_${Date.now()}`;
|
|
1136
|
+
console.log(`[SSH] Permission denied on ${fullPath}, falling back to ${tmpPath} + mv`);
|
|
1137
|
+
doSftpWrite(tmpPath, async (tmpErr) => {
|
|
1138
|
+
if (done)
|
|
1139
|
+
return;
|
|
1140
|
+
if (tmpErr) {
|
|
1141
|
+
finish(new Error('SFTP fallback write failed: ' + tmpErr.message));
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1144
|
+
// 通过已有 shell stream 执行 mv(避免 exec channel 挂起)
|
|
1145
|
+
try {
|
|
1146
|
+
const mvCmd = `mv -f '${tmpPath}' '${fullPath}'`;
|
|
1147
|
+
console.log(`[SSH] Shell exec: ${mvCmd}`);
|
|
1148
|
+
const mvMarker = `__AICmd_MV_${Date.now()}__`;
|
|
1149
|
+
const captureP = this.captureOutput(sessionId, 5000);
|
|
1150
|
+
this.writeData(sessionId, `${mvCmd} && echo ${mvMarker}:OK || echo ${mvMarker}:FAIL\n`);
|
|
1151
|
+
const mvOutput = await captureP;
|
|
1152
|
+
console.log(`[SSH] mv output: ${JSON.stringify(mvOutput.substring(0, 200))}`);
|
|
1153
|
+
if (mvOutput.includes(`${mvMarker}:OK`)) {
|
|
1154
|
+
console.log(`[SSH] SFTP upload via mv: ${fullPath} (${fileBuffer.length} bytes)`);
|
|
1155
|
+
finish(null, fileBuffer.length);
|
|
1156
|
+
return;
|
|
1157
|
+
}
|
|
1158
|
+
// mv 失败,尝试 sudo mv
|
|
1159
|
+
console.log(`[SSH] mv failed, trying sudo mv...`);
|
|
1160
|
+
const sudoMarker = `__AICmd_SUDO_${Date.now()}__`;
|
|
1161
|
+
const sudoCaptureP = this.captureOutput(sessionId, 5000);
|
|
1162
|
+
this.writeData(sessionId, `sudo mv -f '${tmpPath}' '${fullPath}' && echo ${sudoMarker}:OK || echo ${sudoMarker}:FAIL\n`);
|
|
1163
|
+
const sudoOutput = await sudoCaptureP;
|
|
1164
|
+
console.log(`[SSH] sudo mv output: ${JSON.stringify(sudoOutput.substring(0, 200))}`);
|
|
1165
|
+
if (sudoOutput.includes(`${sudoMarker}:OK`)) {
|
|
1166
|
+
console.log(`[SSH] SFTP upload via sudo mv: ${fullPath} (${fileBuffer.length} bytes)`);
|
|
1167
|
+
finish(null, fileBuffer.length);
|
|
1168
|
+
}
|
|
1169
|
+
else {
|
|
1170
|
+
finish(new Error(`Upload failed: cannot write to ${fullPath}`));
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
catch (mvErr) {
|
|
1174
|
+
finish(new Error('Shell mv failed: ' + mvErr.message));
|
|
1175
|
+
}
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
else {
|
|
1179
|
+
finish(err);
|
|
1180
|
+
}
|
|
1181
|
+
});
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
// ========== 定时清理僵尸 Session ==========
|
|
1185
|
+
/**
|
|
1186
|
+
* 启动定时清理任务(每 30 秒执行一次)
|
|
1187
|
+
* 清理磁盘上存在但进程已不存在的 session 元数据
|
|
1188
|
+
* 仅在本实例曾创建过 session 时才执行(避免渲染进程实例误删主进程的数据)
|
|
1189
|
+
*/
|
|
1190
|
+
startPeriodicCleanup() {
|
|
1191
|
+
const CLEANUP_INTERVAL = 30000; // 30 秒
|
|
1192
|
+
this.cleanupTimer = setInterval(() => {
|
|
1193
|
+
try {
|
|
1194
|
+
this.cleanupZombieSessions();
|
|
1195
|
+
}
|
|
1196
|
+
catch (e) {
|
|
1197
|
+
console.error('[SSH] Periodic cleanup error:', e);
|
|
1198
|
+
}
|
|
1199
|
+
}, CLEANUP_INTERVAL);
|
|
1200
|
+
// 避免定时器阻止 Node.js 进程正常退出
|
|
1201
|
+
if (this.cleanupTimer && typeof this.cleanupTimer === 'object' && 'unref' in this.cleanupTimer) {
|
|
1202
|
+
this.cleanupTimer.unref();
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
/**
|
|
1206
|
+
* 清理僵尸 session:从磁盘重新加载,移除进程已不存在的条目
|
|
1207
|
+
*/
|
|
1208
|
+
cleanupZombieSessions() {
|
|
1209
|
+
// 仅当本实例曾创建过 session 时才执行清理(主进程实例)
|
|
1210
|
+
// 渲染进程实例从不创建 session(创建通过 IPC 在主进程完成),跳过以避免误删
|
|
1211
|
+
if (!this.hasCreatedSession)
|
|
1212
|
+
return;
|
|
1213
|
+
// 从磁盘重新加载最新状态
|
|
1214
|
+
this.loadSessionsFromDisk();
|
|
1215
|
+
// 找出磁盘上有但进程已不存在的 session
|
|
1216
|
+
const toRemove = [];
|
|
1217
|
+
for (const sid of this.sessionMetadata.keys()) {
|
|
1218
|
+
if (!this.sessions.has(sid)) {
|
|
1219
|
+
toRemove.push(sid);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
if (toRemove.length > 0) {
|
|
1223
|
+
for (const sid of toRemove) {
|
|
1224
|
+
this.sessionMetadata.delete(sid);
|
|
1225
|
+
}
|
|
1226
|
+
this.saveSessionsToDisk();
|
|
1227
|
+
console.log(`[SSH] Periodic cleanup: removed ${toRemove.length} zombie session(s): ${toRemove.join(', ')}`);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* 停止定时清理(应用退出时调用)
|
|
1232
|
+
*/
|
|
1233
|
+
destroy() {
|
|
1234
|
+
if (this.cleanupTimer) {
|
|
1235
|
+
clearInterval(this.cleanupTimer);
|
|
1236
|
+
this.cleanupTimer = null;
|
|
1237
|
+
}
|
|
1238
|
+
this.closeAllSessions();
|
|
1239
|
+
}
|
|
830
1240
|
/**
|
|
831
1241
|
* 获取活跃会话数量
|
|
832
1242
|
*/
|