dsh-plugin-admin 0.3.0 → 0.4.0

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/lib/client.js CHANGED
@@ -1,2094 +1,2299 @@
1
- window.__ModuleLoader__.load({ id: 'dsh-plugin-admin', factory: (require) => {
2
- var module = { exports: {} }; var exports = module.exports;
3
-
4
- /**
5
- * dsh-plugin-admin browser half: unified "管理中心" (插件管理 & 会话管理)
6
- * page inside the settings panel.
7
- *
8
- * The page rides the shell's `settings.section` slot (the shell owns
9
- * the dialog chrome, navigation, and close); its component is assembled with
10
- * the platform-shared React (module-table seed word, same instance the shell
11
- * renders with), providing a tabbed modern UI to manage both profile plugin
12
- * layers and session lifecycles over the /api RPC gateway.
13
- */
14
-
15
- var React = require('react')
16
- var createElement = React.createElement
17
- var useState = React.useState
18
- var useRef = React.useRef
19
- var useEffect = React.useEffect
20
-
21
- var CSS_TEXT = [
22
- '@keyframes dsh-admin-spin { to { transform: rotate(360deg); } }',
23
- '@keyframes dsh-admin-pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.35; transform: scale(0.85); } }',
24
- '[data-dsh-admin-section] { display: flex; flex-direction: column; width: 100%; gap: 14px; padding: 2px; font-size: 13px; line-height: 1.5; color: var(--dsw-alias-label-primary, #222); max-height: calc(100vh - 140px); overflow: hidden; }',
25
- '[data-dsh-admin-section] * { box-sizing: border-box; }',
26
- '[data-dsh-admin-section] .tabs { display: flex; padding: 3px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.2)); border-radius: 9px; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.3)); gap: 3px; }',
27
- '[data-dsh-admin-section] .tab { flex: 1; border: 0; background: transparent; border-radius: 7px; padding: 7px 14px; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 7px; font-size: 12px; font-weight: 500; color: var(--dsw-alias-label-secondary, #666); transition: all 0.15s ease; font-family: inherit; }',
28
- '[data-dsh-admin-section] .tab:hover:not(.active) { color: var(--dsw-alias-label-primary, #222); background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.3)); }',
29
- '[data-dsh-admin-section] .tab.active { background: var(--dsw-alias-bg-elevated, var(--dsw-alias-bg-base, transparent)); color: var(--dsw-alias-label-primary, #333); font-weight: 600; box-shadow: 0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.04); }',
30
- '[data-dsh-admin-section] .tab-count { font-size: 10px; font-weight: 600; padding: 1px 6px; border-radius: 10px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.4)); color: var(--dsw-alias-label-secondary, #555); }',
31
- '[data-dsh-admin-section] .tab.active .tab-count { background: var(--dsw-static-blue-500, #3b82f6); color: #fff; }',
32
- '[data-dsh-admin-section] .toolbar { display: flex; gap: 8px; align-items: center; padding: 10px; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)); border-radius: 12px; background: var(--dsw-alias-bg-elevated, var(--dsw-alias-bg-base, transparent)); box-shadow: 0 1px 2px rgba(0,0,0,0.02); }',
33
- '[data-dsh-admin-section] .toolbar .input { height: 32px; padding: 0 12px; border-radius: 8px; border-color: var(--dsw-alias-border-subtle, rgba(200,200,210,0.5)); }',
34
- '[data-dsh-admin-section] .search-wrap { flex: 1.6; min-width: 0; position: relative; display: flex; align-items: center; height: 32px; }',
35
- '[data-dsh-admin-section] .search-wrap .input { flex: 1; min-width: 0; padding-left: 30px; font-size: 13px; }',
36
- '[data-dsh-admin-section] .session-search { flex: 1; height: 32px; }',
37
- '[data-dsh-admin-section] .session-search .input { height: 32px; padding: 0 12px; font-size: 13px; border-radius: 8px; border-color: var(--dsw-alias-border-subtle, rgba(200,200,210,0.5)); }',
38
- '[data-dsh-admin-section] .install-wrap { flex: 1; min-width: 0; display: flex; align-items: center; height: 32px; }',
39
- '[data-dsh-admin-section] .install-wrap .input { flex: 1; min-width: 0; font-size: 13px; border-radius: 8px; border-color: var(--dsw-alias-border-subtle, rgba(200,200,210,0.5)); }',
40
- '[data-dsh-admin-section] .search-icon { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); font-size: 12px; opacity: 0.7; pointer-events: none; z-index: 1; }',
41
- '[data-dsh-admin-section] .input { width: 100%; padding: 7px 12px; border-radius: 9px; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.5)); background: var(--dsw-alias-bg-base, transparent); color: inherit; font: inherit; outline: none; transition: border-color 0.15s, box-shadow 0.15s, background 0.15s; }',
42
- '[data-dsh-admin-section] .input:hover { border-color: var(--dsw-alias-label-tertiary, rgba(180,180,195,0.6)); }',
43
- '[data-dsh-admin-section] .input:focus { border-color: var(--dsw-static-blue-500, #3b82f6); box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.16); }',
44
- '[data-dsh-admin-section] .filter-bar { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }',
45
- '[data-dsh-admin-section] .pill { font-size: 11px; padding: 2px 8px; border-radius: 6px; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.45)); background: transparent; cursor: pointer; color: var(--dsw-alias-label-secondary, #555); transition: all 0.12s; font-family: inherit; }',
46
- '[data-dsh-admin-section] .pill:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.3)); }',
47
- '[data-dsh-admin-section] .pill.active { background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.4)); color: var(--dsw-static-blue-500, #3b82f6); font-weight: 600; border-color: currentColor; }',
48
- '[data-dsh-admin-section] .btn { display: inline-flex; align-items: center; justify-content: center; gap: 5px; height: 32px; padding: 0 14px; border-radius: 8px; font-size: 13px; font-weight: 500; cursor: pointer; font-family: inherit; transition: transform 0.15s ease, background 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease, color 0.15s ease; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.5)); background: var(--dsw-alias-interactive-bg-hover, rgba(240,240,245,0.6)); color: var(--dsw-alias-label-secondary, #555); white-space: nowrap; flex: none; box-shadow: 0 1px 2px rgba(0,0,0,0.04); }',
49
- '[data-dsh-admin-section] .btn:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover, rgba(220,220,230,0.7)); border-color: var(--dsw-alias-label-tertiary, rgba(180,180,195,0.65)); color: var(--dsw-alias-label-primary, #222); box-shadow: 0 2px 4px rgba(0,0,0,0.06); }',
50
- '[data-dsh-admin-section] .search-wrap .btn.sm { background: transparent; border: none; box-shadow: none; padding: 2px 6px; color: var(--dsw-alias-label-tertiary, #888); }',
51
- '[data-dsh-admin-section] .search-wrap .btn.sm:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.4)); color: var(--dsw-alias-label-primary, #222); }',
52
- '[data-dsh-admin-section] .btn:active:not(:disabled) { transform: translateY(1px); }',
53
- '[data-dsh-admin-section] .btn:focus-visible, [data-dsh-admin-section] .pill:focus-visible { outline: 2px solid var(--dsw-static-blue-500, #3b82f6); outline-offset: 2px; }',
54
- '[data-dsh-admin-section] .btn:disabled { opacity: 0.45; cursor: not-allowed; }',
55
- '[data-dsh-admin-section] .btn.primary { background: var(--dsw-static-blue-500, #3b82f6); color: #fff; border-color: transparent; font-weight: 600; box-shadow: 0 1px 3px rgba(0,0,0,0.12); }',
56
- '[data-dsh-admin-section] .btn.primary:hover:not(:disabled) { background: var(--dsw-static-blue-400, #60a5fa); color: #fff; box-shadow: 0 2px 6px rgba(0,0,0,0.14); }',
57
- '[data-dsh-admin-section] .btn.primary:active:not(:disabled) { background: var(--dsw-static-blue-600, #2563eb); color: #fff; }',
58
- '[data-dsh-admin-section] .btn.danger { color: var(--dsw-alias-state-error-primary, #dc2626); border-color: var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)); }',
59
- '[data-dsh-admin-section] .btn.danger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover-danger, rgba(239,68,68,0.1)); border-color: rgba(220,38,38,0.35); color: #b91c1c; }',
60
- '[data-dsh-admin-section] .btn.danger-solid { background: var(--dsw-alias-state-error-primary, #dc2626); color: #fff; border-color: transparent; }',
61
- '[data-dsh-admin-section] .btn.danger-solid:hover:not(:disabled) { background: #b91c1c; color: #fff; }',
62
- '[data-dsh-admin-section] .btn.danger-solid:active:not(:disabled) { background: #991b1b; color: #fff; }',
63
- '[data-dsh-admin-section] .btn.sm { height: 28px; padding: 0 10px; font-size: 12px; border-radius: 6px; }',
64
- '[data-dsh-admin-section] .spinner { width: 12px; height: 12px; border: 2px solid transparent; border-top-color: currentColor; border-radius: 50%; animation: dsh-admin-spin 0.7s linear infinite; display: inline-block; flex: none; }',
65
- '[data-dsh-admin-section] .list { display: flex; flex-direction: column; gap: 10px; flex: 1 1 auto; min-height: 0; max-height: 560px; overflow-y: auto; padding: 2px 4px 2px 2px; scrollbar-width: thin; scrollbar-color: var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)) transparent; }',
66
- '[data-dsh-admin-section] .list::-webkit-scrollbar { width: 6px; }',
67
- '[data-dsh-admin-section] .list::-webkit-scrollbar-thumb { border-radius: 99px; background: var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)); }',
68
- '[data-dsh-admin-section] .session-group { display: flex; flex-direction: column; gap: 6px; }',
69
- '[data-dsh-admin-section] .group-header { display: flex; align-items: center; gap: 10px; padding: 10px 12px 8px 12px; font-size: 13px; font-weight: 600; color: var(--dsw-alias-label-primary); border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)); border-radius: 10px; background: var(--dsw-alias-bg-elevated, var(--dsw-alias-bg-base, transparent)); box-shadow: 0 1px 2px rgba(0,0,0,0.02); margin-bottom: 4px; }',
70
- '[data-dsh-admin-section] .group-header:first-child { margin-top: 2px; }',
71
- '[data-dsh-admin-section] .group-title { display: inline-flex; align-items: center; gap: 6px; }',
72
- '[data-dsh-admin-section] .group-count { font-size: 11px; padding: 2px 8px; border-radius: 10px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.3)); color: var(--dsw-alias-label-secondary, #555); font-weight: 500; }',
73
- '[data-dsh-admin-section] .group-header .btn.sm { margin-left: auto; }',
74
- '[data-dsh-admin-section] .group-header .btn.sm + .btn.sm { margin-left: 0; }',
75
- '[data-dsh-admin-section] .group-path { font-family: monospace; font-size: 10px; color: var(--dsw-alias-label-tertiary, #888); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1; min-width: 0; text-align: right; }',
76
- '[data-dsh-admin-section] .card { display: flex; flex-direction: column; gap: 7px; padding: 12px; border-radius: 12px; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)); background: var(--dsw-alias-bg-elevated, var(--dsw-alias-bg-base, transparent)); box-shadow: 0 1px 2px rgba(0,0,0,0.02); transition: transform 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease; }',
77
- '[data-dsh-admin-section] .card:hover { transform: translateY(-1px); border-color: var(--dsw-alias-label-tertiary, rgba(180,180,195,0.6)); box-shadow: 0 8px 20px rgba(0,0,0,0.06); }',
78
- '[data-dsh-admin-section] .card-header { display: flex; align-items: center; gap: 8px; min-width: 0; }',
79
- '[data-dsh-admin-section] .card-title { font-size: 13px; font-weight: 600; color: var(--dsw-alias-label-primary); display: flex; align-items: center; gap: 7px; min-width: 0; flex: 1; }',
80
- '[data-dsh-admin-section] .card-title-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 600; }',
81
- '[data-dsh-admin-section] .card-summary { display: flex; align-items: flex-start; gap: 6px; padding: 6px 9px; border-radius: 6px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.25)); border-left: 2px solid var(--dsw-static-blue-500, #3b82f6); font-size: 12px; line-height: 1.45; color: var(--dsw-alias-label-secondary, #555); margin-top: 1px; margin-bottom: 1px; }',
82
- '[data-dsh-admin-section] .summary-icon { font-size: 11px; line-height: 1.45; flex: none; opacity: 0.85; }',
83
- '[data-dsh-admin-section] .summary-text { flex: 1; min-width: 0; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; word-break: break-word; }',
84
- '[data-dsh-admin-section] .card-sub { font-size: 11px; color: var(--dsw-alias-label-secondary, #666); display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }',
85
- '[data-dsh-admin-section] .card-sub-item { display: inline-flex; align-items: center; gap: 3px; max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }',
86
- '[data-dsh-admin-section] .card-actions { display: flex; gap: 5px; align-items: center; flex: none; }',
87
- '[data-dsh-admin-section] .tag { font-size: 10px; font-weight: 500; padding: 1px 6px; border-radius: 4px; flex: none; display: inline-flex; align-items: center; gap: 4px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.25)); color: var(--dsw-alias-label-secondary, #555); }',
88
- '[data-dsh-admin-section] .tag.plugin { background: rgba(16, 185, 129, 0.12); color: var(--dsw-alias-state-success-primary, #10b981); }',
89
- '[data-dsh-admin-section] .tag.local { background: rgba(59, 130, 246, 0.12); color: var(--dsw-static-blue-500, #3b82f6); }',
90
- '[data-dsh-admin-section] .tag.update { background: rgba(245, 158, 11, 0.14); color: #d97706; font-weight: 600; border: 1px solid rgba(217, 119, 6, 0.25); }',
91
- '[data-dsh-admin-section] .tag.update-error { background: rgba(239, 68, 68, 0.1); color: var(--dsw-alias-state-error-primary, #ef4444); }',
92
- '[data-dsh-admin-section] .plugin-path { font-family: monospace; font-size: 11px; line-height: 1.4; color: var(--dsw-alias-label-secondary, #555); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding: 4px 9px; border-radius: 6px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.25)); }',
93
- '[data-dsh-admin-section] .tag.version { font-family: monospace; }',
94
- '[data-dsh-admin-section] .tag.live { background: rgba(16, 185, 129, 0.12); color: var(--dsw-alias-state-success-primary, #10b981); font-weight: 600; }',
95
- '[data-dsh-admin-section] .tag.archived { background: rgba(245, 158, 11, 0.12); color: var(--dsw-alias-state-warn-label, #f59e0b); }',
96
- '[data-dsh-admin-section] .tag.turns { background: rgba(59, 130, 246, 0.12); color: var(--dsw-static-blue-500, #3b82f6); font-weight: 500; }',
97
- '[data-dsh-admin-section] .dot { width: 7px; height: 7px; border-radius: 50%; flex: none; background: var(--dsw-alias-label-tertiary, #999); }',
98
- '[data-dsh-admin-section] .dot.live { background: var(--dsw-alias-state-success-primary, #10b981); box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.25); animation: dsh-admin-pulse 2s infinite ease-in-out; }',
99
- '[data-dsh-admin-section] .dot.archived { background: var(--dsw-alias-state-warn-label, #f59e0b); }',
100
- '[data-dsh-admin-section] .confirm-bar { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 6px 10px; border-radius: 6px; background: var(--dsw-alias-interactive-bg-hover-danger, rgba(239,68,68,0.08)); border: 1px solid rgba(239,68,68,0.2); }',
101
- '[data-dsh-admin-section] .confirm-text { font-size: 11px; color: var(--dsw-alias-state-error-primary, #ef4444); font-weight: 500; }',
102
- '[data-dsh-admin-section] .confirm-actions { display: flex; gap: 5px; flex: none; }',
103
- '[data-dsh-admin-section] .busy-banner { display: flex; align-items: center; gap: 8px; padding: 7px 11px; border-radius: 7px; background: rgba(59, 130, 246, 0.08); color: var(--dsw-static-blue-500, #3b82f6); font-size: 11px; }',
104
- '[data-dsh-admin-section] .update-strip { display: flex; align-items: center; gap: 8px; padding: 8px 11px; border-radius: 8px; font-size: 12px; font-weight: 500; line-height: 1.4; }',
105
- '[data-dsh-admin-section] .update-strip .btn.sm { margin-left: auto; flex: none; }',
106
- '[data-dsh-admin-section] .update-strip.checking { background: rgba(59, 130, 246, 0.08); color: var(--dsw-static-blue-500, #3b82f6); }',
107
- '[data-dsh-admin-section] .update-strip.ok { background: rgba(16, 185, 129, 0.1); color: var(--dsw-alias-state-success-primary, #10b981); }',
108
- '[data-dsh-admin-section] .update-strip.has-updates { background: rgba(245, 158, 11, 0.12); color: #d97706; border: 1px solid rgba(217, 119, 6, 0.25); }',
109
- '[data-dsh-admin-section] .update-strip.has-errors { background: rgba(239, 68, 68, 0.08); color: var(--dsw-alias-state-error-primary, #ef4444); }',
110
- '[data-dsh-admin-section] .empty { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 28px 12px; color: var(--dsw-alias-label-tertiary, #999); gap: 4px; font-size: 12px; text-align: center; }',
111
- '[data-dsh-admin-section] .error { padding: 7px 11px; border-radius: 7px; color: var(--dsw-alias-state-error-primary, #ef4444); background: var(--dsw-alias-interactive-bg-hover-danger, rgba(239,68,68,0.08)); font-size: 12px; white-space: pre-wrap; max-height: 100px; overflow-y: auto; }',
112
- '[data-dsh-admin-section] .footer { display: flex; justify-content: space-between; align-items: center; padding-top: 4px; font-size: 11px; color: var(--dsw-alias-label-tertiary, #888); border-top: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.3)); flex: none; }',
113
- '[data-dsh-admin-section] .footer .path { max-width: 60%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }',
114
- '[data-dsh-admin-section] .footer .hint { font-style: normal; }',
115
- '[data-dsh-admin-section] .session-id-badge { font-family: monospace; font-size: 10px; opacity: 0.75; }',
116
- '[data-dsh-admin-section] .mcp-test-row { padding: 6px 9px; border-radius: 6px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.25)); font-size: 11px; line-height: 1.4; overflow-wrap: anywhere; }',
117
- '[data-dsh-admin-section] .mcp-test { display: inline-flex; align-items: center; gap: 5px; }',
118
- '[data-dsh-admin-section] .mcp-test.mcp-test-list { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; }',
119
- '[data-dsh-admin-section] .mcp-test-busy { color: var(--dsw-alias-label-secondary, #666); }',
120
- '[data-dsh-admin-section] .mcp-test-ok { color: #16a34a; }',
121
- '[data-dsh-admin-section] .mcp-test-fail { color: var(--dsw-alias-state-error-primary, #ef4444); }',
122
- '[data-dsh-admin-section] .mcp-test-warn { color: #d97706; opacity: 0.95; }',
123
- '[data-dsh-admin-section] .mcp-test-cached { font-size: 10px; color: var(--dsw-alias-label-tertiary, #999); }',
124
- '@media (max-width: 520px) { [data-dsh-admin-section] { gap: 10px; } [data-dsh-admin-section] .toolbar { align-items: stretch; flex-wrap: wrap; padding: 8px; } [data-dsh-admin-section] .toolbar .input-wrap { flex-basis: 100%; } [data-dsh-admin-section] .card-header { align-items: flex-start; } [data-dsh-admin-section] .card-actions { flex-wrap: wrap; justify-content: flex-end; } [data-dsh-admin-section] .footer { gap: 6px; align-items: flex-start; flex-direction: column; } [data-dsh-admin-section] .footer .path { max-width: 100%; } }',
125
- '@keyframes dsh-toast-in { 0% { opacity: 0; transform: translateY(-12px) scale(0.96); } 100% { opacity: 1; transform: translateY(0) scale(1); } }',
126
- '@keyframes dsh-toast-out { 0% { opacity: 1; transform: translateY(0) scale(1); } 100% { opacity: 0; transform: translateY(-8px) scale(0.96); } }',
127
- '.dsh-admin-toast { position: fixed; top: 16px; left: 50%; transform: translateX(-50%); z-index: 99999; padding: 10px 20px; border-radius: 10px; font-size: 13px; font-weight: 500; line-height: 1.4; box-shadow: 0 8px 30px rgba(0,0,0,0.15), 0 2px 8px rgba(0,0,0,0.08); display: flex; align-items: center; gap: 8px; pointer-events: none; animation: dsh-toast-in 0.25s ease-out forwards; max-width: 90vw; word-break: break-word; }',
128
- '.dsh-admin-toast.success { background: rgba(16, 185, 129, 0.95); color: #fff; }',
129
- '.dsh-admin-toast.error { background: rgba(239, 68, 68, 0.95); color: #fff; }',
130
- '.dsh-admin-toast.info { background: rgba(22, 119, 255, 0.95); color: #fff; }',
131
- '.dsh-admin-toast.leaving { animation: dsh-toast-out 0.2s ease-in forwards; }',
132
- ].join('\n')
133
-
134
- function injectStyles() {
135
- var tagId = 'dsh-plugin-admin/unified-section.css'
136
- if (document.querySelector('style[data-plugin-css="' + tagId + '"]') === null) {
137
- var tag = document.createElement('style')
138
- tag.dataset.plugin = 'dsh-plugin-admin'
139
- tag.dataset.pluginCss = tagId
140
- tag.textContent = CSS_TEXT
141
- document.head.appendChild(tag)
142
- }
143
- }
144
-
145
- function baseName(path) {
146
- if (path === null || path === '') return '(无工作目录)'
147
- var parts = path.replace(/\\/g, '/').split('/')
148
- var last = parts[parts.length - 1]
149
- return last === '' ? parts[parts.length - 2] || path : last
150
- }
151
-
152
- function formatDate(ms) {
153
- if (typeof ms !== 'number' || !Number.isFinite(ms)) return ''
154
- var d = new Date(ms)
155
- var pad = function (n) { return (n < 10 ? '0' : '') + String(n) }
156
- return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate())
157
- + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes())
158
- }
159
-
160
- function messageOf(error) {
161
- if (error !== null && typeof error === 'object' && typeof error.message === 'string') return error.message
162
- if (typeof error === 'string') return error
163
- return JSON.stringify(error)
164
- }
165
-
166
- /**
167
- * Show a floating toast notification at the top of the viewport.
168
- * Auto-dismisses after `duration` ms. Supports 'success', 'error', 'info'.
169
- */
170
- function showToast(type, text, duration) {
171
- if (typeof document === 'undefined') return
172
- duration = duration || 3000
173
- var toast = document.createElement('div')
174
- toast.className = 'dsh-admin-toast ' + type
175
- toast.textContent = text
176
- document.body.appendChild(toast)
177
-
178
- var timer = setTimeout(function () {
179
- toast.classList.add('leaving')
180
- setTimeout(function () {
181
- if (toast.parentNode) toast.parentNode.removeChild(toast)
182
- }, 200)
183
- }, duration)
184
-
185
- toast.addEventListener('click', function () {
186
- clearTimeout(timer)
187
- if (!toast.classList.contains('leaving')) {
188
- toast.classList.add('leaving')
189
- setTimeout(function () {
190
- if (toast.parentNode) toast.parentNode.removeChild(toast)
191
- }, 200)
192
- }
193
- })
194
- }
195
-
196
- /**
197
- * Copy text to the clipboard. Uses the async Clipboard API when available;
198
- * falls back to a hidden textarea + execCommand for older browsers or
199
- * non-secure contexts.
200
- */
201
- function copyTextToClipboard(text) {
202
- if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
203
- navigator.clipboard.writeText(text).then(function () {
204
- showToast('success', '📋 会话 ID 已复制')
205
- }, function () {
206
- fallbackCopy(text)
207
- })
208
- return
209
- }
210
- fallbackCopy(text)
211
- }
212
-
213
- function fallbackCopy(text) {
214
- try {
215
- var ta = document.createElement('textarea')
216
- ta.value = text
217
- ta.style.cssText = 'position:fixed;top:-9999px;left:-9999px;opacity:0'
218
- document.body.appendChild(ta)
219
- ta.select()
220
- ta.setSelectionRange(0, text.length)
221
- document.execCommand('copy')
222
- document.body.removeChild(ta)
223
- } catch (e) {
224
- showToast('error', '❌ 复制失败:' + messageOf(e))
225
- }
226
- }
227
-
228
- /* ========================================================================== */
229
- /* Menu Popup Injection (Sessions & Workspaces) */
230
- /* ========================================================================== */
231
-
232
- /**
233
- * Inject plugin items into the existing three-dot menu popup. The workspace
234
- * bundle renders a Menu component (@deepseek-ai/dsh-client-ui-primitives)
235
- * with portal:true, so the popup lives as a div[role="menu"] inside
236
- * document.body with position:fixed. A MutationObserver detects when this
237
- * popup appears, identifies it as a session or workspace menu by checking
238
- * the existing button labels, and injects additional items.
239
- */
240
- function setupMenuInjection(call, refreshSessions) {
241
- if (typeof document === 'undefined') return function () {}
242
-
243
- /**
244
- * Extract the session title from the row's aria-label. The anchor button
245
- * aria-label is: 会话"<title>"的操作 (zh) / Session "<title>" actions (en).
246
- * Extracting from the DOM keeps the injection synchronous — no RPC needed
247
- * just to show the button, so the menu can't close before it appears.
248
- */
249
- function sessionTitleFromRow(row) {
250
- var btn = row.querySelector('button[aria-label*="会话" i][aria-label*="操作" i], button[aria-label*="session" i][aria-label*="actions" i]')
251
- if (btn === null) return null
252
- var label = btn.getAttribute('aria-label') || ''
253
- // zh: 会话"xxx"的操作 → strip 会话"/"的操作
254
- var zh = /会话["“]([^"”]+)["”]/.exec(label)
255
- if (zh) return zh[1].trim()
256
- // en: Session "xxx" actions
257
- var en = /session\s*["“]([^"”]+)["”]/i.exec(label)
258
- if (en) return en[1].trim()
259
- // fallback: whole label minus known prefixes/suffixes
260
- return label.replace(/^会话/, '').replace(/^session/i, '').replace(/["“”]|的操作|actions$/gi, '').trim() || null
261
- }
262
-
263
- /** Find the treeitem row for the anchor button nearest the menu. */
264
- function rowForMenu(menuEl) {
265
- var menuRect = menuEl ? menuEl.getBoundingClientRect() : null
266
- var allRows = document.querySelectorAll('[role="treeitem"]')
267
- if (allRows.length === 0) return null
268
- var rows = []
269
- for (var i = 0; i < allRows.length; i++) {
270
- var r = allRows[i]
271
- // Only rows that contain a session/workspace action button
272
- if (r.querySelector('button[aria-label*="会话" i][aria-label*="操作" i], button[aria-label*="工作区" i][aria-label*="操作" i], button[aria-label*="session" i][aria-label*="actions" i], button[aria-label*="workspace" i][aria-label*="actions" i]')) {
273
- rows.push(r)
274
- }
275
- }
276
- if (rows.length === 0) return null
277
-
278
- // The Menu component renders with side="bottom": menu top sits just
279
- // below the anchor button (button.bottom + 4). Match the row whose
280
- // center is closest to the MENU TOP, not the menu center — the menu
281
- // can be tall (several items), so its center drifts far from the
282
- // clicked row.
283
- if (menuRect === null || menuRect.height === 0) {
284
- // No reliable menu rect. With a single candidate row the choice is
285
- // unambiguous, so return it (jsdom/test environments have zero rects);
286
- // with several rows refuse to guess rather than act on the wrong
287
- // session.
288
- if (rows.length === 1) return rows[0]
289
- return null
290
- }
291
- var closest = rows[0]
292
- var closestDist = Infinity
293
- for (var j = 0; j < rows.length; j++) {
294
- var rect = rows[j].getBoundingClientRect()
295
- if (rect.height === 0) continue
296
- var rowCenter = rect.top + rect.height / 2
297
- var dist = Math.abs(rowCenter - menuRect.top)
298
- if (dist < closestDist) {
299
- closestDist = dist
300
- closest = rows[j]
301
- }
302
- }
303
- return closest
304
- }
305
-
306
- function injectItems(menuEl) {
307
- if (menuEl.querySelector('[data-dsh-admin-injected]')) return
308
-
309
- var text = menuEl.textContent || ''
310
- var isSession = text.indexOf('归档会话') !== -1 || text.indexOf('Archive session') !== -1
311
- var isWorkspace = !isSession && (text.indexOf('删除') !== -1 || text.indexOf('Delete workspace') !== -1)
312
- if (!isSession && !isWorkspace) return
313
-
314
- var viewport = menuEl.querySelector('[role="presentation"]')
315
- if (viewport === null) return
316
-
317
- var row = rowForMenu(menuEl)
318
- if (row === null) return
319
-
320
- if (isSession) {
321
- var title = sessionTitleFromRow(row)
322
- if (title === null) return
323
- // Resolve sessions by title lazily at click time (fresh RPC) so the
324
- // match is always current. Copy-id keeps the fuzzy matcher (a wrong
325
- // match only mis-copies an id); delete must never guess, so it
326
- // resolves by exact title only and refuses duplicate titles — the
327
- // panel's rows act on ids and can disambiguate.
328
- function fetchSessions(done) {
329
- call('sessionAdmin/list', {}).then(function (listResult) {
330
- done((listResult && listResult.ok && listResult.value && listResult.value.sessions) || [])
331
- }, function () { showToast('error', '❌ 无法加载会话列表') })
332
- }
333
- // Normalize a title for comparison: trim, collapse spaces, drop
334
- // trailing ellipsis and truncation artifacts.
335
- function norm(v) {
336
- return (v || '').replace(/\s+/g, ' ').replace(/\.{3,}\s*$/, '').trim().toLowerCase()
337
- }
338
-
339
- function resolveSessionFuzzy(cb) {
340
- fetchSessions(function (sessions) {
341
- var match = null
342
- var nt = norm(title)
343
- for (var i = 0; i < sessions.length; i++) {
344
- var s = sessions[i]
345
- var st = norm(s.title)
346
- if (st === nt) { match = s; break }
347
- // substring both ways (skip too-short needles)
348
- if (nt.length > 3 && st.indexOf(nt) !== -1) { match = s; break }
349
- if (st.length > 3 && nt.indexOf(st) !== -1) { match = s; break }
350
- // fall back to cwd basename match
351
- var cwdBase = s.cwd ? s.cwd.replace(/\\/g, '/').split('/').pop() : ''
352
- if (cwdBase && (cwdBase === nt || nt.indexOf(cwdBase) !== -1 || cwdBase.indexOf(nt) !== -1)) { match = s; break }
353
- }
354
- if (match === null) { showToast('error', '❌ 未找到匹配的会话'); return }
355
- cb(match)
356
- })
357
- }
358
-
359
- function resolveSessionExact(cb) {
360
- fetchSessions(function (sessions) {
361
- var nt = norm(title)
362
- var exact = []
363
- for (var i = 0; i < sessions.length; i++) {
364
- if (norm(sessions[i].title) === nt) exact.push(sessions[i])
365
- }
366
- if (exact.length === 0) { showToast('error', '❌ 未找到匹配的会话'); return }
367
- if (exact.length > 1) {
368
- showToast('error', '❌ 存在 ' + String(exact.length) + ' 个同名会话,无法确定要删除的目标;请在 设置 → 管理中心 → 会话管理 中按会话 ID 删除')
369
- return
370
- }
371
- cb(exact[0])
372
- })
373
- }
374
-
375
- // Copy the session id to the clipboard.
376
- appendMenuItem(viewport, '复制会话 ID', 'normal', function () {
377
- resolveSessionFuzzy(function (session) {
378
- copyTextToClipboard(session.id)
379
- })
380
- })
381
-
382
- // Delete the session. Online sessions are now closable through the
383
- // captured AgentHandle (closeSession disposes the live agent/session
384
- // first, so removing the log cannot resurrect it) — this stops a
385
- // running conversation in that session. The item arms on the first
386
- // click and only fires on a second click within 4s (confirmText below)
387
- // — deletion is physical, so one misclick must never be enough.
388
- appendMenuItem(viewport, '删除会话', 'danger', function () {
389
- resolveSessionExact(function (match) {
390
- var method = match.live ? 'sessionAdmin/closeSession' : 'sessionAdmin/deleteSession'
391
- call(method, { sessionId: match.id }).then(function (result) {
392
- if (result && result.ok) {
393
- showToast('success', '🗑️ 会话已删除')
394
- // Nudge the sidebar so the removed session vanishes now
395
- // instead of lingering in 未分组 until reload.
396
- if (refreshSessions) refreshSessions()
397
- } else {
398
- showToast('error', '❌ 删除会话失败:' + messageOf(result && result.error))
399
- }
400
- }, function (err) { showToast('error', '❌ 删除会话失败:' + messageOf(err)) })
401
- })
402
- }, '⚠️ 再点一次确认删除(在线会话将先关停)')
403
- } else {
404
- // Workspace: reveal in file manager. Path is resolved lazily at click.
405
- var wsTitle = (row.querySelector('[class*="_title"]') || {}).textContent || ''
406
- wsTitle = wsTitle.trim()
407
- if (wsTitle === '') return
408
- appendMenuItem(viewport, '在资源管理器打开', 'normal', function () {
409
- call('sessionAdmin/list', {}).then(function (listResult) {
410
- var workspaces = (listResult && listResult.ok && listResult.value && listResult.value.workspaces) || []
411
- var wsPath = null
412
- for (var i = 0; i < workspaces.length; i++) {
413
- var w = workspaces[i]
414
- var wTitle = (w && w.title) || ''
415
- if (wTitle === wsTitle || (wsTitle !== '' && wTitle !== '' && (wsTitle.indexOf(wTitle) !== -1 || wTitle.indexOf(wsTitle) !== -1))) { wsPath = w && w.path; break }
416
- }
417
- if (wsPath === null) { showToast('error', '❌ 打开失败:未找到工作区路径'); return }
418
- call('fsAdmin/reveal', { path: wsPath }).then(function (result) {
419
- // Success needs no toast — the Explorer window opening is the
420
- // feedback itself. Only failures get a hint.
421
- if (!(result && result.ok)) showToast('error', '❌ 打开失败:' + messageOf(result && result.error))
422
- }, function (err) { showToast('error', '❌ 打开失败:' + messageOf(err)) })
423
- }, function () { showToast('error', '❌ 打开失败:无法加载工作区列表') })
424
- })
425
- }
426
- }
427
-
428
- function appendMenuItem(viewport, label, kind, onClick, confirmText) {
429
- // Separator (only if there are already items — always, to visually group)
430
- var sep = document.createElement('div')
431
- sep.setAttribute('role', 'separator')
432
- sep.setAttribute('data-dsh-admin-injected', '')
433
- sep.style.cssText = 'margin:3px 0;border-top:1px solid var(--dsw-alias-border-subtle,rgba(200,200,210,0.3))'
434
- viewport.appendChild(sep)
435
-
436
- var btn = document.createElement('button')
437
- btn.type = 'button'
438
- btn.setAttribute('role', 'menuitem')
439
- btn.setAttribute('data-dsh-admin-injected', '')
440
- btn.textContent = label
441
- var color = kind === 'danger' ? '#ef4444' : 'inherit'
442
- var hoverBg = kind === 'danger' ? 'rgba(239,68,68,0.12)' : 'rgba(200,200,210,0.3)'
443
- btn.style.cssText = 'display:flex;align-items:center;gap:8px;width:100%;padding:6px 10px;border:0;background:transparent;cursor:pointer;font:inherit;font-size:12px;color:' + color + ';border-radius:5px;text-align:left'
444
- btn.addEventListener('mouseenter', function () { btn.style.background = hoverBg })
445
- btn.addEventListener('mouseleave', function () { btn.style.background = 'transparent' })
446
- // Optional two-step confirm (confirmText): the first click arms the
447
- // item and relabels it; only a second click within 4s runs onClick —
448
- // destructive items must never fire on a single misclick.
449
- var armed = false
450
- var disarmTimer = null
451
- btn.addEventListener('click', function (e) {
452
- e.stopPropagation()
453
- if (confirmText === undefined) { onClick(); return }
454
- if (!armed) {
455
- armed = true
456
- btn.textContent = confirmText
457
- disarmTimer = setTimeout(function () {
458
- armed = false
459
- btn.textContent = label
460
- }, 4000)
461
- return
462
- }
463
- clearTimeout(disarmTimer)
464
- armed = false
465
- btn.textContent = label
466
- onClick()
467
- })
468
- viewport.appendChild(btn)
469
- }
470
-
471
- var observer = new MutationObserver(function (mutations) {
472
- for (var i = 0; i < mutations.length; i++) {
473
- var added = mutations[i].addedNodes
474
- if (!added || added.length === 0) continue
475
- for (var j = 0; j < added.length; j++) {
476
- var node = added[j]
477
- if (node.nodeType !== 1) continue
478
- var el = node
479
- if (el.getAttribute && el.getAttribute('role') === 'menu') {
480
- injectItems(el)
481
- } else {
482
- var menu = el.querySelector && el.querySelector('[role="menu"]')
483
- if (menu) injectItems(menu)
484
- }
485
- }
486
- }
487
- })
488
-
489
- observer.observe(document.body, { childList: true, subtree: true })
490
-
491
- return function () {
492
- observer.disconnect()
493
- }
494
- }
495
-
496
- /**
497
- * Plugins management settings section (standalone, no internal tabs).
498
- */
499
- function PluginsSection(props) {
500
- var pairPlugins = useState({
501
- profileDir: '',
502
- plugins: [],
503
- busy: false,
504
- error: '',
505
- spec: '',
506
- confirming: null,
507
- note: '',
508
- output: '',
509
- filter: 'all',
510
- needle: '',
511
- checkingUpdates: false,
512
- updateChecked: false, // true once a check finished (even if no updates)
513
- updates: {}, // name -> { latest, updateAvailable, error? }
514
- })
515
- var pView = pairPlugins[0]
516
- var setPView = pairPlugins[1]
517
-
518
- var alive = useRef(false)
519
-
520
- function patchPlugin(partial) {
521
- setPView(function (cur) {
522
- var next = {}
523
- for (var k in cur) next[k] = cur[k]
524
- for (var pk in partial) next[pk] = partial[pk]
525
- return next
526
- })
527
- }
528
-
529
- function callRemote(method, args) {
530
- return props.call(method, args)
531
- }
532
-
533
- function reloadPlugins() {
534
- patchPlugin({ busy: true, error: '', note: '' })
535
- callRemote('pluginAdmin/list', {}).then(function (result) {
536
- if (!alive.current) return
537
- if (result.ok) {
538
- patchPlugin({
539
- busy: false,
540
- profileDir: (result.value && result.value.profileDir) || '',
541
- plugins: (result.value && result.value.plugins) || [],
542
- })
543
- } else {
544
- patchPlugin({ busy: false, error: '加载插件失败:' + messageOf(result.error) })
545
- }
546
- }, function (failure) {
547
- if (!alive.current) return
548
- patchPlugin({ busy: false, error: '调用失败:' + messageOf(failure) })
549
- })
550
- }
551
-
552
- /**
553
- * Query the npm registry for newer versions of registry-installed bundles
554
- * and stash per-plugin results. Runs concurrently with the list so the
555
- * panel stays responsive; failures are per-plugin, never fatal.
556
- */
557
- function checkUpdates() {
558
- if (pView.checkingUpdates) return
559
- patchPlugin({ checkingUpdates: true, note: '' })
560
- callRemote('pluginAdmin/checkUpdates', {}).then(function (result) {
561
- if (!alive.current) return
562
- patchPlugin({ checkingUpdates: false })
563
- if (!result.ok) {
564
- patchPlugin({ error: '检查更新失败:' + messageOf(result.error) })
565
- return
566
- }
567
- var list = (result.value && result.value.updates) || []
568
- var map = {}
569
- var updateCount = 0
570
- var checkedCount = 0
571
- var checkErrorCount = 0
572
- for (var i = 0; i < list.length; i++) {
573
- var u = list[i]
574
- map[u.name] = { latest: u.latest, updateAvailable: u.updateAvailable === true, error: u.error || '' }
575
- if (u.updateAvailable === true) updateCount++
576
- if (u.error) checkErrorCount++
577
- checkedCount++
578
- }
579
- var updated = map
580
- patchPlugin({
581
- updates: updated,
582
- updateChecked: true,
583
- note: updateCount > 0
584
- ? '发现 ' + updateCount + ' 个插件有新版本'
585
- : (checkErrorCount > 0
586
- ? '已检查 ' + checkedCount + ' 个插件(' + checkErrorCount + ' 个查询失败),其余均为最新版本'
587
- : (checkedCount > 0 ? '已检查 ' + checkedCount + ' 个插件,均为最新版本' : '')),
588
- })
589
- }, function (failure) {
590
- if (!alive.current) return
591
- patchPlugin({ checkingUpdates: false, error: '检查更新调用失败:' + messageOf(failure) })
592
- })
593
- }
594
-
595
- /** Upgrade one plugin to its latest version (registry install by name). */
596
- function upgradePlugin(name) {
597
- if (pView.busy) return
598
- var spec = name + '@latest'
599
- patchPlugin({ busy: true, error: '', confirming: null, note: '' })
600
- callRemote('pluginAdmin/install', { spec: spec }).then(function (result) {
601
- if (!alive.current) return
602
- if (result.ok) {
603
- patchPlugin({
604
- busy: false,
605
- note: '已更新 ' + name + '。更改在重启 dsh 后生效',
606
- output: (result.value && result.value.output) || '',
607
- profileDir: (result.value && result.value.profileDir) || '',
608
- plugins: (result.value && result.value.plugins) || [],
609
- })
610
- // Refresh the update map so the upgraded entry stops flagging.
611
- checkUpdates()
612
- return
613
- }
614
- patchPlugin({ busy: false, error: '更新失败:' + messageOf(result.error) })
615
- reloadPlugins()
616
- }, function (failure) {
617
- if (!alive.current) return
618
- patchPlugin({ busy: false, error: '调用失败:' + messageOf(failure) })
619
- })
620
- }
621
-
622
- function installPlugin() {
623
- if (pView.busy || pView.spec.trim() === '') return
624
- var spec = pView.spec.trim()
625
- patchPlugin({ busy: true, error: '', confirming: null, note: '' })
626
- callRemote('pluginAdmin/install', { spec: spec }).then(function (result) {
627
- if (!alive.current) return
628
- if (result.ok) {
629
- patchPlugin({
630
- busy: false,
631
- note: '安装完成。更改在重启 dsh 后生效',
632
- output: (result.value && result.value.output) || '',
633
- profileDir: (result.value && result.value.profileDir) || '',
634
- plugins: (result.value && result.value.plugins) || [],
635
- spec: '',
636
- })
637
- return
638
- }
639
- patchPlugin({ busy: false, error: '安装失败:' + messageOf(result.error) })
640
- reloadPlugins()
641
- }, function (failure) {
642
- if (!alive.current) return
643
- patchPlugin({ busy: false, error: '调用失败:' + messageOf(failure) })
644
- })
645
- }
646
-
647
- function removePlugin(name) {
648
- patchPlugin({ busy: true, error: '', confirming: null, note: '' })
649
- callRemote('pluginAdmin/remove', { name: name }).then(function (result) {
650
- if (!alive.current) return
651
- if (result.ok) {
652
- patchPlugin({
653
- busy: false,
654
- note: '卸载完成。更改在重启 dsh 后生效',
655
- output: (result.value && result.value.output) || '',
656
- profileDir: (result.value && result.value.profileDir) || '',
657
- plugins: (result.value && result.value.plugins) || [],
658
- })
659
- return
660
- }
661
- patchPlugin({ busy: false, error: '卸载失败:' + messageOf(result.error) })
662
- reloadPlugins()
663
- }, function (failure) {
664
- if (!alive.current) return
665
- patchPlugin({ busy: false, error: '调用失败:' + messageOf(failure) })
666
- })
667
- }
668
-
669
- useEffect(function () {
670
- alive.current = true
671
- reloadPlugins()
672
- // Auto-check for remote updates on mount (the panel loads lazily when
673
- // the 插件管理 tab is opened, so this runs once per open). The host
674
- // caches registry answers for 5 minutes, so re-opening the tab shortly
675
- // after does not re-hit the registry. The manual ⬆ 检查更新 button stays
676
- // for forcing a fresh check.
677
- checkUpdates()
678
- return function () { alive.current = false }
679
- }, [])
680
-
681
- return createElement('div', { 'data-dsh-admin-section': '' },
682
- renderPluginsView(pView, patchPlugin, installPlugin, removePlugin, checkUpdates, upgradePlugin))
683
- }
684
-
685
- /**
686
- * Sessions management settings section (standalone, no internal tabs).
687
- */
688
- function SessionsSection(props) {
689
- var pairSessions = useState({
690
- sessions: [],
691
- workspaces: [],
692
- busy: false,
693
- error: '',
694
- needle: '',
695
- confirming: null,
696
- filter: 'all',
697
- })
698
- var sView = pairSessions[0]
699
- var setSView = pairSessions[1]
700
-
701
- var alive = useRef(false)
702
-
703
- function patchSession(partial) {
704
- setSView(function (cur) {
705
- var next = {}
706
- for (var k in cur) next[k] = cur[k]
707
- for (var pk in partial) next[pk] = partial[pk]
708
- return next
709
- })
710
- }
711
-
712
- function callRemote(method, args) {
713
- return props.call(method, args)
714
- }
715
-
716
- function reloadSessions() {
717
- patchSession({ busy: true, error: '' })
718
- callRemote('sessionAdmin/list', {}).then(function (result) {
719
- if (!alive.current) return
720
- if (result.ok) {
721
- patchSession({
722
- busy: false,
723
- sessions: (result.value && result.value.sessions) || [],
724
- workspaces: (result.value && result.value.workspaces) || [],
725
- })
726
- } else {
727
- patchSession({ busy: false, error: '加载会话失败:' + messageOf(result.error) })
728
- }
729
- }, function (failure) {
730
- if (!alive.current) return
731
- patchSession({ busy: false, error: '调用失败:' + messageOf(failure) })
732
- })
733
- }
734
-
735
- function actSession(method, sessionId) {
736
- patchSession({ busy: true, error: '', confirming: null })
737
- callRemote('sessionAdmin/' + method, { sessionId: sessionId }).then(function (result) {
738
- if (!alive.current) return
739
- if (result.ok) {
740
- // Refresh this panel's own list, and nudge the sidebar (via the
741
- // sessions service) so a deleted session disappears immediately
742
- // instead of lingering until reload.
743
- if ((method === 'deleteSession' || method === 'closeSession') && props.refreshSessions) props.refreshSessions()
744
- return reloadSessions()
745
- }
746
- patchSession({ busy: false, error: '操作失败:' + messageOf(result.error) })
747
- }, function (failure) {
748
- if (!alive.current) return
749
- patchSession({ busy: false, error: '调用失败:' + messageOf(failure) })
750
- })
751
- }
752
-
753
- useEffect(function () {
754
- alive.current = true
755
- reloadSessions()
756
- return function () { alive.current = false }
757
- }, [])
758
-
759
- return createElement('div', { 'data-dsh-admin-section': '' },
760
- renderSessionsView(sView, patchSession, reloadSessions, actSession))
761
- }
762
-
763
- /**
764
- * MCP configuration settings section (standalone, no internal tabs).
765
- */
766
-
767
- /* ------------------------------------------------------------------------ */
768
- /* MCP test-result cache */
769
- /* */
770
- /* Successful connectivity probes are persisted to localStorage so the */
771
- /* panel shows the last known status after tab switches or reopening the */
772
- /* dialog instead of an empty state. Only OK results are cached (failures */
773
- /* are usually transient); a cached row is labelled with its probe time, */
774
- /* and the cache entry is invalidated when the config is saved or removed, */
775
- /* or pruned when the entry disappears from the host list. */
776
- /* ------------------------------------------------------------------------ */
777
-
778
- var MCP_TEST_CACHE_KEY = 'dsh-plugin-admin/mcp-test-results'
779
-
780
- /**
781
- * Touch localStorage safely: on some environments (jsdom with an opaque
782
- * origin, hardened browsers, privacy modes) merely READING window.localStorage
783
- * throws a SecurityError, so the access itself has to sit inside try/catch.
784
- * Returns null when storage is unavailable.
785
- */
786
- function mcpTestStorage() {
787
- try {
788
- if (typeof window === 'undefined' || !window.localStorage) return null
789
- return window.localStorage
790
- } catch (e) {
791
- return null
792
- }
793
- }
794
-
795
- function loadMcpTestCache() {
796
- var store = mcpTestStorage()
797
- if (store === null) return {}
798
- try {
799
- var parsed = JSON.parse(store.getItem(MCP_TEST_CACHE_KEY))
800
- return parsed !== null && typeof parsed === 'object' ? parsed : {}
801
- } catch (e) {
802
- return {}
803
- }
804
- }
805
-
806
- /** Mirror settled, successful probes into localStorage (best-effort). */
807
- function saveMcpTestCache(state) {
808
- var store = mcpTestStorage()
809
- if (store === null) return
810
- try {
811
- var out = {}
812
- for (var id in state) {
813
- var s = state[id]
814
- // Busy rows keep the previous cached result; failures stay ephemeral.
815
- if (!s || s.busy || s.result === null || s.result === undefined) continue
816
- out[id] = { result: s.result, at: typeof s.at === 'number' ? s.at : Date.now() }
817
- }
818
- store.setItem(MCP_TEST_CACHE_KEY, JSON.stringify(out))
819
- } catch (e) {
820
- // Quota exceeded / storage blocked — the cache is optional, never fatal.
821
- }
822
- }
823
-
824
- /** Drop one entry's cached probe (config saved or entry removed). */
825
- function clearMcpTestCacheEntry(id) {
826
- var store = mcpTestStorage()
827
- if (store === null) return
828
- try {
829
- var state = loadMcpTestCache()
830
- if (state[id] === undefined) return
831
- delete state[id]
832
- store.setItem(MCP_TEST_CACHE_KEY, JSON.stringify(state))
833
- } catch (e) { /* ignore */ }
834
- }
835
-
836
- /** Drop test states whose entry no longer exists in the host list. */
837
- function pruneMcpTestState(map, entries) {
838
- var valid = {}
839
- for (var i = 0; i < entries.length; i++) valid[entries[i].id] = true
840
- var next = {}
841
- var changed = false
842
- for (var id in map) {
843
- if (valid[id]) next[id] = map[id]
844
- else changed = true
845
- }
846
- if (changed) saveMcpTestCache(next)
847
- return next
848
- }
849
-
850
- /** Compact timestamp for a cached probe ("14:32" today, "6-1 14:32" older). */
851
- function formatTestTime(ms) {
852
- if (typeof ms !== 'number' || !Number.isFinite(ms)) return ''
853
- var d = new Date(ms)
854
- var pad = function (n) { return (n < 10 ? '0' : '') + String(n) }
855
- var hm = pad(d.getHours()) + ':' + pad(d.getMinutes())
856
- var now = new Date()
857
- if (d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()) return hm
858
- return (d.getMonth() + 1) + '-' + d.getDate() + ' ' + hm
859
- }
860
-
861
- function McpSection(props) {
862
- var pairMcp = useState({
863
- mcpEntries: [],
864
- mcpBusy: false,
865
- mcpError: '',
866
- mcpEditorOpen: false,
867
- mcpDraft: null,
868
- // entryId -> { busy?, result?, error?, at? }; previous successful probes
869
- // are restored from localStorage so statuses survive panel remounts.
870
- mcpTestState: loadMcpTestCache(),
871
- })
872
- var mView = pairMcp[0]
873
- var setMView = pairMcp[1]
874
-
875
- var alive = useRef(false)
876
-
877
- function patchMcp(partial) {
878
- setMView(function (cur) {
879
- var next = {}
880
- for (var k in cur) next[k] = cur[k]
881
- for (var pk in partial) next[pk] = partial[pk]
882
- return next
883
- })
884
- }
885
-
886
- // Merge a partial into the CURRENT mcpDraft via a functional update, so
887
- // rapid successive field edits (React batching) never lose earlier input.
888
- function patchDraft(partial) {
889
- setMView(function (cur) {
890
- var next = {}
891
- for (var k in cur) next[k] = cur[k]
892
- next.mcpDraft = mergeDraft(cur.mcpDraft, partial)
893
- return next
894
- })
895
- }
896
-
897
- function callRemote(method, args) {
898
- return props.call(method, args)
899
- }
900
-
901
- function reloadMcp() {
902
- patchMcp({ mcpBusy: true, mcpError: '' })
903
- callRemote('mcpAdmin/list', {}).then(function (result) {
904
- if (!alive.current) return
905
- if (result.ok) {
906
- var entries = (result.value && result.value.entries) || []
907
- setMView(function (cur) {
908
- var next = {}
909
- for (var k in cur) next[k] = cur[k]
910
- next.mcpBusy = false
911
- next.mcpEntries = entries
912
- // Drop cached probes whose entry no longer exists on the host.
913
- next.mcpTestState = pruneMcpTestState(cur.mcpTestState, entries)
914
- return next
915
- })
916
- } else {
917
- patchMcp({ mcpBusy: false, mcpError: '加载 MCP 配置失败:' + messageOf(result.error) })
918
- }
919
- }, function (failure) {
920
- if (!alive.current) return
921
- patchMcp({ mcpBusy: false, mcpError: '调用失败:' + messageOf(failure) })
922
- })
923
- }
924
-
925
- function openMcpEditor(entry) {
926
- if (entry !== null && entry !== undefined && (entry.config === null || entry.config === undefined)) {
927
- patchMcp({ mcpError: ' MCP 配置无法安全解析,已禁止在此覆盖;请在 cordis.patch.yml 中手动编辑。' })
928
- return
929
- }
930
- var source = entry !== null && entry !== undefined ? entry.config : null
931
- var draft = source ? {
932
- id: entry.id,
933
- isNew: false,
934
- serverName: source.serverName || entry.id,
935
- transport: source.transport,
936
- command: source.command || '',
937
- url: source.url || '',
938
- args: (source.args || []).join(' '),
939
- argsOriginal: source.args || [],
940
- argsChanged: false,
941
- env: Object.keys(source.env || {}).map(function (key) { return key + '=' + source.env[key] }).join('\n'),
942
- envOriginal: source.env || {},
943
- envChanged: false,
944
- cwd: source.cwd || '',
945
- headers: Object.keys(source.headers || {}).map(function (k) { return k + '=' + source.headers[k] }).join('\n'),
946
- headersOriginal: source.headers || {},
947
- headersChanged: false,
948
- toolCallTimeoutMs: source.toolCallTimeoutMs,
949
- failOnStartupError: source.failOnStartupError === true,
950
- reconnectEnabled: source.reconnect ? source.reconnect.enabled === true : false,
951
- reconnectInitialDelayMs: source.reconnect ? source.reconnect.initialDelayMs : 1000,
952
- reconnectMaxDelayMs: source.reconnect ? source.reconnect.maxDelayMs : 30000,
953
- reconnectMaxAttempts: source.reconnect ? source.reconnect.maxAttempts : 10,
954
- } : {
955
- // New server: pre-fill a collision-free id so the user does not have to
956
- // invent one; they can still edit it or regenerate it.
957
- id: generateMcpId(mView.mcpEntries),
958
- isNew: true,
959
- serverName: '',
960
- transport: 'stdio',
961
- command: '',
962
- url: '',
963
- args: '',
964
- argsOriginal: [],
965
- argsChanged: false,
966
- env: '',
967
- envOriginal: {},
968
- envChanged: false,
969
- cwd: '',
970
- headers: '',
971
- headersOriginal: {},
972
- headersChanged: false,
973
- toolCallTimeoutMs: undefined,
974
- failOnStartupError: false,
975
- reconnectEnabled: false,
976
- reconnectInitialDelayMs: 1000,
977
- reconnectMaxDelayMs: 30000,
978
- reconnectMaxAttempts: 10,
979
- }
980
- patchMcp({ mcpEditorOpen: true, mcpDraft: draft, mcpError: '' })
981
- }
982
-
983
- function closeMcpEditor() {
984
- patchMcp({ mcpEditorOpen: false, mcpDraft: null, mcpError: '' })
985
- }
986
-
987
- function saveMcpDraft() {
988
- var draft = mView.mcpDraft
989
- if (draft === null) return
990
- var config
991
- if (draft.transport === 'streamable-http') {
992
- config = { transport: 'streamable-http', serverName: draft.serverName, url: draft.url }
993
- var headersStr = Object.keys(draft.headersOriginal || {}).map(function (k) { return k + '=' + draft.headersOriginal[k] }).join('\n')
994
- var headers = (draft.headersChanged && draft.headers !== headersStr) ? {} : draft.headersOriginal
995
- if (draft.headersChanged && draft.headers !== headersStr && draft.headers !== '') {
996
- // Newline-only split: header values legitimately contain ';'/','
997
- // (Cookie, Accept), which must never become pair separators.
998
- var pairs = draft.headers.split('\n').map(function (s) { return s.trim() }).filter(Boolean)
999
- for (var i = 0; i < pairs.length; i++) {
1000
- var eq = pairs[i].indexOf('=')
1001
- if (eq > 0) headers[pairs[i].slice(0, eq).trim()] = pairs[i].slice(eq + 1).trim()
1002
- }
1003
- }
1004
- if (Object.keys(headers).length > 0) config.headers = headers
1005
- } else {
1006
- config = { transport: 'stdio', serverName: draft.serverName, command: draft.command }
1007
- var argsStr = (draft.argsOriginal || []).join(' ')
1008
- var args = (draft.argsChanged && draft.args !== argsStr) ? draft.args.split(/\s+/).filter(Boolean) : draft.argsOriginal
1009
- if (args.length > 0) config.args = args
1010
- var envStr = Object.keys(draft.envOriginal || {}).map(function (k) { return k + '=' + draft.envOriginal[k] }).join('\n')
1011
- var env = (draft.envChanged && draft.env !== envStr) ? {} : draft.envOriginal
1012
- if (draft.envChanged && draft.env !== envStr && draft.env !== '') {
1013
- // Newline-only split: values like PATH=C:\a;C:\b would lose their
1014
- // tail (and Windows paths carry ';' everywhere).
1015
- var pairs = draft.env.split('\n').map(function (s) { return s.trim() }).filter(Boolean)
1016
- for (var i = 0; i < pairs.length; i++) {
1017
- var eq = pairs[i].indexOf('=')
1018
- if (eq > 0) env[pairs[i].slice(0, eq).trim()] = pairs[i].slice(eq + 1).trim()
1019
- }
1020
- }
1021
- if (Object.keys(env).length > 0) config.env = env
1022
- if (draft.cwd !== '') config.cwd = draft.cwd
1023
- }
1024
- if (draft.toolCallTimeoutMs !== undefined) config.toolCallTimeoutMs = draft.toolCallTimeoutMs
1025
- if (draft.failOnStartupError) config.failOnStartupError = true
1026
- if (draft.reconnectEnabled) {
1027
- config.reconnect = {
1028
- enabled: true,
1029
- initialDelayMs: Number(draft.reconnectInitialDelayMs),
1030
- maxDelayMs: Number(draft.reconnectMaxDelayMs),
1031
- maxAttempts: Number(draft.reconnectMaxAttempts),
1032
- }
1033
- }
1034
- patchMcp({ mcpBusy: true, mcpError: '' })
1035
- callRemote('mcpAdmin/upsert', { entry: { id: draft.id, config: config } }).then(function (result) {
1036
- if (!alive.current) return
1037
- if (result.ok) {
1038
- // The config changed, so any cached probe no longer describes this
1039
- // server — drop it from storage and from the panel.
1040
- clearMcpTestCacheEntry(draft.id)
1041
- patchMcpTest(draft.id, { busy: false, result: null, error: null })
1042
- patchMcp({ mcpBusy: false, mcpEntries: (result.value && result.value.entries) || [], mcpEditorOpen: false, mcpDraft: null })
1043
- } else {
1044
- patchMcp({ mcpBusy: false, mcpError: '保存 MCP 配置失败:' + messageOf(result.error) })
1045
- }
1046
- }, function (failure) {
1047
- if (!alive.current) return
1048
- patchMcp({ mcpBusy: false, mcpError: '调用失败:' + messageOf(failure) })
1049
- })
1050
- }
1051
-
1052
- function removeMcpEntry(id) {
1053
- patchMcp({ mcpBusy: true, mcpError: '' })
1054
- callRemote('mcpAdmin/remove', { id: id }).then(function (result) {
1055
- if (!alive.current) return
1056
- if (result.ok) {
1057
- // The entry is gone — its cached probe must not linger in storage.
1058
- clearMcpTestCacheEntry(id)
1059
- patchMcp({ mcpBusy: false, mcpEntries: (result.value && result.value.entries) || [] })
1060
- } else {
1061
- patchMcp({ mcpBusy: false, mcpError: '移除 MCP 配置失败:' + messageOf(result.error) })
1062
- }
1063
- }, function (failure) {
1064
- if (!alive.current) return
1065
- patchMcp({ mcpBusy: false, mcpError: '调用失败:' + messageOf(failure) })
1066
- })
1067
- }
1068
-
1069
- /**
1070
- * Set one entry's connectivity-test status against the CURRENT state.
1071
- * Settled successful probes are mirrored into localStorage so the last
1072
- * known status survives tab switches and reopening the settings dialog.
1073
- */
1074
- function patchMcpTest(id, partial) {
1075
- setMView(function (cur) {
1076
- var nextTestState = mergeTestState(cur.mcpTestState, id, partial)
1077
- saveMcpTestCache(nextTestState)
1078
- var next = {}
1079
- for (var k in cur) next[k] = cur[k]
1080
- next.mcpTestState = nextTestState
1081
- return next
1082
- })
1083
- }
1084
-
1085
- /** Run a host-side connectivity probe for one entry and stash the result. */
1086
- function testMcpEntry(id) {
1087
- patchMcpTest(id, { busy: true, result: null, error: null })
1088
- callRemote('mcpAdmin/test', { id: id }).then(function (result) {
1089
- if (!alive.current) return
1090
- if (result.ok && result.value !== null && typeof result.value === 'object') {
1091
- // `at` timestamps the probe; it is what the cached label renders.
1092
- patchMcpTest(id, { busy: false, result: result.value, at: Date.now() })
1093
- } else {
1094
- patchMcpTest(id, { busy: false, result: null, error: messageOf(result.error) })
1095
- }
1096
- }, function (failure) {
1097
- if (!alive.current) return
1098
- patchMcpTest(id, { busy: false, result: null, error: messageOf(failure) })
1099
- })
1100
- }
1101
-
1102
- useEffect(function () {
1103
- alive.current = true
1104
- reloadMcp()
1105
- return function () { alive.current = false }
1106
- }, [])
1107
-
1108
- return createElement('div', { 'data-dsh-admin-section': '' },
1109
- renderMcpSection(mView, patchDraft, reloadMcp, openMcpEditor, closeMcpEditor, saveMcpDraft, removeMcpEntry, testMcpEntry))
1110
- }
1111
-
1112
- /** Unified settings page; only the selected panel mounts and loads. */
1113
- function AdminCenterSection(props) {
1114
- var pairTab = useState('plugins')
1115
- var activeTab = pairTab[0]
1116
- var setActiveTab = pairTab[1]
1117
- var tabs = [
1118
- { id: 'plugins', label: '插件管理', component: PluginsSection },
1119
- { id: 'sessions', label: '会话管理', component: SessionsSection },
1120
- { id: 'mcp', label: 'MCP 配置', component: McpSection },
1121
- ]
1122
- var selected = tabs.find(function (tab) { return tab.id === activeTab }) || tabs[0]
1123
-
1124
- return createElement('div', { 'data-dsh-admin-section': '' },
1125
- createElement('div', { className: 'tabs', role: 'tablist', 'aria-label': '管理中心功能' },
1126
- tabs.map(function (tab) {
1127
- return createElement('button', {
1128
- type: 'button',
1129
- key: tab.id,
1130
- className: 'tab' + (tab.id === selected.id ? ' active' : ''),
1131
- role: 'tab',
1132
- 'aria-selected': tab.id === selected.id,
1133
- onClick: function () { setActiveTab(tab.id) },
1134
- }, tab.label)
1135
- })
1136
- ),
1137
- createElement(selected.component, { key: selected.id, call: props.call, refreshSessions: props.refreshSessions })
1138
- )
1139
- }
1140
-
1141
- /* ========================================================================== */
1142
- /* Render Plugins View */
1143
- /* ========================================================================== */
1144
-
1145
- function renderPluginsView(view, patch, install, remove, checkUpdates, upgrade) {
1146
- var elements = []
1147
-
1148
- // Toolbar: search (primary, wide) + install input + actions in one row.
1149
- elements.push(createElement('div', { className: 'toolbar', key: 'toolbar' },
1150
- createElement('div', { className: 'search-wrap', key: 'search-wrap' },
1151
- createElement('span', { className: 'search-icon', key: 'icon' }, '🔍'),
1152
- createElement('input', {
1153
- className: 'input',
1154
- key: 'search-input',
1155
- placeholder: '搜索插件(名称/版本/路径)...',
1156
- value: view.needle,
1157
- onChange: function (e) { patch({ needle: e.target.value }) },
1158
- }),
1159
- view.needle !== '' ? createElement('button', {
1160
- type: 'button',
1161
- key: 'btn-clear-search',
1162
- className: 'btn sm',
1163
- title: '清空搜索',
1164
- onClick: function () { patch({ needle: '' }) },
1165
- }, '') : null
1166
- ),
1167
- createElement('div', { className: 'input-wrap install-wrap', key: 'install-wrap' },
1168
- createElement('input', {
1169
- className: 'input',
1170
- placeholder: '安装包名/路径...',
1171
- value: view.spec,
1172
- disabled: view.busy,
1173
- onChange: function (e) { patch({ spec: e.target.value }) },
1174
- onKeyDown: function (e) { if (e.key === 'Enter') install() },
1175
- })
1176
- ),
1177
- createElement('button', {
1178
- type: 'button',
1179
- key: 'btn-install',
1180
- className: 'btn primary',
1181
- disabled: view.busy || view.spec.trim() === '',
1182
- onClick: install,
1183
- },
1184
- view.busy ? createElement('span', { className: 'spinner', key: 'spin' }) : null,
1185
- '安装'
1186
- ),
1187
- createElement('button', {
1188
- type: 'button',
1189
- key: 'btn-check-updates',
1190
- className: 'btn',
1191
- disabled: view.busy || view.checkingUpdates,
1192
- onClick: checkUpdates,
1193
- },
1194
- view.checkingUpdates ? createElement('span', { className: 'spinner', key: 'spin' }) : null,
1195
- view.checkingUpdates ? '检查中...' : '⬆️ 检查更新'
1196
- ),
1197
- ))
1198
-
1199
- // Filter Pills
1200
- var totalPlugins = view.plugins.length
1201
- var thirdPartyCount = 0
1202
- var builtinCount = 0
1203
- for (var i = 0; i < view.plugins.length; i++) {
1204
- if (view.plugins[i].removable) thirdPartyCount++
1205
- else builtinCount++
1206
- }
1207
-
1208
- elements.push(createElement('div', { className: 'filter-bar', key: 'filters' },
1209
- createElement('button', {
1210
- type: 'button',
1211
- key: 'filter-all',
1212
- className: 'pill' + (view.filter === 'all' ? ' active' : ''),
1213
- onClick: function () { patch({ filter: 'all' }) },
1214
- }, '全部 (' + String(totalPlugins) + ')'),
1215
- createElement('button', {
1216
- type: 'button',
1217
- key: 'filter-plugin',
1218
- className: 'pill' + (view.filter === 'plugin' ? ' active' : ''),
1219
- onClick: function () { patch({ filter: 'plugin' }) },
1220
- }, '扩展插件 (' + String(thirdPartyCount) + ')'),
1221
- createElement('button', {
1222
- type: 'button',
1223
- key: 'filter-builtin',
1224
- className: 'pill' + (view.filter === 'builtin' ? ' active' : ''),
1225
- onClick: function () { patch({ filter: 'builtin' }) },
1226
- }, '系统内置 (' + String(builtinCount) + ')')
1227
- ))
1228
-
1229
- // Busy banner / Error
1230
- if (view.busy) {
1231
- elements.push(createElement('div', { className: 'busy-banner', key: 'busy' },
1232
- createElement('span', { className: 'spinner', key: 'spin' }),
1233
- '正在执行 pnpm 操作(可能需要数秒至数分钟,请勿关闭窗口)...'
1234
- ))
1235
- }
1236
- if (view.error !== '') {
1237
- elements.push(createElement('div', { className: 'error', key: 'error' }, view.error))
1238
- }
1239
-
1240
- // Update-check status strip: gives the auto-check a visible outcome instead
1241
- // of hiding it in the footer. Checking → spinner; done with updates →
1242
- // orange; done without updates → green; per-plugin query failures surface
1243
- // on the strip rather than vanishing.
1244
- if (view.checkingUpdates) {
1245
- elements.push(createElement('div', { className: 'update-strip checking', key: 'update-checking' },
1246
- createElement('span', { className: 'spinner', key: 'spin' }),
1247
- '正在检查插件版本更新…'
1248
- ))
1249
- } else if (view.updateChecked) {
1250
- var upCount = 0
1251
- var errCount = 0
1252
- for (var un in view.updates) {
1253
- if (view.updates[un].updateAvailable === true) upCount++
1254
- if (view.updates[un].error) errCount++
1255
- }
1256
- var stripClass = upCount > 0 ? 'update-strip has-updates'
1257
- : (errCount > 0 ? 'update-strip has-errors' : 'update-strip ok')
1258
- var stripText = upCount > 0
1259
- ? '⬆️ 发现 ' + upCount + ' 个插件有新版本,可点击卡片上的「更新」升级'
1260
- : (errCount > 0
1261
- ? '⚠️ ' + errCount + ' 个插件查询版本失败(网络或 registry 不可达)'
1262
- : '✅ 已自动检查版本更新,全部为最新版本')
1263
- elements.push(createElement('div', { className: stripClass, key: 'update-result' },
1264
- createElement('span', { key: 't' }, stripText),
1265
- createElement('button', {
1266
- type: 'button',
1267
- key: 'btn-recheck',
1268
- className: 'btn sm',
1269
- disabled: view.busy || view.checkingUpdates,
1270
- onClick: checkUpdates,
1271
- }, '🔄 重新检查')
1272
- ))
1273
- }
1274
-
1275
- // Filter and render rows
1276
- var needle = view.needle.trim().toLowerCase()
1277
- var filtered = filterPlugins(view.plugins, view.filter, needle)
1278
- var rows = []
1279
- for (var j = 0; j < filtered.length; j++) {
1280
- var p = filtered[j]
1281
- rows.push(renderPluginCard(p, view, remove, patch, upgrade))
1282
- }
1283
-
1284
- if (rows.length === 0) {
1285
- rows.push(createElement('div', { className: 'empty', key: 'empty' },
1286
- createElement('div', null, needle !== '' ? '🔍 无匹配的插件(试试其他关键词)' : '📦 暂无匹配的插件层')
1287
- ))
1288
- }
1289
-
1290
- elements.push(createElement('div', { className: 'list', key: 'list' }, rows))
1291
-
1292
- // Footer
1293
- var hintText = view.note !== '' ? view.note : '更改在重启 dsh 后生效(关闭 dsh 进程后重新运行即可)'
1294
- var hintTitle = view.output !== '' ? 'pnpm 输出:\n' + view.output : undefined
1295
- elements.push(createElement('div', { className: 'footer', key: 'footer' },
1296
- createElement('span', { className: 'path', key: 'profile-path', title: view.profileDir }, view.profileDir || 'Profile: 默认'),
1297
- createElement('span', { className: 'hint', key: 'hint', title: hintTitle }, hintText)
1298
- ))
1299
-
1300
- return createElement('div', { key: 'plugins-panel', style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, elements)
1301
- }
1302
-
1303
-
1304
- function renderMcpSection(view, patchDraft, reloadMcp, openMcpEditor, closeMcpEditor, saveMcpDraft, removeMcpEntry, testMcpEntry) {
1305
- var children = []
1306
- var header = createElement('div', { className: 'group-header', key: 'mcp-header', style: { marginTop: 0 } },
1307
- createElement('span', { className: 'group-title', key: 't' }, '🔌 MCP 配置'),
1308
- createElement('span', { className: 'group-count', key: 'c' }, String(view.mcpEntries.length) + ' 个'),
1309
- createElement('button', {
1310
- type: 'button',
1311
- key: 'btn-refresh-mcp',
1312
- className: 'btn',
1313
- disabled: view.mcpBusy,
1314
- onClick: reloadMcp,
1315
- }, '🔄 刷新'),
1316
- createElement('button', {
1317
- type: 'button',
1318
- key: 'btn-add-mcp',
1319
- className: 'btn primary',
1320
- disabled: view.mcpBusy,
1321
- onClick: function () { openMcpEditor(null) },
1322
- }, '➕ 添加服务器'),
1323
- )
1324
- children.push(header)
1325
-
1326
- if (view.mcpError !== '') {
1327
- children.push(createElement('div', { className: 'error', key: 'mcp-error' }, view.mcpError))
1328
- }
1329
-
1330
- var rows = []
1331
- for (var i = 0; i < view.mcpEntries.length; i++) {
1332
- var entry = view.mcpEntries[i]
1333
- var tag = createElement('span', { className: 'tag plugin', key: 'mcp-tag-' + entry.id },
1334
- 'MCP ' + String(entry.serverName || entry.id))
1335
- var testState = (view.mcpTestState && view.mcpTestState[entry.id]) || null
1336
- var testIndicator = null
1337
- if (testState !== null && testState.busy) {
1338
- testIndicator = createElement('span', { className: 'mcp-test mcp-test-busy', key: 'test-busy' },
1339
- createElement('span', { className: 'spinner', key: 'sp' }),
1340
- ' 检测中...')
1341
- } else if (testState !== null && testState.result !== null && testState.result !== undefined) {
1342
- var r = testState.result
1343
- var ok = r.ok === true
1344
- var label = ok ? '✅ 连通'
1345
- : '❌ 不通'
1346
- var detail = ok
1347
- ? (r.serverInfo ? (r.serverInfo.name || '') + (r.serverInfo.version ? ' v' + r.serverInfo.version : '') : '') +
1348
- (typeof r.toolCount === 'number' ? ' · ' + r.toolCount + ' 个工具' : '') +
1349
- (r.pingOk === false ? ' · 初始化成功但 ping 失败' : '')
1350
- : (r.error || '连接失败') + (r.ms !== undefined ? ' (' + r.ms + 'ms)' : '')
1351
- var detailChildren = [
1352
- createElement('span', { key: 'lbl' }, label + (detail !== '' ? ' ' + detail : '')),
1353
- ]
1354
- if (ok && Array.isArray(r.tools) && r.tools.length > 0) {
1355
- detailChildren.push(createElement('span', { key: 'tools-hint', style: { opacity: 0.75 } },
1356
- '工具:' + r.tools.join('、')))
1357
- }
1358
- if (r.warning) {
1359
- detailChildren.push(createElement('span', { key: 'warn', className: 'mcp-test-warn', title: r.warning },
1360
- '⚠️ ' + r.warning))
1361
- }
1362
- // Cached probe: label when it was taken so a restored status is never
1363
- // mistaken for a just-run check. Clicking 🔌 测试 refreshes it.
1364
- if (typeof testState.at === 'number') {
1365
- detailChildren.push(createElement('span', {
1366
- key: 'cached-at',
1367
- className: 'mcp-test-cached',
1368
- title: '上次检测结果(本地缓存)。点击「🔌 测试」可重新检测。',
1369
- }, '· 缓存于 ' + formatTestTime(testState.at)))
1370
- }
1371
- testIndicator = createElement('div', {
1372
- className: 'mcp-test mcp-test-list ' + (ok ? 'mcp-test-ok' : 'mcp-test-fail'),
1373
- key: 'test-result',
1374
- title: detail,
1375
- }, detailChildren)
1376
- } else if (testState !== null && testState.error !== null && testState.error !== undefined) {
1377
- testIndicator = createElement('span', {
1378
- className: 'mcp-test mcp-test-fail',
1379
- key: 'test-error',
1380
- title: testState.error,
1381
- }, '❌ ' + testState.error)
1382
- }
1383
- var rowChildren = [
1384
- createElement('div', { className: 'card-header', key: 'h' },
1385
- createElement('span', { className: 'card-title-text', key: 'name' }, entry.id),
1386
- tag,
1387
- createElement('div', { className: 'card-actions', key: 'a' },
1388
- createElement('button', {
1389
- type: 'button',
1390
- className: 'btn sm',
1391
- disabled: view.mcpBusy || (testState !== null && testState.busy) || entry.config === null || entry.config === undefined,
1392
- title: entry.config === null || entry.config === undefined ? '该配置无法安全解析,请手动编辑 cordis.patch.yml' : (testState !== null && testState.busy ? '检测中...' : (testState !== null && typeof testState.at === 'number' ? '重新检测该服务器的连通性(当前显示的是缓存结果)' : '测试该服务器的连通性')),
1393
- onClick: function (id) { return function () { testMcpEntry(id) } }(entry.id),
1394
- }, testState !== null && testState.busy ? '检测中' : '🔌 测试'),
1395
- createElement('button', {
1396
- type: 'button',
1397
- className: 'btn sm',
1398
- disabled: view.mcpBusy || (testState !== null && testState.busy) || entry.config === null || entry.config === undefined,
1399
- title: entry.config === null || entry.config === undefined ? '该配置无法安全解析,请手动编辑 cordis.patch.yml' : undefined,
1400
- onClick: function (value) { return function () { openMcpEditor(value) } }(entry),
1401
- }, '编辑'),
1402
- createElement('button', {
1403
- type: 'button',
1404
- className: 'btn danger sm',
1405
- disabled: view.mcpBusy,
1406
- onClick: function (id) { return function () { removeMcpEntry(id) } }(entry.id),
1407
- }, '移除'),
1408
- ),
1409
- ),
1410
- ]
1411
- if (testIndicator !== null) {
1412
- rowChildren.push(createElement('div', { className: 'mcp-test-row', key: 'test-row' }, testIndicator))
1413
- }
1414
- rows.push(createElement('div', { className: 'card', key: 'mcp-' + entry.id }, rowChildren))
1415
- }
1416
- if (rows.length === 0) {
1417
- rows.push(createElement('div', { className: 'empty', key: 'mcp-empty' },
1418
- createElement('div', null, '🔌 暂无 MCP 服务器配置')
1419
- ))
1420
- }
1421
- children.push(createElement('div', { className: 'list', key: 'mcp-list' }, rows))
1422
-
1423
- // Editor form. patchDraft merges against the CURRENT draft in state so
1424
- // typing across fields never clobbers earlier edits (stale-closure guard).
1425
- if (view.mcpEditorOpen && view.mcpDraft !== null) {
1426
- var d = view.mcpDraft
1427
- var fieldStyle = { display: 'flex', flexDirection: 'column', gap: '4px', marginBottom: '8px' }
1428
- var labelStyle = { fontSize: '11px', color: 'var(--dsw-alias-label-secondary, #666)' }
1429
- var editor = createElement('div', { className: 'card', key: 'mcp-editor' },
1430
- createElement('div', { className: 'card-header', key: 'h' },
1431
- createElement('span', { className: 'card-title-text', key: 't' }, d.isNew ? '添加 MCP 服务器' : '编辑 ' + d.id),
1432
- ),
1433
- createElement('div', { style: fieldStyle, key: 'f-id' },
1434
- createElement('label', { style: labelStyle }, 'ID(唯一标识,[A-Za-z0-9_-])'),
1435
- createElement('div', { style: { display: 'flex', gap: '6px' } },
1436
- createElement('input', {
1437
- className: 'input',
1438
- value: d.id,
1439
- disabled: !d.isNew,
1440
- onChange: function (e) { patchDraft({ id: e.target.value }) },
1441
- }),
1442
- d.isNew ? createElement('button', {
1443
- type: 'button',
1444
- className: 'btn sm',
1445
- title: '重新生成一个随机 ID',
1446
- onClick: function () { patchDraft({ id: generateMcpId(view.mcpEntries) }) },
1447
- }, '🎲') : null,
1448
- ),
1449
- ),
1450
- createElement('div', { style: fieldStyle, key: 'f-server' },
1451
- createElement('label', { style: labelStyle }, 'serverName(模型命名空间)'),
1452
- createElement('input', {
1453
- className: 'input',
1454
- value: d.serverName,
1455
- onChange: function (e) { patchDraft({ serverName: e.target.value }) },
1456
- }),
1457
- ),
1458
- createElement('div', { style: fieldStyle, key: 'f-transport' },
1459
- createElement('label', { style: labelStyle }, '传输方式'),
1460
- createElement('select', {
1461
- className: 'input',
1462
- value: d.transport,
1463
- onChange: function (e) { patchDraft({ transport: e.target.value }) },
1464
- },
1465
- createElement('option', { value: 'stdio' }, 'stdio(子进程)'),
1466
- createElement('option', { value: 'streamable-http' }, 'streamable-http(HTTP)'),
1467
- ),
1468
- ),
1469
- d.transport === 'stdio' ? createElement('div', { style: fieldStyle, key: 'f-cmd' },
1470
- createElement('label', { style: labelStyle }, 'command(启动命令)'),
1471
- createElement('input', {
1472
- className: 'input',
1473
- value: d.command,
1474
- placeholder: 'npx -y @modelcontextprotocol/server-github',
1475
- onChange: function (e) { patchDraft({ command: e.target.value }) },
1476
- }),
1477
- ) : createElement('div', { style: fieldStyle, key: 'f-url' },
1478
- createElement('label', { style: labelStyle }, 'url(MCP 端点)'),
1479
- createElement('input', {
1480
- className: 'input',
1481
- value: d.url,
1482
- placeholder: 'http://localhost:3000/mcp',
1483
- onChange: function (e) { patchDraft({ url: e.target.value }) },
1484
- }),
1485
- ),
1486
- d.transport === 'streamable-http' ? createElement('div', { style: fieldStyle, key: 'f-headers' },
1487
- createElement('label', { style: labelStyle }, 'headers(每行 KEY=VALUE,可选)'),
1488
- createElement('textarea', {
1489
- className: 'input',
1490
- style: { minHeight: '48px' },
1491
- value: d.headers,
1492
- onChange: function (e) { patchDraft({ headers: e.target.value, headersChanged: true }) },
1493
- }),
1494
- ) : null,
1495
- d.transport === 'stdio' ? createElement('div', { style: fieldStyle, key: 'f-args' },
1496
- createElement('label', { style: labelStyle }, 'args(空格分隔,可选)'),
1497
- createElement('input', {
1498
- className: 'input',
1499
- value: d.args,
1500
- onChange: function (e) { patchDraft({ args: e.target.value, argsChanged: true }) },
1501
- }),
1502
- ) : null,
1503
- d.transport === 'stdio' ? createElement('div', { style: fieldStyle, key: 'f-env' },
1504
- createElement('label', { style: labelStyle }, 'env(每行 KEY=VALUE,可选)'),
1505
- createElement('textarea', {
1506
- className: 'input',
1507
- style: { minHeight: '48px' },
1508
- value: d.env,
1509
- onChange: function (e) { patchDraft({ env: e.target.value, envChanged: true }) },
1510
- }),
1511
- ) : null,
1512
- createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '6px', padding: '4px 0', marginBottom: '4px', borderTop: '1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.3))', paddingTop: '8px' }, key: 'f-reconnect-header' },
1513
- createElement('input', {
1514
- type: 'checkbox',
1515
- id: 'reconnect-toggle',
1516
- checked: d.reconnectEnabled,
1517
- onChange: function (e) { patchDraft({ reconnectEnabled: e.target.checked }) },
1518
- style: { margin: '0' },
1519
- }),
1520
- createElement('label', { htmlFor: 'reconnect-toggle', style: { fontSize: '12px', fontWeight: 500, cursor: 'pointer', color: 'var(--dsw-alias-label-primary, #333)' } }, '启用自动重连'),
1521
- ),
1522
- d.reconnectEnabled ? createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: '8px', marginBottom: '8px', paddingLeft: '4px' }, key: 'f-reconnect-fields' },
1523
- createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: '2px', flex: '1 1 120px' }, key: 'f-reconnect-id' },
1524
- createElement('label', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary, #666)' } }, 'initialDelayMs'),
1525
- createElement('input', {
1526
- className: 'input',
1527
- type: 'number',
1528
- min: 0,
1529
- value: d.reconnectInitialDelayMs,
1530
- onChange: function (e) { patchDraft({ reconnectInitialDelayMs: Number(e.target.value) }) },
1531
- }),
1532
- ),
1533
- createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: '2px', flex: '1 1 120px' }, key: 'f-reconnect-md' },
1534
- createElement('label', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary, #666)' } }, 'maxDelayMs'),
1535
- createElement('input', {
1536
- className: 'input',
1537
- type: 'number',
1538
- min: 0,
1539
- value: d.reconnectMaxDelayMs,
1540
- onChange: function (e) { patchDraft({ reconnectMaxDelayMs: Number(e.target.value) }) },
1541
- }),
1542
- ),
1543
- createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: '2px', flex: '1 1 120px' }, key: 'f-reconnect-ma' },
1544
- createElement('label', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary, #666)' } }, 'maxAttempts'),
1545
- createElement('input', {
1546
- className: 'input',
1547
- type: 'number',
1548
- min: 0,
1549
- value: d.reconnectMaxAttempts,
1550
- onChange: function (e) { patchDraft({ reconnectMaxAttempts: Number(e.target.value) }) },
1551
- }),
1552
- ),
1553
- ) : null,
1554
- createElement('div', { className: 'card-actions', key: 'f-actions', style: { justifyContent: 'flex-end', gap: '6px' } },
1555
- createElement('button', {
1556
- type: 'button',
1557
- className: 'btn',
1558
- disabled: view.mcpBusy,
1559
- onClick: closeMcpEditor,
1560
- }, '取消'),
1561
- createElement('button', {
1562
- type: 'button',
1563
- className: 'btn primary',
1564
- disabled: view.mcpBusy || d.id.trim() === '' || d.serverName.trim() === '' ||
1565
- (d.transport === 'stdio' ? d.command.trim() === '' : d.url.trim() === ''),
1566
- onClick: saveMcpDraft,
1567
- }, view.mcpBusy ? '保存中...' : '保存'),
1568
- ),
1569
- )
1570
- children.push(editor)
1571
- }
1572
-
1573
- return createElement('div', { key: 'mcp-section', style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, children)
1574
- }
1575
-
1576
- // Characters allowed in an MCP entry id: [A-Za-z0-9_-]. The random part uses
1577
- // alphanumerics only so the generated id reads cleanly and always matches the
1578
- // host-side validation regex.
1579
- var MCP_ID_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
1580
-
1581
- /**
1582
- * Generate a fresh MCP entry id that is not already used by any listed entry
1583
- * (an id collision would silently overwrite the existing entry on upsert).
1584
- */
1585
- function generateMcpId(entries) {
1586
- var taken = {}
1587
- for (var i = 0; i < entries.length; i++) taken[entries[i].id] = true
1588
- var candidate
1589
- do {
1590
- candidate = 'mcp-'
1591
- for (var j = 0; j < 8; j++) {
1592
- candidate += MCP_ID_ALPHABET.charAt(Math.floor(Math.random() * MCP_ID_ALPHABET.length))
1593
- }
1594
- } while (taken[candidate])
1595
- return candidate
1596
- }
1597
-
1598
- function mergeDraft(draft, partial) {
1599
- var next = {}
1600
- for (var k in draft) next[k] = draft[k]
1601
- for (var pk in partial) next[pk] = partial[pk]
1602
- return next
1603
- }
1604
-
1605
- /** Set one entry's test status inside the shared mcpTestState map. */
1606
- function mergeTestState(map, id, partial) {
1607
- var next = {}
1608
- for (var k in map) next[k] = map[k]
1609
- next[id] = {}
1610
- var cur = map[id] || {}
1611
- for (var ck in cur) next[id][ck] = cur[ck]
1612
- for (var pk in partial) next[id][pk] = partial[pk]
1613
- return next
1614
- }
1615
- function renderPluginCard(plugin, view, remove, patch, upgrade) {
1616
- var isConfirming = view.confirming === plugin.name
1617
-
1618
- var titleChildren = [
1619
- createElement('span', { className: 'card-title-text', key: 'name' }, plugin.name),
1620
- ]
1621
- if (plugin.version) {
1622
- titleChildren.push(createElement('span', { className: 'tag version', key: 'version' }, 'v' + plugin.version))
1623
- }
1624
- var isLocal = Boolean(plugin.localPath)
1625
- titleChildren.push(createElement('span', {
1626
- className: plugin.removable ? (isLocal ? 'tag local' : 'tag plugin') : 'tag',
1627
- key: 'type-tag',
1628
- },
1629
- plugin.removable ? (isLocal ? '本地安装' : '包安装') : '内置'
1630
- ))
1631
-
1632
- // Remote update badge: only for registry-installed bundles (removable and
1633
- // not a local path) after a check ran. `updates` is keyed by plugin name.
1634
- var updateInfo = view.updates && view.updates[plugin.name]
1635
- if (updateInfo && updateInfo.updateAvailable && updateInfo.latest) {
1636
- titleChildren.push(createElement('span', {
1637
- className: 'tag update',
1638
- key: 'update-badge',
1639
- title: '远程 registry 有新版本:v' + updateInfo.latest + '(当前 v' + plugin.version + ')',
1640
- }, '⬆ 有新版本 v' + updateInfo.latest))
1641
- } else if (updateInfo && updateInfo.error) {
1642
- titleChildren.push(createElement('span', {
1643
- className: 'tag update-error',
1644
- key: 'update-error',
1645
- title: updateInfo.error,
1646
- }, ' 更新检查失败'))
1647
- }
1648
-
1649
- var headerChildren = [
1650
- createElement('div', { className: 'card-title', key: 'title' }, titleChildren),
1651
- ]
1652
-
1653
- if (plugin.removable && !isConfirming) {
1654
- var actionChildren = []
1655
- // 更新 button only when an update is available and the plugin is a
1656
- // registry install (not local path).
1657
- if (updateInfo && updateInfo.updateAvailable && updateInfo.latest && !isLocal) {
1658
- actionChildren.push(createElement('button', {
1659
- type: 'button',
1660
- key: 'btn-upgrade',
1661
- className: 'btn sm',
1662
- disabled: view.busy,
1663
- title: '升级到 v' + updateInfo.latest + '(npm install ' + plugin.name + '@latest)',
1664
- onClick: function () { upgrade(plugin.name) },
1665
- }, '⬆ 更新'))
1666
- }
1667
- actionChildren.push(createElement('button', {
1668
- type: 'button',
1669
- key: 'btn-remove',
1670
- className: 'btn danger sm',
1671
- disabled: view.busy,
1672
- onClick: function () { patch({ confirming: plugin.name }) },
1673
- }, '卸载'))
1674
- headerChildren.push(createElement('div', { className: 'card-actions', key: 'actions' }, actionChildren))
1675
- }
1676
-
1677
- var header = createElement('div', { className: 'card-header', key: 'header' }, headerChildren)
1678
- var cardChildren = [header]
1679
-
1680
- if (plugin.localPath) {
1681
- cardChildren.push(createElement('div', { className: 'plugin-path', key: 'path', title: plugin.localPath },
1682
- '📂 ' + plugin.localPath
1683
- ))
1684
- }
1685
-
1686
- if (isConfirming) {
1687
- cardChildren.push(createElement('div', { className: 'confirm-bar', key: 'confirm' },
1688
- createElement('span', { className: 'confirm-text', key: 'text' }, '⚠️ 确定要卸载该插件吗?'),
1689
- createElement('div', { className: 'confirm-actions', key: 'actions' },
1690
- createElement('button', {
1691
- type: 'button',
1692
- key: 'btn-confirm',
1693
- className: 'btn danger-solid sm',
1694
- disabled: view.busy,
1695
- onClick: function () { remove(plugin.name) },
1696
- }, '确认卸载'),
1697
- createElement('button', {
1698
- type: 'button',
1699
- key: 'btn-cancel',
1700
- className: 'btn sm',
1701
- disabled: view.busy,
1702
- onClick: function () { patch({ confirming: null }) },
1703
- }, '取消')
1704
- )
1705
- ))
1706
- }
1707
-
1708
- return createElement('div', { key: plugin.name, className: 'card' }, cardChildren)
1709
- }
1710
-
1711
- /* ========================================================================== */
1712
- /* Render Sessions View */
1713
- /* ========================================================================== */
1714
-
1715
- /**
1716
- * Live-session display hint. "Online" means the session is still mounted in
1717
- * the dsh host's in-memory SessionStore (created or opened at least once in
1718
- * this process) — NOT that a turn is running. Online sessions can now be
1719
- * closed directly: the admin panel's "关停并删除" disposes the captured agent
1720
- * handle (stopping any running turn), removes the session from the store,
1721
- * and then deletes the log no restart needed.
1722
- */
1723
- var LIVE_HINT = '会话在线:仍挂载于 dsh host 内存(本进程内创建或打开过的会话保持在线,不代表正在运行);可直接"关停并删除"(会中断该会话正在进行的对话)'
1724
-
1725
- /**
1726
- * Canonical session status. Live takes precedence over archived (a session
1727
- * that is both live and in the archived set is shown as 会话在线); otherwise
1728
- * archived wins over ended. Used by both the filter pills and the pill
1729
- * counts so they can never disagree about membership.
1730
- */
1731
- function sessionStatus(s) {
1732
- if (s.live) return 'live'
1733
- if (s.archived) return 'archived'
1734
- return 'ended'
1735
- }
1736
-
1737
- function filterSessions(sessions, filter, needle) {
1738
- var result = []
1739
- for (var i = 0; i < sessions.length; i++) {
1740
- var s = sessions[i]
1741
- if (filter !== 'all' && sessionStatus(s) !== filter) continue
1742
- if (needle !== '') {
1743
- var hay = ((s.title || '') + ' ' + (s.summary || '') + ' ' + (s.cwd || '') + ' '
1744
- + (s.workspaceTitle || '') + ' ' + s.id).toLowerCase()
1745
- if (hay.indexOf(needle) === -1) continue
1746
- }
1747
- result.push(s)
1748
- }
1749
- return result
1750
- }
1751
-
1752
- /**
1753
- * Filter plugin layers by the type pill and a fuzzy name/version/path query.
1754
- * The needle matches case-insensitively against the package name, the
1755
- * installed version, and the local source path, so "tool" finds
1756
- * dsh-custom-tool and "0.2" finds version rows.
1757
- */
1758
- function filterPlugins(plugins, filter, needle) {
1759
- var result = []
1760
- for (var i = 0; i < plugins.length; i++) {
1761
- var p = plugins[i]
1762
- if (filter === 'plugin' && !p.removable) continue
1763
- if (filter === 'builtin' && p.removable) continue
1764
- if (needle !== '') {
1765
- var hay = ((p.name || '') + ' ' + (p.version || '') + ' ' + (p.localPath || '')).toLowerCase()
1766
- if (hay.indexOf(needle) === -1) continue
1767
- }
1768
- result.push(p)
1769
- }
1770
- return result
1771
- }/**
1772
- * Group sessions by their accounting workspace in registry order; sessions
1773
- * without a workspace trail under an "未分组" bucket. Empty workspaces are
1774
- * omitted so the user only sees groups that currently hold a session.
1775
- */
1776
- function buildSessionGroups(filtered, workspaceOrder) {
1777
- var byWs = new Map()
1778
- for (var i = 0; i < workspaceOrder.length; i++) {
1779
- var ws = workspaceOrder[i]
1780
- byWs.set(ws.workspaceId, {
1781
- workspaceId: ws.workspaceId, title: ws.title, path: ws.path, sessions: [],
1782
- })
1783
- }
1784
- var ungrouped = []
1785
- for (var j = 0; j < filtered.length; j++) {
1786
- var s = filtered[j]
1787
- var g = s.workspaceId ? byWs.get(s.workspaceId) : undefined
1788
- if (g !== undefined) g.sessions.push(s)
1789
- else ungrouped.push(s)
1790
- }
1791
- var groups = []
1792
- for (var k = 0; k < workspaceOrder.length; k++) {
1793
- var bucket = byWs.get(workspaceOrder[k].workspaceId)
1794
- if (bucket !== undefined && bucket.sessions.length > 0) groups.push(bucket)
1795
- }
1796
- if (ungrouped.length > 0) {
1797
- groups.push({ workspaceId: null, title: '未分组', path: null, sessions: ungrouped })
1798
- }
1799
- return groups
1800
- }
1801
-
1802
- function renderSessionsView(view, patch, reload, act) {
1803
- var elements = []
1804
-
1805
- // Toolbar: full-width search with inline icon; the refresh action sits at
1806
- // the row's end so the search field gets the whole width.
1807
- elements.push(createElement('div', { className: 'toolbar', key: 'toolbar' },
1808
- createElement('div', { className: 'search-wrap session-search', key: 'wrap' },
1809
- createElement('span', { className: 'search-icon', key: 'icon' }, '🔍'),
1810
- createElement('input', {
1811
- className: 'input',
1812
- placeholder: '搜索标题、内容摘要、目录或 Session ID...',
1813
- value: view.needle,
1814
- onChange: function (e) { patch({ needle: e.target.value }) },
1815
- }),
1816
- view.needle !== '' ? createElement('button', {
1817
- type: 'button',
1818
- key: 'btn-clear-search',
1819
- className: 'btn sm',
1820
- title: '清空搜索',
1821
- onClick: function () { patch({ needle: '' }) },
1822
- }, '✕') : null
1823
- ),
1824
- createElement('button', {
1825
- type: 'button',
1826
- key: 'btn-refresh',
1827
- className: 'btn',
1828
- disabled: view.busy,
1829
- onClick: reload,
1830
- },
1831
- view.busy ? createElement('span', { className: 'spinner', key: 'spin' }) : null,
1832
- '🔄 刷新'
1833
- )
1834
- ))
1835
-
1836
- // Filter Pills
1837
- var totalSessions = view.sessions.length
1838
- var liveCount = 0
1839
- var archivedCount = 0
1840
- var endedCount = 0
1841
- for (var i = 0; i < view.sessions.length; i++) {
1842
- var s = view.sessions[i]
1843
- var st = sessionStatus(s)
1844
- if (st === 'live') liveCount++
1845
- else if (st === 'archived') archivedCount++
1846
- else endedCount++
1847
- }
1848
-
1849
- elements.push(createElement('div', { className: 'filter-bar', key: 'filters' },
1850
- createElement('button', {
1851
- type: 'button',
1852
- key: 'filter-all',
1853
- className: 'pill' + (view.filter === 'all' ? ' active' : ''),
1854
- onClick: function () { patch({ filter: 'all' }) },
1855
- }, '全部 (' + String(totalSessions) + ')'),
1856
- createElement('button', {
1857
- type: 'button',
1858
- key: 'filter-live',
1859
- className: 'pill' + (view.filter === 'live' ? ' active' : ''),
1860
- title: LIVE_HINT,
1861
- onClick: function () { patch({ filter: 'live' }) },
1862
- }, '在线 (' + String(liveCount) + ')'),
1863
- createElement('button', {
1864
- type: 'button',
1865
- key: 'filter-archived',
1866
- className: 'pill' + (view.filter === 'archived' ? ' active' : ''),
1867
- onClick: function () { patch({ filter: 'archived' }) },
1868
- }, '已归档 (' + String(archivedCount) + ')'),
1869
- createElement('button', {
1870
- type: 'button',
1871
- key: 'filter-ended',
1872
- className: 'pill' + (view.filter === 'ended' ? ' active' : ''),
1873
- onClick: function () { patch({ filter: 'ended' }) },
1874
- }, '已结束 (' + String(endedCount) + ')')
1875
- ))
1876
-
1877
- if (view.error !== '') {
1878
- elements.push(createElement('div', { className: 'error', key: 'error' }, view.error))
1879
- }
1880
-
1881
- // Filter then group by workspace (registry order); sessions without an
1882
- // accounting workspace trail under "未分组", matching the sidebar model.
1883
- var needle = view.needle.trim().toLowerCase()
1884
- var filtered = filterSessions(view.sessions, view.filter, needle)
1885
- var groups = buildSessionGroups(filtered, view.workspaces || [])
1886
- var rows = []
1887
- for (var gi = 0; gi < groups.length; gi++) {
1888
- var g = groups[gi]
1889
- var groupKey = g.workspaceId === null ? 'ungrouped' : 'ws-' + g.workspaceId
1890
- rows.push(createElement('div', { className: 'group-header', key: 'header-' + groupKey },
1891
- createElement('span', { className: 'group-title', key: 'title' },
1892
- (g.workspaceId === null ? '📂 ' : '📁 ') + (g.title || '未命名')
1893
- ),
1894
- createElement('span', { className: 'group-count', key: 'count' }, String(g.sessions.length) + ' 个'),
1895
- g.path !== null
1896
- ? createElement('span', { className: 'group-path', key: 'path', title: g.path }, g.path)
1897
- : null
1898
- ))
1899
- for (var si = 0; si < g.sessions.length; si++) {
1900
- rows.push(renderSessionCard(g.sessions[si], view, act, patch))
1901
- }
1902
- }
1903
-
1904
- if (rows.length === 0) {
1905
- rows.push(createElement('div', { className: 'empty', key: 'empty' },
1906
- createElement('div', null, needle !== '' ? '🔍 无匹配的会话内容' : '💬 没有已持久化的会话')
1907
- ))
1908
- }
1909
-
1910
- elements.push(createElement('div', { className: 'list', key: 'list' }, rows))
1911
-
1912
- // Footer
1913
- var summaryText = view.busy ? '加载中...'
1914
- : '共 ' + String(totalSessions) + ' 个会话,当前展示 ' + String(filtered.length) + ' 个'
1915
-
1916
- elements.push(createElement('div', { className: 'footer', key: 'footer' },
1917
- createElement('span', { key: 'summary' }, summaryText),
1918
- createElement('span', { className: 'hint', key: 'hint' }, '会话修改即时同步到侧边栏')
1919
- ))
1920
-
1921
- return createElement('div', { key: 'sessions-panel', style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, elements)
1922
- }
1923
-
1924
- function renderSessionCard(session, view, act, patch) {
1925
- var isConfirming = view.confirming === session.id
1926
- var dotClass = 'dot' + (session.live ? ' live' : session.archived ? ' archived' : '')
1927
- var dotTitle = session.live ? LIVE_HINT : session.archived ? '已归档' : '已结束'
1928
-
1929
- var actions = []
1930
- if (!isConfirming) {
1931
- if (!session.archived && !session.live) {
1932
- actions.push(createElement('button', {
1933
- type: 'button',
1934
- className: 'btn sm',
1935
- key: 'btn-archive',
1936
- disabled: view.busy,
1937
- onClick: function () { act('archive', session.id) },
1938
- }, '归档'))
1939
- }
1940
- if (session.archived) {
1941
- actions.push(createElement('button', {
1942
- type: 'button',
1943
- className: 'btn sm',
1944
- key: 'btn-unarchive',
1945
- disabled: view.busy,
1946
- onClick: function () { act('unarchive', session.id) },
1947
- }, '取消归档'))
1948
- }
1949
- if (!session.live) {
1950
- actions.push(createElement('button', {
1951
- type: 'button',
1952
- className: 'btn danger sm',
1953
- key: 'btn-delete',
1954
- disabled: view.busy,
1955
- onClick: function () { patch({ confirming: session.id }) },
1956
- }, '删除'))
1957
- } else {
1958
- // Online sessions can now be closed through the captured AgentHandle
1959
- // (closeSession disposes the live agent/session first, so the log can
1960
- // be removed without resurrection). This stops a running conversation,
1961
- // so it is a destructive action with its own confirm flow.
1962
- actions.push(createElement('button', {
1963
- type: 'button',
1964
- className: 'btn danger sm',
1965
- key: 'btn-close',
1966
- disabled: view.busy,
1967
- title: '关停该在线会话(停止其 agent 运行)并永久删除日志记录',
1968
- onClick: function () { patch({ confirming: session.id }) },
1969
- }, '关停并删除'))
1970
- }
1971
- }
1972
-
1973
- var titleChildren = [
1974
- createElement('span', { className: dotClass, title: dotTitle, key: 'dot' }),
1975
- createElement('div', { className: 'card-title', key: 'title' },
1976
- createElement('span', { className: 'card-title-text', key: 'name', title: session.title || session.cwd },
1977
- session.title || (session.cwd ? baseName(session.cwd) : '未命名会话')
1978
- ),
1979
- session.live ? createElement('span', { className: 'tag live', key: 'tag-live', title: LIVE_HINT }, '会话在线')
1980
- : session.archived ? createElement('span', { className: 'tag archived', key: 'tag-archived' }, '已归档')
1981
- : null,
1982
- session.messageCount > 0 ? createElement('span', { className: 'tag turns', key: 'tag-turns' }, String(session.messageCount) + ' 条消息') : null
1983
- ),
1984
- ]
1985
- var headerChildren
1986
- if (actions.length > 0) {
1987
- headerChildren = titleChildren.concat([createElement('div', { className: 'card-actions', key: 'actions' }, actions)])
1988
- } else {
1989
- headerChildren = titleChildren
1990
- }
1991
-
1992
- var header = createElement('div', { className: 'card-header', key: 'header' }, headerChildren)
1993
- var cardChildren = [header]
1994
-
1995
- // Content summary block
1996
- if (session.summary) {
1997
- cardChildren.push(createElement('div', { className: 'card-summary', key: 'summary', title: session.summary },
1998
- createElement('span', { className: 'summary-icon', key: 'icon' }, '💬'),
1999
- createElement('span', { className: 'summary-text', key: 'text' }, session.summary)
2000
- ))
2001
- } else if (session.summaryError) {
2002
- cardChildren.push(createElement('div', { className: 'error', key: 'summary-error' },
2003
- '摘要读取失败:' + session.summaryError
2004
- ))
2005
- }
2006
-
2007
- // Sub metadata line
2008
- var subChildren = [
2009
- createElement('span', { className: 'card-sub-item', title: session.cwd || '无工作目录', key: 'path' },
2010
- '📁 ' + (session.cwd ? baseName(session.cwd) + ' (' + session.cwd + ')' : '(无工作目录)')
2011
- ),
2012
- createElement('span', { key: 'sep1' }, '·'),
2013
- createElement('span', { className: 'card-sub-item', key: 'time' }, '🕒 ' + formatDate(session.createdAt)),
2014
- ]
2015
- if (session.id) {
2016
- subChildren.push(createElement('span', { key: 'sep2' }, '·'))
2017
- subChildren.push(createElement('span', { className: 'card-sub-item session-id-badge', key: 'id', title: '会话 ID: ' + session.id },
2018
- '🆔 ' + session.id.slice(0, 8)
2019
- ))
2020
- }
2021
-
2022
- var sub = createElement('div', { className: 'card-sub', key: 'sub' }, subChildren)
2023
- cardChildren.push(sub)
2024
-
2025
- if (isConfirming) {
2026
- cardChildren.push(createElement('div', { className: 'confirm-bar', key: 'confirm' },
2027
- createElement('span', { className: 'confirm-text', key: 'text' },
2028
- session.live
2029
- ? '⚠️ 将关停该在线会话(正在运行则会中断)并永久删除记录与日志,确定?'
2030
- : '⚠️ 确定永久删除该会话记录及日志文件?'),
2031
- createElement('div', { className: 'confirm-actions', key: 'actions' },
2032
- createElement('button', {
2033
- type: 'button',
2034
- key: 'btn-confirm',
2035
- className: 'btn danger-solid sm',
2036
- disabled: view.busy,
2037
- onClick: function () { act(session.live ? 'closeSession' : 'deleteSession', session.id) },
2038
- }, '确认删除'),
2039
- createElement('button', {
2040
- type: 'button',
2041
- key: 'btn-cancel',
2042
- className: 'btn sm',
2043
- disabled: view.busy,
2044
- onClick: function () { patch({ confirming: null }) },
2045
- }, '取消')
2046
- )
2047
- ))
2048
- }
2049
-
2050
- return createElement('div', { key: session.id, className: 'card' }, cardChildren)
2051
- }
2052
-
2053
- /* ========================================================================== */
2054
- /* Plugin Entrypoint */
2055
- /* ========================================================================== */
2056
-
2057
- function apply(ctx) {
2058
- injectStyles()
2059
-
2060
- var call = function (method, args) {
2061
- return ctx.connection.rpc.call('/api', method, { args: args })
2062
- }
2063
-
2064
- // Sidebar right-click menus: delete session (after archive) on session
2065
- // rows, reveal in explorer on workspace rows. Mounted once for the page
2066
- // lifetime; dispose when the plugin unmounts.
2067
- // The sessions service lets us nudge the sidebar list after a delete so
2068
- // the removed session disappears immediately instead of lingering in
2069
- // "未分组" until the next reload.
2070
- var refreshSessions = null
2071
- try {
2072
- var sessionsSvc = ctx.get && ctx.get('sessions')
2073
- if (sessionsSvc && typeof sessionsSvc.refresh === 'function') {
2074
- refreshSessions = function () { sessionsSvc.refresh().catch(function () {}) }
2075
- }
2076
- } catch (e) { refreshSessions = null }
2077
- var disposeSidebar = ctx.effect(function () { return setupMenuInjection(call, refreshSessions) })
2078
-
2079
- // One management-center entry keeps related local administration together;
2080
- // its tab container mounts only the selected panel.
2081
- ctx.slots.inject('settings.section', function () {
2082
- return ctx.slots.register({
2083
- name: 'settings.section',
2084
- id: 'plugin-admin',
2085
- order: 25,
2086
- label: '管理中心',
2087
- inject: function () { return { call: call, refreshSessions: refreshSessions } },
2088
- }, AdminCenterSection)
2089
- })
2090
- }
2091
-
2092
- module.exports = { apply: apply, inject: ['slots', 'connection'] }
2093
- return module.exports
2094
- } });
1
+ window.__ModuleLoader__.load({ id: 'dsh-plugin-admin', factory: (require) => {
2
+ var module = { exports: {} }; var exports = module.exports;
3
+
4
+ /**
5
+ * dsh-plugin-admin browser half: unified "管理中心" (插件管理 & 会话管理)
6
+ * page inside the settings panel.
7
+ *
8
+ * The page rides the shell's `settings.section` slot (the shell owns
9
+ * the dialog chrome, navigation, and close); its component is assembled with
10
+ * the platform-shared React (module-table seed word, same instance the shell
11
+ * renders with), providing a tabbed modern UI to manage both profile plugin
12
+ * layers and session lifecycles over the /api RPC gateway.
13
+ */
14
+
15
+ var React = require('react')
16
+ var createElement = React.createElement
17
+ var useState = React.useState
18
+ var useRef = React.useRef
19
+ var useEffect = React.useEffect
20
+
21
+ var CSS_TEXT = [
22
+ '@keyframes dsh-admin-spin { to { transform: rotate(360deg); } }',
23
+ '@keyframes dsh-admin-pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.35; transform: scale(0.85); } }',
24
+ '[data-dsh-admin-section] { display: flex; flex-direction: column; width: 100%; gap: 14px; padding: 2px; font-size: 13px; line-height: 1.5; color: var(--dsw-alias-label-primary, #222); max-height: calc(100vh - 140px); overflow: hidden; }',
25
+ '[data-dsh-admin-section] * { box-sizing: border-box; }',
26
+ '[data-dsh-admin-section] .tabs { display: flex; padding: 3px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.2)); border-radius: 9px; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.3)); gap: 3px; }',
27
+ '[data-dsh-admin-section] .tab { flex: 1; border: 0; background: transparent; border-radius: 7px; padding: 7px 14px; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 7px; font-size: 12px; font-weight: 500; color: var(--dsw-alias-label-secondary, #666); transition: all 0.15s ease; font-family: inherit; }',
28
+ '[data-dsh-admin-section] .tab:hover:not(.active) { color: var(--dsw-alias-label-primary, #222); background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.3)); }',
29
+ '[data-dsh-admin-section] .tab.active { background: var(--dsw-alias-bg-elevated, var(--dsw-alias-bg-base, transparent)); color: var(--dsw-alias-label-primary, #333); font-weight: 600; box-shadow: 0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.04); }',
30
+ '[data-dsh-admin-section] .tab-count { font-size: 10px; font-weight: 600; padding: 1px 6px; border-radius: 10px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.4)); color: var(--dsw-alias-label-secondary, #555); }',
31
+ '[data-dsh-admin-section] .tab.active .tab-count { background: var(--dsw-static-blue-500, #3b82f6); color: #fff; }',
32
+ '[data-dsh-admin-section] .toolbar { display: flex; gap: 8px; align-items: center; padding: 10px; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)); border-radius: 12px; background: var(--dsw-alias-bg-elevated, var(--dsw-alias-bg-base, transparent)); box-shadow: 0 1px 2px rgba(0,0,0,0.02); }',
33
+ '[data-dsh-admin-section] .toolbar .input { height: 32px; padding: 0 12px; border-radius: 8px; border-color: var(--dsw-alias-border-subtle, rgba(200,200,210,0.5)); }',
34
+ '[data-dsh-admin-section] .search-wrap { flex: 1.6; min-width: 0; position: relative; display: flex; align-items: center; height: 32px; }',
35
+ '[data-dsh-admin-section] .search-wrap .input { flex: 1; min-width: 0; padding-left: 30px; font-size: 13px; }',
36
+ '[data-dsh-admin-section] .session-search { flex: 1; height: 32px; }',
37
+ '[data-dsh-admin-section] .session-search .input { height: 32px; padding: 0 12px; font-size: 13px; border-radius: 8px; border-color: var(--dsw-alias-border-subtle, rgba(200,200,210,0.5)); }',
38
+ '[data-dsh-admin-section] .install-wrap { flex: 1; min-width: 0; display: flex; align-items: center; height: 32px; }',
39
+ '[data-dsh-admin-section] .install-wrap .input { flex: 1; min-width: 0; font-size: 13px; border-radius: 8px; border-color: var(--dsw-alias-border-subtle, rgba(200,200,210,0.5)); }',
40
+ '[data-dsh-admin-section] .search-icon { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); font-size: 12px; opacity: 0.7; pointer-events: none; z-index: 1; }',
41
+ '[data-dsh-admin-section] .input { width: 100%; padding: 7px 12px; border-radius: 9px; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.5)); background: var(--dsw-alias-bg-base, transparent); color: inherit; font: inherit; outline: none; transition: border-color 0.15s, box-shadow 0.15s, background 0.15s; }',
42
+ '[data-dsh-admin-section] .input:hover { border-color: var(--dsw-alias-label-tertiary, rgba(180,180,195,0.6)); }',
43
+ '[data-dsh-admin-section] .input:focus { border-color: var(--dsw-static-blue-500, #3b82f6); box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.16); }',
44
+ '[data-dsh-admin-section] .filter-bar { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }',
45
+ '[data-dsh-admin-section] .pill { font-size: 11px; padding: 2px 8px; border-radius: 6px; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.45)); background: transparent; cursor: pointer; color: var(--dsw-alias-label-secondary, #555); transition: all 0.12s; font-family: inherit; }',
46
+ '[data-dsh-admin-section] .pill:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.3)); }',
47
+ '[data-dsh-admin-section] .pill.active { background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.4)); color: var(--dsw-static-blue-500, #3b82f6); font-weight: 600; border-color: currentColor; }',
48
+ '[data-dsh-admin-section] .btn { display: inline-flex; align-items: center; justify-content: center; gap: 5px; height: 32px; padding: 0 14px; border-radius: 8px; font-size: 13px; font-weight: 500; cursor: pointer; font-family: inherit; transition: transform 0.15s ease, background 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease, color 0.15s ease; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.5)); background: var(--dsw-alias-interactive-bg-hover, rgba(240,240,245,0.6)); color: var(--dsw-alias-label-secondary, #555); white-space: nowrap; flex: none; box-shadow: 0 1px 2px rgba(0,0,0,0.04); }',
49
+ '[data-dsh-admin-section] .btn:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover, rgba(220,220,230,0.7)); border-color: var(--dsw-alias-label-tertiary, rgba(180,180,195,0.65)); color: var(--dsw-alias-label-primary, #222); box-shadow: 0 2px 4px rgba(0,0,0,0.06); }',
50
+ '[data-dsh-admin-section] .search-wrap .btn.sm { background: transparent; border: none; box-shadow: none; padding: 2px 6px; color: var(--dsw-alias-label-tertiary, #888); }',
51
+ '[data-dsh-admin-section] .search-wrap .btn.sm:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.4)); color: var(--dsw-alias-label-primary, #222); }',
52
+ '[data-dsh-admin-section] .btn:active:not(:disabled) { transform: translateY(1px); }',
53
+ '[data-dsh-admin-section] .btn:focus-visible, [data-dsh-admin-section] .pill:focus-visible { outline: 2px solid var(--dsw-static-blue-500, #3b82f6); outline-offset: 2px; }',
54
+ '[data-dsh-admin-section] .btn:disabled { opacity: 0.45; cursor: not-allowed; }',
55
+ '[data-dsh-admin-section] .btn.primary { background: var(--dsw-static-blue-500, #3b82f6); color: #fff; border-color: transparent; font-weight: 600; box-shadow: 0 1px 3px rgba(0,0,0,0.12); }',
56
+ '[data-dsh-admin-section] .btn.primary:hover:not(:disabled) { background: var(--dsw-static-blue-400, #60a5fa); color: #fff; box-shadow: 0 2px 6px rgba(0,0,0,0.14); }',
57
+ '[data-dsh-admin-section] .btn.primary:active:not(:disabled) { background: var(--dsw-static-blue-600, #2563eb); color: #fff; }',
58
+ '[data-dsh-admin-section] .btn.danger { color: var(--dsw-alias-state-error-primary, #dc2626); border-color: var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)); }',
59
+ '[data-dsh-admin-section] .btn.danger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover-danger, rgba(239,68,68,0.1)); border-color: rgba(220,38,38,0.35); color: #b91c1c; }',
60
+ '[data-dsh-admin-section] .btn.danger-solid { background: var(--dsw-alias-state-error-primary, #dc2626); color: #fff; border-color: transparent; }',
61
+ '[data-dsh-admin-section] .btn.danger-solid:hover:not(:disabled) { background: #b91c1c; color: #fff; }',
62
+ '[data-dsh-admin-section] .btn.danger-solid:active:not(:disabled) { background: #991b1b; color: #fff; }',
63
+ '[data-dsh-admin-section] .btn.sm { height: 28px; padding: 0 10px; font-size: 12px; border-radius: 6px; }',
64
+ '[data-dsh-admin-section] .spinner { width: 12px; height: 12px; border: 2px solid transparent; border-top-color: currentColor; border-radius: 50%; animation: dsh-admin-spin 0.7s linear infinite; display: inline-block; flex: none; }',
65
+ '[data-dsh-admin-section] .list { display: flex; flex-direction: column; gap: 10px; flex: 1 1 auto; min-height: 0; max-height: 560px; overflow-y: auto; padding: 2px 4px 2px 2px; scrollbar-width: thin; scrollbar-color: var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)) transparent; }',
66
+ '[data-dsh-admin-section] .list::-webkit-scrollbar { width: 6px; }',
67
+ '[data-dsh-admin-section] .list::-webkit-scrollbar-thumb { border-radius: 99px; background: var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)); }',
68
+ '[data-dsh-admin-section] .session-group { display: flex; flex-direction: column; gap: 6px; }',
69
+ '[data-dsh-admin-section] .group-header { display: flex; align-items: center; gap: 10px; padding: 10px 12px 8px 12px; font-size: 13px; font-weight: 600; color: var(--dsw-alias-label-primary); border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)); border-radius: 10px; background: var(--dsw-alias-bg-elevated, var(--dsw-alias-bg-base, transparent)); box-shadow: 0 1px 2px rgba(0,0,0,0.02); margin-bottom: 4px; }',
70
+ '[data-dsh-admin-section] .group-header:first-child { margin-top: 2px; }',
71
+ '[data-dsh-admin-section] .group-title { display: inline-flex; align-items: center; gap: 6px; }',
72
+ '[data-dsh-admin-section] .group-count { font-size: 11px; padding: 2px 8px; border-radius: 10px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.3)); color: var(--dsw-alias-label-secondary, #555); font-weight: 500; }',
73
+ '[data-dsh-admin-section] .group-header .btn.sm { margin-left: auto; }',
74
+ '[data-dsh-admin-section] .group-header .btn.sm + .btn.sm { margin-left: 0; }',
75
+ '[data-dsh-admin-section] .group-path { font-family: monospace; font-size: 10px; color: var(--dsw-alias-label-tertiary, #888); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1; min-width: 0; text-align: right; }',
76
+ '[data-dsh-admin-section] .card { display: flex; flex-direction: column; gap: 7px; padding: 12px; border-radius: 12px; border: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.4)); background: var(--dsw-alias-bg-elevated, var(--dsw-alias-bg-base, transparent)); box-shadow: 0 1px 2px rgba(0,0,0,0.02); transition: transform 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease; }',
77
+ '[data-dsh-admin-section] .card:hover { transform: translateY(-1px); border-color: var(--dsw-alias-label-tertiary, rgba(180,180,195,0.6)); box-shadow: 0 8px 20px rgba(0,0,0,0.06); }',
78
+ '[data-dsh-admin-section] .card-header { display: flex; align-items: center; gap: 8px; min-width: 0; }',
79
+ '[data-dsh-admin-section] .card-title { font-size: 13px; font-weight: 600; color: var(--dsw-alias-label-primary); display: flex; align-items: center; gap: 7px; min-width: 0; flex: 1; }',
80
+ '[data-dsh-admin-section] .card-title-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 600; }',
81
+ '[data-dsh-admin-section] .card-summary { display: flex; align-items: flex-start; gap: 6px; padding: 6px 9px; border-radius: 6px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.25)); border-left: 2px solid var(--dsw-static-blue-500, #3b82f6); font-size: 12px; line-height: 1.45; color: var(--dsw-alias-label-secondary, #555); margin-top: 1px; margin-bottom: 1px; }',
82
+ '[data-dsh-admin-section] .summary-icon { font-size: 11px; line-height: 1.45; flex: none; opacity: 0.85; }',
83
+ '[data-dsh-admin-section] .summary-text { flex: 1; min-width: 0; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; word-break: break-word; }',
84
+ '[data-dsh-admin-section] .card-sub { font-size: 11px; color: var(--dsw-alias-label-secondary, #666); display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }',
85
+ '[data-dsh-admin-section] .card-sub-item { display: inline-flex; align-items: center; gap: 3px; max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }',
86
+ '[data-dsh-admin-section] .card-actions { display: flex; gap: 5px; align-items: center; flex: none; }',
87
+ '[data-dsh-admin-section] .tag { font-size: 10px; font-weight: 500; padding: 1px 6px; border-radius: 4px; flex: none; display: inline-flex; align-items: center; gap: 4px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.25)); color: var(--dsw-alias-label-secondary, #555); }',
88
+ '[data-dsh-admin-section] .tag.plugin { background: rgba(16, 185, 129, 0.12); color: var(--dsw-alias-state-success-primary, #10b981); }',
89
+ '[data-dsh-admin-section] .tag.local { background: rgba(59, 130, 246, 0.12); color: var(--dsw-static-blue-500, #3b82f6); }',
90
+ '[data-dsh-admin-section] .tag.update { background: rgba(245, 158, 11, 0.14); color: #d97706; font-weight: 600; border: 1px solid rgba(217, 119, 6, 0.25); }',
91
+ '[data-dsh-admin-section] .tag.update-error { background: rgba(239, 68, 68, 0.1); color: var(--dsw-alias-state-error-primary, #ef4444); }',
92
+ '[data-dsh-admin-section] .plugin-path { font-family: monospace; font-size: 11px; line-height: 1.4; color: var(--dsw-alias-label-secondary, #555); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding: 4px 9px; border-radius: 6px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.25)); }',
93
+ '[data-dsh-admin-section] .tag.version { font-family: monospace; }',
94
+ '[data-dsh-admin-section] .tag.live { background: rgba(16, 185, 129, 0.12); color: var(--dsw-alias-state-success-primary, #10b981); font-weight: 600; }',
95
+ '[data-dsh-admin-section] .tag.archived { background: rgba(245, 158, 11, 0.12); color: var(--dsw-alias-state-warn-label, #f59e0b); }',
96
+ '[data-dsh-admin-section] .tag.turns { background: rgba(59, 130, 246, 0.12); color: var(--dsw-static-blue-500, #3b82f6); font-weight: 500; }',
97
+ '[data-dsh-admin-section] .dot { width: 7px; height: 7px; border-radius: 50%; flex: none; background: var(--dsw-alias-label-tertiary, #999); }',
98
+ '[data-dsh-admin-section] .dot.live { background: var(--dsw-alias-state-success-primary, #10b981); box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.25); animation: dsh-admin-pulse 2s infinite ease-in-out; }',
99
+ '[data-dsh-admin-section] .dot.archived { background: var(--dsw-alias-state-warn-label, #f59e0b); }',
100
+ '[data-dsh-admin-section] .confirm-bar { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 6px 10px; border-radius: 6px; background: var(--dsw-alias-interactive-bg-hover-danger, rgba(239,68,68,0.08)); border: 1px solid rgba(239,68,68,0.2); }',
101
+ '[data-dsh-admin-section] .confirm-text { font-size: 11px; color: var(--dsw-alias-state-error-primary, #ef4444); font-weight: 500; }',
102
+ '[data-dsh-admin-section] .confirm-actions { display: flex; gap: 5px; flex: none; }',
103
+ '[data-dsh-admin-section] .busy-banner { display: flex; align-items: center; gap: 8px; padding: 7px 11px; border-radius: 7px; background: rgba(59, 130, 246, 0.08); color: var(--dsw-static-blue-500, #3b82f6); font-size: 11px; }',
104
+ '[data-dsh-admin-section] .update-strip { display: flex; align-items: center; gap: 8px; padding: 8px 11px; border-radius: 8px; font-size: 12px; font-weight: 500; line-height: 1.4; }',
105
+ '[data-dsh-admin-section] .update-strip .btn.sm { margin-left: auto; flex: none; }',
106
+ '[data-dsh-admin-section] .update-strip.checking { background: rgba(59, 130, 246, 0.08); color: var(--dsw-static-blue-500, #3b82f6); }',
107
+ '[data-dsh-admin-section] .update-strip.ok { background: rgba(16, 185, 129, 0.1); color: var(--dsw-alias-state-success-primary, #10b981); }',
108
+ '[data-dsh-admin-section] .update-strip.has-updates { background: rgba(245, 158, 11, 0.12); color: #d97706; border: 1px solid rgba(217, 119, 6, 0.25); }',
109
+ '[data-dsh-admin-section] .update-strip.has-errors { background: rgba(239, 68, 68, 0.08); color: var(--dsw-alias-state-error-primary, #ef4444); }',
110
+ '[data-dsh-admin-section] .empty { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 28px 12px; color: var(--dsw-alias-label-tertiary, #999); gap: 4px; font-size: 12px; text-align: center; }',
111
+ '[data-dsh-admin-section] .error { padding: 7px 11px; border-radius: 7px; color: var(--dsw-alias-state-error-primary, #ef4444); background: var(--dsw-alias-interactive-bg-hover-danger, rgba(239,68,68,0.08)); font-size: 12px; white-space: pre-wrap; max-height: 100px; overflow-y: auto; }',
112
+ '[data-dsh-admin-section] .footer { display: flex; justify-content: space-between; align-items: center; padding-top: 4px; font-size: 11px; color: var(--dsw-alias-label-tertiary, #888); border-top: 1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.3)); flex: none; }',
113
+ '[data-dsh-admin-section] .footer .path { max-width: 60%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }',
114
+ '[data-dsh-admin-section] .footer .hint { font-style: normal; }',
115
+ '[data-dsh-admin-section] .session-id-badge { font-family: monospace; font-size: 10px; opacity: 0.75; }',
116
+ '[data-dsh-admin-section] .mcp-test-row { padding: 6px 9px; border-radius: 6px; background: var(--dsw-alias-interactive-bg-hover, rgba(200,200,210,0.25)); font-size: 11px; line-height: 1.4; overflow-wrap: anywhere; }',
117
+ '[data-dsh-admin-section] .mcp-test { display: inline-flex; align-items: center; gap: 5px; }',
118
+ '[data-dsh-admin-section] .mcp-test.mcp-test-list { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; }',
119
+ '[data-dsh-admin-section] .mcp-test-busy { color: var(--dsw-alias-label-secondary, #666); }',
120
+ '[data-dsh-admin-section] .mcp-test-ok { color: #16a34a; }',
121
+ '[data-dsh-admin-section] .mcp-test-fail { color: var(--dsw-alias-state-error-primary, #ef4444); }',
122
+ '[data-dsh-admin-section] .mcp-test-warn { color: #d97706; opacity: 0.95; }',
123
+ '[data-dsh-admin-section] .mcp-test-cached { font-size: 10px; color: var(--dsw-alias-label-tertiary, #999); }',
124
+ '@media (max-width: 520px) { [data-dsh-admin-section] { gap: 10px; } [data-dsh-admin-section] .toolbar { align-items: stretch; flex-wrap: wrap; padding: 8px; } [data-dsh-admin-section] .toolbar .input-wrap { flex-basis: 100%; } [data-dsh-admin-section] .card-header { align-items: flex-start; } [data-dsh-admin-section] .card-actions { flex-wrap: wrap; justify-content: flex-end; } [data-dsh-admin-section] .footer { gap: 6px; align-items: flex-start; flex-direction: column; } [data-dsh-admin-section] .footer .path { max-width: 100%; } }',
125
+ '@keyframes dsh-toast-in { 0% { opacity: 0; transform: translateY(-12px) scale(0.96); } 100% { opacity: 1; transform: translateY(0) scale(1); } }',
126
+ '@keyframes dsh-toast-out { 0% { opacity: 1; transform: translateY(0) scale(1); } 100% { opacity: 0; transform: translateY(-8px) scale(0.96); } }',
127
+ '.dsh-admin-toast { position: fixed; top: 16px; left: 50%; transform: translateX(-50%); z-index: 99999; padding: 10px 20px; border-radius: 10px; font-size: 13px; font-weight: 500; line-height: 1.4; box-shadow: 0 8px 30px rgba(0,0,0,0.15), 0 2px 8px rgba(0,0,0,0.08); display: flex; align-items: center; gap: 8px; pointer-events: none; animation: dsh-toast-in 0.25s ease-out forwards; max-width: 90vw; word-break: break-word; }',
128
+ '.dsh-admin-toast.success { background: rgba(16, 185, 129, 0.95); color: #fff; }',
129
+ '.dsh-admin-toast.error { background: rgba(239, 68, 68, 0.95); color: #fff; }',
130
+ '.dsh-admin-toast.info { background: rgba(22, 119, 255, 0.95); color: #fff; }',
131
+ '.dsh-admin-toast.leaving { animation: dsh-toast-out 0.2s ease-in forwards; }',
132
+ ].join('\n')
133
+
134
+ function injectStyles() {
135
+ var tagId = 'dsh-plugin-admin/unified-section.css'
136
+ if (document.querySelector('style[data-plugin-css="' + tagId + '"]') === null) {
137
+ var tag = document.createElement('style')
138
+ tag.dataset.plugin = 'dsh-plugin-admin'
139
+ tag.dataset.pluginCss = tagId
140
+ tag.textContent = CSS_TEXT
141
+ document.head.appendChild(tag)
142
+ }
143
+ }
144
+
145
+ function baseName(path) {
146
+ if (path === null || path === '') return '(无工作目录)'
147
+ var parts = path.replace(/\\/g, '/').split('/')
148
+ var last = parts[parts.length - 1]
149
+ return last === '' ? parts[parts.length - 2] || path : last
150
+ }
151
+
152
+ function formatDate(ms) {
153
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) return ''
154
+ var d = new Date(ms)
155
+ var pad = function (n) { return (n < 10 ? '0' : '') + String(n) }
156
+ return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate())
157
+ + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes())
158
+ }
159
+
160
+ function messageOf(error) {
161
+ if (error !== null && typeof error === 'object' && typeof error.message === 'string') return error.message
162
+ if (typeof error === 'string') return error
163
+ return JSON.stringify(error)
164
+ }
165
+
166
+ /**
167
+ * Show a floating toast notification at the top of the viewport.
168
+ * Auto-dismisses after `duration` ms. Supports 'success', 'error', 'info'.
169
+ */
170
+ function showToast(type, text, duration) {
171
+ if (typeof document === 'undefined') return
172
+ duration = duration || 3000
173
+ var toast = document.createElement('div')
174
+ toast.className = 'dsh-admin-toast ' + type
175
+ toast.textContent = text
176
+ document.body.appendChild(toast)
177
+
178
+ var timer = setTimeout(function () {
179
+ toast.classList.add('leaving')
180
+ setTimeout(function () {
181
+ if (toast.parentNode) toast.parentNode.removeChild(toast)
182
+ }, 200)
183
+ }, duration)
184
+
185
+ toast.addEventListener('click', function () {
186
+ clearTimeout(timer)
187
+ if (!toast.classList.contains('leaving')) {
188
+ toast.classList.add('leaving')
189
+ setTimeout(function () {
190
+ if (toast.parentNode) toast.parentNode.removeChild(toast)
191
+ }, 200)
192
+ }
193
+ })
194
+ }
195
+
196
+ /**
197
+ * Copy text to the clipboard. Uses the async Clipboard API when available;
198
+ * falls back to a hidden textarea + execCommand for older browsers or
199
+ * non-secure contexts.
200
+ */
201
+ function copyTextToClipboard(text) {
202
+ if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
203
+ navigator.clipboard.writeText(text).then(function () {
204
+ showToast('success', '📋 会话 ID 已复制')
205
+ }, function () {
206
+ fallbackCopy(text)
207
+ })
208
+ return
209
+ }
210
+ fallbackCopy(text)
211
+ }
212
+
213
+ function fallbackCopy(text) {
214
+ try {
215
+ var ta = document.createElement('textarea')
216
+ ta.value = text
217
+ ta.style.cssText = 'position:fixed;top:-9999px;left:-9999px;opacity:0'
218
+ document.body.appendChild(ta)
219
+ ta.select()
220
+ ta.setSelectionRange(0, text.length)
221
+ document.execCommand('copy')
222
+ document.body.removeChild(ta)
223
+ } catch (e) {
224
+ showToast('error', '❌ 复制失败:' + messageOf(e))
225
+ }
226
+ }
227
+
228
+ /* ========================================================================== */
229
+ /* Menu Popup Injection (Sessions & Workspaces) */
230
+ /* ========================================================================== */
231
+
232
+ /**
233
+ * Inject plugin items into the existing three-dot menu popup. The workspace
234
+ * bundle renders a Menu component (@deepseek-ai/dsh-client-ui-primitives)
235
+ * with portal:true, so the popup lives as a div[role="menu"] inside
236
+ * document.body with position:fixed. A MutationObserver detects when this
237
+ * popup appears, identifies it as a session or workspace menu by checking
238
+ * the existing button labels, and injects additional items.
239
+ */
240
+ function setupMenuInjection(call, refreshSessions) {
241
+ if (typeof document === 'undefined') return function () {}
242
+
243
+ /**
244
+ * Extract the session title from the row's aria-label. The anchor button
245
+ * aria-label is: 会话"<title>"的操作 (zh) / Session "<title>" actions (en).
246
+ * Extracting from the DOM keeps the injection synchronous — no RPC needed
247
+ * just to show the button, so the menu can't close before it appears.
248
+ */
249
+ function sessionTitleFromRow(row) {
250
+ var btn = row.querySelector('button[aria-label*="会话" i][aria-label*="操作" i], button[aria-label*="session" i][aria-label*="actions" i]')
251
+ if (btn === null) return null
252
+ var label = btn.getAttribute('aria-label') || ''
253
+ // zh: 会话"xxx"的操作 → strip 会话"/"的操作
254
+ var zh = /会话["“]([^"”]+)["”]/.exec(label)
255
+ if (zh) return zh[1].trim()
256
+ // en: Session "xxx" actions
257
+ var en = /session\s*["“]([^"”]+)["”]/i.exec(label)
258
+ if (en) return en[1].trim()
259
+ // fallback: whole label minus known prefixes/suffixes
260
+ return label.replace(/^会话/, '').replace(/^session/i, '').replace(/["“”]|的操作|actions$/gi, '').trim() || null
261
+ }
262
+
263
+ /** Find the treeitem row for the anchor button nearest the menu. */
264
+ function rowForMenu(menuEl) {
265
+ var menuRect = menuEl ? menuEl.getBoundingClientRect() : null
266
+ var allRows = document.querySelectorAll('[role="treeitem"]')
267
+ if (allRows.length === 0) return null
268
+ var rows = []
269
+ for (var i = 0; i < allRows.length; i++) {
270
+ var r = allRows[i]
271
+ // Only rows that contain a session/workspace action button
272
+ if (r.querySelector('button[aria-label*="会话" i][aria-label*="操作" i], button[aria-label*="工作区" i][aria-label*="操作" i], button[aria-label*="session" i][aria-label*="actions" i], button[aria-label*="workspace" i][aria-label*="actions" i]')) {
273
+ rows.push(r)
274
+ }
275
+ }
276
+ if (rows.length === 0) return null
277
+
278
+ // The Menu component renders with side="bottom": menu top sits just
279
+ // below the anchor button (button.bottom + 4). Match the row whose
280
+ // center is closest to the MENU TOP, not the menu center — the menu
281
+ // can be tall (several items), so its center drifts far from the
282
+ // clicked row.
283
+ if (menuRect === null || menuRect.height === 0) {
284
+ // No reliable menu rect. With a single candidate row the choice is
285
+ // unambiguous, so return it (jsdom/test environments have zero rects);
286
+ // with several rows refuse to guess rather than act on the wrong
287
+ // session.
288
+ if (rows.length === 1) return rows[0]
289
+ return null
290
+ }
291
+ var closest = rows[0]
292
+ var closestDist = Infinity
293
+ for (var j = 0; j < rows.length; j++) {
294
+ var rect = rows[j].getBoundingClientRect()
295
+ if (rect.height === 0) continue
296
+ var rowCenter = rect.top + rect.height / 2
297
+ var dist = Math.abs(rowCenter - menuRect.top)
298
+ if (dist < closestDist) {
299
+ closestDist = dist
300
+ closest = rows[j]
301
+ }
302
+ }
303
+ return closest
304
+ }
305
+
306
+ function injectItems(menuEl) {
307
+ if (menuEl.querySelector('[data-dsh-admin-injected]')) return
308
+
309
+ var text = menuEl.textContent || ''
310
+ var isSession = text.indexOf('归档会话') !== -1 || text.indexOf('Archive session') !== -1
311
+ var isWorkspace = !isSession && (text.indexOf('删除') !== -1 || text.indexOf('Delete workspace') !== -1)
312
+ if (!isSession && !isWorkspace) return
313
+
314
+ var viewport = menuEl.querySelector('[role="presentation"]')
315
+ if (viewport === null) return
316
+
317
+ var row = rowForMenu(menuEl)
318
+ if (row === null) return
319
+
320
+ if (isSession) {
321
+ var title = sessionTitleFromRow(row)
322
+ if (title === null) return
323
+ // Resolve sessions by title lazily at click time (fresh RPC) so the
324
+ // match is always current. Copy-id keeps the fuzzy matcher (a wrong
325
+ // match only mis-copies an id); delete must never guess, so it
326
+ // resolves by exact title only and refuses duplicate titles — the
327
+ // panel's rows act on ids and can disambiguate.
328
+ function fetchSessions(done) {
329
+ call('sessionAdmin/list', {}).then(function (listResult) {
330
+ done((listResult && listResult.ok && listResult.value && listResult.value.sessions) || [])
331
+ }, function () { showToast('error', '❌ 无法加载会话列表') })
332
+ }
333
+ // Normalize a title for comparison: trim, collapse spaces, drop
334
+ // trailing ellipsis and truncation artifacts.
335
+ function norm(v) {
336
+ return (v || '').replace(/\s+/g, ' ').replace(/\.{3,}\s*$/, '').trim().toLowerCase()
337
+ }
338
+
339
+ function resolveSessionFuzzy(cb) {
340
+ fetchSessions(function (sessions) {
341
+ var match = null
342
+ var nt = norm(title)
343
+ for (var i = 0; i < sessions.length; i++) {
344
+ var s = sessions[i]
345
+ var st = norm(s.title)
346
+ if (st === nt) { match = s; break }
347
+ // substring both ways (skip too-short needles)
348
+ if (nt.length > 3 && st.indexOf(nt) !== -1) { match = s; break }
349
+ if (st.length > 3 && nt.indexOf(st) !== -1) { match = s; break }
350
+ // fall back to cwd basename match
351
+ var cwdBase = s.cwd ? s.cwd.replace(/\\/g, '/').split('/').pop() : ''
352
+ if (cwdBase && (cwdBase === nt || nt.indexOf(cwdBase) !== -1 || cwdBase.indexOf(nt) !== -1)) { match = s; break }
353
+ }
354
+ if (match === null) { showToast('error', '❌ 未找到匹配的会话'); return }
355
+ cb(match)
356
+ })
357
+ }
358
+
359
+ function resolveSessionExact(cb) {
360
+ fetchSessions(function (sessions) {
361
+ var nt = norm(title)
362
+ var exact = []
363
+ for (var i = 0; i < sessions.length; i++) {
364
+ if (norm(sessions[i].title) === nt) exact.push(sessions[i])
365
+ }
366
+ if (exact.length === 0) { showToast('error', '❌ 未找到匹配的会话'); return }
367
+ if (exact.length > 1) {
368
+ showToast('error', '❌ 存在 ' + String(exact.length) + ' 个同名会话,无法确定要删除的目标;请在 设置 → 管理中心 → 会话管理 中按会话 ID 删除')
369
+ return
370
+ }
371
+ cb(exact[0])
372
+ })
373
+ }
374
+
375
+ // Copy the session id to the clipboard.
376
+ appendMenuItem(viewport, '复制会话 ID', 'normal', function () {
377
+ resolveSessionFuzzy(function (session) {
378
+ copyTextToClipboard(session.id)
379
+ })
380
+ })
381
+
382
+ // Delete the session. Online sessions are now closable through the
383
+ // captured AgentHandle (closeSession disposes the live agent/session
384
+ // first, so removing the log cannot resurrect it) — this stops a
385
+ // running conversation in that session. The item arms on the first
386
+ // click and only fires on a second click within 4s (confirmText below)
387
+ // — deletion is physical, so one misclick must never be enough.
388
+ appendMenuItem(viewport, '删除会话', 'danger', function () {
389
+ resolveSessionExact(function (match) {
390
+ var method = match.live ? 'sessionAdmin/closeSession' : 'sessionAdmin/deleteSession'
391
+ call(method, { sessionId: match.id }).then(function (result) {
392
+ if (result && result.ok) {
393
+ showToast('success', '🗑️ 会话已删除')
394
+ // Nudge the sidebar so the removed session vanishes now
395
+ // instead of lingering in 未分组 until reload.
396
+ if (refreshSessions) refreshSessions()
397
+ } else {
398
+ showToast('error', '❌ 删除会话失败:' + messageOf(result && result.error))
399
+ }
400
+ }, function (err) { showToast('error', '❌ 删除会话失败:' + messageOf(err)) })
401
+ })
402
+ }, '⚠️ 再点一次确认删除(在线会话将先关停)')
403
+ } else {
404
+ // Workspace: reveal in file manager. Path is resolved lazily at click.
405
+ var wsTitle = (row.querySelector('[class*="_title"]') || {}).textContent || ''
406
+ wsTitle = wsTitle.trim()
407
+ if (wsTitle === '') return
408
+ appendMenuItem(viewport, '在资源管理器打开', 'normal', function () {
409
+ call('sessionAdmin/list', {}).then(function (listResult) {
410
+ var workspaces = (listResult && listResult.ok && listResult.value && listResult.value.workspaces) || []
411
+ var wsPath = null
412
+ for (var i = 0; i < workspaces.length; i++) {
413
+ var w = workspaces[i]
414
+ var wTitle = (w && w.title) || ''
415
+ if (wTitle === wsTitle || (wsTitle !== '' && wTitle !== '' && (wsTitle.indexOf(wTitle) !== -1 || wTitle.indexOf(wsTitle) !== -1))) { wsPath = w && w.path; break }
416
+ }
417
+ if (wsPath === null) { showToast('error', '❌ 打开失败:未找到工作区路径'); return }
418
+ call('fsAdmin/reveal', { path: wsPath }).then(function (result) {
419
+ // Success needs no toast — the Explorer window opening is the
420
+ // feedback itself. Only failures get a hint.
421
+ if (!(result && result.ok)) showToast('error', '❌ 打开失败:' + messageOf(result && result.error))
422
+ }, function (err) { showToast('error', '❌ 打开失败:' + messageOf(err)) })
423
+ }, function () { showToast('error', '❌ 打开失败:无法加载工作区列表') })
424
+ })
425
+ }
426
+ }
427
+
428
+ function appendMenuItem(viewport, label, kind, onClick, confirmText) {
429
+ // Separator (only if there are already items — always, to visually group)
430
+ var sep = document.createElement('div')
431
+ sep.setAttribute('role', 'separator')
432
+ sep.setAttribute('data-dsh-admin-injected', '')
433
+ sep.style.cssText = 'margin:3px 0;border-top:1px solid var(--dsw-alias-border-subtle,rgba(200,200,210,0.3))'
434
+ viewport.appendChild(sep)
435
+
436
+ var btn = document.createElement('button')
437
+ btn.type = 'button'
438
+ btn.setAttribute('role', 'menuitem')
439
+ btn.setAttribute('data-dsh-admin-injected', '')
440
+ btn.textContent = label
441
+ var color = kind === 'danger' ? '#ef4444' : 'inherit'
442
+ var hoverBg = kind === 'danger' ? 'rgba(239,68,68,0.12)' : 'rgba(200,200,210,0.3)'
443
+ btn.style.cssText = 'display:flex;align-items:center;gap:8px;width:100%;padding:6px 10px;border:0;background:transparent;cursor:pointer;font:inherit;font-size:12px;color:' + color + ';border-radius:5px;text-align:left'
444
+ btn.addEventListener('mouseenter', function () { btn.style.background = hoverBg })
445
+ btn.addEventListener('mouseleave', function () { btn.style.background = 'transparent' })
446
+ // Optional two-step confirm (confirmText): the first click arms the
447
+ // item and relabels it; only a second click within 4s runs onClick —
448
+ // destructive items must never fire on a single misclick.
449
+ var armed = false
450
+ var disarmTimer = null
451
+ btn.addEventListener('click', function (e) {
452
+ e.stopPropagation()
453
+ if (confirmText === undefined) { onClick(); return }
454
+ if (!armed) {
455
+ armed = true
456
+ btn.textContent = confirmText
457
+ disarmTimer = setTimeout(function () {
458
+ armed = false
459
+ btn.textContent = label
460
+ }, 4000)
461
+ return
462
+ }
463
+ clearTimeout(disarmTimer)
464
+ armed = false
465
+ btn.textContent = label
466
+ onClick()
467
+ })
468
+ viewport.appendChild(btn)
469
+ }
470
+
471
+ var observer = new MutationObserver(function (mutations) {
472
+ for (var i = 0; i < mutations.length; i++) {
473
+ var added = mutations[i].addedNodes
474
+ if (!added || added.length === 0) continue
475
+ for (var j = 0; j < added.length; j++) {
476
+ var node = added[j]
477
+ if (node.nodeType !== 1) continue
478
+ var el = node
479
+ if (el.getAttribute && el.getAttribute('role') === 'menu') {
480
+ injectItems(el)
481
+ } else {
482
+ var menu = el.querySelector && el.querySelector('[role="menu"]')
483
+ if (menu) injectItems(menu)
484
+ }
485
+ }
486
+ }
487
+ })
488
+
489
+ observer.observe(document.body, { childList: true, subtree: true })
490
+
491
+ return function () {
492
+ observer.disconnect()
493
+ }
494
+ }
495
+
496
+ /**
497
+ * Plugins management settings section (standalone, no internal tabs).
498
+ */
499
+ function PluginsSection(props) {
500
+ // Lazy initializer: the seed object (and its localStorage read) must be
501
+ // built once at mount, not re-parsed on every render.
502
+ var pairPlugins = useState(function () {
503
+ return {
504
+ profileDir: '',
505
+ plugins: [],
506
+ busy: false,
507
+ error: '',
508
+ spec: '',
509
+ confirming: null,
510
+ note: '',
511
+ output: '',
512
+ filter: 'all',
513
+ needle: '',
514
+ checkingUpdates: false,
515
+ updateChecked: false, // true once a check finished (even if no updates)
516
+ // Seed from persisted reminders so the ⬆ 有新版本 badge is visible the
517
+ // moment the panel mounts (before the fresh host check resolves) — the
518
+ // reminder is only dropped once a check confirms the upgrade completed.
519
+ updates: loadUpdateReminders(), // name -> { latest, updateAvailable, error?, at? }
520
+ }
521
+ })
522
+ var pView = pairPlugins[0]
523
+ var setPView = pairPlugins[1]
524
+
525
+ var alive = useRef(false)
526
+ // In-flight check guard as a ref, not state: the state field drives the
527
+ // disabled button visuals, but gating ASYNC handlers on it races — a stale
528
+ // closure reads TRUE after an earlier check already settled and silently
529
+ // skips a required follow-up (the post-upgrade refresh), or FALSE mid-flight
530
+ // and lets a second one through. Refs are immune to closure staleness.
531
+ var checkingRef = useRef(false)
532
+
533
+ function patchPlugin(partial) {
534
+ setPView(function (cur) {
535
+ var next = {}
536
+ for (var k in cur) next[k] = cur[k]
537
+ for (var pk in partial) next[pk] = partial[pk]
538
+ return next
539
+ })
540
+ }
541
+
542
+ function callRemote(method, args) {
543
+ return props.call(method, args)
544
+ }
545
+
546
+ function reloadPlugins() {
547
+ patchPlugin({ busy: true, error: '', note: '' })
548
+ callRemote('pluginAdmin/list', {}).then(function (result) {
549
+ if (!alive.current) return
550
+ if (result.ok) {
551
+ patchPlugin({
552
+ busy: false,
553
+ profileDir: (result.value && result.value.profileDir) || '',
554
+ plugins: (result.value && result.value.plugins) || [],
555
+ })
556
+ } else {
557
+ patchPlugin({ busy: false, error: '加载插件失败:' + messageOf(result.error) })
558
+ }
559
+ }, function (failure) {
560
+ if (!alive.current) return
561
+ patchPlugin({ busy: false, error: '调用失败:' + messageOf(failure) })
562
+ })
563
+ }
564
+
565
+ /**
566
+ * Query the npm registry for newer versions of registry-installed bundles
567
+ * and stash per-plugin results. The resolution MERGES the fresh authoritative
568
+ * results onto the previously persisted reminders:
569
+ * - newer version confirmed -> (re)arm & persist the reminder
570
+ * - confirmed up to date -> drop the reminder (更新完删除提醒)
571
+ * - per-plugin check error -> keep the known reminder (a transient
572
+ * registry failure must not erase it);
573
+ * with no known reminder the failure
574
+ * itself is recorded so cards/strip/
575
+ * note can surface it
576
+ * - no longer a registry install -> drop stale reminders
577
+ * The AUTO check on panel open is cache-friendly; a manual check passes
578
+ * force=true so the host bypasses its 5-minute TTL, re-queries the registry
579
+ * and refreshes the cached content (检查更新 = 强制重新查,而不是回放缓存).
580
+ * Runs concurrently with the list so the panel stays responsive; failures
581
+ * are per-plugin, never fatal.
582
+ * @param force - true to force the host to bypass its update cache.
583
+ */
584
+ function checkUpdates(force) {
585
+ if (checkingRef.current) return
586
+ checkingRef.current = true
587
+ patchPlugin({ checkingUpdates: true, note: '' })
588
+ callRemote('pluginAdmin/checkUpdates', { force: force === true }).then(function (result) {
589
+ checkingRef.current = false
590
+ if (!alive.current) return
591
+ if (!result.ok) {
592
+ patchPlugin({ checkingUpdates: false, error: '检查更新失败:' + messageOf(result.error) })
593
+ // A failed call must not wipe previously known reminders — they stay
594
+ // seeded from localStorage and keep rendering on the cards.
595
+ return
596
+ }
597
+ var list = (result.value && result.value.updates) || []
598
+ // Merge INSIDE the functional updater against the LATEST committed
599
+ // state, never the render closure's snapshot: a reminder armed by an
600
+ // in-flight check resolving alongside an upgrade commit must survive
601
+ // (a stale-snapshot full replace erased it). The updater stays pure —
602
+ // localStorage persistence is owned by the mirror effect below.
603
+ setPView(function (cur) {
604
+ var next = {}
605
+ for (var k in cur) next[k] = cur[k]
606
+ next.checkingUpdates = false
607
+ next.updates = mergeUpdateReminders(cur.updates || {}, list)
608
+ next.updateChecked = true
609
+ next.note = updateCheckNote(next.updates, list.length)
610
+ return next
611
+ })
612
+ }, function (failure) {
613
+ checkingRef.current = false
614
+ if (!alive.current) return
615
+ patchPlugin({ checkingUpdates: false, error: '检查更新调用失败:' + messageOf(failure) })
616
+ })
617
+ }
618
+
619
+ /** Upgrade one plugin to its latest version (registry install by name). */
620
+ function upgradePlugin(name) {
621
+ if (pView.busy) return
622
+ var spec = name + '@latest'
623
+ patchPlugin({ busy: true, error: '', confirming: null, note: '' })
624
+ callRemote('pluginAdmin/install', { spec: spec }).then(function (result) {
625
+ if (!alive.current) return
626
+ if (result.ok) {
627
+ // The upgrade consumed this reminder: strip it from the CURRENT state
628
+ // inside the updater (更新完删除提醒) — never from the click-time
629
+ // closure snapshot, which may miss reminders an in-flight check armed
630
+ // meanwhile (erasing those was exactly scenario 7's stale-snapshot
631
+ // bug). localStorage follows via the shared mirror effect; the forced
632
+ // refresh below confirms the new version is current.
633
+ setPView(function (cur) {
634
+ var next = {}
635
+ for (var k in cur) next[k] = cur[k]
636
+ next.busy = false
637
+ next.note = '已更新 ' + name + '。更改在重启 dsh 后生效'
638
+ next.output = (result.value && result.value.output) || ''
639
+ next.profileDir = (result.value && result.value.profileDir) || ''
640
+ next.plugins = (result.value && result.value.plugins) || []
641
+ var remaining = {}
642
+ for (var rk in cur.updates) {
643
+ if (rk !== name) remaining[rk] = cur.updates[rk]
644
+ }
645
+ next.updates = remaining
646
+ return next
647
+ })
648
+ // Refresh the update map so the upgraded entry stops flagging.
649
+ // Force: the @latest spec installed the registry's CURRENT latest,
650
+ // but the host TTL cache may still hold an older latest published
651
+ // minutes ago — comparing against that would re-flag the freshly
652
+ // upgraded plugin. Bypass the cache and resync its content instead.
653
+ checkUpdates(true)
654
+ return
655
+ }
656
+ patchPlugin({ busy: false, error: '更新失败:' + messageOf(result.error) })
657
+ reloadPlugins()
658
+ }, function (failure) {
659
+ if (!alive.current) return
660
+ patchPlugin({ busy: false, error: '调用失败:' + messageOf(failure) })
661
+ })
662
+ }
663
+
664
+ function installPlugin() {
665
+ if (pView.busy || pView.spec.trim() === '') return
666
+ var spec = pView.spec.trim()
667
+ patchPlugin({ busy: true, error: '', confirming: null, note: '' })
668
+ callRemote('pluginAdmin/install', { spec: spec }).then(function (result) {
669
+ if (!alive.current) return
670
+ if (result.ok) {
671
+ patchPlugin({
672
+ busy: false,
673
+ note: '安装完成。更改在重启 dsh 后生效',
674
+ output: (result.value && result.value.output) || '',
675
+ profileDir: (result.value && result.value.profileDir) || '',
676
+ plugins: (result.value && result.value.plugins) || [],
677
+ spec: '',
678
+ })
679
+ return
680
+ }
681
+ patchPlugin({ busy: false, error: '安装失败:' + messageOf(result.error) })
682
+ reloadPlugins()
683
+ }, function (failure) {
684
+ if (!alive.current) return
685
+ patchPlugin({ busy: false, error: '调用失败:' + messageOf(failure) })
686
+ })
687
+ }
688
+
689
+ function removePlugin(name) {
690
+ patchPlugin({ busy: true, error: '', confirming: null, note: '' })
691
+ callRemote('pluginAdmin/remove', { name: name }).then(function (result) {
692
+ if (!alive.current) return
693
+ if (result.ok) {
694
+ patchPlugin({
695
+ busy: false,
696
+ note: '卸载完成。更改在重启 dsh 后生效',
697
+ output: (result.value && result.value.output) || '',
698
+ profileDir: (result.value && result.value.profileDir) || '',
699
+ plugins: (result.value && result.value.plugins) || [],
700
+ })
701
+ return
702
+ }
703
+ patchPlugin({ busy: false, error: '卸载失败:' + messageOf(result.error) })
704
+ reloadPlugins()
705
+ }, function (failure) {
706
+ if (!alive.current) return
707
+ patchPlugin({ busy: false, error: '调用失败:' + messageOf(failure) })
708
+ })
709
+ }
710
+
711
+ useEffect(function () {
712
+ alive.current = true
713
+ reloadPlugins()
714
+ // Auto-check for remote updates on mount (the panel loads lazily when
715
+ // the 插件管理 tab is opened, so this runs once per open). The auto path
716
+ // is cache-friendly: the host serves its 5-minute cache, so re-opening
717
+ // the tab shortly after does not re-hit the registry. The manual
718
+ // 检查更新 button is the force path — it bypasses the cache and
719
+ // refreshes its content.
720
+ checkUpdates()
721
+ return function () { alive.current = false }
722
+ }, [])
723
+
724
+ // Single persistence point: localStorage always mirrors the LATEST
725
+ // committed reminders. Moving saves out of the async handlers (and out of
726
+ // the functional updaters, which must stay pure) removes drift by
727
+ // construction whatever merge won the last commit is what survives
728
+ // dialog reopen and dsh restarts (best-effort; unavailable storage just
729
+ // degrades to session-only badges).
730
+ useEffect(function () {
731
+ saveUpdateReminders(pView.updates || {})
732
+ }, [pView.updates])
733
+
734
+ return createElement('div', { 'data-dsh-admin-section': '' },
735
+ renderPluginsView(pView, patchPlugin, installPlugin, removePlugin, checkUpdates, upgradePlugin))
736
+ }
737
+
738
+ /**
739
+ * Sessions management settings section (standalone, no internal tabs).
740
+ */
741
+ function SessionsSection(props) {
742
+ var pairSessions = useState({
743
+ sessions: [],
744
+ workspaces: [],
745
+ busy: false,
746
+ error: '',
747
+ needle: '',
748
+ confirming: null,
749
+ filter: 'all',
750
+ })
751
+ var sView = pairSessions[0]
752
+ var setSView = pairSessions[1]
753
+
754
+ var alive = useRef(false)
755
+
756
+ function patchSession(partial) {
757
+ setSView(function (cur) {
758
+ var next = {}
759
+ for (var k in cur) next[k] = cur[k]
760
+ for (var pk in partial) next[pk] = partial[pk]
761
+ return next
762
+ })
763
+ }
764
+
765
+ function callRemote(method, args) {
766
+ return props.call(method, args)
767
+ }
768
+
769
+ function reloadSessions() {
770
+ patchSession({ busy: true, error: '' })
771
+ callRemote('sessionAdmin/list', {}).then(function (result) {
772
+ if (!alive.current) return
773
+ if (result.ok) {
774
+ patchSession({
775
+ busy: false,
776
+ sessions: (result.value && result.value.sessions) || [],
777
+ workspaces: (result.value && result.value.workspaces) || [],
778
+ })
779
+ } else {
780
+ patchSession({ busy: false, error: '加载会话失败:' + messageOf(result.error) })
781
+ }
782
+ }, function (failure) {
783
+ if (!alive.current) return
784
+ patchSession({ busy: false, error: '调用失败:' + messageOf(failure) })
785
+ })
786
+ }
787
+
788
+ function actSession(method, sessionId) {
789
+ patchSession({ busy: true, error: '', confirming: null })
790
+ callRemote('sessionAdmin/' + method, { sessionId: sessionId }).then(function (result) {
791
+ if (!alive.current) return
792
+ if (result.ok) {
793
+ // Refresh this panel's own list, and nudge the sidebar (via the
794
+ // sessions service) so a deleted session disappears immediately
795
+ // instead of lingering until reload.
796
+ if ((method === 'deleteSession' || method === 'closeSession') && props.refreshSessions) props.refreshSessions()
797
+ return reloadSessions()
798
+ }
799
+ patchSession({ busy: false, error: '操作失败:' + messageOf(result.error) })
800
+ }, function (failure) {
801
+ if (!alive.current) return
802
+ patchSession({ busy: false, error: '调用失败:' + messageOf(failure) })
803
+ })
804
+ }
805
+
806
+ useEffect(function () {
807
+ alive.current = true
808
+ reloadSessions()
809
+ return function () { alive.current = false }
810
+ }, [])
811
+
812
+ return createElement('div', { 'data-dsh-admin-section': '' },
813
+ renderSessionsView(sView, patchSession, reloadSessions, actSession))
814
+ }
815
+
816
+ /**
817
+ * MCP configuration settings section (standalone, no internal tabs).
818
+ */
819
+
820
+ /* ------------------------------------------------------------------------ */
821
+ /* MCP test-result cache */
822
+ /* */
823
+ /* Successful connectivity probes are persisted to localStorage so the */
824
+ /* panel shows the last known status after tab switches or reopening the */
825
+ /* dialog instead of an empty state. Only OK results are cached (failures */
826
+ /* are usually transient); a cached row is labelled with its probe time, */
827
+ /* and the cache entry is invalidated when the config is saved or removed, */
828
+ /* or pruned when the entry disappears from the host list. */
829
+ /* ------------------------------------------------------------------------ */
830
+
831
+ var MCP_TEST_CACHE_KEY = 'dsh-plugin-admin/mcp-test-results'
832
+
833
+ /**
834
+ * Touch localStorage safely: on some environments (jsdom with an opaque
835
+ * origin, hardened browsers, privacy modes) merely READING window.localStorage
836
+ * throws a SecurityError, so the access itself has to sit inside try/catch.
837
+ * Returns null when storage is unavailable.
838
+ */
839
+ function safeLocalStorage() {
840
+ try {
841
+ if (typeof window === 'undefined' || !window.localStorage) return null
842
+ return window.localStorage
843
+ } catch (e) {
844
+ return null
845
+ }
846
+ }
847
+
848
+ function mcpTestStorage() {
849
+ return safeLocalStorage()
850
+ }
851
+
852
+ function loadMcpTestCache() {
853
+ var store = mcpTestStorage()
854
+ if (store === null) return {}
855
+ try {
856
+ var parsed = JSON.parse(store.getItem(MCP_TEST_CACHE_KEY))
857
+ if (parsed === null || typeof parsed !== 'object') return {}
858
+ // Purge failure records persisted by older builds: only a durable OK is
859
+ // worth restoring on mount; a stale ❌ from a past outage must not
860
+ // outlive the session it happened in.
861
+ var out = {}
862
+ for (var id in parsed) {
863
+ var entry = parsed[id]
864
+ if (entry && entry.result && entry.result.ok === true) out[id] = entry
865
+ }
866
+ return out
867
+ } catch (e) {
868
+ return {}
869
+ }
870
+ }
871
+
872
+ /** Mirror settled, successful probes into localStorage (best-effort). */
873
+ function saveMcpTestCache(state) {
874
+ var store = mcpTestStorage()
875
+ if (store === null) return
876
+ try {
877
+ var out = {}
878
+ for (var id in state) {
879
+ var s = state[id]
880
+ // Busy rows keep the previous cached result; failures stay ephemeral —
881
+ // INCLUDING structured {ok:false} probes (timeout, connection refused),
882
+ // which arrive as a truthy result object and need their own ok check.
883
+ if (!s || s.busy || s.result === null || s.result === undefined
884
+ || s.result.ok !== true) continue
885
+ out[id] = { result: s.result, at: typeof s.at === 'number' ? s.at : Date.now() }
886
+ }
887
+ store.setItem(MCP_TEST_CACHE_KEY, JSON.stringify(out))
888
+ } catch (e) {
889
+ // Quota exceeded / storage blocked — the cache is optional, never fatal.
890
+ }
891
+ }
892
+
893
+ /** Drop one entry's cached probe (config saved or entry removed). */
894
+ function clearMcpTestCacheEntry(id) {
895
+ var store = mcpTestStorage()
896
+ if (store === null) return
897
+ try {
898
+ var state = loadMcpTestCache()
899
+ if (state[id] === undefined) return
900
+ delete state[id]
901
+ store.setItem(MCP_TEST_CACHE_KEY, JSON.stringify(state))
902
+ } catch (e) { /* ignore */ }
903
+ }
904
+
905
+ /** Drop test states whose entry no longer exists in the host list. */
906
+ function pruneMcpTestState(map, entries) {
907
+ var valid = {}
908
+ for (var i = 0; i < entries.length; i++) valid[entries[i].id] = true
909
+ var next = {}
910
+ var changed = false
911
+ for (var id in map) {
912
+ if (valid[id]) next[id] = map[id]
913
+ else changed = true
914
+ }
915
+ if (changed) saveMcpTestCache(next)
916
+ return next
917
+ }
918
+
919
+ /** Compact timestamp for a cached probe ("14:32" today, "6-1 14:32" older). */
920
+ function formatTestTime(ms) {
921
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) return ''
922
+ var d = new Date(ms)
923
+ var pad = function (n) { return (n < 10 ? '0' : '') + String(n) }
924
+ var hm = pad(d.getHours()) + ':' + pad(d.getMinutes())
925
+ var now = new Date()
926
+ if (d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()) return hm
927
+ return (d.getMonth() + 1) + '-' + d.getDate() + ' ' + hm
928
+ }
929
+
930
+ /* Update-reminder persistence */
931
+ /* */
932
+ /* A "⬆ 有新版本" reminder is a durable fact, not a transient fetch result: */
933
+ /* once a newer version is detected it is kept in localStorage until a */
934
+ /* check confirms the installed version is current again (i.e. the update */
935
+ /* actually completed). This is what keeps the badge visible after closing */
936
+ /* and reopening the 管理中心, across dsh restarts, and even when a later */
937
+ /* re-check hits a transient network failure — and what clears it only once */
938
+ /* the plugin is upgraded (更新完删除提醒). */
939
+ /* ------------------------------------------------------------------------ */
940
+
941
+ var UPDATE_REMINDER_KEY = 'dsh-plugin-admin/update-reminders'
942
+
943
+ /** Shape-merge a reminder entry (keeps the original truthy fields). */
944
+ function mergeReminder(entry, partial) {
945
+ var next = {}
946
+ for (var k in entry) next[k] = entry[k]
947
+ for (var pk in partial) next[pk] = partial[pk]
948
+ return next
949
+ }
950
+
951
+ /**
952
+ * Load persisted update reminders as state entries:
953
+ * { name: { latest, at, updateAvailable, error } }. Storage-unavailable
954
+ * environments (opaque-origin jsdom, privacy modes) just get an empty map.
955
+ */
956
+ function loadUpdateReminders() {
957
+ var store = safeLocalStorage()
958
+ if (store === null) return {}
959
+ try {
960
+ var parsed = JSON.parse(store.getItem(UPDATE_REMINDER_KEY))
961
+ var out = {}
962
+ if (parsed !== null && typeof parsed === 'object') {
963
+ for (var name in parsed) {
964
+ var r = parsed[name]
965
+ if (r && typeof r.latest === 'string' && r.latest.length > 0) {
966
+ out[name] = {
967
+ latest: r.latest,
968
+ at: typeof r.at === 'number' ? r.at : 0,
969
+ updateAvailable: true,
970
+ error: '',
971
+ }
972
+ }
973
+ }
974
+ }
975
+ return out
976
+ } catch (e) {
977
+ return {}
978
+ }
979
+ }
980
+
981
+ /** Mirror the current reminder set into localStorage (best-effort). */
982
+ function saveUpdateReminders(map) {
983
+ var store = safeLocalStorage()
984
+ if (store === null) return
985
+ try {
986
+ var out = {}
987
+ for (var name in map) {
988
+ var r = map[name]
989
+ if (r && r.updateAvailable === true && typeof r.latest === 'string' && r.latest.length > 0) {
990
+ out[name] = { latest: r.latest, at: typeof r.at === 'number' ? r.at : Date.now() }
991
+ }
992
+ }
993
+ store.setItem(UPDATE_REMINDER_KEY, JSON.stringify(out))
994
+ } catch (e) {
995
+ // Quota exceeded / storage blocked the reminder is optional, never fatal.
996
+ }
997
+ }
998
+
999
+ /**
1000
+ * Merge one check response into the CURRENT reminder map. Pure on purpose:
1001
+ * it runs inside the setPView updater, so it reads only its arguments and
1002
+ * must never touch localStorage or other component state. Per-entry semantics
1003
+ * (list = fresh host results, one row per live registry install):
1004
+ * - updateAvailable -> (re)arm the reminder
1005
+ * - confirmed current -> drop any entry (更新完删除提醒)
1006
+ * - query error -> keep a prior reminder untouched (error attached);
1007
+ * without one, record an ephemeral failure
1008
+ * ({updateAvailable:false}) so cards/strip/note can
1009
+ * surface it saveUpdateReminders skips those
1010
+ * - entries absent from `list` are no longer live registry installs ->
1011
+ * stale reminders dropped
1012
+ * @param curMap - the CURRENT updates state ({ name -> entry }).
1013
+ * @param list - per-plugin check results.
1014
+ * @returns the complete next map.
1015
+ */
1016
+ function mergeUpdateReminders(curMap, list) {
1017
+ var liveNames = {}
1018
+ for (var a = 0; a < list.length; a++) liveNames[list[a].name] = true
1019
+ var map = {}
1020
+ for (var k in curMap) {
1021
+ if (curMap[k] && liveNames[k]) map[k] = curMap[k]
1022
+ }
1023
+ for (var i = 0; i < list.length; i++) {
1024
+ var u = list[i]
1025
+ if (u.updateAvailable === true) {
1026
+ map[u.name] = { latest: u.latest, updateAvailable: true, error: '', at: Date.now() }
1027
+ } else if (u.error) {
1028
+ // A prior reminder survives untouched with the transient error
1029
+ // alongside; WITHOUT one the failure itself lands in the map so an
1030
+ // all-failed first check cannot claim 全部为最新版本.
1031
+ map[u.name] = map[u.name]
1032
+ ? mergeReminder(map[u.name], { error: u.error || '' })
1033
+ : { latest: '', updateAvailable: false, error: u.error || '', at: Date.now() }
1034
+ } else if (u.latest !== null && u.latest !== undefined) {
1035
+ delete map[u.name]
1036
+ }
1037
+ }
1038
+ return map
1039
+ }
1040
+
1041
+ /** Aggregate summary line for a finished check (pure). */
1042
+ function updateCheckNote(map, checkedCount) {
1043
+ var updateCount = 0
1044
+ var checkErrorCount = 0
1045
+ for (var n in map) {
1046
+ if (map[n].updateAvailable === true) updateCount++
1047
+ if (map[n].error) checkErrorCount++
1048
+ }
1049
+ if (updateCount > 0) return '发现 ' + updateCount + ' 个插件有新版本'
1050
+ if (checkErrorCount > 0) {
1051
+ return '已检查 ' + checkedCount + ' 个插件(' + checkErrorCount + ' 个查询失败)'
1052
+ + (checkedCount > checkErrorCount ? ',其余均为最新版本' : '')
1053
+ }
1054
+ return checkedCount > 0 ? '已检查 ' + checkedCount + ' 个插件,均为最新版本' : ''
1055
+ }
1056
+
1057
+ function McpSection(props) {
1058
+ var pairMcp = useState({
1059
+ mcpEntries: [],
1060
+ mcpBusy: false,
1061
+ mcpError: '',
1062
+ mcpEditorOpen: false,
1063
+ mcpDraft: null,
1064
+ // entryId -> { busy?, result?, error?, at? }; previous successful probes
1065
+ // are restored from localStorage so statuses survive panel remounts.
1066
+ mcpTestState: loadMcpTestCache(),
1067
+ })
1068
+ var mView = pairMcp[0]
1069
+ var setMView = pairMcp[1]
1070
+
1071
+ var alive = useRef(false)
1072
+
1073
+ function patchMcp(partial) {
1074
+ setMView(function (cur) {
1075
+ var next = {}
1076
+ for (var k in cur) next[k] = cur[k]
1077
+ for (var pk in partial) next[pk] = partial[pk]
1078
+ return next
1079
+ })
1080
+ }
1081
+
1082
+ // Merge a partial into the CURRENT mcpDraft via a functional update, so
1083
+ // rapid successive field edits (React batching) never lose earlier input.
1084
+ function patchDraft(partial) {
1085
+ setMView(function (cur) {
1086
+ var next = {}
1087
+ for (var k in cur) next[k] = cur[k]
1088
+ next.mcpDraft = mergeDraft(cur.mcpDraft, partial)
1089
+ return next
1090
+ })
1091
+ }
1092
+
1093
+ function callRemote(method, args) {
1094
+ return props.call(method, args)
1095
+ }
1096
+
1097
+ function reloadMcp() {
1098
+ patchMcp({ mcpBusy: true, mcpError: '' })
1099
+ callRemote('mcpAdmin/list', {}).then(function (result) {
1100
+ if (!alive.current) return
1101
+ if (result.ok) {
1102
+ var entries = (result.value && result.value.entries) || []
1103
+ setMView(function (cur) {
1104
+ var next = {}
1105
+ for (var k in cur) next[k] = cur[k]
1106
+ next.mcpBusy = false
1107
+ next.mcpEntries = entries
1108
+ // Drop cached probes whose entry no longer exists on the host.
1109
+ next.mcpTestState = pruneMcpTestState(cur.mcpTestState, entries)
1110
+ return next
1111
+ })
1112
+ } else {
1113
+ patchMcp({ mcpBusy: false, mcpError: '加载 MCP 配置失败:' + messageOf(result.error) })
1114
+ }
1115
+ }, function (failure) {
1116
+ if (!alive.current) return
1117
+ patchMcp({ mcpBusy: false, mcpError: '调用失败:' + messageOf(failure) })
1118
+ })
1119
+ }
1120
+
1121
+ function openMcpEditor(entry) {
1122
+ if (entry !== null && entry !== undefined && (entry.config === null || entry.config === undefined)) {
1123
+ patchMcp({ mcpError: '该 MCP 配置无法安全解析,已禁止在此覆盖;请在 cordis.patch.yml 中手动编辑。' })
1124
+ return
1125
+ }
1126
+ var source = entry !== null && entry !== undefined ? entry.config : null
1127
+ var draft = source ? {
1128
+ id: entry.id,
1129
+ isNew: false,
1130
+ serverName: source.serverName || entry.id,
1131
+ transport: source.transport,
1132
+ command: source.command || '',
1133
+ url: source.url || '',
1134
+ args: (source.args || []).join(' '),
1135
+ argsOriginal: source.args || [],
1136
+ argsChanged: false,
1137
+ env: Object.keys(source.env || {}).map(function (key) { return key + '=' + source.env[key] }).join('\n'),
1138
+ envOriginal: source.env || {},
1139
+ envChanged: false,
1140
+ cwd: source.cwd || '',
1141
+ headers: Object.keys(source.headers || {}).map(function (k) { return k + '=' + source.headers[k] }).join('\n'),
1142
+ headersOriginal: source.headers || {},
1143
+ headersChanged: false,
1144
+ toolCallTimeoutMs: source.toolCallTimeoutMs,
1145
+ failOnStartupError: source.failOnStartupError === true,
1146
+ reconnectEnabled: source.reconnect ? source.reconnect.enabled === true : false,
1147
+ reconnectInitialDelayMs: source.reconnect ? source.reconnect.initialDelayMs : 1000,
1148
+ reconnectMaxDelayMs: source.reconnect ? source.reconnect.maxDelayMs : 30000,
1149
+ reconnectMaxAttempts: source.reconnect ? source.reconnect.maxAttempts : 10,
1150
+ } : {
1151
+ // New server: pre-fill a collision-free id so the user does not have to
1152
+ // invent one; they can still edit it or regenerate it.
1153
+ id: generateMcpId(mView.mcpEntries),
1154
+ isNew: true,
1155
+ serverName: '',
1156
+ transport: 'stdio',
1157
+ command: '',
1158
+ url: '',
1159
+ args: '',
1160
+ argsOriginal: [],
1161
+ argsChanged: false,
1162
+ env: '',
1163
+ envOriginal: {},
1164
+ envChanged: false,
1165
+ cwd: '',
1166
+ headers: '',
1167
+ headersOriginal: {},
1168
+ headersChanged: false,
1169
+ toolCallTimeoutMs: undefined,
1170
+ failOnStartupError: false,
1171
+ reconnectEnabled: false,
1172
+ reconnectInitialDelayMs: 1000,
1173
+ reconnectMaxDelayMs: 30000,
1174
+ reconnectMaxAttempts: 10,
1175
+ }
1176
+ patchMcp({ mcpEditorOpen: true, mcpDraft: draft, mcpError: '' })
1177
+ }
1178
+
1179
+ function closeMcpEditor() {
1180
+ patchMcp({ mcpEditorOpen: false, mcpDraft: null, mcpError: '' })
1181
+ }
1182
+
1183
+ function saveMcpDraft() {
1184
+ var draft = mView.mcpDraft
1185
+ if (draft === null) return
1186
+ // A NEW entry must not collide with an existing id: the host's upsert
1187
+ // locates its target block by id and would replace that entry in place,
1188
+ // silently destroying its config. The edit form keeps its own id (the
1189
+ // field is disabled), so this guard only ever fires on the add form.
1190
+ if (draft.isNew) {
1191
+ for (var ci = 0; ci < mView.mcpEntries.length; ci++) {
1192
+ if (mView.mcpEntries[ci].id === draft.id) {
1193
+ patchMcp({ mcpError: 'ID \'' + draft.id + '\' 已被其他 MCP 条目占用,请换一个再保存。' })
1194
+ return
1195
+ }
1196
+ }
1197
+ }
1198
+ var config
1199
+ if (draft.transport === 'streamable-http') {
1200
+ config = { transport: 'streamable-http', serverName: draft.serverName, url: draft.url }
1201
+ var headersStr = Object.keys(draft.headersOriginal || {}).map(function (k) { return k + '=' + draft.headersOriginal[k] }).join('\n')
1202
+ var headers = (draft.headersChanged && draft.headers !== headersStr) ? {} : draft.headersOriginal
1203
+ if (draft.headersChanged && draft.headers !== headersStr && draft.headers !== '') {
1204
+ // Newline-only split: header values legitimately contain ';'/','
1205
+ // (Cookie, Accept), which must never become pair separators.
1206
+ var pairs = draft.headers.split('\n').map(function (s) { return s.trim() }).filter(Boolean)
1207
+ for (var i = 0; i < pairs.length; i++) {
1208
+ var eq = pairs[i].indexOf('=')
1209
+ if (eq > 0) headers[pairs[i].slice(0, eq).trim()] = pairs[i].slice(eq + 1).trim()
1210
+ }
1211
+ }
1212
+ if (Object.keys(headers).length > 0) config.headers = headers
1213
+ } else {
1214
+ config = { transport: 'stdio', serverName: draft.serverName, command: draft.command }
1215
+ var argsStr = (draft.argsOriginal || []).join(' ')
1216
+ var args = (draft.argsChanged && draft.args !== argsStr) ? draft.args.split(/\s+/).filter(Boolean) : draft.argsOriginal
1217
+ if (args.length > 0) config.args = args
1218
+ var envStr = Object.keys(draft.envOriginal || {}).map(function (k) { return k + '=' + draft.envOriginal[k] }).join('\n')
1219
+ var env = (draft.envChanged && draft.env !== envStr) ? {} : draft.envOriginal
1220
+ if (draft.envChanged && draft.env !== envStr && draft.env !== '') {
1221
+ // Newline-only split: values like PATH=C:\a;C:\b would lose their
1222
+ // tail (and Windows paths carry ';' everywhere).
1223
+ var pairs = draft.env.split('\n').map(function (s) { return s.trim() }).filter(Boolean)
1224
+ for (var i = 0; i < pairs.length; i++) {
1225
+ var eq = pairs[i].indexOf('=')
1226
+ if (eq > 0) env[pairs[i].slice(0, eq).trim()] = pairs[i].slice(eq + 1).trim()
1227
+ }
1228
+ }
1229
+ if (Object.keys(env).length > 0) config.env = env
1230
+ if (draft.cwd !== '') config.cwd = draft.cwd
1231
+ }
1232
+ if (draft.toolCallTimeoutMs !== undefined) config.toolCallTimeoutMs = draft.toolCallTimeoutMs
1233
+ if (draft.failOnStartupError) config.failOnStartupError = true
1234
+ if (draft.reconnectEnabled) {
1235
+ config.reconnect = {
1236
+ enabled: true,
1237
+ initialDelayMs: Number(draft.reconnectInitialDelayMs),
1238
+ maxDelayMs: Number(draft.reconnectMaxDelayMs),
1239
+ maxAttempts: Number(draft.reconnectMaxAttempts),
1240
+ }
1241
+ }
1242
+ patchMcp({ mcpBusy: true, mcpError: '' })
1243
+ callRemote('mcpAdmin/upsert', { entry: { id: draft.id, config: config } }).then(function (result) {
1244
+ if (!alive.current) return
1245
+ if (result.ok) {
1246
+ // The config changed, so any cached probe no longer describes this
1247
+ // server — drop it from storage and from the panel.
1248
+ clearMcpTestCacheEntry(draft.id)
1249
+ patchMcpTest(draft.id, { busy: false, result: null, error: null })
1250
+ patchMcp({ mcpBusy: false, mcpEntries: (result.value && result.value.entries) || [], mcpEditorOpen: false, mcpDraft: null })
1251
+ } else {
1252
+ patchMcp({ mcpBusy: false, mcpError: '保存 MCP 配置失败:' + messageOf(result.error) })
1253
+ }
1254
+ }, function (failure) {
1255
+ if (!alive.current) return
1256
+ patchMcp({ mcpBusy: false, mcpError: '调用失败:' + messageOf(failure) })
1257
+ })
1258
+ }
1259
+
1260
+ function removeMcpEntry(id) {
1261
+ patchMcp({ mcpBusy: true, mcpError: '' })
1262
+ callRemote('mcpAdmin/remove', { id: id }).then(function (result) {
1263
+ if (!alive.current) return
1264
+ if (result.ok) {
1265
+ // The entry is gone — its cached probe must not linger in storage.
1266
+ clearMcpTestCacheEntry(id)
1267
+ patchMcp({ mcpBusy: false, mcpEntries: (result.value && result.value.entries) || [] })
1268
+ } else {
1269
+ patchMcp({ mcpBusy: false, mcpError: '移除 MCP 配置失败:' + messageOf(result.error) })
1270
+ }
1271
+ }, function (failure) {
1272
+ if (!alive.current) return
1273
+ patchMcp({ mcpBusy: false, mcpError: '调用失败:' + messageOf(failure) })
1274
+ })
1275
+ }
1276
+
1277
+ /**
1278
+ * Set one entry's connectivity-test status against the CURRENT state.
1279
+ * Settled successful probes are mirrored into localStorage so the last
1280
+ * known status survives tab switches and reopening the settings dialog.
1281
+ */
1282
+ function patchMcpTest(id, partial) {
1283
+ setMView(function (cur) {
1284
+ var nextTestState = mergeTestState(cur.mcpTestState, id, partial)
1285
+ saveMcpTestCache(nextTestState)
1286
+ var next = {}
1287
+ for (var k in cur) next[k] = cur[k]
1288
+ next.mcpTestState = nextTestState
1289
+ return next
1290
+ })
1291
+ }
1292
+
1293
+ /** Run a host-side connectivity probe for one entry and stash the result. */
1294
+ function testMcpEntry(id) {
1295
+ patchMcpTest(id, { busy: true, result: null, error: null })
1296
+ callRemote('mcpAdmin/test', { id: id }).then(function (result) {
1297
+ if (!alive.current) return
1298
+ if (result.ok && result.value !== null && typeof result.value === 'object') {
1299
+ // `at` timestamps the probe; it is what the cached label renders.
1300
+ patchMcpTest(id, { busy: false, result: result.value, at: Date.now() })
1301
+ } else {
1302
+ patchMcpTest(id, { busy: false, result: null, error: messageOf(result.error) })
1303
+ }
1304
+ }, function (failure) {
1305
+ if (!alive.current) return
1306
+ patchMcpTest(id, { busy: false, result: null, error: messageOf(failure) })
1307
+ })
1308
+ }
1309
+
1310
+ useEffect(function () {
1311
+ alive.current = true
1312
+ reloadMcp()
1313
+ return function () { alive.current = false }
1314
+ }, [])
1315
+
1316
+ return createElement('div', { 'data-dsh-admin-section': '' },
1317
+ renderMcpSection(mView, patchDraft, reloadMcp, openMcpEditor, closeMcpEditor, saveMcpDraft, removeMcpEntry, testMcpEntry))
1318
+ }
1319
+
1320
+ /** Unified settings page; only the selected panel mounts and loads. */
1321
+ function AdminCenterSection(props) {
1322
+ var pairTab = useState('plugins')
1323
+ var activeTab = pairTab[0]
1324
+ var setActiveTab = pairTab[1]
1325
+ var tabs = [
1326
+ { id: 'plugins', label: '插件管理', component: PluginsSection },
1327
+ { id: 'sessions', label: '会话管理', component: SessionsSection },
1328
+ { id: 'mcp', label: 'MCP 配置', component: McpSection },
1329
+ ]
1330
+ var selected = tabs.find(function (tab) { return tab.id === activeTab }) || tabs[0]
1331
+
1332
+ return createElement('div', { 'data-dsh-admin-section': '' },
1333
+ createElement('div', { className: 'tabs', role: 'tablist', 'aria-label': '管理中心功能' },
1334
+ tabs.map(function (tab) {
1335
+ return createElement('button', {
1336
+ type: 'button',
1337
+ key: tab.id,
1338
+ className: 'tab' + (tab.id === selected.id ? ' active' : ''),
1339
+ role: 'tab',
1340
+ 'aria-selected': tab.id === selected.id,
1341
+ onClick: function () { setActiveTab(tab.id) },
1342
+ }, tab.label)
1343
+ })
1344
+ ),
1345
+ createElement(selected.component, { key: selected.id, call: props.call, refreshSessions: props.refreshSessions })
1346
+ )
1347
+ }
1348
+
1349
+ /* ========================================================================== */
1350
+ /* Render Plugins View */
1351
+ /* ========================================================================== */
1352
+
1353
+ function renderPluginsView(view, patch, install, remove, checkUpdates, upgrade) {
1354
+ var elements = []
1355
+
1356
+ // Toolbar: search (primary, wide) + install input + actions in one row.
1357
+ elements.push(createElement('div', { className: 'toolbar', key: 'toolbar' },
1358
+ createElement('div', { className: 'search-wrap', key: 'search-wrap' },
1359
+ createElement('span', { className: 'search-icon', key: 'icon' }, '🔍'),
1360
+ createElement('input', {
1361
+ className: 'input',
1362
+ key: 'search-input',
1363
+ placeholder: '搜索插件(名称/版本/路径)...',
1364
+ value: view.needle,
1365
+ onChange: function (e) { patch({ needle: e.target.value }) },
1366
+ }),
1367
+ view.needle !== '' ? createElement('button', {
1368
+ type: 'button',
1369
+ key: 'btn-clear-search',
1370
+ className: 'btn sm',
1371
+ title: '清空搜索',
1372
+ onClick: function () { patch({ needle: '' }) },
1373
+ }, '') : null
1374
+ ),
1375
+ createElement('div', { className: 'input-wrap install-wrap', key: 'install-wrap' },
1376
+ createElement('input', {
1377
+ className: 'input',
1378
+ placeholder: '安装包名/路径...',
1379
+ value: view.spec,
1380
+ disabled: view.busy,
1381
+ onChange: function (e) { patch({ spec: e.target.value }) },
1382
+ onKeyDown: function (e) { if (e.key === 'Enter') install() },
1383
+ })
1384
+ ),
1385
+ createElement('button', {
1386
+ type: 'button',
1387
+ key: 'btn-install',
1388
+ className: 'btn primary',
1389
+ disabled: view.busy || view.spec.trim() === '',
1390
+ onClick: install,
1391
+ },
1392
+ view.busy ? createElement('span', { className: 'spinner', key: 'spin' }) : null,
1393
+ '安装'
1394
+ ),
1395
+ createElement('button', {
1396
+ type: 'button',
1397
+ key: 'btn-check-updates',
1398
+ className: 'btn',
1399
+ disabled: view.busy || view.checkingUpdates,
1400
+ title: '强制绕过 5 分钟缓存,重新查询 registry 并刷新缓存',
1401
+ onClick: function () { checkUpdates(true) },
1402
+ },
1403
+ view.checkingUpdates ? createElement('span', { className: 'spinner', key: 'spin' }) : null,
1404
+ view.checkingUpdates ? '检查中...' : '⬆️ 检查更新'
1405
+ ),
1406
+ ))
1407
+
1408
+ // Filter Pills
1409
+ var totalPlugins = view.plugins.length
1410
+ var thirdPartyCount = 0
1411
+ var builtinCount = 0
1412
+ for (var i = 0; i < view.plugins.length; i++) {
1413
+ if (view.plugins[i].removable) thirdPartyCount++
1414
+ else builtinCount++
1415
+ }
1416
+
1417
+ elements.push(createElement('div', { className: 'filter-bar', key: 'filters' },
1418
+ createElement('button', {
1419
+ type: 'button',
1420
+ key: 'filter-all',
1421
+ className: 'pill' + (view.filter === 'all' ? ' active' : ''),
1422
+ onClick: function () { patch({ filter: 'all' }) },
1423
+ }, '全部 (' + String(totalPlugins) + ')'),
1424
+ createElement('button', {
1425
+ type: 'button',
1426
+ key: 'filter-plugin',
1427
+ className: 'pill' + (view.filter === 'plugin' ? ' active' : ''),
1428
+ onClick: function () { patch({ filter: 'plugin' }) },
1429
+ }, '扩展插件 (' + String(thirdPartyCount) + ')'),
1430
+ createElement('button', {
1431
+ type: 'button',
1432
+ key: 'filter-builtin',
1433
+ className: 'pill' + (view.filter === 'builtin' ? ' active' : ''),
1434
+ onClick: function () { patch({ filter: 'builtin' }) },
1435
+ }, '系统内置 (' + String(builtinCount) + ')')
1436
+ ))
1437
+
1438
+ // Busy banner / Error
1439
+ if (view.busy) {
1440
+ elements.push(createElement('div', { className: 'busy-banner', key: 'busy' },
1441
+ createElement('span', { className: 'spinner', key: 'spin' }),
1442
+ '正在执行 pnpm 操作(可能需要数秒至数分钟,请勿关闭窗口)...'
1443
+ ))
1444
+ }
1445
+ if (view.error !== '') {
1446
+ elements.push(createElement('div', { className: 'error', key: 'error' }, view.error))
1447
+ }
1448
+
1449
+ // Update-check status strip: gives the auto-check a visible outcome instead
1450
+ // of hiding it in the footer. Checking → spinner; done with updates →
1451
+ // orange; done without updates → green; per-plugin query failures surface
1452
+ // on the strip rather than vanishing. Purely informational — the single
1453
+ // re-check entry point is the toolbar「⬆️ 检查更新」button (which forces a
1454
+ // fresh registry query), so no redundant button lives in the strip.
1455
+ if (view.checkingUpdates) {
1456
+ elements.push(createElement('div', { className: 'update-strip checking', key: 'update-checking' },
1457
+ createElement('span', { className: 'spinner', key: 'spin' }),
1458
+ '正在检查插件版本更新…'
1459
+ ))
1460
+ } else if (view.updateChecked) {
1461
+ var upCount = 0
1462
+ var errCount = 0
1463
+ for (var un in view.updates) {
1464
+ if (view.updates[un].updateAvailable === true) upCount++
1465
+ if (view.updates[un].error) errCount++
1466
+ }
1467
+ var stripClass = upCount > 0 ? 'update-strip has-updates'
1468
+ : (errCount > 0 ? 'update-strip has-errors' : 'update-strip ok')
1469
+ var stripText = upCount > 0
1470
+ ? '⬆️ 发现 ' + upCount + ' 个插件有新版本,可点击卡片上的「更新」升级'
1471
+ : (errCount > 0
1472
+ ? '⚠️ 有 ' + errCount + ' 个插件查询版本失败(网络或 registry 不可达)'
1473
+ : '✅ 已自动检查版本更新,全部为最新版本')
1474
+ elements.push(createElement('div', { className: stripClass, key: 'update-result' },
1475
+ createElement('span', { key: 't' }, stripText)
1476
+ ))
1477
+ }
1478
+
1479
+ // Filter and render rows
1480
+ var needle = view.needle.trim().toLowerCase()
1481
+ var filtered = filterPlugins(view.plugins, view.filter, needle)
1482
+ var rows = []
1483
+ for (var j = 0; j < filtered.length; j++) {
1484
+ var p = filtered[j]
1485
+ rows.push(renderPluginCard(p, view, remove, patch, upgrade))
1486
+ }
1487
+
1488
+ if (rows.length === 0) {
1489
+ rows.push(createElement('div', { className: 'empty', key: 'empty' },
1490
+ createElement('div', null, needle !== '' ? '🔍 无匹配的插件(试试其他关键词)' : '📦 暂无匹配的插件层')
1491
+ ))
1492
+ }
1493
+
1494
+ elements.push(createElement('div', { className: 'list', key: 'list' }, rows))
1495
+
1496
+ // Footer
1497
+ var hintText = view.note !== '' ? view.note : '更改在重启 dsh 后生效(关闭 dsh 进程后重新运行即可)'
1498
+ var hintTitle = view.output !== '' ? 'pnpm 输出:\n' + view.output : undefined
1499
+ elements.push(createElement('div', { className: 'footer', key: 'footer' },
1500
+ createElement('span', { className: 'path', key: 'profile-path', title: view.profileDir }, view.profileDir || 'Profile: 默认'),
1501
+ createElement('span', { className: 'hint', key: 'hint', title: hintTitle }, hintText)
1502
+ ))
1503
+
1504
+ return createElement('div', { key: 'plugins-panel', style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, elements)
1505
+ }
1506
+
1507
+
1508
+ function renderMcpSection(view, patchDraft, reloadMcp, openMcpEditor, closeMcpEditor, saveMcpDraft, removeMcpEntry, testMcpEntry) {
1509
+ var children = []
1510
+ var header = createElement('div', { className: 'group-header', key: 'mcp-header', style: { marginTop: 0 } },
1511
+ createElement('span', { className: 'group-title', key: 't' }, '🔌 MCP 配置'),
1512
+ createElement('span', { className: 'group-count', key: 'c' }, String(view.mcpEntries.length) + ' '),
1513
+ createElement('button', {
1514
+ type: 'button',
1515
+ key: 'btn-refresh-mcp',
1516
+ className: 'btn',
1517
+ disabled: view.mcpBusy,
1518
+ onClick: reloadMcp,
1519
+ }, '🔄 刷新'),
1520
+ createElement('button', {
1521
+ type: 'button',
1522
+ key: 'btn-add-mcp',
1523
+ className: 'btn primary',
1524
+ disabled: view.mcpBusy,
1525
+ onClick: function () { openMcpEditor(null) },
1526
+ }, '➕ 添加服务器'),
1527
+ )
1528
+ children.push(header)
1529
+
1530
+ if (view.mcpError !== '') {
1531
+ children.push(createElement('div', { className: 'error', key: 'mcp-error' }, view.mcpError))
1532
+ }
1533
+
1534
+ var rows = []
1535
+ for (var i = 0; i < view.mcpEntries.length; i++) {
1536
+ var entry = view.mcpEntries[i]
1537
+ var tag = createElement('span', { className: 'tag plugin', key: 'mcp-tag-' + entry.id },
1538
+ 'MCP ' + String(entry.serverName || entry.id))
1539
+ var testState = (view.mcpTestState && view.mcpTestState[entry.id]) || null
1540
+ var testIndicator = null
1541
+ if (testState !== null && testState.busy) {
1542
+ testIndicator = createElement('span', { className: 'mcp-test mcp-test-busy', key: 'test-busy' },
1543
+ createElement('span', { className: 'spinner', key: 'sp' }),
1544
+ ' 检测中...')
1545
+ } else if (testState !== null && testState.result !== null && testState.result !== undefined) {
1546
+ var r = testState.result
1547
+ var ok = r.ok === true
1548
+ var label = ok ? '✅ 连通'
1549
+ : '❌ 不通'
1550
+ var detail = ok
1551
+ ? (r.serverInfo ? (r.serverInfo.name || '') + (r.serverInfo.version ? ' v' + r.serverInfo.version : '') : '') +
1552
+ (typeof r.toolCount === 'number' ? ' · ' + r.toolCount + ' 个工具' : '') +
1553
+ (r.pingOk === false ? ' · 初始化成功但 ping 失败' : '')
1554
+ : (r.error || '连接失败') + (r.ms !== undefined ? ' (' + r.ms + 'ms)' : '')
1555
+ var detailChildren = [
1556
+ createElement('span', { key: 'lbl' }, label + (detail !== '' ? ' ' + detail : '')),
1557
+ ]
1558
+ if (ok && Array.isArray(r.tools) && r.tools.length > 0) {
1559
+ detailChildren.push(createElement('span', { key: 'tools-hint', style: { opacity: 0.75 } },
1560
+ '工具:' + r.tools.join('')))
1561
+ }
1562
+ if (r.warning) {
1563
+ detailChildren.push(createElement('span', { key: 'warn', className: 'mcp-test-warn', title: r.warning },
1564
+ '⚠️ ' + r.warning))
1565
+ }
1566
+ // Cached probe: label when it was taken so a restored status is never
1567
+ // mistaken for a just-run check. Clicking 🔌 测试 refreshes it.
1568
+ if (typeof testState.at === 'number') {
1569
+ detailChildren.push(createElement('span', {
1570
+ key: 'cached-at',
1571
+ className: 'mcp-test-cached',
1572
+ title: '上次检测结果(本地缓存)。点击「🔌 测试」可重新检测。',
1573
+ }, '· 缓存于 ' + formatTestTime(testState.at)))
1574
+ }
1575
+ testIndicator = createElement('div', {
1576
+ className: 'mcp-test mcp-test-list ' + (ok ? 'mcp-test-ok' : 'mcp-test-fail'),
1577
+ key: 'test-result',
1578
+ title: detail,
1579
+ }, detailChildren)
1580
+ } else if (testState !== null && testState.error !== null && testState.error !== undefined) {
1581
+ testIndicator = createElement('span', {
1582
+ className: 'mcp-test mcp-test-fail',
1583
+ key: 'test-error',
1584
+ title: testState.error,
1585
+ }, '❌ ' + testState.error)
1586
+ }
1587
+ var rowChildren = [
1588
+ createElement('div', { className: 'card-header', key: 'h' },
1589
+ createElement('span', { className: 'card-title-text', key: 'name' }, entry.id),
1590
+ tag,
1591
+ createElement('div', { className: 'card-actions', key: 'a' },
1592
+ createElement('button', {
1593
+ type: 'button',
1594
+ className: 'btn sm',
1595
+ disabled: view.mcpBusy || (testState !== null && testState.busy) || entry.config === null || entry.config === undefined,
1596
+ title: entry.config === null || entry.config === undefined ? '该配置无法安全解析,请手动编辑 cordis.patch.yml' : (testState !== null && testState.busy ? '检测中...' : (testState !== null && typeof testState.at === 'number' ? '重新检测该服务器的连通性(当前显示的是缓存结果)' : '测试该服务器的连通性')),
1597
+ onClick: function (id) { return function () { testMcpEntry(id) } }(entry.id),
1598
+ }, testState !== null && testState.busy ? '检测中' : '🔌 测试'),
1599
+ createElement('button', {
1600
+ type: 'button',
1601
+ className: 'btn sm',
1602
+ disabled: view.mcpBusy || (testState !== null && testState.busy) || entry.config === null || entry.config === undefined,
1603
+ title: entry.config === null || entry.config === undefined ? '该配置无法安全解析,请手动编辑 cordis.patch.yml' : undefined,
1604
+ onClick: function (value) { return function () { openMcpEditor(value) } }(entry),
1605
+ }, '编辑'),
1606
+ createElement('button', {
1607
+ type: 'button',
1608
+ className: 'btn danger sm',
1609
+ disabled: view.mcpBusy,
1610
+ onClick: function (id) { return function () { removeMcpEntry(id) } }(entry.id),
1611
+ }, '移除'),
1612
+ ),
1613
+ ),
1614
+ ]
1615
+ if (testIndicator !== null) {
1616
+ rowChildren.push(createElement('div', { className: 'mcp-test-row', key: 'test-row' }, testIndicator))
1617
+ }
1618
+ rows.push(createElement('div', { className: 'card', key: 'mcp-' + entry.id }, rowChildren))
1619
+ }
1620
+ if (rows.length === 0) {
1621
+ rows.push(createElement('div', { className: 'empty', key: 'mcp-empty' },
1622
+ createElement('div', null, '🔌 暂无 MCP 服务器配置')
1623
+ ))
1624
+ }
1625
+ children.push(createElement('div', { className: 'list', key: 'mcp-list' }, rows))
1626
+
1627
+ // Editor form. patchDraft merges against the CURRENT draft in state so
1628
+ // typing across fields never clobbers earlier edits (stale-closure guard).
1629
+ if (view.mcpEditorOpen && view.mcpDraft !== null) {
1630
+ var d = view.mcpDraft
1631
+ var fieldStyle = { display: 'flex', flexDirection: 'column', gap: '4px', marginBottom: '8px' }
1632
+ var labelStyle = { fontSize: '11px', color: 'var(--dsw-alias-label-secondary, #666)' }
1633
+ var editor = createElement('div', { className: 'card', key: 'mcp-editor' },
1634
+ createElement('div', { className: 'card-header', key: 'h' },
1635
+ createElement('span', { className: 'card-title-text', key: 't' }, d.isNew ? '添加 MCP 服务器' : '编辑 ' + d.id),
1636
+ ),
1637
+ createElement('div', { style: fieldStyle, key: 'f-id' },
1638
+ createElement('label', { style: labelStyle }, 'ID(唯一标识,[A-Za-z0-9_-])'),
1639
+ createElement('div', { style: { display: 'flex', gap: '6px' } },
1640
+ createElement('input', {
1641
+ className: 'input',
1642
+ value: d.id,
1643
+ disabled: !d.isNew,
1644
+ onChange: function (e) { patchDraft({ id: e.target.value }) },
1645
+ }),
1646
+ d.isNew ? createElement('button', {
1647
+ type: 'button',
1648
+ className: 'btn sm',
1649
+ title: '重新生成一个随机 ID',
1650
+ onClick: function () { patchDraft({ id: generateMcpId(view.mcpEntries) }) },
1651
+ }, '🎲') : null,
1652
+ ),
1653
+ ),
1654
+ createElement('div', { style: fieldStyle, key: 'f-server' },
1655
+ createElement('label', { style: labelStyle }, 'serverName(模型命名空间)'),
1656
+ createElement('input', {
1657
+ className: 'input',
1658
+ value: d.serverName,
1659
+ onChange: function (e) { patchDraft({ serverName: e.target.value }) },
1660
+ }),
1661
+ ),
1662
+ createElement('div', { style: fieldStyle, key: 'f-transport' },
1663
+ createElement('label', { style: labelStyle }, '传输方式'),
1664
+ createElement('select', {
1665
+ className: 'input',
1666
+ value: d.transport,
1667
+ onChange: function (e) { patchDraft({ transport: e.target.value }) },
1668
+ },
1669
+ createElement('option', { value: 'stdio' }, 'stdio(子进程)'),
1670
+ createElement('option', { value: 'streamable-http' }, 'streamable-http(HTTP)'),
1671
+ ),
1672
+ ),
1673
+ d.transport === 'stdio' ? createElement('div', { style: fieldStyle, key: 'f-cmd' },
1674
+ createElement('label', { style: labelStyle }, 'command(启动命令)'),
1675
+ createElement('input', {
1676
+ className: 'input',
1677
+ value: d.command,
1678
+ placeholder: 'npx -y @modelcontextprotocol/server-github',
1679
+ onChange: function (e) { patchDraft({ command: e.target.value }) },
1680
+ }),
1681
+ ) : createElement('div', { style: fieldStyle, key: 'f-url' },
1682
+ createElement('label', { style: labelStyle }, 'url(MCP 端点)'),
1683
+ createElement('input', {
1684
+ className: 'input',
1685
+ value: d.url,
1686
+ placeholder: 'http://localhost:3000/mcp',
1687
+ onChange: function (e) { patchDraft({ url: e.target.value }) },
1688
+ }),
1689
+ ),
1690
+ d.transport === 'streamable-http' ? createElement('div', { style: fieldStyle, key: 'f-headers' },
1691
+ createElement('label', { style: labelStyle }, 'headers(每行 KEY=VALUE,可选)'),
1692
+ createElement('textarea', {
1693
+ className: 'input',
1694
+ style: { minHeight: '48px' },
1695
+ value: d.headers,
1696
+ onChange: function (e) { patchDraft({ headers: e.target.value, headersChanged: true }) },
1697
+ }),
1698
+ ) : null,
1699
+ d.transport === 'stdio' ? createElement('div', { style: fieldStyle, key: 'f-args' },
1700
+ createElement('label', { style: labelStyle }, 'args(空格分隔,可选)'),
1701
+ createElement('input', {
1702
+ className: 'input',
1703
+ value: d.args,
1704
+ onChange: function (e) { patchDraft({ args: e.target.value, argsChanged: true }) },
1705
+ }),
1706
+ ) : null,
1707
+ d.transport === 'stdio' ? createElement('div', { style: fieldStyle, key: 'f-env' },
1708
+ createElement('label', { style: labelStyle }, 'env(每行 KEY=VALUE,可选)'),
1709
+ createElement('textarea', {
1710
+ className: 'input',
1711
+ style: { minHeight: '48px' },
1712
+ value: d.env,
1713
+ onChange: function (e) { patchDraft({ env: e.target.value, envChanged: true }) },
1714
+ }),
1715
+ ) : null,
1716
+ createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '6px', padding: '4px 0', marginBottom: '4px', borderTop: '1px solid var(--dsw-alias-border-subtle, rgba(200,200,210,0.3))', paddingTop: '8px' }, key: 'f-reconnect-header' },
1717
+ createElement('input', {
1718
+ type: 'checkbox',
1719
+ id: 'reconnect-toggle',
1720
+ checked: d.reconnectEnabled,
1721
+ onChange: function (e) { patchDraft({ reconnectEnabled: e.target.checked }) },
1722
+ style: { margin: '0' },
1723
+ }),
1724
+ createElement('label', { htmlFor: 'reconnect-toggle', style: { fontSize: '12px', fontWeight: 500, cursor: 'pointer', color: 'var(--dsw-alias-label-primary, #333)' } }, '启用自动重连'),
1725
+ ),
1726
+ d.reconnectEnabled ? createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: '8px', marginBottom: '8px', paddingLeft: '4px' }, key: 'f-reconnect-fields' },
1727
+ createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: '2px', flex: '1 1 120px' }, key: 'f-reconnect-id' },
1728
+ createElement('label', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary, #666)' } }, 'initialDelayMs'),
1729
+ createElement('input', {
1730
+ className: 'input',
1731
+ type: 'number',
1732
+ min: 0,
1733
+ value: d.reconnectInitialDelayMs,
1734
+ onChange: function (e) { patchDraft({ reconnectInitialDelayMs: Number(e.target.value) }) },
1735
+ }),
1736
+ ),
1737
+ createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: '2px', flex: '1 1 120px' }, key: 'f-reconnect-md' },
1738
+ createElement('label', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary, #666)' } }, 'maxDelayMs'),
1739
+ createElement('input', {
1740
+ className: 'input',
1741
+ type: 'number',
1742
+ min: 0,
1743
+ value: d.reconnectMaxDelayMs,
1744
+ onChange: function (e) { patchDraft({ reconnectMaxDelayMs: Number(e.target.value) }) },
1745
+ }),
1746
+ ),
1747
+ createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: '2px', flex: '1 1 120px' }, key: 'f-reconnect-ma' },
1748
+ createElement('label', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary, #666)' } }, 'maxAttempts'),
1749
+ createElement('input', {
1750
+ className: 'input',
1751
+ type: 'number',
1752
+ min: 0,
1753
+ value: d.reconnectMaxAttempts,
1754
+ onChange: function (e) { patchDraft({ reconnectMaxAttempts: Number(e.target.value) }) },
1755
+ }),
1756
+ ),
1757
+ ) : null,
1758
+ createElement('div', { className: 'card-actions', key: 'f-actions', style: { justifyContent: 'flex-end', gap: '6px' } },
1759
+ createElement('button', {
1760
+ type: 'button',
1761
+ className: 'btn',
1762
+ disabled: view.mcpBusy,
1763
+ onClick: closeMcpEditor,
1764
+ }, '取消'),
1765
+ createElement('button', {
1766
+ type: 'button',
1767
+ className: 'btn primary',
1768
+ disabled: view.mcpBusy || d.id.trim() === '' || d.serverName.trim() === '' ||
1769
+ (d.transport === 'stdio' ? d.command.trim() === '' : d.url.trim() === ''),
1770
+ onClick: saveMcpDraft,
1771
+ }, view.mcpBusy ? '保存中...' : '保存'),
1772
+ ),
1773
+ )
1774
+ children.push(editor)
1775
+ }
1776
+
1777
+ return createElement('div', { key: 'mcp-section', style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, children)
1778
+ }
1779
+
1780
+ // Characters allowed in an MCP entry id: [A-Za-z0-9_-]. The random part uses
1781
+ // alphanumerics only so the generated id reads cleanly and always matches the
1782
+ // host-side validation regex.
1783
+ var MCP_ID_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
1784
+
1785
+ /**
1786
+ * Generate a fresh MCP entry id that is not already used by any listed entry
1787
+ * (an id collision would silently overwrite the existing entry on upsert).
1788
+ */
1789
+ function generateMcpId(entries) {
1790
+ var taken = {}
1791
+ for (var i = 0; i < entries.length; i++) taken[entries[i].id] = true
1792
+ var candidate
1793
+ do {
1794
+ candidate = 'mcp-'
1795
+ for (var j = 0; j < 8; j++) {
1796
+ candidate += MCP_ID_ALPHABET.charAt(Math.floor(Math.random() * MCP_ID_ALPHABET.length))
1797
+ }
1798
+ } while (taken[candidate])
1799
+ return candidate
1800
+ }
1801
+
1802
+ function mergeDraft(draft, partial) {
1803
+ var next = {}
1804
+ for (var k in draft) next[k] = draft[k]
1805
+ for (var pk in partial) next[pk] = partial[pk]
1806
+ return next
1807
+ }
1808
+
1809
+ /** Set one entry's test status inside the shared mcpTestState map. */
1810
+ function mergeTestState(map, id, partial) {
1811
+ var next = {}
1812
+ for (var k in map) next[k] = map[k]
1813
+ next[id] = {}
1814
+ var cur = map[id] || {}
1815
+ for (var ck in cur) next[id][ck] = cur[ck]
1816
+ for (var pk in partial) next[id][pk] = partial[pk]
1817
+ return next
1818
+ }
1819
+ function renderPluginCard(plugin, view, remove, patch, upgrade) {
1820
+ var isConfirming = view.confirming === plugin.name
1821
+
1822
+ var titleChildren = [
1823
+ createElement('span', { className: 'card-title-text', key: 'name' }, plugin.name),
1824
+ ]
1825
+ if (plugin.version) {
1826
+ titleChildren.push(createElement('span', { className: 'tag version', key: 'version' }, 'v' + plugin.version))
1827
+ }
1828
+ var isLocal = Boolean(plugin.localPath)
1829
+ titleChildren.push(createElement('span', {
1830
+ className: plugin.removable ? (isLocal ? 'tag local' : 'tag plugin') : 'tag',
1831
+ key: 'type-tag',
1832
+ },
1833
+ plugin.removable ? (isLocal ? '本地安装' : '包安装') : '内置'
1834
+ ))
1835
+
1836
+ // Remote update badge: only for registry-installed bundles (removable and
1837
+ // not a local path) after a check ran. `updates` is keyed by plugin name.
1838
+ var updateInfo = view.updates && view.updates[plugin.name]
1839
+ if (updateInfo && updateInfo.updateAvailable && updateInfo.latest) {
1840
+ titleChildren.push(createElement('span', {
1841
+ className: 'tag update',
1842
+ key: 'update-badge',
1843
+ title: '远程 registry 有新版本:v' + updateInfo.latest + '(当前 v' + plugin.version + ')'
1844
+ + (typeof updateInfo.at === 'number' && updateInfo.at > 0 ? ',检测于 ' + formatTestTime(updateInfo.at) + ',更新后提醒自动消除' : ''),
1845
+ }, '⬆ 有新版本 v' + updateInfo.latest))
1846
+ } else if (updateInfo && updateInfo.error) {
1847
+ titleChildren.push(createElement('span', {
1848
+ className: 'tag update-error',
1849
+ key: 'update-error',
1850
+ title: updateInfo.error,
1851
+ }, '⚠ 更新检查失败'))
1852
+ }
1853
+
1854
+ var headerChildren = [
1855
+ createElement('div', { className: 'card-title', key: 'title' }, titleChildren),
1856
+ ]
1857
+
1858
+ if (plugin.removable && !isConfirming) {
1859
+ var actionChildren = []
1860
+ // 更新 button — only when an update is available and the plugin is a
1861
+ // registry install (not local path).
1862
+ if (updateInfo && updateInfo.updateAvailable && updateInfo.latest && !isLocal) {
1863
+ actionChildren.push(createElement('button', {
1864
+ type: 'button',
1865
+ key: 'btn-upgrade',
1866
+ className: 'btn sm',
1867
+ disabled: view.busy,
1868
+ title: '升级到 v' + updateInfo.latest + '(npm install ' + plugin.name + '@latest)',
1869
+ onClick: function () { upgrade(plugin.name) },
1870
+ }, '⬆ 更新'))
1871
+ }
1872
+ actionChildren.push(createElement('button', {
1873
+ type: 'button',
1874
+ key: 'btn-remove',
1875
+ className: 'btn danger sm',
1876
+ disabled: view.busy,
1877
+ onClick: function () { patch({ confirming: plugin.name }) },
1878
+ }, '卸载'))
1879
+ headerChildren.push(createElement('div', { className: 'card-actions', key: 'actions' }, actionChildren))
1880
+ }
1881
+
1882
+ var header = createElement('div', { className: 'card-header', key: 'header' }, headerChildren)
1883
+ var cardChildren = [header]
1884
+
1885
+ if (plugin.localPath) {
1886
+ cardChildren.push(createElement('div', { className: 'plugin-path', key: 'path', title: plugin.localPath },
1887
+ '📂 ' + plugin.localPath
1888
+ ))
1889
+ }
1890
+
1891
+ if (isConfirming) {
1892
+ cardChildren.push(createElement('div', { className: 'confirm-bar', key: 'confirm' },
1893
+ createElement('span', { className: 'confirm-text', key: 'text' }, '⚠️ 确定要卸载该插件吗?'),
1894
+ createElement('div', { className: 'confirm-actions', key: 'actions' },
1895
+ createElement('button', {
1896
+ type: 'button',
1897
+ key: 'btn-confirm',
1898
+ className: 'btn danger-solid sm',
1899
+ disabled: view.busy,
1900
+ onClick: function () { remove(plugin.name) },
1901
+ }, '确认卸载'),
1902
+ createElement('button', {
1903
+ type: 'button',
1904
+ key: 'btn-cancel',
1905
+ className: 'btn sm',
1906
+ disabled: view.busy,
1907
+ onClick: function () { patch({ confirming: null }) },
1908
+ }, '取消')
1909
+ )
1910
+ ))
1911
+ }
1912
+
1913
+ return createElement('div', { key: plugin.name, className: 'card' }, cardChildren)
1914
+ }
1915
+
1916
+ /* ========================================================================== */
1917
+ /* Render Sessions View */
1918
+ /* ========================================================================== */
1919
+
1920
+ /**
1921
+ * Live-session display hint. "Online" means the session is still mounted in
1922
+ * the dsh host's in-memory SessionStore (created or opened at least once in
1923
+ * this process) — NOT that a turn is running. Online sessions can now be
1924
+ * closed directly: the admin panel's "关停并删除" disposes the captured agent
1925
+ * handle (stopping any running turn), removes the session from the store,
1926
+ * and then deletes the log no restart needed.
1927
+ */
1928
+ var LIVE_HINT = '会话在线:仍挂载于 dsh host 内存(本进程内创建或打开过的会话保持在线,不代表正在运行);可直接"关停并删除"(会中断该会话正在进行的对话)'
1929
+
1930
+ /**
1931
+ * Canonical session status. Live takes precedence over archived (a session
1932
+ * that is both live and in the archived set is shown as 会话在线); otherwise
1933
+ * archived wins over ended. Used by both the filter pills and the pill
1934
+ * counts so they can never disagree about membership.
1935
+ */
1936
+ function sessionStatus(s) {
1937
+ if (s.live) return 'live'
1938
+ if (s.archived) return 'archived'
1939
+ return 'ended'
1940
+ }
1941
+
1942
+ function filterSessions(sessions, filter, needle) {
1943
+ var result = []
1944
+ for (var i = 0; i < sessions.length; i++) {
1945
+ var s = sessions[i]
1946
+ if (filter !== 'all' && sessionStatus(s) !== filter) continue
1947
+ if (needle !== '') {
1948
+ var hay = ((s.title || '') + ' ' + (s.summary || '') + ' ' + (s.cwd || '') + ' '
1949
+ + (s.workspaceTitle || '') + ' ' + s.id).toLowerCase()
1950
+ if (hay.indexOf(needle) === -1) continue
1951
+ }
1952
+ result.push(s)
1953
+ }
1954
+ return result
1955
+ }
1956
+
1957
+ /**
1958
+ * Filter plugin layers by the type pill and a fuzzy name/version/path query.
1959
+ * The needle matches case-insensitively against the package name, the
1960
+ * installed version, and the local source path, so "tool" finds
1961
+ * dsh-custom-tool and "0.2" finds version rows.
1962
+ */
1963
+ function filterPlugins(plugins, filter, needle) {
1964
+ var result = []
1965
+ for (var i = 0; i < plugins.length; i++) {
1966
+ var p = plugins[i]
1967
+ if (filter === 'plugin' && !p.removable) continue
1968
+ if (filter === 'builtin' && p.removable) continue
1969
+ if (needle !== '') {
1970
+ var hay = ((p.name || '') + ' ' + (p.version || '') + ' ' + (p.localPath || '')).toLowerCase()
1971
+ if (hay.indexOf(needle) === -1) continue
1972
+ }
1973
+ result.push(p)
1974
+ }
1975
+ return result
1976
+ }/**
1977
+ * Group sessions by their accounting workspace in registry order; sessions
1978
+ * without a workspace trail under an "未分组" bucket. Empty workspaces are
1979
+ * omitted so the user only sees groups that currently hold a session.
1980
+ */
1981
+ function buildSessionGroups(filtered, workspaceOrder) {
1982
+ var byWs = new Map()
1983
+ for (var i = 0; i < workspaceOrder.length; i++) {
1984
+ var ws = workspaceOrder[i]
1985
+ byWs.set(ws.workspaceId, {
1986
+ workspaceId: ws.workspaceId, title: ws.title, path: ws.path, sessions: [],
1987
+ })
1988
+ }
1989
+ var ungrouped = []
1990
+ for (var j = 0; j < filtered.length; j++) {
1991
+ var s = filtered[j]
1992
+ var g = s.workspaceId ? byWs.get(s.workspaceId) : undefined
1993
+ if (g !== undefined) g.sessions.push(s)
1994
+ else ungrouped.push(s)
1995
+ }
1996
+ var groups = []
1997
+ for (var k = 0; k < workspaceOrder.length; k++) {
1998
+ var bucket = byWs.get(workspaceOrder[k].workspaceId)
1999
+ if (bucket !== undefined && bucket.sessions.length > 0) groups.push(bucket)
2000
+ }
2001
+ if (ungrouped.length > 0) {
2002
+ groups.push({ workspaceId: null, title: '未分组', path: null, sessions: ungrouped })
2003
+ }
2004
+ return groups
2005
+ }
2006
+
2007
+ function renderSessionsView(view, patch, reload, act) {
2008
+ var elements = []
2009
+
2010
+ // Toolbar: full-width search with inline icon; the refresh action sits at
2011
+ // the row's end so the search field gets the whole width.
2012
+ elements.push(createElement('div', { className: 'toolbar', key: 'toolbar' },
2013
+ createElement('div', { className: 'search-wrap session-search', key: 'wrap' },
2014
+ createElement('span', { className: 'search-icon', key: 'icon' }, '🔍'),
2015
+ createElement('input', {
2016
+ className: 'input',
2017
+ placeholder: '搜索标题、内容摘要、目录或 Session ID...',
2018
+ value: view.needle,
2019
+ onChange: function (e) { patch({ needle: e.target.value }) },
2020
+ }),
2021
+ view.needle !== '' ? createElement('button', {
2022
+ type: 'button',
2023
+ key: 'btn-clear-search',
2024
+ className: 'btn sm',
2025
+ title: '清空搜索',
2026
+ onClick: function () { patch({ needle: '' }) },
2027
+ }, '') : null
2028
+ ),
2029
+ createElement('button', {
2030
+ type: 'button',
2031
+ key: 'btn-refresh',
2032
+ className: 'btn',
2033
+ disabled: view.busy,
2034
+ onClick: reload,
2035
+ },
2036
+ view.busy ? createElement('span', { className: 'spinner', key: 'spin' }) : null,
2037
+ '🔄 刷新'
2038
+ )
2039
+ ))
2040
+
2041
+ // Filter Pills
2042
+ var totalSessions = view.sessions.length
2043
+ var liveCount = 0
2044
+ var archivedCount = 0
2045
+ var endedCount = 0
2046
+ for (var i = 0; i < view.sessions.length; i++) {
2047
+ var s = view.sessions[i]
2048
+ var st = sessionStatus(s)
2049
+ if (st === 'live') liveCount++
2050
+ else if (st === 'archived') archivedCount++
2051
+ else endedCount++
2052
+ }
2053
+
2054
+ elements.push(createElement('div', { className: 'filter-bar', key: 'filters' },
2055
+ createElement('button', {
2056
+ type: 'button',
2057
+ key: 'filter-all',
2058
+ className: 'pill' + (view.filter === 'all' ? ' active' : ''),
2059
+ onClick: function () { patch({ filter: 'all' }) },
2060
+ }, '全部 (' + String(totalSessions) + ')'),
2061
+ createElement('button', {
2062
+ type: 'button',
2063
+ key: 'filter-live',
2064
+ className: 'pill' + (view.filter === 'live' ? ' active' : ''),
2065
+ title: LIVE_HINT,
2066
+ onClick: function () { patch({ filter: 'live' }) },
2067
+ }, '在线 (' + String(liveCount) + ')'),
2068
+ createElement('button', {
2069
+ type: 'button',
2070
+ key: 'filter-archived',
2071
+ className: 'pill' + (view.filter === 'archived' ? ' active' : ''),
2072
+ onClick: function () { patch({ filter: 'archived' }) },
2073
+ }, '已归档 (' + String(archivedCount) + ')'),
2074
+ createElement('button', {
2075
+ type: 'button',
2076
+ key: 'filter-ended',
2077
+ className: 'pill' + (view.filter === 'ended' ? ' active' : ''),
2078
+ onClick: function () { patch({ filter: 'ended' }) },
2079
+ }, '已结束 (' + String(endedCount) + ')')
2080
+ ))
2081
+
2082
+ if (view.error !== '') {
2083
+ elements.push(createElement('div', { className: 'error', key: 'error' }, view.error))
2084
+ }
2085
+
2086
+ // Filter then group by workspace (registry order); sessions without an
2087
+ // accounting workspace trail under "未分组", matching the sidebar model.
2088
+ var needle = view.needle.trim().toLowerCase()
2089
+ var filtered = filterSessions(view.sessions, view.filter, needle)
2090
+ var groups = buildSessionGroups(filtered, view.workspaces || [])
2091
+ var rows = []
2092
+ for (var gi = 0; gi < groups.length; gi++) {
2093
+ var g = groups[gi]
2094
+ var groupKey = g.workspaceId === null ? 'ungrouped' : 'ws-' + g.workspaceId
2095
+ rows.push(createElement('div', { className: 'group-header', key: 'header-' + groupKey },
2096
+ createElement('span', { className: 'group-title', key: 'title' },
2097
+ (g.workspaceId === null ? '📂 ' : '📁 ') + (g.title || '未命名')
2098
+ ),
2099
+ createElement('span', { className: 'group-count', key: 'count' }, String(g.sessions.length) + ' 个'),
2100
+ g.path !== null
2101
+ ? createElement('span', { className: 'group-path', key: 'path', title: g.path }, g.path)
2102
+ : null
2103
+ ))
2104
+ for (var si = 0; si < g.sessions.length; si++) {
2105
+ rows.push(renderSessionCard(g.sessions[si], view, act, patch))
2106
+ }
2107
+ }
2108
+
2109
+ if (rows.length === 0) {
2110
+ rows.push(createElement('div', { className: 'empty', key: 'empty' },
2111
+ createElement('div', null, needle !== '' ? '🔍 无匹配的会话内容' : '💬 没有已持久化的会话')
2112
+ ))
2113
+ }
2114
+
2115
+ elements.push(createElement('div', { className: 'list', key: 'list' }, rows))
2116
+
2117
+ // Footer
2118
+ var summaryText = view.busy ? '加载中...'
2119
+ : '共 ' + String(totalSessions) + ' 个会话,当前展示 ' + String(filtered.length) + ' 个'
2120
+
2121
+ elements.push(createElement('div', { className: 'footer', key: 'footer' },
2122
+ createElement('span', { key: 'summary' }, summaryText),
2123
+ createElement('span', { className: 'hint', key: 'hint' }, '会话修改即时同步到侧边栏')
2124
+ ))
2125
+
2126
+ return createElement('div', { key: 'sessions-panel', style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, elements)
2127
+ }
2128
+
2129
+ function renderSessionCard(session, view, act, patch) {
2130
+ var isConfirming = view.confirming === session.id
2131
+ var dotClass = 'dot' + (session.live ? ' live' : session.archived ? ' archived' : '')
2132
+ var dotTitle = session.live ? LIVE_HINT : session.archived ? '已归档' : '已结束'
2133
+
2134
+ var actions = []
2135
+ if (!isConfirming) {
2136
+ if (!session.archived && !session.live) {
2137
+ actions.push(createElement('button', {
2138
+ type: 'button',
2139
+ className: 'btn sm',
2140
+ key: 'btn-archive',
2141
+ disabled: view.busy,
2142
+ onClick: function () { act('archive', session.id) },
2143
+ }, '归档'))
2144
+ }
2145
+ if (session.archived) {
2146
+ actions.push(createElement('button', {
2147
+ type: 'button',
2148
+ className: 'btn sm',
2149
+ key: 'btn-unarchive',
2150
+ disabled: view.busy,
2151
+ onClick: function () { act('unarchive', session.id) },
2152
+ }, '取消归档'))
2153
+ }
2154
+ if (!session.live) {
2155
+ actions.push(createElement('button', {
2156
+ type: 'button',
2157
+ className: 'btn danger sm',
2158
+ key: 'btn-delete',
2159
+ disabled: view.busy,
2160
+ onClick: function () { patch({ confirming: session.id }) },
2161
+ }, '删除'))
2162
+ } else {
2163
+ // Online sessions can now be closed through the captured AgentHandle
2164
+ // (closeSession disposes the live agent/session first, so the log can
2165
+ // be removed without resurrection). This stops a running conversation,
2166
+ // so it is a destructive action with its own confirm flow.
2167
+ actions.push(createElement('button', {
2168
+ type: 'button',
2169
+ className: 'btn danger sm',
2170
+ key: 'btn-close',
2171
+ disabled: view.busy,
2172
+ title: '关停该在线会话(停止其 agent 运行)并永久删除日志记录',
2173
+ onClick: function () { patch({ confirming: session.id }) },
2174
+ }, '关停并删除'))
2175
+ }
2176
+ }
2177
+
2178
+ var titleChildren = [
2179
+ createElement('span', { className: dotClass, title: dotTitle, key: 'dot' }),
2180
+ createElement('div', { className: 'card-title', key: 'title' },
2181
+ createElement('span', { className: 'card-title-text', key: 'name', title: session.title || session.cwd },
2182
+ session.title || (session.cwd ? baseName(session.cwd) : '未命名会话')
2183
+ ),
2184
+ session.live ? createElement('span', { className: 'tag live', key: 'tag-live', title: LIVE_HINT }, '会话在线')
2185
+ : session.archived ? createElement('span', { className: 'tag archived', key: 'tag-archived' }, '已归档')
2186
+ : null,
2187
+ session.messageCount > 0 ? createElement('span', { className: 'tag turns', key: 'tag-turns' }, String(session.messageCount) + ' 条消息') : null
2188
+ ),
2189
+ ]
2190
+ var headerChildren
2191
+ if (actions.length > 0) {
2192
+ headerChildren = titleChildren.concat([createElement('div', { className: 'card-actions', key: 'actions' }, actions)])
2193
+ } else {
2194
+ headerChildren = titleChildren
2195
+ }
2196
+
2197
+ var header = createElement('div', { className: 'card-header', key: 'header' }, headerChildren)
2198
+ var cardChildren = [header]
2199
+
2200
+ // Content summary block
2201
+ if (session.summary) {
2202
+ cardChildren.push(createElement('div', { className: 'card-summary', key: 'summary', title: session.summary },
2203
+ createElement('span', { className: 'summary-icon', key: 'icon' }, '💬'),
2204
+ createElement('span', { className: 'summary-text', key: 'text' }, session.summary)
2205
+ ))
2206
+ } else if (session.summaryError) {
2207
+ cardChildren.push(createElement('div', { className: 'error', key: 'summary-error' },
2208
+ '摘要读取失败:' + session.summaryError
2209
+ ))
2210
+ }
2211
+
2212
+ // Sub metadata line
2213
+ var subChildren = [
2214
+ createElement('span', { className: 'card-sub-item', title: session.cwd || '无工作目录', key: 'path' },
2215
+ '📁 ' + (session.cwd ? baseName(session.cwd) + ' (' + session.cwd + ')' : '(无工作目录)')
2216
+ ),
2217
+ createElement('span', { key: 'sep1' }, '·'),
2218
+ createElement('span', { className: 'card-sub-item', key: 'time' }, '🕒 ' + formatDate(session.createdAt)),
2219
+ ]
2220
+ if (session.id) {
2221
+ subChildren.push(createElement('span', { key: 'sep2' }, '·'))
2222
+ subChildren.push(createElement('span', { className: 'card-sub-item session-id-badge', key: 'id', title: '会话 ID: ' + session.id },
2223
+ '🆔 ' + session.id.slice(0, 8)
2224
+ ))
2225
+ }
2226
+
2227
+ var sub = createElement('div', { className: 'card-sub', key: 'sub' }, subChildren)
2228
+ cardChildren.push(sub)
2229
+
2230
+ if (isConfirming) {
2231
+ cardChildren.push(createElement('div', { className: 'confirm-bar', key: 'confirm' },
2232
+ createElement('span', { className: 'confirm-text', key: 'text' },
2233
+ session.live
2234
+ ? '⚠️ 将关停该在线会话(正在运行则会中断)并永久删除记录与日志,确定?'
2235
+ : '⚠️ 确定永久删除该会话记录及日志文件?'),
2236
+ createElement('div', { className: 'confirm-actions', key: 'actions' },
2237
+ createElement('button', {
2238
+ type: 'button',
2239
+ key: 'btn-confirm',
2240
+ className: 'btn danger-solid sm',
2241
+ disabled: view.busy,
2242
+ onClick: function () { act(session.live ? 'closeSession' : 'deleteSession', session.id) },
2243
+ }, '确认删除'),
2244
+ createElement('button', {
2245
+ type: 'button',
2246
+ key: 'btn-cancel',
2247
+ className: 'btn sm',
2248
+ disabled: view.busy,
2249
+ onClick: function () { patch({ confirming: null }) },
2250
+ }, '取消')
2251
+ )
2252
+ ))
2253
+ }
2254
+
2255
+ return createElement('div', { key: session.id, className: 'card' }, cardChildren)
2256
+ }
2257
+
2258
+ /* ========================================================================== */
2259
+ /* Plugin Entrypoint */
2260
+ /* ========================================================================== */
2261
+
2262
+ function apply(ctx) {
2263
+ injectStyles()
2264
+
2265
+ var call = function (method, args) {
2266
+ return ctx.connection.rpc.call('/api', method, { args: args })
2267
+ }
2268
+
2269
+ // Sidebar right-click menus: delete session (after archive) on session
2270
+ // rows, reveal in explorer on workspace rows. Mounted once for the page
2271
+ // lifetime; dispose when the plugin unmounts.
2272
+ // The sessions service lets us nudge the sidebar list after a delete so
2273
+ // the removed session disappears immediately instead of lingering in
2274
+ // "未分组" until the next reload.
2275
+ var refreshSessions = null
2276
+ try {
2277
+ var sessionsSvc = ctx.get && ctx.get('sessions')
2278
+ if (sessionsSvc && typeof sessionsSvc.refresh === 'function') {
2279
+ refreshSessions = function () { sessionsSvc.refresh().catch(function () {}) }
2280
+ }
2281
+ } catch (e) { refreshSessions = null }
2282
+ var disposeSidebar = ctx.effect(function () { return setupMenuInjection(call, refreshSessions) })
2283
+
2284
+ // One management-center entry keeps related local administration together;
2285
+ // its tab container mounts only the selected panel.
2286
+ ctx.slots.inject('settings.section', function () {
2287
+ return ctx.slots.register({
2288
+ name: 'settings.section',
2289
+ id: 'plugin-admin',
2290
+ order: 25,
2291
+ label: '管理中心',
2292
+ inject: function () { return { call: call, refreshSessions: refreshSessions } },
2293
+ }, AdminCenterSection)
2294
+ })
2295
+ }
2296
+
2297
+ module.exports = { apply: apply, inject: ['slots', 'connection'] }
2298
+ return module.exports
2299
+ } });