@unihc/dsh-process-manager 0.0.0-stage → 1.0.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/client.js ADDED
@@ -0,0 +1,1537 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@local/dsh-process-manager',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+ const { useState, useEffect, useMemo, useRef, useCallback } = React
7
+
8
+ const NS = 'processManager'
9
+ const TAB_ID = '@local/dsh-process-manager/panel'
10
+ const TAB_KIND = 'process-manager'
11
+ const OP_FLAG = 'dsh.process-manager.opened.v1'
12
+ const COMMANDS = [
13
+ 'process-snapshot', 'process-inspect', 'process-stop',
14
+ 'process-startup-set', 'process-explain', 'process-tool',
15
+ ]
16
+ const SOURCE_ORDER = { run: 0, folder: 1, task: 2, service: 3 }
17
+
18
+ function compareStartupEntries(a, b) {
19
+ if (a.enabled !== b.enabled) return a.enabled ? -1 : 1
20
+ const bySource = (SOURCE_ORDER[a.source] ?? 9) - (SOURCE_ORDER[b.source] ?? 9)
21
+ if (bySource !== 0) return bySource
22
+ return String(a.labelEn ?? a.label ?? a.name).localeCompare(String(b.labelEn ?? b.label ?? b.name), 'zh-Hans')
23
+ }
24
+
25
+ const zh = {
26
+ title: '进程与启动项',
27
+ guide: '按应用看清正在运行的进程,并查看、禁用或恢复开机自启项',
28
+ openPanel: '打开进程与启动项',
29
+ noSession: '请先打开一个会话',
30
+ tabProcesses: '进程',
31
+ tabStartup: '开机启动',
32
+ refresh: '刷新',
33
+ refreshing: '采集中…',
34
+ fullscreen: '全屏',
35
+ snapshot: '快照',
36
+ loading: '正在采集系统信息…',
37
+ loadingHint: '首次约 2–4 秒,采集期间不会修改任何东西',
38
+ loadFailed: '采集失败',
39
+ retry: '重试',
40
+ sessionMissing: '当前会话不可用,请重新打开面板',
41
+ summaryProcesses: '进程',
42
+ summaryApps: '应用',
43
+ summaryMemory: '内存',
44
+ summaryCpu: 'CPU',
45
+ summaryAutostart: '自启运行',
46
+ search: '搜索应用、发布者、说明或 PID',
47
+ filterAll: '全部',
48
+ filterLabel: '筛选',
49
+ sortLabel: '排序',
50
+ filterApps: '应用',
51
+ filterBackground: '后台',
52
+ filterSystem: '系统',
53
+ sortMemory: '内存',
54
+ sortCpu: 'CPU',
55
+ sortName: '名称',
56
+ expandAll: '展开全部',
57
+ collapseAll: '收起',
58
+ noMatches: '没有匹配的进程',
59
+ groupCount: '{n} 个进程',
60
+ autostart: '自启',
61
+ serviceCount: '{n} 个服务',
62
+ systemItem: '系统',
63
+ riskNormal: '普通',
64
+ riskCaution: '谨慎',
65
+ riskCritical: '关键',
66
+ riskProtected: '受保护',
67
+ riskLegend: '关键进程不允许结束',
68
+ criticalHint: '关键进程:面板不允许结束它',
69
+ factsTitle: '基本信息',
70
+ details: '详情',
71
+ snapshotHint: '只读采集的进程与启动项快照',
72
+ noMatchesHint: '调整搜索或筛选条件,或刷新后再试',
73
+ adminPreNote: '这一项需要管理员权限:确认后 Windows 会弹出 UAC;取消 UAC 不会修改任何东西。',
74
+ serviceStopHint: '该进程托管 Windows 服务:直接结束进程不等于停止服务。请到「开机启动」页对相应服务选择禁用并勾选「同时停止正在运行的服务」,或用「服务」管理器。',
75
+ stale: '数据可能已过期,建议刷新',
76
+ back: '返回',
77
+ appPurpose: '它是干什么的',
78
+ path: '路径',
79
+ publisher: '发布者',
80
+ product: '产品',
81
+ version: '版本',
82
+ signature: '数字签名',
83
+ startedAt: '启动时间',
84
+ commandLine: '命令行',
85
+ windowTitle: '窗口标题',
86
+ pid: 'PID',
87
+ pids: 'PID',
88
+ services: '托管服务',
89
+ parentChain: '父进程链',
90
+ relatedStartup: '关联启动项',
91
+ unknown: '未知',
92
+ copyPath: '复制路径',
93
+ copyCommand: '复制命令',
94
+ copied: '已复制',
95
+ copyFailed: '复制失败',
96
+ reveal: '打开位置',
97
+ closeApp: '正常关闭',
98
+ killApp: '强制结束',
99
+ killGroup: '结束整个应用',
100
+ closeHint: '请求主窗口正常关闭;没有窗口的进程请用强制结束',
101
+ killHint: '强制结束可能丢失未保存的数据',
102
+ noWindow: '该应用没有可关闭的主窗口,请用强制结束',
103
+ confirmStopTitle: '正常关闭进程',
104
+ confirmKillTitle: '强制结束进程',
105
+ confirmKillGroupTitle: '结束整个应用',
106
+ confirmStopDesc: '让「{name}」的主窗口正常关闭,可能弹出保存提示。',
107
+ confirmKillDesc: '立即结束「{name}」,未保存的数据会丢失。',
108
+ confirmKillGroupDesc: '立即结束「{name}」的 {n} 个进程,未保存的数据会丢失。',
109
+ confirm: '确认',
110
+ confirmAdmin: '确认并请求管理员权限',
111
+ cancel: '取消',
112
+ working: '处理中…',
113
+ opDone: '操作完成',
114
+ opFailed: '操作失败',
115
+ needAdmin: '需要管理员权限',
116
+ needAdminDesc: 'Windows 会弹出 UAC 授权窗口,请选择「是」;拒绝则不会做任何修改。',
117
+ applyAdmin: '申请管理员权限并重试',
118
+ adminDenied: '未获得管理员权限,未做任何修改',
119
+ protectedHint: '受保护的系统项,面板不会结束它',
120
+ aiExplain: 'AI 解读',
121
+ aiWorking: 'AI 解读中…',
122
+ aiTitle: 'AI 解读',
123
+ aiFailed: 'AI 解读失败',
124
+ aiEmpty: 'AI 没有返回内容',
125
+ aiHint: '会向当前模型发送一次只读事实请求',
126
+ startupTitle: '开机启动项',
127
+ startupEmpty: '没有匹配的启动项',
128
+ startupSearch: '搜索启动项、命令或说明',
129
+ startupAll: '全部',
130
+ startupRun: '注册表 Run',
131
+ startupFolder: '启动文件夹',
132
+ startupTask: '计划任务',
133
+ startupService: '自动服务',
134
+ showSystem: '显示 Windows 系统项',
135
+ hideSystem: '隐藏 Windows 系统项',
136
+ enabled: '已启用',
137
+ disabled: '已禁用',
138
+ runningNow: '运行中',
139
+ admin: '需管理员',
140
+ readOnly: '只读',
141
+ triggerLogin: '登录时',
142
+ triggerBoot: '开机时',
143
+ sourceRun: 'Run',
144
+ sourceFolder: '启动文件夹',
145
+ sourceTask: '计划任务',
146
+ sourceService: '服务',
147
+ scopeUser: '当前用户',
148
+ scopeMachine: '所有用户',
149
+ startupDisableTitle: '取消开机自启',
150
+ startupEnableTitle: '恢复开机自启',
151
+ startupDisableDesc: '禁用「{name}」的开机自启。这是与任务管理器相同的可逆开关,不会删除程序或注册表项。',
152
+ startupEnableDesc: '重新启用「{name}」的开机自启。',
153
+ startupDisable: '禁用',
154
+ startupEnable: '启用',
155
+ stopRunningService: '同时停止正在运行的服务',
156
+ stopRunningServiceHint: '勾选后会立即停止该服务;不勾选只改启动类型,下次重启生效。',
157
+ startupDone: '启动项已更新',
158
+ startupProtectedHint: 'Windows 系统项只读,请用「服务」或任务计划程序管理',
159
+ startupRunOnce: '一次性启动项,只读',
160
+ openTaskmgr: '任务管理器',
161
+ openStartupSettings: '启动项设置',
162
+ openServices: '服务',
163
+ snapshotTime: '数据时间',
164
+ footerHint: '只读采集;结束与开关需用户确认',
165
+ noDetail: '没有选中项',
166
+ staleHint: '数据可能已过期,刷新以获取当前状态',
167
+ serviceRunning: '正在运行',
168
+ serviceStopped: '已停止',
169
+ startupRunning: '正在运行',
170
+ secondsAgo: '{n} 秒前',
171
+ minutesAgo: '{n} 分钟前',
172
+ justNow: '刚刚',
173
+ aiForGroup: 'AI 解读主进程',
174
+ explainTarget: '解读“{name}”',
175
+ detailLoading: '正在读取签名与文件信息…',
176
+ showProcesses: '进程列表',
177
+ groupProcesses: '包含的进程',
178
+ hideSystemHint: '默认隐藏 Windows 自带任务与系统服务,避免误操作',
179
+ noStartup: '没有启动项',
180
+ }
181
+
182
+ const en = {
183
+ title: 'Processes and startup',
184
+ guide: 'See running processes grouped by app, and review, disable or restore startup entries',
185
+ openPanel: 'Open processes and startup',
186
+ noSession: 'Open a session first',
187
+ tabProcesses: 'Processes',
188
+ tabStartup: 'Startup',
189
+ refresh: 'Refresh',
190
+ refreshing: 'Sampling…',
191
+ fullscreen: 'Full screen',
192
+ snapshot: 'Snapshot',
193
+ loading: 'Sampling the system…',
194
+ loadingHint: 'About 2–4 seconds. Nothing is changed while sampling.',
195
+ loadFailed: 'Sampling failed',
196
+ retry: 'Retry',
197
+ sessionMissing: 'This session is not available; reopen the panel.',
198
+ summaryProcesses: 'Processes',
199
+ summaryApps: 'Apps',
200
+ summaryMemory: 'Memory',
201
+ summaryCpu: 'CPU',
202
+ summaryAutostart: 'From startup',
203
+ search: 'Search app, publisher, purpose or PID',
204
+ filterAll: 'All',
205
+ filterLabel: 'Filter',
206
+ sortLabel: 'Sort',
207
+ filterApps: 'Apps',
208
+ filterBackground: 'Background',
209
+ filterSystem: 'System',
210
+ sortMemory: 'Memory',
211
+ sortCpu: 'CPU',
212
+ sortName: 'Name',
213
+ expandAll: 'Expand all',
214
+ collapseAll: 'Collapse',
215
+ noMatches: 'No matching processes',
216
+ groupCount: '{n} processes',
217
+ autostart: 'Startup',
218
+ serviceCount: '{n} services',
219
+ systemItem: 'System',
220
+ riskNormal: 'Normal',
221
+ riskCaution: 'Careful',
222
+ riskCritical: 'Critical',
223
+ riskProtected: 'Protected',
224
+ riskLegend: 'Critical processes cannot be stopped here',
225
+ criticalHint: 'Critical process: the panel will not end it',
226
+ factsTitle: 'Details',
227
+ details: 'Details',
228
+ snapshotHint: 'Read-only snapshot of processes and startup entries',
229
+ noMatchesHint: 'Adjust the search or filters, or refresh.',
230
+ adminPreNote: 'This entry needs administrator rights: Windows shows UAC after you confirm; cancelling UAC changes nothing.',
231
+ serviceStopHint: 'This process hosts Windows services; ending it is not the same as stopping a service. Disable the service on the Startup tab with “Also stop the running service”, or use the Services manager.',
232
+ stale: 'This snapshot may be stale; refresh for current state',
233
+ back: 'Back',
234
+ appPurpose: 'What it is for',
235
+ path: 'Path',
236
+ publisher: 'Publisher',
237
+ product: 'Product',
238
+ version: 'Version',
239
+ signature: 'Signature',
240
+ startedAt: 'Started',
241
+ commandLine: 'Command line',
242
+ windowTitle: 'Window title',
243
+ pid: 'PID',
244
+ pids: 'PIDs',
245
+ services: 'Hosted services',
246
+ parentChain: 'Parent chain',
247
+ relatedStartup: 'Startup entries',
248
+ unknown: 'Unknown',
249
+ copyPath: 'Copy path',
250
+ copyCommand: 'Copy command',
251
+ copied: 'Copied',
252
+ copyFailed: 'Copy failed',
253
+ reveal: 'Show location',
254
+ closeApp: 'Close',
255
+ killApp: 'End task',
256
+ killGroup: 'End app',
257
+ closeHint: 'Asks the main window to close; windowless processes need End task',
258
+ killHint: 'Ending a task can lose unsaved work',
259
+ noWindow: 'This app has no main window to close; use End task',
260
+ confirmStopTitle: 'Close process',
261
+ confirmKillTitle: 'End process',
262
+ confirmKillGroupTitle: 'End application',
263
+ confirmStopDesc: 'Ask the main window of “{name}” to close; a save prompt may appear.',
264
+ confirmKillDesc: 'End “{name}” immediately; unsaved data will be lost.',
265
+ confirmKillGroupDesc: 'End all {n} processes of “{name}” immediately; unsaved data will be lost.',
266
+ confirm: 'Confirm',
267
+ confirmAdmin: 'Confirm and request admin',
268
+ cancel: 'Cancel',
269
+ working: 'Working…',
270
+ opDone: 'Done',
271
+ opFailed: 'Operation failed',
272
+ needAdmin: 'Administrator rights required',
273
+ needAdminDesc: 'Windows will show a UAC prompt; choose Yes. Cancelling changes nothing.',
274
+ applyAdmin: 'Request administrator and retry',
275
+ adminDenied: 'Administrator rights were not granted; nothing changed',
276
+ protectedHint: 'Protected system item; the panel will not stop it',
277
+ aiExplain: 'Explain with AI',
278
+ aiWorking: 'Explaining…',
279
+ aiTitle: 'AI explanation',
280
+ aiFailed: 'AI explanation failed',
281
+ aiEmpty: 'The model returned no text',
282
+ aiHint: 'Sends one read-only fact request to the current model',
283
+ startupTitle: 'Startup entries',
284
+ startupEmpty: 'No matching startup entries',
285
+ startupSearch: 'Search entry, command or purpose',
286
+ startupAll: 'All',
287
+ startupRun: 'Run keys',
288
+ startupFolder: 'Startup folder',
289
+ startupTask: 'Scheduled tasks',
290
+ startupService: 'Auto services',
291
+ showSystem: 'Show Windows items',
292
+ hideSystem: 'Hide Windows items',
293
+ enabled: 'Enabled',
294
+ disabled: 'Disabled',
295
+ runningNow: 'Running',
296
+ admin: 'Admin needed',
297
+ readOnly: 'Read-only',
298
+ triggerLogin: 'At logon',
299
+ triggerBoot: 'At boot',
300
+ sourceRun: 'Run',
301
+ sourceFolder: 'Startup folder',
302
+ sourceTask: 'Task',
303
+ sourceService: 'Service',
304
+ scopeUser: 'Current user',
305
+ scopeMachine: 'All users',
306
+ startupDisableTitle: 'Disable startup entry',
307
+ startupEnableTitle: 'Enable startup entry',
308
+ startupDisableDesc: 'Disable autostart for “{name}”. This is the same reversible switch Task Manager uses; no program or registry value is deleted.',
309
+ startupEnableDesc: 'Turn autostart for “{name}” back on.',
310
+ startupDisable: 'Disable',
311
+ startupEnable: 'Enable',
312
+ stopRunningService: 'Also stop the running service',
313
+ stopRunningServiceHint: 'Stops the service now; without it only the startup type changes and takes effect on the next restart.',
314
+ startupDone: 'Startup entry updated',
315
+ startupProtectedHint: 'Windows-owned items are read-only here; use Services or Task Scheduler',
316
+ startupRunOnce: 'One-shot entry; read-only',
317
+ openTaskmgr: 'Task Manager',
318
+ openStartupSettings: 'Startup apps',
319
+ openServices: 'Services',
320
+ snapshotTime: 'Sampled',
321
+ footerHint: 'Read-only sampling; stopping and startup changes need confirmation',
322
+ noDetail: 'Nothing selected',
323
+ staleHint: 'This snapshot may be stale; refresh for current state',
324
+ serviceRunning: 'Running',
325
+ serviceStopped: 'Stopped',
326
+ startupRunning: 'Running now',
327
+ secondsAgo: '{n}s ago',
328
+ minutesAgo: '{n}m ago',
329
+ justNow: 'just now',
330
+ aiForGroup: 'Explain main process',
331
+ explainTarget: 'Explain “{name}”',
332
+ detailLoading: 'Reading signature and file information…',
333
+ showProcesses: 'Process list',
334
+ groupProcesses: 'Processes in this app',
335
+ hideSystemHint: 'Windows tasks and services are hidden by default to avoid mistakes',
336
+ noStartup: 'No startup entries',
337
+ }
338
+
339
+ const CSS = `
340
+ .dsh-proc-root { position: relative; display: flex; flex-direction: column; height: 100%; min-height: 0; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); font-size: 13px; line-height: 1.45; }
341
+ .dsh-proc-root, .dsh-proc-root *, .dsh-proc-root *::before, .dsh-proc-root *::after { box-sizing: border-box; }
342
+ .dsh-proc-header { display: flex; align-items: center; gap: 6px; padding: 10px 12px 8px; border-bottom: 1px solid var(--dsw-alias-border-l1); }
343
+ .dsh-proc-title { margin: 0; font-size: 14px; font-weight: 600; }
344
+ .dsh-proc-spacer { flex: 1; }
345
+ .dsh-proc-badge { border: 1px solid var(--dsw-alias-border-l1); border-radius: 999px; padding: 1px 6px; font-size: 11px; color: var(--dsw-alias-label-secondary); white-space: nowrap; }
346
+ .dsh-proc-badge.ok { color: var(--dsw-alias-state-success-primary); border-color: currentColor; }
347
+ .dsh-proc-badge.warn { color: var(--dsw-alias-state-warn-primary); border-color: currentColor; }
348
+ .dsh-proc-btn { display: inline-flex; align-items: center; gap: 4px; border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1); color: inherit; border-radius: 6px; padding: 3px 8px; font: inherit; font-size: 12px; cursor: pointer; white-space: nowrap; }
349
+ .dsh-proc-btn:hover { background: var(--dsw-alias-bg-layer-2); }
350
+ .dsh-proc-btn:disabled { opacity: .5; cursor: default; }
351
+ .dsh-proc-btn.ghost { background: transparent; border-color: transparent; color: var(--dsw-alias-label-secondary); }
352
+ .dsh-proc-btn.ghost:hover { background: var(--dsw-alias-bg-layer-1); }
353
+ .dsh-proc-btn.primary { border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-brand-primary); }
354
+ .dsh-proc-btn.danger { border-color: var(--dsw-alias-state-error-primary); color: var(--dsw-alias-state-error-primary); }
355
+ .dsh-proc-tabs { display: flex; gap: 4px; padding: 8px 12px 0; }
356
+ .dsh-proc-tab { flex: 1; border: 1px solid var(--dsw-alias-border-l1); background: transparent; color: var(--dsw-alias-label-secondary); border-radius: 6px; padding: 4px 6px; font: inherit; font-size: 12px; cursor: pointer; }
357
+ .dsh-proc-tab.active { background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary); border-color: var(--dsw-alias-border-l2); font-weight: 600; }
358
+ .dsh-proc-body { flex: 1; min-height: 0; overflow: auto; padding: 10px 12px 16px; display: flex; flex-direction: column; gap: 10px; }
359
+ .dsh-proc-banner { border-radius: 8px; padding: 7px 9px; font-size: 12px; border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-secondary); }
360
+ .dsh-proc-banner.error { border-color: var(--dsw-alias-state-error-primary); color: var(--dsw-alias-state-error-primary); }
361
+ .dsh-proc-banner.warn { border-color: var(--dsw-alias-state-warn-primary); color: var(--dsw-alias-state-warn-primary); }
362
+ .dsh-proc-metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(62px, 1fr)); gap: 6px; }
363
+ .dsh-proc-metric { border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; padding: 6px 8px; background: var(--dsw-alias-bg-layer-1); min-width: 0; }
364
+ .dsh-proc-metric-label { font-size: 11px; color: var(--dsw-alias-label-secondary); }
365
+ .dsh-proc-metric-value { font-size: 14px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
366
+ .dsh-proc-toolbar { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
367
+ .dsh-proc-input { flex: 1 1 140px; min-width: 0; border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1); color: inherit; border-radius: 6px; padding: 4px 8px; font: inherit; font-size: 12px; }
368
+ .dsh-proc-input:focus { outline: none; border-color: var(--dsw-alias-brand-primary); }
369
+ .dsh-proc-select { border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1); color: inherit; border-radius: 6px; padding: 4px 6px; font: inherit; font-size: 12px; }
370
+ .dsh-proc-chips { display: flex; flex-wrap: wrap; gap: 4px; }
371
+ .dsh-proc-chip { border: 1px solid var(--dsw-alias-border-l1); background: transparent; color: var(--dsw-alias-label-secondary); border-radius: 999px; padding: 2px 8px; font: inherit; font-size: 11px; cursor: pointer; white-space: nowrap; }
372
+ .dsh-proc-chip.active { background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-primary); border-color: var(--dsw-alias-border-l2); }
373
+ .dsh-proc-list { display: flex; flex-direction: column; gap: 6px; }
374
+ .dsh-proc-group { border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; background: var(--dsw-alias-bg-layer-1); overflow: hidden; }
375
+ .dsh-proc-group-head { display: flex; align-items: center; gap: 6px; width: 100%; padding: 7px 8px; }
376
+ .dsh-proc-group-head:hover { background: var(--dsw-alias-bg-layer-2); }
377
+ .dsh-proc-chevronbtn { display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; flex: none; border: 0; background: transparent; color: inherit; padding: 0; cursor: pointer; }
378
+ .dsh-proc-group-main { min-width: 0; flex: 1; border: 0; background: transparent; color: inherit; font: inherit; text-align: left; padding: 0; cursor: pointer; }
379
+ .dsh-proc-group-title { display: flex; align-items: center; gap: 4px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
380
+ .dsh-proc-group-sub { font-size: 11px; color: var(--dsw-alias-label-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
381
+ .dsh-proc-group-num { font-size: 11px; color: var(--dsw-alias-label-secondary); text-align: right; white-space: nowrap; }
382
+ .dsh-proc-chevron { width: 12px; height: 12px; flex: none; color: var(--dsw-alias-label-secondary); transition: transform .12s ease; }
383
+ .dsh-proc-chevron.open { transform: rotate(90deg); }
384
+ .dsh-proc-proc { display: flex; align-items: center; gap: 6px; width: 100%; border: 0; border-top: 1px solid var(--dsw-alias-border-l1); background: transparent; color: inherit; font: inherit; text-align: left; padding: 5px 8px 5px 26px; cursor: pointer; font-size: 12px; }
385
+ .dsh-proc-proc:hover { background: var(--dsw-alias-bg-layer-2); }
386
+ .dsh-proc-proc-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; }
387
+ .dsh-proc-proc-num { color: var(--dsw-alias-label-secondary); font-size: 11px; white-space: nowrap; }
388
+ .dsh-proc-muted { color: var(--dsw-alias-label-secondary); font-size: 12px; }
389
+ .dsh-proc-small { font-size: 11px; }
390
+ .dsh-proc-pill { display: inline-flex; align-items: center; border: 1px solid var(--dsw-alias-border-l1); border-radius: 999px; padding: 0 5px; font-size: 10px; line-height: 16px; color: var(--dsw-alias-label-secondary); white-space: nowrap; }
391
+ .dsh-proc-pill.caution { color: var(--dsw-alias-state-warn-primary); border-color: currentColor; }
392
+ .dsh-proc-pill.critical, .dsh-proc-pill.protected { color: var(--dsw-alias-state-error-primary); border-color: currentColor; }
393
+ .dsh-proc-pill.ok { color: var(--dsw-alias-state-success-primary); border-color: currentColor; }
394
+ .dsh-proc-pill.brand { color: var(--dsw-alias-brand-primary); border-color: currentColor; }
395
+ .dsh-proc-empty { padding: 24px 8px; text-align: center; color: var(--dsw-alias-label-secondary); font-size: 12px; }
396
+ .dsh-proc-empty-title { font-size: 13px; color: var(--dsw-alias-label-primary); margin-bottom: 4px; }
397
+ .dsh-proc-footer { border-top: 1px solid var(--dsw-alias-border-l1); padding: 6px 12px; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; font-size: 11px; color: var(--dsw-alias-label-secondary); }
398
+ .dsh-proc-back { display: inline-flex; align-items: center; gap: 4px; border: 0; background: transparent; color: var(--dsw-alias-label-secondary); font: inherit; font-size: 12px; cursor: pointer; padding: 0; }
399
+ .dsh-proc-back:hover { color: var(--dsw-alias-label-primary); }
400
+ .dsh-proc-detail-head { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
401
+ .dsh-proc-detail-title { font-size: 14px; font-weight: 600; margin: 0; }
402
+ .dsh-proc-card { border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; background: var(--dsw-alias-bg-layer-1); padding: 8px 10px; }
403
+ .dsh-proc-card-title { font-size: 11px; font-weight: 600; color: var(--dsw-alias-label-secondary); margin-bottom: 4px; text-transform: uppercase; letter-spacing: .02em; }
404
+ .dsh-proc-facts { display: grid; grid-template-columns: 64px minmax(0, 1fr); gap: 3px 8px; margin: 0; font-size: 12px; }
405
+ .dsh-proc-facts dt { color: var(--dsw-alias-label-secondary); }
406
+ .dsh-proc-facts dd { margin: 0; overflow-wrap: anywhere; }
407
+ .dsh-proc-actions { display: flex; flex-wrap: wrap; gap: 6px; }
408
+ .dsh-proc-switch { width: 30px; height: 16px; border-radius: 999px; border: 1px solid var(--dsw-alias-border-l2); background: var(--dsw-alias-bg-base); position: relative; cursor: pointer; flex: none; padding: 0; }
409
+ .dsh-proc-switch::after { content: ''; position: absolute; top: 1px; left: 1px; width: 12px; height: 12px; border-radius: 50%; background: var(--dsw-alias-label-secondary); transition: transform .12s ease; }
410
+ .dsh-proc-switch.on { background: var(--dsw-alias-brand-primary); border-color: var(--dsw-alias-brand-primary); }
411
+ .dsh-proc-switch.on::after { transform: translateX(14px); background: #fff; }
412
+ .dsh-proc-switch:disabled { opacity: .45; cursor: default; }
413
+ .dsh-proc-startup { border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; background: var(--dsw-alias-bg-layer-1); padding: 8px; display: flex; flex-direction: column; gap: 5px; }
414
+ .dsh-proc-startup-head { display: flex; align-items: flex-start; gap: 8px; }
415
+ .dsh-proc-startup-main { flex: 1; min-width: 0; }
416
+ .dsh-proc-startup-title { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; font-weight: 600; }
417
+ .dsh-proc-startup-sub { font-size: 12px; color: var(--dsw-alias-label-secondary); }
418
+ .dsh-proc-cmd { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; color: var(--dsw-alias-label-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
419
+ .dsh-proc-startup-actions { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; }
420
+ .dsh-proc-ai { border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; background: var(--dsw-alias-bg-layer-2); padding: 8px 10px; font-size: 12px; white-space: pre-wrap; }
421
+ .dsh-proc-confirm { display: flex; flex-direction: column; gap: 8px; }
422
+ .dsh-proc-confirm-title { font-size: 14px; font-weight: 600; }
423
+ .dsh-proc-confirm-list { border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; padding: 6px 8px; font-size: 12px; max-height: 180px; overflow: auto; background: var(--dsw-alias-bg-layer-1); }
424
+ .dsh-proc-check { display: flex; align-items: flex-start; gap: 6px; font-size: 12px; color: var(--dsw-alias-label-secondary); }
425
+ .dsh-proc-toast { position: absolute; left: 12px; right: 12px; bottom: 44px; border-radius: 8px; padding: 7px 9px; font-size: 12px; background: var(--dsw-alias-bg-overlay); border: 1px solid var(--dsw-alias-border-l2); box-shadow: 0 4px 16px rgba(0,0,0,.14); }
426
+ .dsh-proc-toast.error { border-color: var(--dsw-alias-state-error-primary); color: var(--dsw-alias-state-error-primary); }
427
+ .dsh-proc-footer-actions { display: flex; gap: 4px; flex-wrap: wrap; margin-left: auto; }
428
+ .dsh-proc-link { border: 0; background: transparent; color: var(--dsw-alias-brand-primary); font: inherit; font-size: 12px; cursor: pointer; padding: 0; flex: none; white-space: nowrap; }
429
+ .dsh-proc-link:hover { text-decoration: underline; }
430
+ .dsh-proc-spin { display: inline-block; width: 12px; height: 12px; border: 2px solid var(--dsw-alias-border-l2); border-top-color: var(--dsw-alias-brand-primary); border-radius: 50%; animation: dsh-proc-spin .8s linear infinite; vertical-align: -2px; }
431
+ @keyframes dsh-proc-spin { to { transform: rotate(360deg); } }
432
+ .dsh-proc-footer-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-width: 34px; height: 34px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; background: transparent; color: var(--dsw-alias-label-secondary); cursor: pointer; font: inherit; font-size: 12px; }
433
+ .dsh-proc-footer-btn:hover { background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary); }
434
+ .dsh-proc-footer-btn:disabled { opacity: .5; cursor: default; }
435
+ .dsh-proc-footer-label { white-space: nowrap; }
436
+ .dsh-proc-cmdrow { display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; font-size: 12px; padding: 2px 0; color: var(--dsw-alias-label-secondary); }
437
+ .dsh-proc-cmdrow.error { color: var(--dsw-alias-state-error-primary); }
438
+ `
439
+
440
+ function pickLang() {
441
+ return String(document.documentElement.lang || '').toLowerCase().startsWith('zh') ? 'zh' : 'en'
442
+ }
443
+
444
+ function localGet(key) {
445
+ try { return localStorage.getItem(key) } catch { return null }
446
+ }
447
+
448
+ function localSet(key, value) {
449
+ try { localStorage.setItem(key, value) } catch { /* ignore */ }
450
+ }
451
+
452
+ function parseJson(text) {
453
+ try { return JSON.parse(text) } catch { return undefined }
454
+ }
455
+
456
+ function isAbort(error) {
457
+ if (!error) return false
458
+ const name = String(error.name ?? '')
459
+ const code = String(error.code ?? '')
460
+ return name === 'AbortError' || code === 'ABORTED' || code === 'gateway/cancelled' || /abort/i.test(String(error.message ?? ''))
461
+ }
462
+
463
+ function errorText(error) {
464
+ if (!error) return ''
465
+ if (typeof error === 'string') return error
466
+ const code = error.code ? `[${error.code}] ` : ''
467
+ return code + String(error.message ?? error)
468
+ }
469
+
470
+ async function copyText(text) {
471
+ try {
472
+ await navigator.clipboard.writeText(text)
473
+ return true
474
+ } catch {
475
+ return false
476
+ }
477
+ }
478
+
479
+ function format(template, values) {
480
+ let result = String(template ?? '')
481
+ for (const [key, value] of Object.entries(values ?? {})) {
482
+ result = result.split(`{${key}}`).join(String(value))
483
+ }
484
+ return result
485
+ }
486
+
487
+ function fmtBytes(bytes) {
488
+ let value = Number(bytes)
489
+ if (!Number.isFinite(value) || value <= 0) return '0 B'
490
+ const units = ['B', 'KB', 'MB', 'GB', 'TB']
491
+ let index = 0
492
+ while (value >= 1024 && index < units.length - 1) {
493
+ value /= 1024
494
+ index += 1
495
+ }
496
+ return `${value.toFixed(index === 0 || value >= 100 ? 0 : 1)} ${units[index]}`
497
+ }
498
+
499
+ function fmtPercent(value) {
500
+ const number = Number(value)
501
+ if (!Number.isFinite(number) || number <= 0) return '0%'
502
+ return `${number >= 10 ? number.toFixed(0) : number.toFixed(1)}%`
503
+ }
504
+
505
+ function parseDate(iso) {
506
+ const text = String(iso ?? '')
507
+ if (text === '') return null
508
+ const normalized = text.replace(/(\.\d{3})\d+/, '$1')
509
+ const date = new Date(normalized)
510
+ return Number.isNaN(date.getTime()) ? null : date
511
+ }
512
+
513
+ function fmtClock(iso) {
514
+ const date = parseDate(iso)
515
+ if (date === null) return ''
516
+ const pad = value => String(value).padStart(2, '0')
517
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
518
+ }
519
+
520
+ function fmtAgo(iso, t) {
521
+ const date = parseDate(iso)
522
+ if (date === null) return ''
523
+ const seconds = Math.max(0, Math.round((Date.now() - date.getTime()) / 1000))
524
+ if (seconds < 10) return t('justNow')
525
+ if (seconds < 120) return format(t('secondsAgo'), { n: seconds })
526
+ return format(t('minutesAgo'), { n: Math.round(seconds / 60) })
527
+ }
528
+
529
+ function fmtDateTime(iso) {
530
+ const date = parseDate(iso)
531
+ if (date === null) return ''
532
+ const pad = value => String(value).padStart(2, '0')
533
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
534
+ }
535
+
536
+ function signatureLabel(status, lang) {
537
+ const labels = lang === 'en'
538
+ ? { Valid: 'Valid', NotSigned: 'Not signed', HashMismatch: 'Hash mismatch', NotTrusted: 'Not trusted', UnknownError: 'Unknown', Unknown: 'Unknown' }
539
+ : { Valid: '有效', NotSigned: '未签名', HashMismatch: '哈希不匹配', NotTrusted: '不受信任', UnknownError: '未知', Unknown: '未知' }
540
+ return labels[status] ?? String(status ?? '')
541
+ }
542
+
543
+ function shortSigner(subject) {
544
+ const text = String(subject ?? '')
545
+ const match = /CN=([^,]+)/i.exec(text)
546
+ return match ? match[1].trim() : text
547
+ }
548
+
549
+ function labelOf(item, lang) {
550
+ if (!item) return ''
551
+ return lang === 'en' ? (item.label_en || item.label || item.name || '') : (item.label || item.label_en || item.name || '')
552
+ }
553
+
554
+ function purposeOf(item, lang) {
555
+ if (!item) return ''
556
+ return lang === 'en' ? (item.purpose_en || item.purpose || '') : (item.purpose || item.purpose_en || '')
557
+ }
558
+
559
+ function riskTone(risk) {
560
+ return risk === 'critical' || risk === 'protected' ? 'critical' : risk === 'caution' ? 'caution' : ''
561
+ }
562
+
563
+ function riskText(t, risk) {
564
+ if (risk === 'critical') return t('riskCritical')
565
+ if (risk === 'caution') return t('riskCaution')
566
+ if (risk === 'protected') return t('riskProtected')
567
+ return t('riskNormal')
568
+ }
569
+
570
+ function sourceText(t, source) {
571
+ if (source === 'run') return t('sourceRun')
572
+ if (source === 'folder') return t('sourceFolder')
573
+ if (source === 'task') return t('sourceTask')
574
+ if (source === 'service') return t('sourceService')
575
+ return source
576
+ }
577
+
578
+ function targetOf(process) {
579
+ const target = { pid: process.pid, name: process.name }
580
+ if (process.path) target.path = process.path
581
+ if (process.started_at) target.started = process.started_at
582
+ return target
583
+ }
584
+
585
+ function isRunOnce(entry) {
586
+ return entry?.source === 'run' && /runonce/i.test(String(entry?.detail?.key ?? ''))
587
+ }
588
+
589
+ function isEntryReadOnly(entry) {
590
+ if (!entry) return true
591
+ if (entry.risk === 'protected') return true
592
+ if (entry.system === true) return true
593
+ if (isRunOnce(entry)) return true
594
+ return false
595
+ }
596
+
597
+ function labelForEntry(entry, lang) {
598
+ if (entry.source === 'task') {
599
+ const app = lang === 'en' ? (entry.app_label_en || entry.app_label) : (entry.app_label || entry.app_label_en)
600
+ return entry.label + (app ? ` · ${app}` : '')
601
+ }
602
+ return labelOf(entry, lang)
603
+ }
604
+
605
+ function normalizeCommandResult(res, fallbackMessage) {
606
+ if (!res || res.ok !== true) {
607
+ return { ok: false, code: res?.error?.code ?? 'REMOTE', message: res?.error?.message ?? fallbackMessage }
608
+ }
609
+ if (res.value === undefined) return { ok: false, code: 'NO_COMMAND', message: fallbackMessage }
610
+ const result = res.value.result
611
+ if (!result) return { ok: false, code: 'NO_RESULT', message: fallbackMessage }
612
+ const parsed = parseJson(result.text ?? '')
613
+ if (parsed !== undefined && parsed !== null && typeof parsed === 'object') return parsed
614
+ return { ok: result.kind === 'success', code: result.kind === 'success' ? 'NO_DATA' : 'ERR', message: result.text ?? fallbackMessage }
615
+ }
616
+
617
+ function ProcessIcon({ size = 16 }) {
618
+ return h('svg', { width: size, height: size, viewBox: '0 0 36 36', fill: 'none', 'aria-hidden': true, focusable: 'false' },
619
+ h('circle', { cx: 8, cy: 11, r: 2, fill: 'var(--dsw-alias-brand-primary)' }),
620
+ h('path', { d: 'M13 11h9', stroke: 'var(--dsw-alias-label-secondary)', strokeWidth: 2.6, strokeLinecap: 'round' }),
621
+ h('rect', { x: 25, y: 8, width: 7, height: 6, rx: 3, fill: 'var(--dsw-alias-state-success-primary)' }),
622
+ h('circle', { cx: 8, cy: 18, r: 2, fill: 'var(--dsw-alias-label-secondary)' }),
623
+ h('path', { d: 'M13 18h16', stroke: 'var(--dsw-alias-label-secondary)', strokeWidth: 2.6, strokeLinecap: 'round' }),
624
+ h('circle', { cx: 8, cy: 25, r: 2, fill: 'var(--dsw-alias-label-secondary)' }),
625
+ h('path', { d: 'M13 25h11', stroke: 'var(--dsw-alias-label-secondary)', strokeWidth: 2.6, strokeLinecap: 'round' }))
626
+ }
627
+
628
+ function Chevron({ open }) {
629
+ return h('svg', { className: `dsh-proc-chevron${open ? ' open' : ''}`, viewBox: '0 0 12 12', fill: 'none', 'aria-hidden': true },
630
+ h('path', { d: 'M4.5 2.5 8 6l-3.5 3.5', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' }))
631
+ }
632
+
633
+ function Metric({ label, value }) {
634
+ return h('div', { className: 'dsh-proc-metric' },
635
+ h('div', { className: 'dsh-proc-metric-label' }, label),
636
+ h('div', { className: 'dsh-proc-metric-value' }, value))
637
+ }
638
+
639
+ function Pill({ tone, children }) {
640
+ return h('span', { className: `dsh-proc-pill${tone ? ` ${tone}` : ''}` }, children)
641
+ }
642
+
643
+ function Empty({ title, hint }) {
644
+ return h('div', { className: 'dsh-proc-empty' },
645
+ title ? h('div', { className: 'dsh-proc-empty-title' }, title) : null,
646
+ hint ? h('div', null, hint) : null)
647
+ }
648
+
649
+ function CompactCommandRow({ node, t }) {
650
+ // Snapshot and inspection are panel bookkeeping, not conversation steps.
651
+ if (node?.name === 'process-snapshot' || node?.name === 'process-inspect') return null
652
+ const text = node?.outcome?.text ?? ''
653
+ const parsed = parseJson(text)
654
+ const isError = node?.outcome?.kind === 'error' || (parsed !== undefined && parsed?.ok === false)
655
+ const message = parsed !== undefined && parsed !== null && typeof parsed === 'object' ? String(parsed.message ?? '') : String(text ?? '')
656
+ const label = isError ? t('opFailed') : node?.name === 'process-explain' ? t('aiExplain') : node?.name === 'process-tool' ? t('openTaskmgr') : t('opDone')
657
+ return h('div', { className: `dsh-proc-cmdrow${isError ? ' error' : ''}` },
658
+ h('span', { style: { fontWeight: 500 } }, label),
659
+ message ? h('span', null, message) : null)
660
+ }
661
+
662
+ function makeFooterButton(ctx, fallbackT) {
663
+ return function ProcessFooterButton(props) {
664
+ const t = props.t ?? fallbackT
665
+ const wide = props.wide === true
666
+ const readMounted = useCallback(() => {
667
+ try { return ctx.sidebarRight?.mounted?.getSnapshot?.() } catch { return undefined }
668
+ }, [ctx])
669
+ const [mounted, setMounted] = useState(readMounted)
670
+ useEffect(() => {
671
+ const observable = ctx.sidebarRight?.mounted
672
+ if (!observable || typeof observable.subscribe !== 'function') return undefined
673
+ const unsubscribe = observable.subscribe(() => setMounted(readMounted()))
674
+ if (typeof unsubscribe === 'function') return unsubscribe
675
+ return undefined
676
+ }, [ctx, readMounted])
677
+ const enabled = mounted !== undefined
678
+ return h('button', {
679
+ type: 'button',
680
+ className: 'dsh-proc-footer-btn',
681
+ disabled: !enabled,
682
+ title: enabled ? t('openPanel') : t('noSession'),
683
+ 'aria-label': t('openPanel'),
684
+ 'data-testid': 'proc-footer-button',
685
+ onClick: () => {
686
+ if (!enabled) return
687
+ try { ctx.sidebarRight.openTab(TAB_KIND) } catch { /* no session surface yet */ }
688
+ },
689
+ },
690
+ h(ProcessIcon, { size: wide ? 16 : 18 }),
691
+ wide ? h('span', { className: 'dsh-proc-footer-label' }, t('title')) : null)
692
+ }
693
+ }
694
+
695
+ function makePanel(ctx, fallbackT) {
696
+ return function ProcessPanel(props) {
697
+ const t = props.t ?? fallbackT
698
+ const sessionId = props.sessionId
699
+ const lang = pickLang()
700
+ const [tab, setTab] = useState('processes')
701
+ const [snapshot, setSnapshot] = useState(null)
702
+ const [loading, setLoading] = useState(true)
703
+ const [refreshing, setRefreshing] = useState(false)
704
+ const [error, setError] = useState(null)
705
+ const [toast, setToast] = useState(null)
706
+ const [query, setQuery] = useState('')
707
+ const [startupQuery, setStartupQuery] = useState('')
708
+ const [kindFilter, setKindFilter] = useState('all')
709
+ const [sort, setSort] = useState('memory')
710
+ const [expanded, setExpanded] = useState(() => new Set())
711
+ const [selected, setSelected] = useState(null)
712
+ const [inspect, setInspect] = useState(null)
713
+ const [aiBusy, setAiBusy] = useState(false)
714
+ const [hiddenPids, setHiddenPids] = useState(() => new Set())
715
+ const [startupSource, setStartupSource] = useState('all')
716
+ const [showSystem, setShowSystem] = useState(false)
717
+ const [confirm, setConfirm] = useState(null)
718
+ const abortRef = useRef(null)
719
+ const mutationAbort = useRef(null)
720
+ const mountedRef = useRef(true)
721
+ const aiCache = useRef(new Map())
722
+ const inspectCache = useRef(new Map())
723
+ const tRef = useRef(t)
724
+ tRef.current = t
725
+ const toastTimer = useRef(null)
726
+
727
+ const notify = useCallback((message, isError = false) => {
728
+ if (toastTimer.current) clearTimeout(toastTimer.current)
729
+ setToast({ message, isError })
730
+ toastTimer.current = setTimeout(() => {
731
+ if (mountedRef.current) setToast(null)
732
+ }, isError ? 6000 : 3500)
733
+ }, [])
734
+
735
+ useEffect(() => {
736
+ mountedRef.current = true
737
+ return () => {
738
+ mountedRef.current = false
739
+ if (toastTimer.current) clearTimeout(toastTimer.current)
740
+ if (abortRef.current) abortRef.current.abort()
741
+ if (mutationAbort.current) mutationAbort.current.abort()
742
+ }
743
+ }, [])
744
+
745
+ const runRemoteCommand = useCallback(async (line, { signal } = {}) => {
746
+ if (typeof sessionId !== 'string' || sessionId === '') {
747
+ return { ok: false, code: 'NO_SESSION', message: tRef.current('sessionMissing') }
748
+ }
749
+ try {
750
+ const controller = signal === undefined ? new AbortController() : null
751
+ const res = await ctx.remote.commands.execute(sessionId, line, [], signal ?? controller.signal)
752
+ return normalizeCommandResult(res, tRef.current('opFailed'))
753
+ } catch (error) {
754
+ if (isAbort(error)) return { ok: false, code: 'ABORTED', message: tRef.current('cancel') }
755
+ return { ok: false, code: error?.code ?? 'REMOTE', message: errorText(error) }
756
+ }
757
+ }, [ctx, sessionId])
758
+
759
+ const loadSnapshot = useCallback(async ({ quiet = false } = {}) => {
760
+ if (typeof sessionId !== 'string' || sessionId === '') {
761
+ setLoading(false)
762
+ setError(tRef.current('sessionMissing'))
763
+ return null
764
+ }
765
+ const controller = new AbortController()
766
+ abortRef.current = controller
767
+ if (!quiet) setRefreshing(true)
768
+ setError(null)
769
+ try {
770
+ const ack = await runRemoteCommand('/process-snapshot {}', { signal: controller.signal })
771
+ if (ack.code === 'ABORTED') return null
772
+ if (ack.ok !== true || typeof ack.path !== 'string') throw new Error(ack.message || tRef.current('loadFailed'))
773
+ const read = await ctx.remote.workspaceFiles.read(sessionId, ack.path, { offset: 1, limit: 5000 }, controller.signal)
774
+ if (read?.ok !== true) throw new Error(errorText(read?.error ?? tRef.current('loadFailed')))
775
+ const parsed = parseJson(read.value?.text ?? '')
776
+ if (!parsed || parsed.v !== 1 || !parsed.snapshot) throw new Error(tRef.current('loadFailed'))
777
+ if (!mountedRef.current) return null
778
+ setSnapshot(parsed.snapshot)
779
+ setHiddenPids(new Set())
780
+ inspectCache.current.clear()
781
+ setSelected(current => {
782
+ if (!current) return current
783
+ if (current.kind === 'process') {
784
+ return parsed.snapshot.processes.some(item => item.pid === current.pid) ? current : null
785
+ }
786
+ return parsed.snapshot.groups.some(item => item.key === current.key) ? current : null
787
+ })
788
+ return parsed.snapshot
789
+ } catch (cause) {
790
+ if (isAbort(cause)) return null
791
+ if (mountedRef.current) setError(errorText(cause))
792
+ return null
793
+ } finally {
794
+ if (mountedRef.current) {
795
+ setRefreshing(false)
796
+ setLoading(false)
797
+ }
798
+ }
799
+ }, [ctx, runRemoteCommand, sessionId])
800
+
801
+ useEffect(() => {
802
+ setLoading(true)
803
+ loadSnapshot()
804
+ return () => {
805
+ if (abortRef.current) abortRef.current.abort()
806
+ }
807
+ }, [loadSnapshot])
808
+
809
+ useEffect(() => {
810
+ const onFocus = () => {
811
+ if (document.visibilityState === 'hidden') return
812
+ if (confirm || refreshing) return
813
+ const at = parseDate(snapshot?.collected_at)?.getTime() ?? 0
814
+ if (Date.now() - at > 20000) loadSnapshot({ quiet: true })
815
+ }
816
+ window.addEventListener('focus', onFocus)
817
+ document.addEventListener('visibilitychange', onFocus)
818
+ return () => {
819
+ window.removeEventListener('focus', onFocus)
820
+ document.removeEventListener('visibilitychange', onFocus)
821
+ }
822
+ }, [loadSnapshot, snapshot, confirm, refreshing])
823
+
824
+ const openProcess = useCallback(async (pid) => {
825
+ setSelected({ kind: 'process', pid })
826
+ const cached = inspectCache.current.get(pid)
827
+ if (cached) {
828
+ setInspect({ pid, data: cached })
829
+ return
830
+ }
831
+ setInspect({ pid, loading: true })
832
+ const controller = new AbortController()
833
+ const line = `/process-inspect ${JSON.stringify({ pid })}`
834
+ const result = await runRemoteCommand(line, { signal: controller.signal })
835
+ if (!mountedRef.current) return
836
+ if (result.ok === true) {
837
+ inspectCache.current.set(pid, result)
838
+ setInspect({ pid, data: result })
839
+ } else {
840
+ setInspect({ pid, error: result.message || tRef.current('opFailed') })
841
+ }
842
+ }, [runRemoteCommand])
843
+
844
+ const runMutation = useCallback(async (current) => {
845
+ if (!current) return
846
+ setConfirm(previous => previous ? { ...previous, busy: true, error: null } : previous)
847
+ const payload = { ...current.payload }
848
+ if (current.kind === 'stop' || current.kind === 'startup') payload.elevate = current.elevation === true
849
+ // System-level startup entries always need elevation. Asking for it on
850
+ // the first confirm avoids a failed non-elevated attempt and a
851
+ // localized "access denied" that would otherwise hide the UAC step.
852
+ if (current.kind === 'startup' && current.adminRequired) payload.elevate = true
853
+ if (current.kind === 'startup' && payload.source === 'service') payload.stopRunning = current.stopRunning === true
854
+ const name = current.kind === 'stop' ? 'process-stop' : 'process-startup-set'
855
+ const controller = new AbortController()
856
+ mutationAbort.current = controller
857
+ const result = await runRemoteCommand(`/${name} ${JSON.stringify(payload)}`, { signal: controller.signal })
858
+ mutationAbort.current = null
859
+ if (!mountedRef.current) return
860
+ if (result.code === 'ELEVATION_REQUIRED') {
861
+ setConfirm(previous => previous ? { ...previous, busy: false, elevation: true, error: null } : previous)
862
+ return
863
+ }
864
+ if (result.ok !== true) {
865
+ const denied = Array.isArray(result.results) && result.results.some(item => item.code === 'ACCESS_DENIED')
866
+ if (denied && current.kind === 'stop' && current.elevation !== true) {
867
+ setConfirm(previous => previous ? { ...previous, busy: false, elevation: true, error: null } : previous)
868
+ return
869
+ }
870
+ setConfirm(previous => previous ? { ...previous, busy: false, error: result.message || tRef.current('opFailed') } : previous)
871
+ return
872
+ }
873
+ setConfirm(null)
874
+ if (current.kind === 'stop') {
875
+ const stopped = Array.isArray(result.stopped) ? result.stopped : []
876
+ if (stopped.length > 0) {
877
+ setHiddenPids(previous => {
878
+ const next = new Set(previous)
879
+ for (const pid of stopped) next.add(pid)
880
+ return next
881
+ })
882
+ }
883
+ setSelected(null)
884
+ notify(result.message || tRef.current('opDone'))
885
+ loadSnapshot({ quiet: true })
886
+ } else {
887
+ const enabled = result.enabled === true
888
+ setSnapshot(previous => {
889
+ if (!previous) return previous
890
+ return {
891
+ ...previous,
892
+ startup: {
893
+ ...previous.startup,
894
+ entries: previous.startup.entries.map(entry => (
895
+ entry.source === current.payload.source && sameEntryDetail(entry, current.payload)
896
+ ? { ...entry, enabled }
897
+ : entry
898
+ )),
899
+ },
900
+ }
901
+ })
902
+ notify(result.message || tRef.current('startupDone'))
903
+ loadSnapshot({ quiet: true })
904
+ }
905
+ }, [loadSnapshot, notify, runRemoteCommand])
906
+
907
+ const startStop = useCallback((mode, targets, titleKey, description) => {
908
+ if (!targets.length) return
909
+ setConfirm({
910
+ kind: 'stop',
911
+ titleKey,
912
+ description,
913
+ targets,
914
+ payload: {
915
+ mode,
916
+ targets: targets.map(targetOf),
917
+ ...(mode === 'kill' ? { confirm: '结束' } : {}),
918
+ },
919
+ busy: false,
920
+ error: null,
921
+ elevation: false,
922
+ })
923
+ }, [])
924
+
925
+ const askProcessStop = useCallback((process, mode) => {
926
+ const name = labelOf(process, lang)
927
+ if (mode === 'close') {
928
+ startStop('close', [process], 'confirmStopTitle', format(t('confirmStopDesc'), { name }))
929
+ } else {
930
+ startStop('kill', [process], 'confirmKillTitle', format(t('confirmKillDesc'), { name }))
931
+ }
932
+ }, [lang, startStop, t])
933
+
934
+ const askGroupStop = useCallback((group, processes, mode = 'kill') => {
935
+ const name = labelOf(group, lang)
936
+ if (mode === 'close') {
937
+ const windowed = processes.filter(process => process.has_window)
938
+ if (windowed.length === 0) {
939
+ notify(t('noWindow'), true)
940
+ return
941
+ }
942
+ startStop('close', windowed, 'confirmStopTitle', format(t('confirmStopDesc'), { name }))
943
+ return
944
+ }
945
+ startStop('kill', processes, 'confirmKillGroupTitle', format(t('confirmKillGroupDesc'), { name, n: processes.length }))
946
+ }, [lang, notify, startStop, t])
947
+
948
+ const askStartup = useCallback((entry, enabled) => {
949
+ const name = labelOf(entry, lang)
950
+ const payload = { source: entry.source, detail: entry.detail, enabled }
951
+ if (entry.source === 'run') payload.expect = entry.command
952
+ if (entry.source === 'folder') payload.expect = entry.exe_path || ''
953
+ if (!enabled) payload.confirm = '禁用'
954
+ setConfirm({
955
+ kind: 'startup',
956
+ titleKey: enabled ? 'startupEnableTitle' : 'startupDisableTitle',
957
+ description: format(enabled ? t('startupEnableDesc') : t('startupDisableDesc'), { name }),
958
+ payload,
959
+ entry,
960
+ adminRequired: entry.admin_required === true,
961
+ stopRunning: false,
962
+ busy: false,
963
+ error: null,
964
+ elevation: false,
965
+ })
966
+ }, [lang, t])
967
+
968
+ const explain = useCallback(async (pid, label) => {
969
+ if (!pid) return
970
+ setAiBusy(true)
971
+ const result = await runRemoteCommand(`/process-explain ${JSON.stringify({ pid, lang })}`, {})
972
+ if (!mountedRef.current) return
973
+ setAiBusy(false)
974
+ if (result.ok !== true) {
975
+ notify(result.message || t('aiFailed'), true)
976
+ return
977
+ }
978
+ aiCache.current.set(pid, { text: result.text, label })
979
+ setInspect(current => (current && current.pid === pid ? { ...current } : current))
980
+ notify(t('aiTitle'))
981
+ }, [lang, notify, runRemoteCommand, t])
982
+
983
+ const openTool = useCallback(async (tool, path) => {
984
+ const result = await runRemoteCommand(`/process-tool ${JSON.stringify({ tool, path })}`, {})
985
+ if (result.ok !== true) notify(result.message || t('opFailed'), true)
986
+ }, [notify, runRemoteCommand, t])
987
+
988
+ const toggleGroup = useCallback((key) => {
989
+ setExpanded(previous => {
990
+ const next = new Set(previous)
991
+ if (next.has(key)) next.delete(key)
992
+ else next.add(key)
993
+ return next
994
+ })
995
+ }, [])
996
+
997
+ const groups = useMemo(() => {
998
+ if (!snapshot) return []
999
+ const needle = query.trim().toLowerCase()
1000
+ const list = snapshot.groups
1001
+ .filter(group => group.pids.some(pid => !hiddenPids.has(pid)))
1002
+ .filter(group => kindFilter === 'all' || group.kind === kindFilter)
1003
+ .filter(group => {
1004
+ if (needle === '') return true
1005
+ if (group.pids.some(pid => String(pid) === needle)) return true
1006
+ return [group.label, group.label_en, group.publisher, group.purpose, group.purpose_en]
1007
+ .join(' ').toLowerCase().includes(needle)
1008
+ })
1009
+ return [...list].sort((a, b) => {
1010
+ if (sort === 'cpu') return b.cpu_percent - a.cpu_percent
1011
+ if (sort === 'name') return String(a.label_en ?? a.label).localeCompare(String(b.label_en ?? b.label))
1012
+ return b.mem_bytes - a.mem_bytes
1013
+ })
1014
+ }, [snapshot, hiddenPids, query, kindFilter, sort])
1015
+
1016
+ const processesByGroup = useMemo(() => {
1017
+ const map = new Map()
1018
+ if (!snapshot) return map
1019
+ for (const process of snapshot.processes) {
1020
+ if (hiddenPids.has(process.pid)) continue
1021
+ const list = map.get(process.app_key) ?? []
1022
+ list.push(process)
1023
+ map.set(process.app_key, list)
1024
+ }
1025
+ for (const list of map.values()) list.sort((a, b) => b.mem_bytes - a.mem_bytes)
1026
+ return map
1027
+ }, [snapshot, hiddenPids])
1028
+
1029
+ const startupCounts = useMemo(() => {
1030
+ const counts = { all: 0, run: 0, folder: 0, task: 0, service: 0 }
1031
+ if (!snapshot) return counts
1032
+ for (const entry of snapshot.startup.entries) {
1033
+ if (!showSystem) {
1034
+ if (entry.risk === 'protected') continue
1035
+ if (entry.system === true) continue
1036
+ }
1037
+ counts.all += 1
1038
+ counts[entry.source] = (counts[entry.source] ?? 0) + 1
1039
+ }
1040
+ return counts
1041
+ }, [snapshot, showSystem])
1042
+
1043
+ const startupEntries = useMemo(() => {
1044
+ if (!snapshot) return []
1045
+ const needle = startupQuery.trim().toLowerCase()
1046
+ const filtered = snapshot.startup.entries.filter(entry => {
1047
+ if (!showSystem) {
1048
+ if (entry.risk === 'protected') return false
1049
+ if (entry.system === true) return false
1050
+ }
1051
+ if (startupSource !== 'all' && entry.source !== startupSource) return false
1052
+ if (needle !== '') {
1053
+ const haystack = [entry.label, entry.label_en, entry.name, entry.app_label, entry.app_label_en, entry.exe_path, entry.publisher, entry.purpose, entry.purpose_en, entry.command]
1054
+ .join(' ').toLowerCase()
1055
+ if (!haystack.includes(needle)) return false
1056
+ }
1057
+ return true
1058
+ })
1059
+ return [...filtered].sort(compareStartupEntries)
1060
+ }, [snapshot, showSystem, startupSource, startupQuery])
1061
+
1062
+ const selectedGroup = selected?.kind === 'group' ? snapshot?.groups.find(group => group.key === selected.key) : null
1063
+ const selectedProcess = selected?.kind === 'process' ? snapshot?.processes.find(process => process.pid === selected.pid) : null
1064
+
1065
+ const headerActions = h(React.Fragment, null,
1066
+ h('button', {
1067
+ type: 'button', className: 'dsh-proc-btn ghost', disabled: refreshing, title: t('refresh'),
1068
+ 'data-testid': 'proc-refresh', onClick: () => loadSnapshot(),
1069
+ }, refreshing ? h('span', { className: 'dsh-proc-spin' }) : t('refresh')),
1070
+ ctx.layout && typeof ctx.layout.openRightbar === 'function'
1071
+ ? h('button', {
1072
+ type: 'button', className: 'dsh-proc-btn ghost', title: t('fullscreen'),
1073
+ onClick: () => { try { ctx.layout.openRightbar(true, true) } catch { /* not available */ } },
1074
+ }, t('fullscreen'))
1075
+ : null)
1076
+
1077
+ if (confirm) {
1078
+ const current = confirm
1079
+ return h('div', { className: 'dsh-proc-root' },
1080
+ h('style', null, CSS),
1081
+ h('div', { className: 'dsh-proc-header' },
1082
+ h(ProcessIcon, { size: 18 }),
1083
+ h('h2', { className: 'dsh-proc-title' }, t(current.titleKey)),
1084
+ h('span', { className: 'dsh-proc-spacer' })),
1085
+ h('div', { className: 'dsh-proc-body' },
1086
+ h('div', { className: 'dsh-proc-confirm' },
1087
+ h('div', { className: 'dsh-proc-confirm-title' }, t(current.titleKey)),
1088
+ h('div', { className: 'dsh-proc-muted' }, current.description),
1089
+ current.kind === 'stop' && current.targets.length > 0
1090
+ ? h('div', { className: 'dsh-proc-confirm-list' }, current.targets.map(target => h('div', { key: `${target.pid}` },
1091
+ `${labelOf(target, lang)} · ${target.name} · PID ${target.pid}`)))
1092
+ : null,
1093
+ current.kind === 'stop' && current.payload.mode === 'kill'
1094
+ ? h('div', { className: 'dsh-proc-banner warn' }, t('killHint'))
1095
+ : current.kind === 'stop' ? h('div', { className: 'dsh-proc-banner' }, t('closeHint')) : null,
1096
+ current.kind === 'startup' && current.adminRequired && !current.elevation
1097
+ ? h('div', { className: 'dsh-proc-banner' }, t('adminPreNote'))
1098
+ : null,
1099
+ current.kind === 'startup' && current.payload.source === 'service' && current.payload.enabled !== true
1100
+ ? h('label', { className: 'dsh-proc-check' },
1101
+ h('input', {
1102
+ type: 'checkbox',
1103
+ checked: current.stopRunning === true,
1104
+ onChange: event => setConfirm(previous => previous ? { ...previous, stopRunning: event.target.checked } : previous),
1105
+ }),
1106
+ h('span', null,
1107
+ h('div', null, t('stopRunningService')),
1108
+ h('div', { className: 'dsh-proc-small' }, t('stopRunningServiceHint'))))
1109
+ : null,
1110
+ current.elevation
1111
+ ? h('div', { className: 'dsh-proc-banner warn' },
1112
+ h('div', { style: { fontWeight: 600 } }, t('needAdmin')),
1113
+ h('div', null, t('needAdminDesc')))
1114
+ : null,
1115
+ current.error ? h('div', { className: 'dsh-proc-banner error' }, current.error) : null,
1116
+ h('div', { className: 'dsh-proc-actions' },
1117
+ h('button', {
1118
+ type: 'button', className: 'dsh-proc-btn', disabled: current.busy,
1119
+ onClick: () => setConfirm(null),
1120
+ }, t('cancel')),
1121
+ h('button', {
1122
+ type: 'button',
1123
+ className: `dsh-proc-btn ${current.kind === 'stop' && current.payload.mode === 'kill' ? 'danger' : 'primary'}`,
1124
+ disabled: current.busy,
1125
+ 'data-testid': 'proc-confirm',
1126
+ onClick: () => runMutation(current),
1127
+ }, current.busy ? t('working') : current.elevation ? t('applyAdmin') : (current.kind === 'startup' && current.adminRequired ? t('confirmAdmin') : t('confirm')))))),
1128
+ h('div', { className: 'dsh-proc-footer' },
1129
+ h('span', null, t('footerHint'))))
1130
+ }
1131
+
1132
+ const processBody = h(React.Fragment, null,
1133
+ snapshot
1134
+ ? h('div', { className: 'dsh-proc-metrics' },
1135
+ h(Metric, { label: t('summaryProcesses'), value: String(snapshot.summary.process_count) }),
1136
+ h(Metric, { label: t('summaryApps'), value: String(snapshot.summary.app_count) }),
1137
+ h(Metric, { label: t('summaryMemory'), value: fmtBytes(snapshot.summary.mem_bytes) }),
1138
+ h(Metric, { label: t('summaryCpu'), value: fmtPercent(snapshot.summary.cpu_percent) }),
1139
+ h(Metric, { label: t('summaryAutostart'), value: String(snapshot.summary.autostart_running) }))
1140
+ : null,
1141
+ snapshot && snapshot.groups.some(group => group.risk === 'critical' || group.risk === 'protected')
1142
+ ? h('div', { className: 'dsh-proc-muted dsh-proc-small' }, t('riskLegend'))
1143
+ : null,
1144
+ h('div', { className: 'dsh-proc-toolbar' },
1145
+ h('input', {
1146
+ className: 'dsh-proc-input', placeholder: t('search'), value: query,
1147
+ 'aria-label': t('search'), 'data-testid': 'proc-search',
1148
+ onChange: event => setQuery(event.target.value),
1149
+ }),
1150
+ h('select', {
1151
+ className: 'dsh-proc-select', value: kindFilter, 'aria-label': t('filterLabel'),
1152
+ onChange: event => setKindFilter(event.target.value),
1153
+ },
1154
+ h('option', { value: 'all' }, t('filterAll')),
1155
+ h('option', { value: 'app' }, t('filterApps')),
1156
+ h('option', { value: 'background' }, t('filterBackground')),
1157
+ h('option', { value: 'system' }, t('filterSystem'))),
1158
+ h('select', {
1159
+ className: 'dsh-proc-select', value: sort, 'aria-label': t('sortLabel'),
1160
+ onChange: event => setSort(event.target.value),
1161
+ },
1162
+ h('option', { value: 'memory' }, t('sortMemory')),
1163
+ h('option', { value: 'cpu' }, t('sortCpu')),
1164
+ h('option', { value: 'name' }, t('sortName'))),
1165
+ h('button', {
1166
+ type: 'button', className: 'dsh-proc-btn ghost',
1167
+ onClick: () => setExpanded(new Set(groups.map(group => group.key))),
1168
+ }, t('expandAll')),
1169
+ expanded.size > 0
1170
+ ? h('button', { type: 'button', className: 'dsh-proc-btn ghost', onClick: () => setExpanded(new Set()) }, t('collapseAll'))
1171
+ : null),
1172
+ groups.length === 0
1173
+ ? h(Empty, { title: t('noMatches'), hint: t('noMatchesHint') })
1174
+ : h('div', { className: 'dsh-proc-list' }, groups.map(group => {
1175
+ const open = expanded.has(group.key)
1176
+ const children = processesByGroup.get(group.key) ?? []
1177
+ return h('div', { className: 'dsh-proc-group', key: group.key },
1178
+ h('div', { className: 'dsh-proc-group-head' },
1179
+ h('button', {
1180
+ type: 'button', className: 'dsh-proc-chevronbtn',
1181
+ 'aria-label': open ? t('collapseAll') : t('expandAll'),
1182
+ 'data-testid': 'proc-group',
1183
+ onClick: () => toggleGroup(group.key),
1184
+ }, h(Chevron, { open })),
1185
+ h('button', {
1186
+ type: 'button', className: 'dsh-proc-group-main',
1187
+ onClick: () => toggleGroup(group.key),
1188
+ },
1189
+ h('div', { className: 'dsh-proc-group-title' },
1190
+ h('span', null, labelOf(group, lang)),
1191
+ group.autostart ? h(Pill, { tone: 'brand' }, t('autostart')) : null,
1192
+ group.risk === 'caution' ? h(Pill, { tone: 'caution' }, t('riskCaution')) : null),
1193
+ h('div', { className: 'dsh-proc-group-sub' },
1194
+ [group.publisher, format(t('groupCount'), { n: group.process_count }), fmtBytes(group.mem_bytes), `CPU ${fmtPercent(group.cpu_percent)}`].filter(Boolean).join(' · '))),
1195
+ h('button', {
1196
+ type: 'button', className: 'dsh-proc-link',
1197
+ title: t('details'),
1198
+ onClick: event => { event.stopPropagation(); setSelected({ kind: 'group', key: group.key }) },
1199
+ }, t('details'))),
1200
+ open
1201
+ ? h('div', null, children.map(process => h('button', {
1202
+ type: 'button', key: process.pid, className: 'dsh-proc-proc',
1203
+ 'data-testid': 'proc-row',
1204
+ onClick: () => openProcess(process.pid),
1205
+ },
1206
+ h('span', { className: 'dsh-proc-proc-name' }, process.name),
1207
+ process.has_window ? h(Pill, { tone: 'brand' }, t('filterApps')) : null,
1208
+ process.autostart.length > 0 ? h(Pill, { tone: 'brand' }, t('autostart')) : null,
1209
+ process.services.length > 0 ? h(Pill, null, format(t('serviceCount'), { n: process.services.length })) : null,
1210
+ h('span', { className: 'dsh-proc-proc-num' }, `PID ${process.pid} · ${fmtBytes(process.mem_bytes)}`))))
1211
+ : null)
1212
+ })))
1213
+
1214
+ const startupBody = h(React.Fragment, null,
1215
+ h('div', { className: 'dsh-proc-toolbar' },
1216
+ h('input', {
1217
+ className: 'dsh-proc-input', placeholder: t('startupSearch'), value: startupQuery,
1218
+ 'aria-label': t('startupSearch'), 'data-testid': 'proc-startup-search',
1219
+ onChange: event => setStartupQuery(event.target.value),
1220
+ }),
1221
+ h('button', {
1222
+ type: 'button', className: 'dsh-proc-btn ghost',
1223
+ onClick: () => setShowSystem(value => !value),
1224
+ }, showSystem ? t('hideSystem') : t('showSystem'))),
1225
+ h('div', { className: 'dsh-proc-chips' },
1226
+ [['all', t('startupAll')], ['run', t('startupRun')], ['folder', t('startupFolder')], ['task', t('startupTask')], ['service', t('startupService')]].map(([key, label]) => h('button', {
1227
+ type: 'button', key, className: `dsh-proc-chip${startupSource === key ? ' active' : ''}`,
1228
+ onClick: () => setStartupSource(key),
1229
+ }, `${label} ${startupCounts[key] ?? 0}`))),
1230
+ !showSystem ? h('div', { className: 'dsh-proc-muted dsh-proc-small' }, t('hideSystemHint')) : null,
1231
+ startupEntries.length === 0
1232
+ ? h(Empty, { title: t('startupEmpty'), hint: startupQuery.trim() !== '' ? t('noMatchesHint') : t('hideSystemHint') })
1233
+ : h('div', { className: 'dsh-proc-list' }, startupEntries.map(entry => {
1234
+ const readOnly = isEntryReadOnly(entry)
1235
+ const running = entry.running_pids.length > 0
1236
+ const label = labelForEntry(entry, lang)
1237
+ return h('div', { className: 'dsh-proc-startup', key: entry.id, 'data-testid': 'proc-startup-entry' },
1238
+ h('div', { className: 'dsh-proc-startup-head' },
1239
+ h('button', {
1240
+ type: 'button', role: 'switch',
1241
+ 'aria-checked': entry.enabled, 'aria-label': label,
1242
+ className: `dsh-proc-switch${entry.enabled ? ' on' : ''}`,
1243
+ disabled: readOnly,
1244
+ title: readOnly ? t('startupProtectedHint') : entry.enabled ? t('startupDisable') : t('startupEnable'),
1245
+ onClick: () => askStartup(entry, !entry.enabled),
1246
+ }),
1247
+ h('div', { className: 'dsh-proc-startup-main' },
1248
+ h('div', { className: 'dsh-proc-startup-title' },
1249
+ h('span', null, label),
1250
+ h(Pill, null, sourceText(t, entry.source)),
1251
+ entry.enabled ? h(Pill, { tone: 'ok' }, t('enabled')) : h(Pill, null, t('disabled')),
1252
+ running ? h(Pill, { tone: 'brand' }, `${t('runningNow')}${entry.running_pids[0] ? ` · PID ${entry.running_pids[0]}` : ''}`) : null,
1253
+ readOnly ? h(Pill, null, t('readOnly')) : null,
1254
+ entry.admin_required ? h(Pill, null, t('admin')) : null),
1255
+ h('div', { className: 'dsh-proc-startup-sub' }, purposeOf(entry, lang)))),
1256
+ entry.command ? h('div', { className: 'dsh-proc-cmd', title: entry.command }, entry.command) : null,
1257
+ h('div', { className: 'dsh-proc-muted dsh-proc-small' },
1258
+ [entry.name !== label ? entry.name : '', entry.publisher, entry.description, entry.triggers?.map(trigger => trigger === 'boot' ? t('triggerBoot') : trigger === 'once' ? t('startupRunOnce') : t('triggerLogin')).join('/')]
1259
+ .filter(Boolean).join(' · ')),
1260
+ h('div', { className: 'dsh-proc-startup-actions' },
1261
+ readOnly
1262
+ ? h('span', { className: 'dsh-proc-muted dsh-proc-small' }, t('startupProtectedHint'))
1263
+ : h('button', {
1264
+ type: 'button', className: 'dsh-proc-btn',
1265
+ onClick: () => askStartup(entry, !entry.enabled),
1266
+ }, entry.enabled ? t('startupDisable') : t('startupEnable')),
1267
+ entry.exe_path
1268
+ ? h('button', { type: 'button', className: 'dsh-proc-btn ghost', onClick: () => openTool('reveal', entry.exe_path) }, t('reveal'))
1269
+ : null,
1270
+ entry.command
1271
+ ? h('button', {
1272
+ type: 'button', className: 'dsh-proc-btn ghost',
1273
+ onClick: async () => notify((await copyText(entry.command)) ? t('copied') : t('copyFailed'), false),
1274
+ }, t('copyCommand'))
1275
+ : null))
1276
+ })))
1277
+
1278
+ const detailBody = selectedProcess
1279
+ ? (() => {
1280
+ const process = selectedProcess
1281
+ const data = inspect?.data
1282
+ const ai = aiCache.current.get(process.pid)
1283
+ const risk = process.risk
1284
+ return h(React.Fragment, null,
1285
+ h('div', { className: 'dsh-proc-detail-head' },
1286
+ h('button', { type: 'button', className: 'dsh-proc-back', onClick: () => setSelected(null), 'data-testid': 'proc-back' }, `← ${t('back')}`),
1287
+ h('h3', { className: 'dsh-proc-detail-title' }, labelOf(process, lang)),
1288
+ h(Pill, { tone: riskTone(risk) }, riskText(t, risk)),
1289
+ process.autostart.length > 0 ? h(Pill, { tone: 'brand' }, t('autostart')) : null),
1290
+ h('div', { className: 'dsh-proc-muted' }, purposeOf(process, lang)),
1291
+ process.protected_reason ? h('div', { className: 'dsh-proc-banner warn' }, process.protected_reason) : null,
1292
+ process.services.length > 0 ? h('div', { className: 'dsh-proc-banner' }, t('serviceStopHint')) : null,
1293
+ h('div', { className: 'dsh-proc-card' },
1294
+ h('div', { className: 'dsh-proc-card-title' }, t('factsTitle')),
1295
+ h('dl', { className: 'dsh-proc-facts' },
1296
+ h('dt', null, t('pid') || 'PID'), h('dd', null, String(process.pid)),
1297
+ h('dt', null, t('path')), h('dd', null, process.path || t('unknown')),
1298
+ h('dt', null, t('publisher')), h('dd', null, process.company || t('unknown')),
1299
+ h('dt', null, t('product')), h('dd', null, process.product || process.description || t('unknown')),
1300
+ h('dt', null, t('version')), h('dd', null, process.version || t('unknown')),
1301
+ h('dt', null, t('startedAt')), h('dd', null, process.started_at ? [fmtDateTime(process.started_at), fmtAgo(process.started_at, t)].filter(Boolean).join(' · ') : t('unknown')),
1302
+ h('dt', null, t('commandLine')), h('dd', null, process.cmdline || t('unknown')),
1303
+ process.window_title ? h('dt', null, t('windowTitle')) : null,
1304
+ process.window_title ? h('dd', null, process.window_title) : null,
1305
+ data?.signature_status ? h('dt', null, t('signature')) : null,
1306
+ data?.signature_status ? h('dd', null, `${signatureLabel(data.signature_status, lang)}${data.signature_signer ? ` · ${shortSigner(data.signature_signer)}` : ''}`) : null)),
1307
+ inspect?.loading ? h('div', { className: 'dsh-proc-muted' }, t('detailLoading')) : null,
1308
+ h('div', { className: 'dsh-proc-actions' },
1309
+ h('button', {
1310
+ type: 'button', className: 'dsh-proc-btn',
1311
+ disabled: process.risk === 'protected' || process.risk === 'critical',
1312
+ title: process.risk === 'protected' ? t('protectedHint') : process.risk === 'critical' ? t('criticalHint') : t('closeHint'),
1313
+ onClick: () => askProcessStop(process, 'close'),
1314
+ }, t('closeApp')),
1315
+ h('button', {
1316
+ type: 'button', className: 'dsh-proc-btn danger',
1317
+ disabled: process.risk === 'protected' || process.risk === 'critical',
1318
+ title: process.risk === 'protected' ? t('protectedHint') : process.risk === 'critical' ? t('criticalHint') : t('killHint'),
1319
+ onClick: () => askProcessStop(process, 'kill'),
1320
+ }, t('killApp')),
1321
+ process.path ? h('button', { type: 'button', className: 'dsh-proc-btn ghost', onClick: () => openTool('reveal', process.path) }, t('reveal')) : null,
1322
+ process.cmdline ? h('button', {
1323
+ type: 'button', className: 'dsh-proc-btn ghost',
1324
+ onClick: async () => notify((await copyText(process.cmdline)) ? t('copied') : t('copyFailed')),
1325
+ }, t('copyCommand')) : null,
1326
+ h('button', {
1327
+ type: 'button', className: 'dsh-proc-btn ghost', disabled: aiBusy,
1328
+ title: t('aiHint'),
1329
+ onClick: () => explain(process.pid, labelOf(process, lang)),
1330
+ }, aiBusy ? t('aiWorking') : t('aiExplain'))),
1331
+ ai
1332
+ ? h('div', { className: 'dsh-proc-ai' }, ai.text)
1333
+ : null,
1334
+ process.services.length > 0
1335
+ ? h('div', { className: 'dsh-proc-card' },
1336
+ h('div', { className: 'dsh-proc-card-title' }, t('services')),
1337
+ process.services.map(service => h('div', { key: service.name, className: 'dsh-proc-small' },
1338
+ h('div', null, `${service.display || service.name}${service.description ? ` · ${service.description.slice(0, 120)}` : ''}`))))
1339
+ : null,
1340
+ data?.parents?.length
1341
+ ? h('div', { className: 'dsh-proc-card' },
1342
+ h('div', { className: 'dsh-proc-card-title' }, t('parentChain')),
1343
+ h('div', { className: 'dsh-proc-small' }, data.parents.map(parent => `${parent.name} (${parent.pid})`).join(' → ')))
1344
+ : null,
1345
+ data?.related_startup?.length
1346
+ ? h('div', { className: 'dsh-proc-card' },
1347
+ h('div', { className: 'dsh-proc-card-title' }, t('relatedStartup')),
1348
+ data.related_startup.map(entry => h('div', { key: `${entry.source}:${entry.label}`, className: 'dsh-proc-small' },
1349
+ `${entry.label} · ${entry.enabled ? t('enabled') : t('disabled')} · ${sourceText(t, entry.source)}`)))
1350
+ : null)
1351
+ })()
1352
+ : selectedGroup
1353
+ ? (() => {
1354
+ const group = selectedGroup
1355
+ const processes = processesByGroup.get(group.key) ?? []
1356
+ const ai = aiCache.current.get(group.root_pid)
1357
+ return h(React.Fragment, null,
1358
+ h('div', { className: 'dsh-proc-detail-head' },
1359
+ h('button', { type: 'button', className: 'dsh-proc-back', onClick: () => setSelected(null) }, `← ${t('back')}`),
1360
+ h('h3', { className: 'dsh-proc-detail-title' }, labelOf(group, lang)),
1361
+ h(Pill, { tone: riskTone(group.risk) }, riskText(t, group.risk)),
1362
+ group.autostart ? h(Pill, { tone: 'brand' }, t('autostart')) : null),
1363
+ h('div', { className: 'dsh-proc-muted' }, purposeOf(group, lang)),
1364
+ h('div', { className: 'dsh-proc-card' },
1365
+ h('div', { className: 'dsh-proc-card-title' }, t('factsTitle')),
1366
+ h('dl', { className: 'dsh-proc-facts' },
1367
+ h('dt', null, t('summaryProcesses')), h('dd', null, String(group.process_count)),
1368
+ h('dt', null, t('summaryMemory')), h('dd', null, fmtBytes(group.mem_bytes)),
1369
+ h('dt', null, t('summaryCpu')), h('dd', null, fmtPercent(group.cpu_percent)),
1370
+ h('dt', null, t('publisher')), h('dd', null, group.publisher || t('unknown')),
1371
+ h('dt', null, t('path')), h('dd', null, processes[0]?.path || t('unknown')))),
1372
+ h('div', { className: 'dsh-proc-actions' },
1373
+ h('button', {
1374
+ type: 'button', className: 'dsh-proc-btn',
1375
+ disabled: group.risk === 'protected' || group.risk === 'critical' || !processes.some(process => process.has_window),
1376
+ title: group.risk === 'protected' ? t('protectedHint') : group.risk === 'critical' ? t('criticalHint') : t('closeHint'),
1377
+ onClick: () => askGroupStop(group, processes, 'close'),
1378
+ }, t('closeApp')),
1379
+ h('button', {
1380
+ type: 'button', className: 'dsh-proc-btn danger',
1381
+ disabled: group.risk === 'protected' || group.risk === 'critical',
1382
+ title: group.risk === 'protected' ? t('protectedHint') : group.risk === 'critical' ? t('criticalHint') : t('killHint'),
1383
+ onClick: () => askGroupStop(group, processes, 'kill'),
1384
+ }, t('killGroup')),
1385
+ h('button', {
1386
+ type: 'button', className: 'dsh-proc-btn ghost', disabled: aiBusy,
1387
+ onClick: () => explain(group.root_pid, labelOf(group, lang)),
1388
+ }, aiBusy ? t('aiWorking') : t('aiForGroup'))),
1389
+ ai ? h('div', { className: 'dsh-proc-ai' }, ai.text) : null,
1390
+ h('div', { className: 'dsh-proc-card' },
1391
+ h('div', { className: 'dsh-proc-card-title' }, t('groupProcesses')),
1392
+ processes.map(process => h('button', {
1393
+ type: 'button', key: process.pid, className: 'dsh-proc-proc', style: { paddingLeft: 8 },
1394
+ onClick: () => openProcess(process.pid),
1395
+ },
1396
+ h('span', { className: 'dsh-proc-proc-name' }, process.name),
1397
+ process.has_window ? h(Pill, { tone: 'brand' }, t('filterApps')) : null,
1398
+ h('span', { className: 'dsh-proc-proc-num' }, `PID ${process.pid} · ${fmtBytes(process.mem_bytes)}`)))))
1399
+ })()
1400
+ : h(Empty, { title: t('noDetail') })
1401
+
1402
+ return h('div', { className: 'dsh-proc-root' },
1403
+ h('style', null, CSS),
1404
+ h('div', { className: 'dsh-proc-header' },
1405
+ h(ProcessIcon, { size: 18 }),
1406
+ h('h2', { className: 'dsh-proc-title' }, t('title')),
1407
+ h('span', { className: 'dsh-proc-badge', title: t('snapshotHint') }, t('snapshot')),
1408
+ h('span', { className: 'dsh-proc-spacer' }),
1409
+ headerActions),
1410
+ h('div', { className: 'dsh-proc-tabs' },
1411
+ h('button', {
1412
+ type: 'button', className: `dsh-proc-tab${tab === 'processes' ? ' active' : ''}`,
1413
+ onClick: () => { setTab('processes'); setSelected(null) }, 'data-testid': 'proc-tab-processes',
1414
+ }, `${t('tabProcesses')}${snapshot ? ` ${snapshot.summary.process_count}` : ''}`),
1415
+ h('button', {
1416
+ type: 'button', className: `dsh-proc-tab${tab === 'startup' ? ' active' : ''}`,
1417
+ onClick: () => { setTab('startup'); setSelected(null) }, 'data-testid': 'proc-tab-startup',
1418
+ }, `${t('tabStartup')}${snapshot ? ` ${startupCounts.all}` : ''}`)),
1419
+ h('div', { className: 'dsh-proc-body' },
1420
+ error ? h('div', { className: 'dsh-proc-banner error' },
1421
+ h('div', null, error),
1422
+ h('button', { type: 'button', className: 'dsh-proc-btn', style: { marginTop: 4 }, onClick: () => loadSnapshot() }, t('retry')))
1423
+ : null,
1424
+ snapshot && !refreshing && (parseDate(snapshot.collected_at)?.getTime() ?? 0) < Date.now() - 120000
1425
+ ? h('div', { className: 'dsh-proc-banner warn' }, t('staleHint'))
1426
+ : null,
1427
+ loading
1428
+ ? h('div', { className: 'dsh-proc-empty' },
1429
+ h('span', { className: 'dsh-proc-spin' }),
1430
+ h('div', { className: 'dsh-proc-empty-title' }, t('loading')),
1431
+ h('div', null, t('loadingHint')))
1432
+ : selected ? detailBody : tab === 'processes' ? processBody : startupBody),
1433
+ h('div', { className: 'dsh-proc-footer' },
1434
+ snapshot
1435
+ ? h('span', null, `${t('snapshotTime')} ${fmtClock(snapshot.collected_at)} · ${fmtAgo(snapshot.collected_at, t)}`)
1436
+ : h('span', null, t('footerHint')),
1437
+ h('div', { className: 'dsh-proc-footer-actions' },
1438
+ h('button', { type: 'button', className: 'dsh-proc-btn ghost', onClick: () => openTool('taskmgr') }, t('openTaskmgr')),
1439
+ h('button', { type: 'button', className: 'dsh-proc-btn ghost', onClick: () => openTool('startupapps') }, t('openStartupSettings')),
1440
+ h('button', { type: 'button', className: 'dsh-proc-btn ghost', onClick: () => openTool('services') }, t('openServices')))),
1441
+ toast ? h('div', { className: `dsh-proc-toast${toast.isError ? ' error' : ''}`, role: 'status' }, toast.message) : null)
1442
+ }
1443
+ }
1444
+
1445
+ function sameEntryDetail(entry, payload) {
1446
+ const detail = payload?.detail ?? {}
1447
+ if (payload.source === 'run') return entry.detail.hive === detail.hive && entry.detail.key === detail.key && entry.detail.name === detail.name
1448
+ if (payload.source === 'folder') return entry.detail.scope === detail.scope && entry.detail.file === detail.file
1449
+ if (payload.source === 'task') return entry.detail.path === detail.path && entry.detail.name === detail.name
1450
+ if (payload.source === 'service') return entry.detail.name === detail.name
1451
+ return false
1452
+ }
1453
+
1454
+ class PanelErrorBoundary extends React.Component {
1455
+ constructor(props) {
1456
+ super(props)
1457
+ this.state = { error: null }
1458
+ }
1459
+
1460
+ static getDerivedStateFromError(error) {
1461
+ return { error }
1462
+ }
1463
+
1464
+ render() {
1465
+ if (this.state.error) {
1466
+ return h('div', { className: 'dsh-proc-empty' },
1467
+ h('div', { className: 'dsh-proc-empty-title' }, '面板渲染失败 / Panel render failed'),
1468
+ h('div', null, String(this.state.error?.message ?? this.state.error)))
1469
+ }
1470
+ return this.props.children
1471
+ }
1472
+ }
1473
+
1474
+ function autoOpen(ctx) {
1475
+ if (localGet(OP_FLAG) === '1') return
1476
+ let timer = null
1477
+ let attempts = 0
1478
+ const tryOpen = () => {
1479
+ if (localGet(OP_FLAG) === '1') return
1480
+ try {
1481
+ if (ctx.sidebarRight?.mounted?.getSnapshot?.() === undefined) return
1482
+ ctx.sidebarRight.openTab(TAB_KIND)
1483
+ localSet(OP_FLAG, '1')
1484
+ } catch {
1485
+ if (attempts < 10) {
1486
+ attempts += 1
1487
+ timer = setTimeout(tryOpen, 300)
1488
+ }
1489
+ }
1490
+ }
1491
+ let unsubscribe = null
1492
+ try {
1493
+ unsubscribe = ctx.sidebarRight?.mounted?.subscribe?.(() => {
1494
+ if (timer) clearTimeout(timer)
1495
+ timer = setTimeout(tryOpen, 400)
1496
+ }) ?? null
1497
+ } catch { /* no session surface */ }
1498
+ timer = setTimeout(tryOpen, 600)
1499
+ ctx.effect(() => () => {
1500
+ if (timer) clearTimeout(timer)
1501
+ if (typeof unsubscribe === 'function') unsubscribe()
1502
+ }, 'proc: auto-open cleanup')
1503
+ }
1504
+
1505
+ function apply(ctx) {
1506
+ ctx.effect(() => ctx.locale.register(NS, { zh, en, ja: en, es: en, fr: en, de: en, ru: en, pt: en }), 'proc: dictionaries')
1507
+ const translate = ctx.locale.bind(NS)
1508
+ const Panel = makePanel(ctx, translate)
1509
+ const Footer = makeFooterButton(ctx, translate)
1510
+ const GuardedPanel = props => h(PanelErrorBoundary, null, h(Panel, props))
1511
+ ctx.effect(() => ctx.sidebarRightTabs.register({
1512
+ id: TAB_ID,
1513
+ kind: TAB_KIND,
1514
+ priority: 'extension',
1515
+ title: () => translate('title'),
1516
+ guide: [{ id: 'main', order: 90, title: () => translate('title'), description: () => translate('guide') }],
1517
+ }), 'proc: tab type')
1518
+ ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
1519
+ name: 'sidebar.right.pane.tab', key: TAB_ID, locale: NS,
1520
+ }, GuardedPanel))
1521
+ ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
1522
+ name: 'sidebar.footer.action', id: 'process-manager', order: 90, locale: NS,
1523
+ }, Footer))
1524
+ ctx.slots.inject('conversation.chat.commandview', function* () {
1525
+ for (const key of COMMANDS) {
1526
+ yield ctx.slots.register({ name: 'conversation.chat.commandview', key, locale: NS }, CompactCommandRow)
1527
+ }
1528
+ })
1529
+ autoOpen(ctx)
1530
+ }
1531
+
1532
+ return {
1533
+ inject: ['slots', 'locale', 'layout', 'remote', 'remote.commands', 'remote.workspaceFiles', 'sidebarRight', 'sidebarRightTabs'],
1534
+ apply,
1535
+ }
1536
+ },
1537
+ })