dsh-ops-kit 0.4.1 → 0.4.2

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
@@ -8,7 +8,7 @@
8
8
  **English** | [简体中文](README.zh-CN.md)
9
9
 
10
10
  Server operations from a DeepSeek Harness chat: **34 tools plus a sidebar panel**,
11
- no SDK, and no credentials stored by the plugin.
11
+ no SDK, and no credentials stored by default (key auth).
12
12
 
13
13
  ## Install
14
14
 
@@ -25,7 +25,7 @@ on the servers you manage — the plugin works over SSH.
25
25
  Upgrading: `dsh plugin --profile <profile> add dsh-ops-kit@latest`, or use the
26
26
  plugin market's update button.
27
27
 
28
- no SDK, and no credentials stored by the plugin.
28
+ no SDK, and no credentials stored by default (key auth).
29
29
 
30
30
  🔒 marks an action that needs `confirm: true` — the tool fails closed instead of
31
31
  asking in a second turn.
@@ -98,8 +98,11 @@ asking in a second turn.
98
98
 
99
99
  - **No SDK, no credential storage by default.** Key authentication goes through
100
100
  the system `ssh` client in `BatchMode`, so the plugin never reads your keys.
101
- Password authentication uses the plugin's own `ssh2` client and is the only
102
- case where a secret is stored (see below).
101
+ Password authentication uses the plugin's own `ssh2` client: the password goes
102
+ to the **system keychain** (macOS `security`, Linux `secret-tool`). Only when
103
+ neither exists does it fall back to a 0600 file whose content is base64 —
104
+ obfuscation, not encryption. Passwords also stay off command lines (MySQL
105
+ dumps/restores read them over stdin).
103
106
  - **Password or key.** A host can be added with only IP + user + password; that
104
107
  path needs `ssh2` present in the profile. A host without a stored password
105
108
  uses the system `ssh` client and your keys or agent.
package/README.zh-CN.md CHANGED
@@ -95,7 +95,9 @@ dsh plugin --profile <你的 profile> add dsh-ops-kit
95
95
  ## 设计取向
96
96
 
97
97
  - **无 SDK,默认不存凭据。** 密钥认证走系统 `ssh` 客户端(`BatchMode`),插件完全
98
- 不读你的密钥文件。密码认证走插件自带的 `ssh2` 客户端,也是唯一会落盘密钥的场景。
98
+ 不读你的密钥文件。若用密码认证,密码优先存进**系统钥匙串**(macOS `security`、
99
+ Linux `secret-tool`);两者都没有时才退回 0600 文件,且文件里是 base64 编码,
100
+ 只是混淆不是加密。数据库备份/恢复的密码经 stdin 传入,不出现在命令行。
99
101
  - **密码或密钥皆可。** 只填 IP + 用户名 + 密码就能添加主机;这条路径要求该 profile
100
102
  里已有 `ssh2`。没有存密码的主机则走系统 `ssh` 和你的密钥 / agent。
101
103
  - **清单放在 profile 之外。** 主机信息存在 `$DSH_HOME/ops-kit/hosts.json`
package/client.js CHANGED
@@ -391,16 +391,6 @@ window.__ModuleLoader__.load({
391
391
  .ops-copy:hover{color:var(--dsw-alias-text-primary,#e6e6e6)}
392
392
  .ops-progress{height:6px;border-radius:3px;background:rgba(255,255,255,.08);overflow:hidden;margin-top:6px}
393
393
  .ops-progress i{display:block;height:100%;background:var(--dsw-alias-accent,#4c8dff);transition:width .2s}
394
- .ops-logbox{width:100%;box-sizing:border-box;min-height:220px;max-height:58vh;overflow-y:auto;overflow-x:hidden;background:#0b0e11;border-radius:8px;padding:10px 12px;font-family:ui-monospace,Menlo,monospace;font-size:12px;line-height:1.55;white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}
395
- .ops-busy{text-align:center;padding:26px 18px}
396
- .ops-spinner{width:26px;height:26px;margin:0 auto;border-radius:50%;border:3px solid var(--dsw-alias-border,#3a3f45);border-top-color:var(--dsw-alias-accent,#4c8dff);animation:ops-spin .8s linear infinite}
397
- @keyframes ops-spin{to{transform:rotate(360deg)}}
398
- .ops-log-fold{margin:2px 0 4px 10px;border:0;background:transparent;color:var(--dsw-alias-text-secondary,#9aa0a6);font-size:11px;cursor:pointer;padding:0}
399
- .ops-log-fold:hover{color:var(--dsw-alias-accent,#4c8dff)}
400
- .ops-log-frames{border-left:2px solid var(--dsw-alias-border,#3a3f45);margin:2px 0 6px 12px;padding-left:10px;opacity:.8}
401
- .ops-log-err{color:#ff6b6b}
402
- .ops-log-warn{color:#e5b650}
403
- .ops-chart-tip{position:absolute;top:4px;background:var(--dsw-alias-surface,#1d2126);border:1px solid var(--dsw-alias-border,#3a3f45);border-radius:8px;padding:6px 8px;pointer-events:none;z-index:5;white-space:nowrap;box-shadow:0 6px 18px rgba(0,0,0,.35)}
404
394
  .ops-dot.warn{background:#f0b232}
405
395
  .ops-dot.unknown{background:#6b7280}
406
396
  .ops-fm{display:flex;gap:12px;align-items:flex-start}
@@ -426,6 +416,16 @@ window.__ModuleLoader__.load({
426
416
  .ops-modal-x{border:0;background:transparent;color:var(--dsw-alias-text-secondary,#9aa0a6);font-size:18px;cursor:pointer;line-height:1}
427
417
  .ops-modal-row{display:flex;gap:10px;font-size:13px;line-height:1.7;padding:3px 0}
428
418
  .ops-modal-row b{min-width:64px;color:var(--dsw-alias-text-secondary,#9aa0a6);font-weight:500}
419
+ .ops-details{display:grid;gap:4px;margin:0 0 10px;font-size:12px}
420
+ .ops-details>div{display:flex;gap:10px}
421
+ .ops-details dt{min-width:64px;color:var(--dsw-alias-text-secondary,#9aa0a6);margin:0}
422
+ .ops-details dd{margin:0;word-break:break-all}
423
+ .ops-btn-danger{background:var(--dsw-alias-danger,#ff6b6b);border-color:var(--dsw-alias-danger,#ff6b6b);color:#fff}
424
+ .ops-errbar{display:flex;align-items:flex-start;gap:10px;border:1px solid var(--dsw-alias-danger,#ff6b6b);background:rgba(255,107,107,.08);border-radius:8px;padding:8px 10px;font-size:12px;line-height:1.6}
425
+ .ops-jobs{position:fixed;right:18px;bottom:18px;z-index:50;display:flex;flex-direction:column;gap:8px;width:min(360px,calc(100vw - 36px))}
426
+ .ops-jobs-item{border:1px solid var(--dsw-alias-border,#3a3f45);background:var(--dsw-alias-surface,#1d2126);border-radius:10px;padding:10px 12px;box-shadow:0 8px 24px rgba(0,0,0,.25)}
427
+ .ops-jobs-item.failed{border-color:var(--dsw-alias-danger,#ff6b6b)}
428
+ .ops-spinner-sm{width:14px;height:14px;border-width:2px;margin:0;flex:none}
429
429
  .ops-result-ok{color:#3fbf7f;font-weight:600}
430
430
  .ops-result-bad{color:#ff6b6b;font-weight:600}
431
431
  .ops-composer{display:flex;gap:8px;align-items:flex-end;padding:10px 14px;border-top:1px solid var(--dsw-alias-border,#3a3f45)}
@@ -448,7 +448,10 @@ window.__ModuleLoader__.load({
448
448
  const text = await response.text()
449
449
  let body
450
450
  try { body = JSON.parse(text) } catch { body = { error: text.slice(0, 300) } }
451
- if (!response.ok) throw new Error(body?.error || `HTTP ${response.status}`)
451
+ if (!response.ok) {
452
+ const hint = body?.hint ? `(${body.hint})` : ''
453
+ throw new Error((body?.error || `HTTP ${response.status}`) + hint)
454
+ }
452
455
  return body
453
456
  } catch (e) {
454
457
  if (e && e.name === 'AbortError') throw new Error(`请求超时(${Math.round(timeoutMs / 1000)}s):服务器响应太慢,稍后重试`)
@@ -470,23 +473,41 @@ window.__ModuleLoader__.load({
470
473
  h('circle', { cx: 6.5, cy: 17, r: 0.9, fill: 'currentColor' }))
471
474
  }
472
475
 
473
- const PORT_PURPOSE = {
474
- 22: '远程管理', 80: '网站', 443: '网站(加密)', 3306: '数据库 MySQL', 33060: '数据库 MySQL',
475
- 6379: '缓存 Redis', 8888: '宝塔面板', 8080: 'Java 服务', 25: '邮件', 111: '系统服务',
476
- 27017: '数据库 MongoDB', 5432: '数据库 PostgreSQL', 9200: '搜索 Elasticsearch',
477
- }
478
- const SERVICE_NAME = {
479
- 'nginx.service': '网站服务(Nginx)',
480
- 'mysqld.service': '数据库(MySQL)',
481
- 'redis.service': '缓存(Redis)',
482
- 'sshd.service': '远程登录',
483
- 'crond.service': '定时任务',
484
- 'firewalld.service': '防火墙',
485
- 'docker.service': '容器引擎',
486
- 'scorepocket.service': '业务应用',
487
- 'site_total.service': '业务应用',
488
- }
489
- const purposeOf = (row) => PORT_PURPOSE[row.port] || (row.process ? row.process : '未知')
476
+ const PORT_PURPOSE = zh
477
+ ? {
478
+ 22: '远程管理', 80: '网站', 443: '网站(加密)', 3306: '数据库 MySQL', 33060: '数据库 MySQL',
479
+ 6379: '缓存 Redis', 8888: '宝塔面板', 8080: 'Java 服务', 25: '邮件', 111: '系统服务',
480
+ 27017: '数据库 MongoDB', 5432: '数据库 PostgreSQL', 9200: '搜索 Elasticsearch',
481
+ }
482
+ : {
483
+ 22: 'Remote admin', 80: 'Web', 443: 'Web (TLS)', 3306: 'MySQL', 33060: 'MySQL',
484
+ 6379: 'Redis', 8888: 'BT panel', 8080: 'Java service', 25: 'Mail', 111: 'rpcbind',
485
+ 27017: 'MongoDB', 5432: 'PostgreSQL', 9200: 'Elasticsearch',
486
+ }
487
+ const SERVICE_NAME = zh
488
+ ? {
489
+ 'nginx.service': '网站服务(Nginx)',
490
+ 'mysqld.service': '数据库(MySQL)',
491
+ 'redis.service': '缓存(Redis)',
492
+ 'sshd.service': '远程登录',
493
+ 'crond.service': '定时任务',
494
+ 'firewalld.service': '防火墙',
495
+ 'docker.service': '容器引擎',
496
+ 'scorepocket.service': '业务应用',
497
+ 'site_total.service': '业务应用',
498
+ }
499
+ : {
500
+ 'nginx.service': 'Web (Nginx)',
501
+ 'mysqld.service': 'Database (MySQL)',
502
+ 'redis.service': 'Cache (Redis)',
503
+ 'sshd.service': 'SSH',
504
+ 'crond.service': 'Cron',
505
+ 'firewalld.service': 'Firewall',
506
+ 'docker.service': 'Docker',
507
+ 'scorepocket.service': 'App',
508
+ 'site_total.service': 'App',
509
+ }
510
+ const purposeOf = (row) => PORT_PURPOSE[row.port] || (row.process ? row.process : (zh ? '未知' : 'unknown'))
490
511
  const serviceLabel = (name) => SERVICE_NAME[name] || String(name).replace(/\.service$/, '')
491
512
 
492
513
  /** Strip ANSI escapes so a PTY stream reads as plain text in a <pre>. */
@@ -730,7 +751,7 @@ window.__ModuleLoader__.load({
730
751
  const [health, setHealth] = React.useState(null)
731
752
  const [certs, setCerts] = React.useState([])
732
753
  const [backups, setBackups] = React.useState([])
733
- const [backupForm, setBackupForm] = React.useState({ type: 'mysql', database: '', path: '/etc/nginx', dir: '/home/backup', keep: 7 })
754
+ const [backupForm, setBackupForm] = React.useState({ type: 'mysql', database: '', user: 'root', password: '', path: '/etc/nginx', dir: '/home/backup', keep: 7 })
734
755
  const [cronJobs, setCronJobs] = React.useState([])
735
756
  const [cronForm, setCronForm] = React.useState({ frequency: 'daily', hour: '3', minute: '0', command: '' })
736
757
  const [deployJobs, setDeployJobs] = React.useState([])
@@ -755,6 +776,22 @@ window.__ModuleLoader__.load({
755
776
  const [fsFavs, setFsFavs] = React.useState({ favs: [], recents: [] })
756
777
  const [fsBusy, setFsBusy] = React.useState('')
757
778
  const [adding, setAdding] = React.useState(false)
779
+ const [confirmState, setConfirmState] = React.useState(null)
780
+ const [taskJobs, setTaskJobs] = React.useState([])
781
+ const taskJobsRef = React.useRef(taskJobs)
782
+ React.useEffect(() => { taskJobsRef.current = taskJobs }, [taskJobs])
783
+ const anyJobRunning = taskJobs.some(job => job.status === 'running')
784
+
785
+ /** Promise 版确认框,替代会阻塞渲染的 window.confirm。 */
786
+ const confirmDialog = React.useCallback((options = {}) => new Promise((resolve) => {
787
+ setConfirmState({ ...options, value: '', resolve })
788
+ }), [])
789
+
790
+ const trackJob = React.useCallback((snapshot) => {
791
+ if (!snapshot || !snapshot.id) return null
792
+ setTaskJobs(list => [...list.filter(job => job.id !== snapshot.id), { ...snapshot, title: snapshot.label || '任务' }])
793
+ return snapshot
794
+ }, [])
758
795
 
759
796
  const loadBase = React.useCallback(async () => {
760
797
  try {
@@ -774,6 +811,43 @@ window.__ModuleLoader__.load({
774
811
 
775
812
  React.useEffect(() => { void loadBase() }, [loadBase])
776
813
 
814
+ // 后台任务(备份/恢复/清理/发布)每 2 秒问一次进度,不阻塞界面。
815
+ React.useEffect(() => {
816
+ if (!anyJobRunning) return
817
+ let alive = true
818
+ const tick = async () => {
819
+ const running = taskJobsRef.current.filter(job => job.status === 'running')
820
+ for (const job of running) {
821
+ try {
822
+ const data = await api(`job?id=${encodeURIComponent(job.id)}`, {}, 15_000)
823
+ if (!alive) return
824
+ setTaskJobs(list => list.map(item => item.id === job.id ? { ...item, ...data } : item))
825
+ if (data.status === 'done') {
826
+ setNotice(`${job.label || '任务'} 已完成`)
827
+ if (job.kind === 'backup' || job.kind === 'restore') void loadBackups(job.host)
828
+ if (job.kind === 'deploy') void loadDeploys(job.host)
829
+ } else if (data.status === 'failed') {
830
+ setError(`${job.label || '任务'} 失败:${data.error || '未知错误'}`)
831
+ }
832
+ } catch { /* 下一轮再试 */ }
833
+ }
834
+ }
835
+ const timer = setInterval(() => { void tick() }, 2000)
836
+ return () => { alive = false; clearInterval(timer) }
837
+ }, [anyJobRunning])
838
+
839
+ React.useEffect(() => {
840
+ const onKey = (event) => {
841
+ if (event.key !== 'Escape') return
842
+ if (confirmState) { confirmState.resolve(false); setConfirmState(null); return }
843
+ if (fsEdit) { setFsEdit(null); return }
844
+ if (fsPreview) { setFsPreview(null); return }
845
+ if (cleanPreview) { setCleanPreview(null); return }
846
+ }
847
+ window.addEventListener('keydown', onKey)
848
+ return () => window.removeEventListener('keydown', onKey)
849
+ }, [confirmState, fsEdit, fsPreview, cleanPreview])
850
+
777
851
  const timeoutFor = (kind) => {
778
852
  const sec = kind === 'scan'
779
853
  ? (config.scanSec ?? 90)
@@ -816,7 +890,8 @@ window.__ModuleLoader__.load({
816
890
  }
817
891
 
818
892
  const killPid = async (pid) => {
819
- if (!window.confirm(`${T.confirmKill} PID ${pid}`)) return
893
+ const ok = await confirmDialog({ title: T.end, message: `${T.confirmKill} PID ${pid}?`, danger: true })
894
+ if (!ok) return
820
895
  setBusy('kill:' + pid)
821
896
  try {
822
897
  const data = await api('kill', { method: 'POST', body: JSON.stringify({ host: cHost || hosts[0]?.name, pid, signal: 'TERM', confirm: true }) }, timeoutFor('action'))
@@ -985,7 +1060,8 @@ window.__ModuleLoader__.load({
985
1060
  }
986
1061
 
987
1062
  const fsDelete = async (path) => {
988
- if (!window.confirm(`${T.confirmDel} ${path}`)) return
1063
+ const ok = await confirmDialog({ title: T.fsDelete, message: `${T.confirmDel} ${path}?`, details: [{ k: '路径', v: path }], danger: true })
1064
+ if (!ok) return
989
1065
  setFsBusy('del:' + path)
990
1066
  try {
991
1067
  await api('fs', { method: 'POST', body: JSON.stringify({ host: cHost || hosts[0]?.name, action: 'delete', path, confirm: true }) }, timeoutFor('action'))
@@ -993,6 +1069,18 @@ window.__ModuleLoader__.load({
993
1069
  } catch (e) { setError(String(e.message || e)) } finally { setFsBusy('') }
994
1070
  }
995
1071
 
1072
+ const fsDeleteSelected = async () => {
1073
+ const paths = selectedPaths()
1074
+ if (!paths.length) return
1075
+ const ok = await confirmDialog({ title: T.fsDelete, message: `${T.confirmDel} ${paths.length} 项?`, details: paths.slice(0, 8).map(item => ({ k: '路径', v: item })), danger: true })
1076
+ if (!ok) return
1077
+ setFsBusy('del')
1078
+ try {
1079
+ await api('fs', { method: 'POST', body: JSON.stringify({ host: cHost || hosts[0]?.name, action: 'delete', paths, confirm: true }) }, timeoutFor('action'))
1080
+ setFsSelSet({}); setFsSel(null); await loadFiles(fsPath)
1081
+ } catch (e) { setError(String(e.message || e)) } finally { setFsBusy('') }
1082
+ }
1083
+
996
1084
  const loadTree = async (path) => {
997
1085
  try {
998
1086
  const data = await api(`files?host=${encodeURIComponent(cHost || hosts[0]?.name)}&dirs=1&path=${encodeURIComponent(path)}`, {}, timeoutFor('action'))
@@ -1135,14 +1223,27 @@ window.__ModuleLoader__.load({
1135
1223
  } catch (e) { setError(String(e.message || e)) } finally { setBusy('') }
1136
1224
  }
1137
1225
 
1138
- const runConsole = async () => {
1226
+ const runConsole = async (options = {}) => {
1139
1227
  const command = consoleCmd.trim()
1140
1228
  if (!command) return
1141
1229
  setBusy('console')
1142
1230
  try {
1143
- const data = await api('exec', { method: 'POST', body: JSON.stringify({ command, hosts: [cHost || hosts[0]?.name] }) }, timeoutFor('action'))
1231
+ const payload = { command, hosts: [cHost || hosts[0]?.name] }
1232
+ if (options.confirm) payload.confirm = true
1233
+ const data = await api('exec', { method: 'POST', body: JSON.stringify(payload) }, timeoutFor('action'))
1234
+ if (data?.needsConfirm) {
1235
+ const ok = await confirmDialog({
1236
+ title: '这条命令会改动服务器',
1237
+ message: (data.reasons || []).join(';') || '命令可能造成不可逆的破坏,确认后才会执行。',
1238
+ details: [{ k: '命令', v: command }],
1239
+ okText: '仍然执行',
1240
+ danger: true,
1241
+ })
1242
+ if (ok) await runConsole({ confirm: true })
1243
+ return
1244
+ }
1144
1245
  const row = (data.results || [])[0]
1145
- setConsoleOut(row ? (row.ok ? row.stdout || '(no output)' : `exit ${row.code}\n${row.stderr || ''}`) : 'no result')
1246
+ setConsoleOut(row ? (row.ok ? row.stdout || '(no output)' : `exit ${row.code}\n${row.stderr || ''}${row.hint ? '\n\n建议:' + row.hint : ''}`) : 'no result')
1146
1247
  setConsoleHistory([command, ...consoleHistory.filter(item => item !== command)].slice(0, 20))
1147
1248
  } catch (e) { setConsoleOut(String(e.message || e)) } finally { setBusy('') }
1148
1249
  }
@@ -1312,25 +1413,33 @@ window.__ModuleLoader__.load({
1312
1413
  }, [detailHost, detailTab, cHost, hosts, loadInv])
1313
1414
 
1314
1415
  const doAction = async (kind, name, action, hostOverride) => {
1315
- if (action !== 'logs' && !window.confirm(`${action} ${name}?`)) return
1416
+ if (action !== 'logs') {
1417
+ const ok = await confirmDialog({ title: action === 'restart' ? T.restart : action, message: `${T.end} ${name}?`, details: [{ k: T.name, v: name }, { k: '动作', v: action }], danger: true })
1418
+ if (!ok) return
1419
+ }
1316
1420
  const key = `act:${kind}:${name}:${action}`
1317
1421
  setBusy(key)
1318
1422
  setOutput(action === 'logs' ? T.reading : '…')
1319
1423
  try {
1320
1424
  const data = await api('app', { method: 'POST', body: JSON.stringify({ host: hostOverride || cHost || hosts[0]?.name, kind, name, action, confirm: true }) }, timeoutFor('action'))
1321
- setOutput(data.ok ? (data.stdout || data.stderr || 'ok') : (data.stderr || 'failed'))
1425
+ setOutput(data.ok ? (data.stdout || data.stderr || 'ok') : `${data.stderr || 'failed'}${data.hint ? '\n\n建议:' + data.hint : ''}`)
1322
1426
  } catch (e) { setOutput(String(e.message || e)) } finally { setBusy('') }
1323
1427
  }
1324
1428
 
1325
1429
  const cleanupHost = async (name) => {
1326
- if (!window.confirm(`${T.cleanup}:${name}\n${T.cleanDetail || ''}`)) return
1327
- setBusy('clean:' + name)
1328
- try {
1329
- const data = await api('cleanup', { method: 'POST', body: JSON.stringify({ host: name, confirm: true }) }, timeoutFor('action') * 2)
1330
- setNotice(data.ok ? `${T.freed} ${data.before}% → ${data.after}%` : (data.error || 'failed'))
1331
- if (uiMode === 'simple') setHostCtx(name, { phase: data.ok ? 'ok' : 'fail', message: data.ok ? `磁盘已从 ${data.before}% 降到 ${data.after}%` : (data.error || T.stillBad) })
1430
+ const ok = await confirmDialog({ title: T.cleanup, message: T.cleanDetail || `${T.cleanup}:${name}`, details: [{ k: T.name, v: name }], danger: true })
1431
+ if (!ok) return
1432
+ try {
1433
+ const data = await api('cleanup', { method: 'POST', body: JSON.stringify({ host: name, confirm: true }) }, 30_000)
1434
+ if (data?.job) {
1435
+ trackJob(data.job)
1436
+ setNotice('清理已在后台开始,完成后会提示')
1437
+ } else {
1438
+ setNotice(data.ok ? `${T.freed} ${data.before}% → ${data.after}%` : (data.error || 'failed'))
1439
+ if (uiMode === 'simple') setHostCtx(name, { phase: data.ok ? 'ok' : 'fail', message: data.ok ? `磁盘已从 ${data.before}% 降到 ${data.after}%` : (data.error || T.stillBad) })
1440
+ }
1332
1441
  setTimeout(() => setNotice(''), 4000)
1333
- } catch (e) { setError(String(e.message || e)) } finally { setBusy('') }
1442
+ } catch (e) { setError(String(e.message || e)) }
1334
1443
  }
1335
1444
 
1336
1445
  const openFile = async (path, appName) => {
@@ -1343,7 +1452,8 @@ window.__ModuleLoader__.load({
1343
1452
 
1344
1453
  const saveFile = async () => {
1345
1454
  if (!fileState) return
1346
- if (!window.confirm(`${T.saveFile}: ${fileState.path}?`)) return
1455
+ const ok = await confirmDialog({ title: T.saveFile, message: T.editHint, details: [{ k: '文件', v: fileState.path }] })
1456
+ if (!ok) return
1347
1457
  setFileState({ ...fileState, busy: true })
1348
1458
  try {
1349
1459
  const data = await api('file', { method: 'POST', body: JSON.stringify({ host: cHost || hosts[0]?.name, path: fileState.path, content: fileState.content, confirm: true }) }, timeoutFor('action') * 2)
@@ -1392,7 +1502,8 @@ window.__ModuleLoader__.load({
1392
1502
  }
1393
1503
 
1394
1504
  const removeHost = async (name) => {
1395
- if (!window.confirm(`remove ${name}?`)) return
1505
+ const ok = await confirmDialog({ title: T.remove, message: `${T.remove} ${name}?`, details: [{ k: T.name, v: name }], danger: true })
1506
+ if (!ok) return
1396
1507
  try { await api('hosts', { method: 'POST', body: JSON.stringify({ action: 'remove', name }) }); await loadBase() }
1397
1508
  catch (e) { setError(String(e.message || e)) }
1398
1509
  }
@@ -1669,7 +1780,8 @@ window.__ModuleLoader__.load({
1669
1780
  setNotice(T.contactDev)
1670
1781
  return
1671
1782
  }
1672
- if (!window.confirm(`${T.actionRestartWeb}?\n${T.actionRestartHint}`)) return
1783
+ const ok = await confirmDialog({ title: T.actionRestartWeb, message: T.actionRestartHint, danger: true })
1784
+ if (!ok) return
1673
1785
  setHostCtx(host.name, { phase: 'restarting', message: T.restarting })
1674
1786
  try {
1675
1787
  await api('service', { method: 'POST', body: JSON.stringify({ host: host.name, service: monitor.target, action: 'restart', confirm: true }) }, timeoutFor('action'))
@@ -2174,24 +2286,33 @@ window.__ModuleLoader__.load({
2174
2286
  try {
2175
2287
  const paths = selectedLogPaths()
2176
2288
  if (!paths.length && !cleanSel.journal) { setError(T.cleanNothingSelected); return }
2177
- const data = await api('cleanup', { method: 'POST', body: JSON.stringify({ host: cleanPreview.host, confirm: true, paths, includeJournal: cleanSel.journal }) }, timeoutFor('action') * 3)
2178
- setNotice(T.logCleanResult.replace('{0}', data.freedMb ?? 0).replace('{1}', data.before ?? '?').replace('{2}', data.after ?? '?'))
2289
+ const data = await api('cleanup', { method: 'POST', body: JSON.stringify({ host: cleanPreview.host, confirm: true, paths, includeJournal: cleanSel.journal }) }, 30_000)
2290
+ if (data?.job) {
2291
+ trackJob(data.job)
2292
+ setNotice('清理已在后台开始,完成后会提示')
2293
+ } else {
2294
+ setNotice(T.logCleanResult.replace('{0}', data.freedMb ?? 0).replace('{1}', data.before ?? '?').replace('{2}', data.after ?? '?'))
2295
+ }
2179
2296
  setTimeout(() => setNotice(''), 5000)
2180
2297
  setCleanPreview(null)
2181
- await loadLogUsage()
2182
2298
  } catch (e) { setError(String(e.message || e)) } finally { setCleanRunBusy(false) }
2183
2299
  }
2184
2300
 
2185
2301
  const cleanByPolicy = async () => {
2186
2302
  const keep = Number(config.logKeepDays) || 7
2187
2303
  const journal = Number(config.logJournalMb) || 200
2188
- if (!window.confirm(`${T.logCleanNow}?\n${T.logPolicy.replace('{0}', keep).replace('{1}', journal)}`)) return
2304
+ const ok = await confirmDialog({ title: T.logCleanNow, message: T.logPolicy.replace('{0}', keep).replace('{1}', journal), details: [{ k: '保留天数', v: `${keep} 天` }, { k: 'journal 上限', v: `${journal} MB` }], danger: true })
2305
+ if (!ok) return
2189
2306
  setLogPolicyBusy(true)
2190
2307
  try {
2191
- const data = await api('cleanup', { method: 'POST', body: JSON.stringify({ host: cHost || hosts[0]?.name, confirm: true }) }, timeoutFor('action') * 3)
2192
- setNotice(T.logCleanResult.replace('{0}', data.freedMb ?? 0).replace('{1}', data.before ?? '?').replace('{2}', data.after ?? '?'))
2308
+ const data = await api('cleanup', { method: 'POST', body: JSON.stringify({ host: cHost || hosts[0]?.name, confirm: true }) }, 30_000)
2309
+ if (data?.job) {
2310
+ trackJob(data.job)
2311
+ setNotice('清理已在后台开始,完成后会提示')
2312
+ } else {
2313
+ setNotice(T.logCleanResult.replace('{0}', data.freedMb ?? 0).replace('{1}', data.before ?? '?').replace('{2}', data.after ?? '?'))
2314
+ }
2193
2315
  setTimeout(() => setNotice(''), 5000)
2194
- await loadLogUsage()
2195
2316
  } catch (e) { setError(String(e.message || e)) } finally { setLogPolicyBusy(false) }
2196
2317
  }
2197
2318
 
@@ -2379,7 +2500,8 @@ const termKey = (event) => {
2379
2500
  }
2380
2501
 
2381
2502
  const removeChannelUi = async (id) => {
2382
- if (!window.confirm(T.channelRemove + '?')) return
2503
+ const ok = await confirmDialog({ title: T.channelRemove, message: T.channelRemove + '?', danger: true })
2504
+ if (!ok) return
2383
2505
  try {
2384
2506
  const data = await api('channels', { method: 'POST', body: JSON.stringify({ action: 'remove', id }) })
2385
2507
  setChannels(data.channels || [])
@@ -2423,24 +2545,47 @@ const termKey = (event) => {
2423
2545
  setOpOut('')
2424
2546
  try {
2425
2547
  const payload = { host: dhost(), ...backupForm, keep: Number(backupForm.keep) || 7 }
2426
- const record = await api('backups', { method: 'POST', body: JSON.stringify(payload) }, 25 * 60_000)
2427
- setOpOut(record.ok ? `备份完成:${record.file}(${(record.size / 1024).toFixed(0)} KB,${(record.ms / 1000).toFixed(1)}s)` : `备份失败:${record.error}`)
2428
- await loadBackups(dhost())
2548
+ const data = await api('backups', { method: 'POST', body: JSON.stringify(payload) }, 30_000)
2549
+ if (data?.job) {
2550
+ trackJob(data.job)
2551
+ setOpOut('备份已在后台开始,可继续操作;完成后右下角会提示。')
2552
+ } else {
2553
+ setOpOut(data.ok ? `备份完成:${data.file}(${(data.size / 1024).toFixed(0)} KB)` : `备份失败:${data.error}`)
2554
+ await loadBackups(dhost())
2555
+ }
2429
2556
  } catch (e) { setError(String(e.message || e)) } finally { setOpBusy('') }
2430
2557
  }
2431
2558
 
2432
2559
  const restoreBackupNow = async (id) => {
2433
- if (!window.confirm(T.restoreWarn)) return
2560
+ const record = (backups || []).find(item => item.id === id)
2561
+ const details = record ? [
2562
+ { k: '目标', v: record.type === 'mysql' ? `数据库 ${record.target}` : record.target },
2563
+ { k: '备份时间', v: fmt(record.at) },
2564
+ { k: '大小', v: record.size ? `${(record.size / 1048576).toFixed(1)} MB` : '未知' },
2565
+ { k: '文件', v: record.file },
2566
+ ] : [{ k: '备份', v: id }]
2567
+ const answer = await confirmDialog({
2568
+ title: T.backupRestore,
2569
+ message: `${T.restoreWarn} 恢复前会自动保存一份 pre-restore 快照。`,
2570
+ details,
2571
+ okText: T.backupRestore,
2572
+ danger: true,
2573
+ ...(record && record.type === 'mysql' ? { prompt: 'MySQL 密码(没密码留空)', secret: true } : {}),
2574
+ })
2575
+ if (!answer && answer !== '') return
2434
2576
  setOpBusy('restore:' + id)
2435
2577
  try {
2436
- const data = await api('backups', { method: 'POST', body: JSON.stringify({ host: dhost(), action: 'restore', id }) }, 25 * 60_000)
2437
- setOpOut(data.ok ? '恢复完成' : `恢复失败:${data.output}`)
2438
- await loadBackups(dhost())
2578
+ const body = { host: dhost(), action: 'restore', id }
2579
+ if (record && record.type === 'mysql') { body.password = String(answer); body.user = record.user || '' }
2580
+ const data = await api('backups', { method: 'POST', body: JSON.stringify(body) }, 30_000)
2581
+ if (data?.job) { trackJob(data.job); setOpOut('恢复已在后台开始,可继续操作') }
2582
+ else setOpOut(data.ok ? '恢复完成' : `恢复失败:${data.output}`)
2439
2583
  } catch (e) { setError(String(e.message || e)) } finally { setOpBusy('') }
2440
2584
  }
2441
2585
 
2442
2586
  const removeBackupNow = async (id) => {
2443
- if (!window.confirm('删除这条备份?')) return
2587
+ const ok = await confirmDialog({ title: T.backupRemove, message: '删除这条备份?备份文件会从服务器上移除。', details: [{ k: '备份', v: id }], danger: true })
2588
+ if (!ok) return
2444
2589
  try {
2445
2590
  const data = await api('backups', { method: 'POST', body: JSON.stringify({ host: dhost(), action: 'remove', id }) }, 60_000)
2446
2591
  setBackups(data.backups || [])
@@ -2496,9 +2641,14 @@ const termKey = (event) => {
2496
2641
  setOpBusy('deploy:' + id)
2497
2642
  setOpOut('')
2498
2643
  try {
2499
- const data = await api('deploy', { method: 'POST', body: JSON.stringify({ host: dhost(), action: 'run', id }) }, 30 * 60_000)
2500
- setOpOut((data.ok ? '发布成功' : `发布失败:${data.error || ''}${data.rolledBack ? '(已回滚)' : ''}`)
2501
- + '\n' + (data.steps || []).map(step => `[${step.ok ? '✓' : '✗'}] ${step.label}\n${step.output}`).join('\n\n'))
2644
+ const data = await api('deploy', { method: 'POST', body: JSON.stringify({ host: dhost(), action: 'run', id }) }, 30_000)
2645
+ if (data?.job) {
2646
+ trackJob(data.job)
2647
+ setOpOut('发布已在后台开始,可继续操作;完成后右下角会提示。')
2648
+ } else {
2649
+ setOpOut((data.ok ? '发布成功' : `发布失败:${data.error || ''}${data.rolledBack ? '(已回滚)' : ''}`)
2650
+ + '\n' + (data.steps || []).map(step => `[${step.ok ? '✓' : '✗'}] ${step.label}\n${step.output}`).join('\n\n'))
2651
+ }
2502
2652
  } catch (e) { setError(String(e.message || e)) } finally { setOpBusy('') }
2503
2653
  }
2504
2654
 
@@ -2520,7 +2670,8 @@ const termKey = (event) => {
2520
2670
  }
2521
2671
 
2522
2672
  const restoreVersion = async (backup) => {
2523
- if (!window.confirm(`${T.fileRestore}?`)) return
2673
+ const ok = await confirmDialog({ title: T.fileRestore, message: `${T.fileRestore}?`, details: [{ k: '文件', v: histPath.trim() }, { k: '版本', v: backup }], danger: true })
2674
+ if (!ok) return
2524
2675
  try {
2525
2676
  const data = await api('file-history', { method: 'POST', body: JSON.stringify({ host: dhost(), path: histPath.trim(), action: 'restore', backup }) }, 60_000)
2526
2677
  setNotice(data.ok ? '已回滚' : '回滚失败')
@@ -2561,7 +2712,8 @@ const termKey = (event) => {
2561
2712
  }
2562
2713
 
2563
2714
  const removeServiceUi = async (id) => {
2564
- if (!window.confirm(T.serviceRemove + '?')) return
2715
+ const ok = await confirmDialog({ title: T.serviceRemove, message: T.serviceRemove + '?', danger: true })
2716
+ if (!ok) return
2565
2717
  try {
2566
2718
  const data = await api('services', { method: 'POST', body: JSON.stringify({ host: dhost(), action: 'remove', id }) }, 20_000)
2567
2719
  setServices(data.services || [])
@@ -2621,7 +2773,8 @@ const termKey = (event) => {
2621
2773
 
2622
2774
  const removeTemplateUi = async () => {
2623
2775
  if (!templateId) return
2624
- if (!window.confirm(T.templateDelete + '?')) return
2776
+ const ok = await confirmDialog({ title: T.templateDelete, message: T.templateDelete + '?', danger: true })
2777
+ if (!ok) return
2625
2778
  try {
2626
2779
  const data = await api('templates', { method: 'POST', body: JSON.stringify({ action: 'remove', id: templateId }) }, 20_000)
2627
2780
  setTemplates(data.templates || [])
@@ -2688,7 +2841,8 @@ const termKey = (event) => {
2688
2841
  }
2689
2842
 
2690
2843
  const removeMonitor = async (id) => {
2691
- if (!window.confirm(T.monRemove + '?')) return
2844
+ const ok = await confirmDialog({ title: T.monRemove, message: T.monRemove + '?', danger: true })
2845
+ if (!ok) return
2692
2846
  try {
2693
2847
  const data = await api('monitors', { method: 'POST', body: JSON.stringify({ host: detailHost || cHost, action: 'remove', id }) })
2694
2848
  setMonitors(data.monitors || [])
@@ -2758,7 +2912,10 @@ const termKey = (event) => {
2758
2912
  const runGenerated = async () => {
2759
2913
  if (!aiResult?.command) return
2760
2914
  if (!term?.id || term.closed) { setError(T.aiNeedTerm); return }
2761
- if (aiResult.dangerous && !window.confirm(T.risk + '\n\n' + aiResult.command)) return
2915
+ if (aiResult.dangerous) {
2916
+ const ok = await confirmDialog({ title: T.risk, message: '这条命令可能造成不可逆的破坏,确认后才会发送到终端。', details: [{ k: '命令', v: aiResult.command }], danger: true })
2917
+ if (!ok) return
2918
+ }
2762
2919
  await sendKey(aiResult.command + '\r')
2763
2920
  setAiResult(null)
2764
2921
  setAiIntent('')
@@ -2795,7 +2952,7 @@ const termKey = (event) => {
2795
2952
  h('button', { className: 'ops-btn ops-btn-sm', disabled: selectedPaths().length === 0 || fsBusy === 'compress', onClick: () => { void fsCompress() } }, T.fsCompress),
2796
2953
  h('button', { className: 'ops-btn ops-btn-sm', disabled: selectedPaths().length !== 1 || fsBusy === 'extract', onClick: () => { void fsExtract() } }, T.fsExtract),
2797
2954
  h('button', { className: 'ops-btn ops-btn-sm', disabled: !fsSel, onClick: () => { void fsRename() } }, T.fsRename),
2798
- h('button', { className: 'ops-btn ops-btn-sm', disabled: selectedPaths().length === 0, onClick: () => { const paths = selectedPaths(); if (paths.length && window.confirm(`${T.confirmDel} ${paths.length} 项?`)) { void (async () => { setFsBusy('del'); try { await api('fs', { method: 'POST', body: JSON.stringify({ host: cHost || hosts[0]?.name, action: 'delete', paths, confirm: true }) }, timeoutFor('action')); setFsSelSet({}); setFsSel(null); await loadFiles(fsPath) } catch (e) { setError(String(e.message || e)) } finally { setFsBusy('') } })() } } }, T.fsDelete),
2955
+ h('button', { className: 'ops-btn ops-btn-sm', disabled: selectedPaths().length === 0, onClick: () => { void fsDeleteSelected() } }, T.fsDelete),
2799
2956
  selectedPaths().length ? h('span', { className: 'ops-dim', style: { fontSize: '12px' } }, `${T.fsSelectedCount} ${selectedPaths().length}`) : null),
2800
2957
  fsProgress
2801
2958
  ? h('div', null,
@@ -3192,7 +3349,11 @@ const termKey = (event) => {
3192
3349
  h('button', { className: `ops-tab${backupForm.type === 'dir' ? ' on' : ''}`, onClick: () => setBackupForm({ ...backupForm, type: 'dir' }) }, T.backupDirKind)),
3193
3350
  h('div', { className: 'ops-chips', style: { marginTop: '8px' } },
3194
3351
  backupForm.type === 'mysql'
3195
- ? h('input', { className: 'ops-input', style: { flex: '1 1 200px' }, value: backupForm.database, placeholder: '数据库名(留空=全部)', onChange: e => setBackupForm({ ...backupForm, database: e.target.value }) })
3352
+ ? [
3353
+ h('input', { key: 'db', className: 'ops-input', style: { flex: '1 1 150px' }, value: backupForm.database, placeholder: '数据库名(留空=全部)', onChange: e => setBackupForm({ ...backupForm, database: e.target.value }) }),
3354
+ h('input', { key: 'user', className: 'ops-input', style: { width: '110px' }, value: backupForm.user, placeholder: 'MySQL 用户', onChange: e => setBackupForm({ ...backupForm, user: e.target.value }) }),
3355
+ h('input', { key: 'pwd', className: 'ops-input', type: 'password', style: { width: '140px' }, value: backupForm.password, placeholder: '密码(可空)', onChange: e => setBackupForm({ ...backupForm, password: e.target.value }) }),
3356
+ ]
3196
3357
  : h('input', { className: 'ops-input', style: { flex: '1 1 260px' }, value: backupForm.path, placeholder: '/www/wwwroot 或 /etc/nginx', onChange: e => setBackupForm({ ...backupForm, path: e.target.value }) }),
3197
3358
  h('input', { className: 'ops-input', style: { width: '160px' }, value: backupForm.dir, placeholder: '/home/backup', onChange: e => setBackupForm({ ...backupForm, dir: e.target.value }) }),
3198
3359
  h('label', { className: 'ops-sub', style: { display: 'flex', gap: '6px', alignItems: 'center' }, title: T.tipKeep }, T.backupKeep,
@@ -3691,16 +3852,64 @@ const termKey = (event) => {
3691
3852
  h('button', { className: 'ops-btn ops-btn-sm', onClick: () => setCleanPreview(null) }, T.cleanCancel),
3692
3853
  h('button', { className: 'ops-btn ops-btn-primary ops-btn-sm', disabled: backupBusy || cleanRunBusy, onClick: () => { void confirmClean() } }, cleanRunBusy ? T.cleaning : T.cleanConfirm)))) : null
3693
3854
 
3855
+ const taskTray = taskJobs.length
3856
+ ? h('div', { className: 'ops-jobs', role: 'status', 'aria-live': 'polite' },
3857
+ taskJobs.slice(-3).map(job => h('div', { key: job.id, className: `ops-jobs-item ${job.status}` },
3858
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
3859
+ job.status === 'running' ? h('span', { className: 'ops-spinner ops-spinner-sm' }) : h('span', null, job.status === 'done' ? '✅' : '⚠️'),
3860
+ h('span', { style: { flex: 1, fontSize: 12 } }, `${job.title}${job.status === 'running' ? ' · 进行中' : job.status === 'done' ? ' · 完成' : ' · 失败'}`),
3861
+ h('button', { className: 'ops-copy', 'aria-label': '关闭任务', onClick: () => setTaskJobs(list => list.filter(item => item.id !== job.id)) }, '✕')),
3862
+ job.status === 'failed' ? h('div', { className: 'ops-err', style: { fontSize: 11, marginTop: 4 } }, job.error) : null)))
3863
+ : null
3864
+
3865
+ const confirmView = confirmState ? (() => {
3866
+ const close = (value) => {
3867
+ const resolve = confirmState.resolve
3868
+ setConfirmState(null)
3869
+ resolve(value)
3870
+ }
3871
+ return h('div', { className: 'ops-modal-mask', onClick: () => close(false) },
3872
+ h('div', { className: 'ops-modal', role: 'dialog', 'aria-modal': 'true', style: { width: 'min(520px, 100%)' }, onClick: event => event.stopPropagation() },
3873
+ h('div', { className: 'ops-modal-h' },
3874
+ h('span', { className: 'ops-modal-title' }, confirmState.title || '请确认'),
3875
+ h('button', { className: 'ops-modal-x', 'aria-label': '关闭', onClick: () => close(false) }, '✕')),
3876
+ h('div', { style: { padding: '4px 14px 0' } },
3877
+ confirmState.message ? h('p', { style: { margin: '0 0 10px', fontSize: 13, lineHeight: 1.7 } }, confirmState.message) : null,
3878
+ Array.isArray(confirmState.details) && confirmState.details.length
3879
+ ? h('dl', { className: 'ops-details' },
3880
+ confirmState.details.map((row, index) => h('div', { key: index }, h('dt', null, row.k), h('dd', null, String(row.v ?? '')))))
3881
+ : null,
3882
+ confirmState.prompt
3883
+ ? h('input', {
3884
+ className: 'ops-input',
3885
+ type: confirmState.secret ? 'password' : 'text',
3886
+ placeholder: confirmState.prompt,
3887
+ value: confirmState.value || '',
3888
+ onChange: event => setConfirmState(current => (current ? { ...current, value: event.target.value } : current)),
3889
+ })
3890
+ : null),
3891
+ h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, padding: '12px 14px 14px' } },
3892
+ h('button', { className: 'ops-btn ops-btn-sm', onClick: () => close(false) }, T.cancel),
3893
+ h('button', { className: `ops-btn ops-btn-sm ${confirmState.danger ? 'ops-btn-danger' : 'ops-btn-primary'}`, onClick: () => close(confirmState.prompt ? (confirmState.value || '') : true) },
3894
+ confirmState.okText || '确定'))))
3895
+ })() : null
3896
+
3694
3897
  return h('div', { className: 'ops-page' },
3695
3898
  h('style', null, CSS),
3696
3899
  header,
3697
3900
  nav,
3698
- error ? h('p', { className: 'ops-err' }, error) : null,
3901
+ error
3902
+ ? h('div', { className: 'ops-errbar', role: 'alert' },
3903
+ h('span', { style: { flex: 1 } }, error),
3904
+ h('button', { className: 'ops-btn ops-btn-sm', onClick: () => setError('') }, T.close))
3905
+ : null,
3699
3906
  body,
3700
3907
  monitorDialogView,
3701
3908
  fsEditView,
3702
3909
  fsPreviewView,
3703
3910
  cleanPreviewView,
3911
+ confirmView,
3912
+ taskTray,
3704
3913
  busyOverlay)
3705
3914
  }
3706
3915